@rulemetric/local 0.13.0 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/meta.json +2 -2
- package/dist/server.mjs +512 -300
- package/dist/supabase/migrations/00218_backfill_session_events_model.sql +30 -0
- package/dist/supabase/migrations/00219_weekly_digest.sql +64 -0
- package/dist/supabase/migrations/00220_snapshot_payload_lifecycle.sql +107 -0
- package/dist/supabase/migrations/00221_snapshot_payload_expiry.sql +34 -0
- package/dist/supabase/migrations/00222_memory_experiment_engine.sql +20 -0
- package/dist/supabase/migrations/00223_measurement_preferences.sql +21 -0
- package/dist/supabase/migrations/00224_measurement_job_snapshots.sql +246 -0
- package/dist/supabase/migrations/00225_pi_measurement_preferences.sql +22 -0
- package/dist/supabase/migrations/00226_memory_trial_snapshot.sql +5 -0
- package/dist/supabase/migrations/00227_marketing_leads.sql +16 -0
- package/dist/supabase/migrations/00228_snapshot_prune_dispatch.sql +16 -0
- package/dist/web/assets/{docs-CP7YCEUM.js → docs-BeHYBoMl.js} +95 -100
- package/dist/web/assets/index-CzGyJDl3.js +147 -0
- package/dist/web/assets/index-HYdcsh3R.css +1 -0
- package/dist/web/index.html +12 -5
- package/package.json +2 -2
- package/dist/web/assets/index-CujhsOsn.js +0 -147
- package/dist/web/assets/index-YQbc4i81.css +0 -1
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
var xb=es=>{throw TypeError(es)};var aj=(es,$,ts)=>$.has(es)||xb("Cannot "+ts);var Wa=(es,$,ts)=>(aj(es,$,"read from private field"),ts?ts.call(es):$.get(es)),Hl=(es,$,ts)=>$.has(es)?xb("Cannot add the same private member more than once"):$ instanceof WeakSet?$.add(es):$.set(es,ts),Pl=(es,$,ts,is)=>(aj(es,$,"write to private field"),is?is.call(es,ts):$.set(es,ts),ts),Xl=(es,$,ts)=>(aj(es,$,"access private method"),ts);var Gp=(es,$,ts,is)=>({set _(cs){Pl(es,$,cs,ts)},get _(){return Wa(es,$,is)}});import{r as requireReact,a as requireReactDom,b as reactExports,j as jsxRuntimeExports,R as React,c as ReactDOM,L as LoaderCircle,O as OctagonX,T as TriangleAlert,I as Info,C as CircleCheck,B as Button,_ as __awaiter,d as __rest,e as cn$1,N as Navigate,f as Outlet,g as getAugmentedNamespace,u as useLocation,h as Root,i as LayoutDashboard,P as Plug,A as Activity,k as Layers,F as FlaskConical,l as TrendingUp,m as Brain,D as DollarSign,S as Sparkles,G as Globe,n as Lightbulb,o as TestTube,p as SlidersHorizontal,q as BookOpen,s as Link,t as Shield,M as Megaphone,v as Root2,w as Trigger,x as Portal2,y as Content2,z as Item2,E as Separator2,H as Label2,J as Root$1,K as Fallback,Q as Root$2,U as Content,V as Close,X as X$1,W as Title,Y as Description,Z as Trigger$1,$ as Portal,a0 as Overlay,a1 as useNavigate,a2 as Bell,a3 as CheckCheck,a4 as CircleAlert,a5 as ClipboardList,a6 as BadgeCheck,a7 as BellRing,a8 as Menu,a9 as User,aa as LogOut,ab as CircleArrowUp,ac as UPDATE_CLI_SHORT,ad as CircleX,ae as INSTALL_CLI,af as useCopyToClipboard,ag as Check,ah as Copy,ai as INSTALL_CLI_LATEST,aj as Hourglass,ak as RefreshCw,al as Badge,am as PartyPopper,an as Radar,ao as Send,ap as ClipboardCheck,aq as ArrowRight,ar as CircleDot,as as Gauge,at as GitCompareArrows,au as Github,av as Root$3,aw as useSearchParams,ax as Card,ay as CardHeader,az as CardTitle,aA as CardDescription,aB as CardContent,aC as CardFooter,aD as Provider,aE as Root3,aF as Trigger$2,aG as Portal$1,aH as Content2$1,aI as Arrow2,aJ as Zap,aK as MessageSquare,aL as CodeXml,aM as ChartColumn,aN as GitCommitHorizontal,aO as Clock,aP as FileText,aQ as ChevronRight,aR as useTabParam,aS as Tabs,aT as TabsList,aU as TabsTrigger,aV as TabsContent,aW as Download,aX as Wifi,aY as WifiOff,aZ as Key,a_ as EyeOff,a$ as Eye,b0 as Plus,b1 as Trash2,b2 as Terminal,b3 as FileJson,b4 as ChevronDown,b5 as ArrowUp,b6 as ArrowDown,b7 as ArrowUpDown,b8 as useParams,b9 as ArrowLeft,ba as GitBranch,bb as CircleHelp,bc as Root2$1,bd as Trigger$3,be as Icon,bf as Value,bg as Portal$2,bh as Content2$2,bi as Viewport,bj as Item,bk as ItemIndicator,bl as ItemText,bm as ScrollUpButton,bn as ChevronUp,bo as ScrollDownButton,bp as Rocket,bq as Folder,br as Play,bs as ThumbsUp,bt as ThumbsDown,bu as Square,bv as DocsPage,bw as CircleDashed,bx as Package,by as Wrench,bz as ExternalLink,bA as Upload,bB as Search,bC as Pencil,bD as RotateCcw,bE as Archive,bF as Star,bG as Bot,bH as Undo2,bI as CircleMinus,bJ as Ban,bK as Building2,bL as Users,bM as Mail,bN as UserPlus,bO as Ellipsis,bP as ArrowRightLeft,bQ as Database,bR as UserCheck,bS as ShieldAlert,bT as BrowserRouter,bU as Routes,bV as Route}from"./docs-BeHYBoMl.js";(function(){const $=document.createElement("link").relList;if($&&$.supports&&$.supports("modulepreload"))return;for(const cs of document.querySelectorAll('link[rel="modulepreload"]'))is(cs);new MutationObserver(cs=>{for(const Qr of cs)if(Qr.type==="childList")for(const ja of Qr.addedNodes)ja.tagName==="LINK"&&ja.rel==="modulepreload"&&is(ja)}).observe(document,{childList:!0,subtree:!0});function ts(cs){const Qr={};return cs.integrity&&(Qr.integrity=cs.integrity),cs.referrerPolicy&&(Qr.referrerPolicy=cs.referrerPolicy),cs.crossOrigin==="use-credentials"?Qr.credentials="include":cs.crossOrigin==="anonymous"?Qr.credentials="omit":Qr.credentials="same-origin",Qr}function is(cs){if(cs.ep)return;cs.ep=!0;const Qr=ts(cs);fetch(cs.href,Qr)}})();var client={exports:{}},reactDomClient_production={},scheduler={exports:{}},scheduler_production={};/**
|
|
2
|
+
* @license React
|
|
3
|
+
* scheduler.production.js
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
6
|
+
*
|
|
7
|
+
* This source code is licensed under the MIT license found in the
|
|
8
|
+
* LICENSE file in the root directory of this source tree.
|
|
9
|
+
*/var hasRequiredScheduler_production;function requireScheduler_production(){return hasRequiredScheduler_production||(hasRequiredScheduler_production=1,(function(es){function $(ul,hl){var jl=ul.length;ul.push(hl);e:for(;0<jl;){var Nl=jl-1>>>1,zl=ul[Nl];if(0<cs(zl,hl))ul[Nl]=hl,ul[jl]=zl,jl=Nl;else break e}}function ts(ul){return ul.length===0?null:ul[0]}function is(ul){if(ul.length===0)return null;var hl=ul[0],jl=ul.pop();if(jl!==hl){ul[0]=jl;e:for(var Nl=0,zl=ul.length,Zl=zl>>>1;Nl<Zl;){var Dl=2*(Nl+1)-1,Il=ul[Dl],Fl=Dl+1,ql=ul[Fl];if(0>cs(Il,jl))Fl<zl&&0>cs(ql,Il)?(ul[Nl]=ql,ul[Fl]=jl,Nl=Fl):(ul[Nl]=Il,ul[Dl]=jl,Nl=Dl);else if(Fl<zl&&0>cs(ql,jl))ul[Nl]=ql,ul[Fl]=jl,Nl=Fl;else break e}}return hl}function cs(ul,hl){var jl=ul.sortIndex-hl.sortIndex;return jl!==0?jl:ul.id-hl.id}if(es.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var Qr=performance;es.unstable_now=function(){return Qr.now()}}else{var ja=Date,Na=ja.now();es.unstable_now=function(){return ja.now()-Na}}var Aa=[],Oa=[],Ia=1,La=null,Ba=3,Ma=!1,qa=!1,Fa=!1,Ha=!1,Ka=typeof setTimeout=="function"?setTimeout:null,Ga=typeof clearTimeout=="function"?clearTimeout:null,Va=typeof setImmediate<"u"?setImmediate:null;function Ja(ul){for(var hl=ts(Oa);hl!==null;){if(hl.callback===null)is(Oa);else if(hl.startTime<=ul)is(Oa),hl.sortIndex=hl.expirationTime,$(Aa,hl);else break;hl=ts(Oa)}}function Ya(ul){if(Fa=!1,Ja(ul),!qa)if(ts(Aa)!==null)qa=!0,el||(el=!0,nl());else{var hl=ts(Oa);hl!==null&&Tl(Ya,hl.startTime-ul)}}var el=!1,tl=-1,rl=5,cl=-1;function dl(){return Ha?!0:!(es.unstable_now()-cl<rl)}function fl(){if(Ha=!1,el){var ul=es.unstable_now();cl=ul;var hl=!0;try{e:{qa=!1,Fa&&(Fa=!1,Ga(tl),tl=-1),Ma=!0;var jl=Ba;try{t:{for(Ja(ul),La=ts(Aa);La!==null&&!(La.expirationTime>ul&&dl());){var Nl=La.callback;if(typeof Nl=="function"){La.callback=null,Ba=La.priorityLevel;var zl=Nl(La.expirationTime<=ul);if(ul=es.unstable_now(),typeof zl=="function"){La.callback=zl,Ja(ul),hl=!0;break t}La===ts(Aa)&&is(Aa),Ja(ul)}else is(Aa);La=ts(Aa)}if(La!==null)hl=!0;else{var Zl=ts(Oa);Zl!==null&&Tl(Ya,Zl.startTime-ul),hl=!1}}break e}finally{La=null,Ba=jl,Ma=!1}hl=void 0}}finally{hl?nl():el=!1}}}var nl;if(typeof Va=="function")nl=function(){Va(fl)};else if(typeof MessageChannel<"u"){var ol=new MessageChannel,pl=ol.port2;ol.port1.onmessage=fl,nl=function(){pl.postMessage(null)}}else nl=function(){Ka(fl,0)};function Tl(ul,hl){tl=Ka(function(){ul(es.unstable_now())},hl)}es.unstable_IdlePriority=5,es.unstable_ImmediatePriority=1,es.unstable_LowPriority=4,es.unstable_NormalPriority=3,es.unstable_Profiling=null,es.unstable_UserBlockingPriority=2,es.unstable_cancelCallback=function(ul){ul.callback=null},es.unstable_forceFrameRate=function(ul){0>ul||125<ul?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):rl=0<ul?Math.floor(1e3/ul):5},es.unstable_getCurrentPriorityLevel=function(){return Ba},es.unstable_next=function(ul){switch(Ba){case 1:case 2:case 3:var hl=3;break;default:hl=Ba}var jl=Ba;Ba=hl;try{return ul()}finally{Ba=jl}},es.unstable_requestPaint=function(){Ha=!0},es.unstable_runWithPriority=function(ul,hl){switch(ul){case 1:case 2:case 3:case 4:case 5:break;default:ul=3}var jl=Ba;Ba=ul;try{return hl()}finally{Ba=jl}},es.unstable_scheduleCallback=function(ul,hl,jl){var Nl=es.unstable_now();switch(typeof jl=="object"&&jl!==null?(jl=jl.delay,jl=typeof jl=="number"&&0<jl?Nl+jl:Nl):jl=Nl,ul){case 1:var zl=-1;break;case 2:zl=250;break;case 5:zl=1073741823;break;case 4:zl=1e4;break;default:zl=5e3}return zl=jl+zl,ul={id:Ia++,callback:hl,priorityLevel:ul,startTime:jl,expirationTime:zl,sortIndex:-1},jl>Nl?(ul.sortIndex=jl,$(Oa,ul),ts(Aa)===null&&ul===ts(Oa)&&(Fa?(Ga(tl),tl=-1):Fa=!0,Tl(Ya,jl-Nl))):(ul.sortIndex=zl,$(Aa,ul),qa||Ma||(qa=!0,el||(el=!0,nl()))),ul},es.unstable_shouldYield=dl,es.unstable_wrapCallback=function(ul){var hl=Ba;return function(){var jl=Ba;Ba=hl;try{return ul.apply(this,arguments)}finally{Ba=jl}}}})(scheduler_production)),scheduler_production}var hasRequiredScheduler;function requireScheduler(){return hasRequiredScheduler||(hasRequiredScheduler=1,scheduler.exports=requireScheduler_production()),scheduler.exports}/**
|
|
10
|
+
* @license React
|
|
11
|
+
* react-dom-client.production.js
|
|
12
|
+
*
|
|
13
|
+
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
14
|
+
*
|
|
15
|
+
* This source code is licensed under the MIT license found in the
|
|
16
|
+
* LICENSE file in the root directory of this source tree.
|
|
17
|
+
*/var hasRequiredReactDomClient_production;function requireReactDomClient_production(){if(hasRequiredReactDomClient_production)return reactDomClient_production;hasRequiredReactDomClient_production=1;var es=requireScheduler(),$=requireReact(),ts=requireReactDom();function is(os){var Kr="https://react.dev/errors/"+os;if(1<arguments.length){Kr+="?args[]="+encodeURIComponent(arguments[1]);for(var Xr=2;Xr<arguments.length;Xr++)Kr+="&args[]="+encodeURIComponent(arguments[Xr])}return"Minified React error #"+os+"; visit "+Kr+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function cs(os){return!(!os||os.nodeType!==1&&os.nodeType!==9&&os.nodeType!==11)}function Qr(os){var Kr=os,Xr=os;if(os.alternate)for(;Kr.return;)Kr=Kr.return;else{os=Kr;do Kr=os,(Kr.flags&4098)!==0&&(Xr=Kr.return),os=Kr.return;while(os)}return Kr.tag===3?Xr:null}function ja(os){if(os.tag===13){var Kr=os.memoizedState;if(Kr===null&&(os=os.alternate,os!==null&&(Kr=os.memoizedState)),Kr!==null)return Kr.dehydrated}return null}function Na(os){if(os.tag===31){var Kr=os.memoizedState;if(Kr===null&&(os=os.alternate,os!==null&&(Kr=os.memoizedState)),Kr!==null)return Kr.dehydrated}return null}function Aa(os){if(Qr(os)!==os)throw Error(is(188))}function Oa(os){var Kr=os.alternate;if(!Kr){if(Kr=Qr(os),Kr===null)throw Error(is(188));return Kr!==os?null:os}for(var Xr=os,Ca=Kr;;){var Pa=Xr.return;if(Pa===null)break;var Da=Pa.alternate;if(Da===null){if(Ca=Pa.return,Ca!==null){Xr=Ca;continue}break}if(Pa.child===Da.child){for(Da=Pa.child;Da;){if(Da===Xr)return Aa(Pa),os;if(Da===Ca)return Aa(Pa),Kr;Da=Da.sibling}throw Error(is(188))}if(Xr.return!==Ca.return)Xr=Pa,Ca=Da;else{for(var za=!1,Qa=Pa.child;Qa;){if(Qa===Xr){za=!0,Xr=Pa,Ca=Da;break}if(Qa===Ca){za=!0,Ca=Pa,Xr=Da;break}Qa=Qa.sibling}if(!za){for(Qa=Da.child;Qa;){if(Qa===Xr){za=!0,Xr=Da,Ca=Pa;break}if(Qa===Ca){za=!0,Ca=Da,Xr=Pa;break}Qa=Qa.sibling}if(!za)throw Error(is(189))}}if(Xr.alternate!==Ca)throw Error(is(190))}if(Xr.tag!==3)throw Error(is(188));return Xr.stateNode.current===Xr?os:Kr}function Ia(os){var Kr=os.tag;if(Kr===5||Kr===26||Kr===27||Kr===6)return os;for(os=os.child;os!==null;){if(Kr=Ia(os),Kr!==null)return Kr;os=os.sibling}return null}var La=Object.assign,Ba=Symbol.for("react.element"),Ma=Symbol.for("react.transitional.element"),qa=Symbol.for("react.portal"),Fa=Symbol.for("react.fragment"),Ha=Symbol.for("react.strict_mode"),Ka=Symbol.for("react.profiler"),Ga=Symbol.for("react.consumer"),Va=Symbol.for("react.context"),Ja=Symbol.for("react.forward_ref"),Ya=Symbol.for("react.suspense"),el=Symbol.for("react.suspense_list"),tl=Symbol.for("react.memo"),rl=Symbol.for("react.lazy"),cl=Symbol.for("react.activity"),dl=Symbol.for("react.memo_cache_sentinel"),fl=Symbol.iterator;function nl(os){return os===null||typeof os!="object"?null:(os=fl&&os[fl]||os["@@iterator"],typeof os=="function"?os:null)}var ol=Symbol.for("react.client.reference");function pl(os){if(os==null)return null;if(typeof os=="function")return os.$$typeof===ol?null:os.displayName||os.name||null;if(typeof os=="string")return os;switch(os){case Fa:return"Fragment";case Ka:return"Profiler";case Ha:return"StrictMode";case Ya:return"Suspense";case el:return"SuspenseList";case cl:return"Activity"}if(typeof os=="object")switch(os.$$typeof){case qa:return"Portal";case Va:return os.displayName||"Context";case Ga:return(os._context.displayName||"Context")+".Consumer";case Ja:var Kr=os.render;return os=os.displayName,os||(os=Kr.displayName||Kr.name||"",os=os!==""?"ForwardRef("+os+")":"ForwardRef"),os;case tl:return Kr=os.displayName||null,Kr!==null?Kr:pl(os.type)||"Memo";case rl:Kr=os._payload,os=os._init;try{return pl(os(Kr))}catch{}}return null}var Tl=Array.isArray,ul=$.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,hl=ts.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,jl={pending:!1,data:null,method:null,action:null},Nl=[],zl=-1;function Zl(os){return{current:os}}function Dl(os){0>zl||(os.current=Nl[zl],Nl[zl]=null,zl--)}function Il(os,Kr){zl++,Nl[zl]=os.current,os.current=Kr}var Fl=Zl(null),ql=Zl(null),nu=Zl(null),Gl=Zl(null);function cu(os,Kr){switch(Il(nu,Kr),Il(ql,os),Il(Fl,null),Kr.nodeType){case 9:case 11:os=(os=Kr.documentElement)&&(os=os.namespaceURI)?PE(os):0;break;default:if(os=Kr.tagName,Kr=Kr.namespaceURI)Kr=PE(Kr),os=DE(Kr,os);else switch(os){case"svg":os=1;break;case"math":os=2;break;default:os=0}}Dl(Fl),Il(Fl,os)}function Al(){Dl(Fl),Dl(ql),Dl(nu)}function Ml(os){os.memoizedState!==null&&Il(Gl,os);var Kr=Fl.current,Xr=DE(Kr,os.type);Kr!==Xr&&(Il(ql,os),Il(Fl,Xr))}function Ql(os){ql.current===os&&(Dl(Fl),Dl(ql)),Gl.current===os&&(Dl(Gl),vh._currentValue=jl)}var eu,xu;function fu(os){if(eu===void 0)try{throw Error()}catch(Xr){var Kr=Xr.stack.trim().match(/\n( *(at )?)/);eu=Kr&&Kr[1]||"",xu=-1<Xr.stack.indexOf(`
|
|
18
|
+
at`)?" (<anonymous>)":-1<Xr.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
19
|
+
`+eu+os+xu}var Ou=!1;function yu(os,Kr){if(!os||Ou)return"";Ou=!0;var Xr=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var Ca={DetermineComponentFrameRoot:function(){try{if(Kr){var Cl=function(){throw Error()};if(Object.defineProperty(Cl.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Cl,[])}catch(vl){var gl=vl}Reflect.construct(os,[],Cl)}else{try{Cl.call()}catch(vl){gl=vl}os.call(Cl.prototype)}}else{try{throw Error()}catch(vl){gl=vl}(Cl=os())&&typeof Cl.catch=="function"&&Cl.catch(function(){})}}catch(vl){if(vl&&gl&&typeof vl.stack=="string")return[vl.stack,gl.stack]}return[null,null]}};Ca.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var Pa=Object.getOwnPropertyDescriptor(Ca.DetermineComponentFrameRoot,"name");Pa&&Pa.configurable&&Object.defineProperty(Ca.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Da=Ca.DetermineComponentFrameRoot(),za=Da[0],Qa=Da[1];if(za&&Qa){var Xa=za.split(`
|
|
20
|
+
`),xl=Qa.split(`
|
|
21
|
+
`);for(Pa=Ca=0;Ca<Xa.length&&!Xa[Ca].includes("DetermineComponentFrameRoot");)Ca++;for(;Pa<xl.length&&!xl[Pa].includes("DetermineComponentFrameRoot");)Pa++;if(Ca===Xa.length||Pa===xl.length)for(Ca=Xa.length-1,Pa=xl.length-1;1<=Ca&&0<=Pa&&Xa[Ca]!==xl[Pa];)Pa--;for(;1<=Ca&&0<=Pa;Ca--,Pa--)if(Xa[Ca]!==xl[Pa]){if(Ca!==1||Pa!==1)do if(Ca--,Pa--,0>Pa||Xa[Ca]!==xl[Pa]){var wl=`
|
|
22
|
+
`+Xa[Ca].replace(" at new "," at ");return os.displayName&&wl.includes("<anonymous>")&&(wl=wl.replace("<anonymous>",os.displayName)),wl}while(1<=Ca&&0<=Pa);break}}}finally{Ou=!1,Error.prepareStackTrace=Xr}return(Xr=os?os.displayName||os.name:"")?fu(Xr):""}function ic(os,Kr){switch(os.tag){case 26:case 27:case 5:return fu(os.type);case 16:return fu("Lazy");case 13:return os.child!==Kr&&Kr!==null?fu("Suspense Fallback"):fu("Suspense");case 19:return fu("SuspenseList");case 0:case 15:return yu(os.type,!1);case 11:return yu(os.type.render,!1);case 1:return yu(os.type,!0);case 31:return fu("Activity");default:return""}}function Iu(os){try{var Kr="",Xr=null;do Kr+=ic(os,Xr),Xr=os,os=os.return;while(os);return Kr}catch(Ca){return`
|
|
23
|
+
Error generating stack: `+Ca.message+`
|
|
24
|
+
`+Ca.stack}}var Bl=Object.prototype.hasOwnProperty,ru=es.unstable_scheduleCallback,Mu=es.unstable_cancelCallback,lc=es.unstable_shouldYield,Tu=es.unstable_requestPaint,Eu=es.unstable_now,Ua=es.unstable_getCurrentPriorityLevel,ll=es.unstable_ImmediatePriority,yl=es.unstable_UserBlockingPriority,$l=es.unstable_NormalPriority,kl=es.unstable_LowPriority,Za=es.unstable_IdlePriority,al=es.log,El=es.unstable_setDisableYieldValue,bl=null,_l=null;function Ol(os){if(typeof al=="function"&&El(os),_l&&typeof _l.setStrictMode=="function")try{_l.setStrictMode(bl,os)}catch{}}var Rl=Math.clz32?Math.clz32:Yl,Ul=Math.log,Ll=Math.LN2;function Yl(os){return os>>>=0,os===0?32:31-(Ul(os)/Ll|0)|0}var au=256,su=262144,Lu=4194304;function ac(os){var Kr=os&42;if(Kr!==0)return Kr;switch(os&-os){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return os&261888;case 262144:case 524288:case 1048576:case 2097152:return os&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return os&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return os}}function Lm(os,Kr,Xr){var Ca=os.pendingLanes;if(Ca===0)return 0;var Pa=0,Da=os.suspendedLanes,za=os.pingedLanes;os=os.warmLanes;var Qa=Ca&134217727;return Qa!==0?(Ca=Qa&~Da,Ca!==0?Pa=ac(Ca):(za&=Qa,za!==0?Pa=ac(za):Xr||(Xr=Qa&~os,Xr!==0&&(Pa=ac(Xr))))):(Qa=Ca&~Da,Qa!==0?Pa=ac(Qa):za!==0?Pa=ac(za):Xr||(Xr=Ca&~os,Xr!==0&&(Pa=ac(Xr)))),Pa===0?0:Kr!==0&&Kr!==Pa&&(Kr&Da)===0&&(Da=Pa&-Pa,Xr=Kr&-Kr,Da>=Xr||Da===32&&(Xr&4194048)!==0)?Kr:Pa}function tu(os,Kr){return(os.pendingLanes&~(os.suspendedLanes&~os.pingedLanes)&Kr)===0}function bu(os,Kr){switch(os){case 1:case 2:case 4:case 8:case 64:return Kr+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return Kr+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ku(){var os=Lu;return Lu<<=1,(Lu&62914560)===0&&(Lu=4194304),os}function uc(os){for(var Kr=[],Xr=0;31>Xr;Xr++)Kr.push(os);return Kr}function Wu(os,Kr){os.pendingLanes|=Kr,Kr!==268435456&&(os.suspendedLanes=0,os.pingedLanes=0,os.warmLanes=0)}function Vc(os,Kr,Xr,Ca,Pa,Da){var za=os.pendingLanes;os.pendingLanes=Xr,os.suspendedLanes=0,os.pingedLanes=0,os.warmLanes=0,os.expiredLanes&=Xr,os.entangledLanes&=Xr,os.errorRecoveryDisabledLanes&=Xr,os.shellSuspendCounter=0;var Qa=os.entanglements,Xa=os.expirationTimes,xl=os.hiddenUpdates;for(Xr=za&~Xr;0<Xr;){var wl=31-Rl(Xr),Cl=1<<wl;Qa[wl]=0,Xa[wl]=-1;var gl=xl[wl];if(gl!==null)for(xl[wl]=null,wl=0;wl<gl.length;wl++){var vl=gl[wl];vl!==null&&(vl.lane&=-536870913)}Xr&=~Cl}Ca!==0&&Qc(os,Ca,0),Da!==0&&Pa===0&&os.tag!==0&&(os.suspendedLanes|=Da&~(za&~Kr))}function Qc(os,Kr,Xr){os.pendingLanes|=Kr,os.suspendedLanes&=~Kr;var Ca=31-Rl(Kr);os.entangledLanes|=Kr,os.entanglements[Ca]=os.entanglements[Ca]|1073741824|Xr&261930}function mc(os,Kr){var Xr=os.entangledLanes|=Kr;for(os=os.entanglements;Xr;){var Ca=31-Rl(Xr),Pa=1<<Ca;Pa&Kr|os[Ca]&Kr&&(os[Ca]|=Kr),Xr&=~Pa}}function Fc(os,Kr){var Xr=Kr&-Kr;return Xr=(Xr&42)!==0?1:Vp(Xr),(Xr&(os.suspendedLanes|Kr))!==0?0:Xr}function Vp(os){switch(os){case 2:os=1;break;case 8:os=4;break;case 32:os=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:os=128;break;case 268435456:os=134217728;break;default:os=0}return os}function Qp(os){return os&=-os,2<os?8<os?(os&134217727)!==0?32:268435456:8:2}function Ej(){var os=hl.p;return os!==0?os:(os=window.event,os===void 0?32:ab(os.type))}function bj(os,Kr){var Xr=hl.p;try{return hl.p=os,Kr()}finally{hl.p=Xr}}var Sd=Math.random().toString(36).slice(2),Xu="__reactFiber$"+Sd,xc="__reactProps$"+Sd,$m="__reactContainer$"+Sd,Yp="__reactEvents$"+Sd,Cb="__reactListeners$"+Sd,Tb="__reactHandles$"+Sd,Rj="__reactResources$"+Sd,Lx="__reactMarker$"+Sd;function Jp(os){delete os[Xu],delete os[xc],delete os[Yp],delete os[Cb],delete os[Tb]}function Pm(os){var Kr=os[Xu];if(Kr)return Kr;for(var Xr=os.parentNode;Xr;){if(Kr=Xr[$m]||Xr[Xu]){if(Xr=Kr.alternate,Kr.child!==null||Xr!==null&&Xr.child!==null)for(os=HE(os);os!==null;){if(Xr=os[Xu])return Xr;os=HE(os)}return Kr}os=Xr,Xr=os.parentNode}return null}function Dm(os){if(os=os[Xu]||os[$m]){var Kr=os.tag;if(Kr===5||Kr===6||Kr===13||Kr===31||Kr===26||Kr===27||Kr===3)return os}return null}function $x(os){var Kr=os.tag;if(Kr===5||Kr===26||Kr===27||Kr===6)return os.stateNode;throw Error(is(33))}function Mm(os){var Kr=os[Rj];return Kr||(Kr=os[Rj]={hoistableStyles:new Map,hoistableScripts:new Map}),Kr}function Qu(os){os[Lx]=!0}var _j=new Set,wj={};function lm(os,Kr){Bm(os,Kr),Bm(os+"Capture",Kr)}function Bm(os,Kr){for(wj[os]=Kr,os=0;os<Kr.length;os++)_j.add(Kr[os])}var kb=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),Nj={},Sj={};function Ab(os){return Bl.call(Sj,os)?!0:Bl.call(Nj,os)?!1:kb.test(os)?Sj[os]=!0:(Nj[os]=!0,!1)}function Ih(os,Kr,Xr){if(Ab(Kr))if(Xr===null)os.removeAttribute(Kr);else{switch(typeof Xr){case"undefined":case"function":case"symbol":os.removeAttribute(Kr);return;case"boolean":var Ca=Kr.toLowerCase().slice(0,5);if(Ca!=="data-"&&Ca!=="aria-"){os.removeAttribute(Kr);return}}os.setAttribute(Kr,""+Xr)}}function Lh(os,Kr,Xr){if(Xr===null)os.removeAttribute(Kr);else{switch(typeof Xr){case"undefined":case"function":case"symbol":case"boolean":os.removeAttribute(Kr);return}os.setAttribute(Kr,""+Xr)}}function nd(os,Kr,Xr,Ca){if(Ca===null)os.removeAttribute(Xr);else{switch(typeof Ca){case"undefined":case"function":case"symbol":case"boolean":os.removeAttribute(Xr);return}os.setAttributeNS(Kr,Xr,""+Ca)}}function kc(os){switch(typeof os){case"bigint":case"boolean":case"number":case"string":case"undefined":return os;case"object":return os;default:return""}}function Cj(os){var Kr=os.type;return(os=os.nodeName)&&os.toLowerCase()==="input"&&(Kr==="checkbox"||Kr==="radio")}function Ob(os,Kr,Xr){var Ca=Object.getOwnPropertyDescriptor(os.constructor.prototype,Kr);if(!os.hasOwnProperty(Kr)&&typeof Ca<"u"&&typeof Ca.get=="function"&&typeof Ca.set=="function"){var Pa=Ca.get,Da=Ca.set;return Object.defineProperty(os,Kr,{configurable:!0,get:function(){return Pa.call(this)},set:function(za){Xr=""+za,Da.call(this,za)}}),Object.defineProperty(os,Kr,{enumerable:Ca.enumerable}),{getValue:function(){return Xr},setValue:function(za){Xr=""+za},stopTracking:function(){os._valueTracker=null,delete os[Kr]}}}}function Wp(os){if(!os._valueTracker){var Kr=Cj(os)?"checked":"value";os._valueTracker=Ob(os,Kr,""+os[Kr])}}function Tj(os){if(!os)return!1;var Kr=os._valueTracker;if(!Kr)return!0;var Xr=Kr.getValue(),Ca="";return os&&(Ca=Cj(os)?os.checked?"true":"false":os.value),os=Ca,os!==Xr?(Kr.setValue(os),!0):!1}function $h(os){if(os=os||(typeof document<"u"?document:void 0),typeof os>"u")return null;try{return os.activeElement||os.body}catch{return os.body}}var Ib=/[\n"\\]/g;function Ac(os){return os.replace(Ib,function(Kr){return"\\"+Kr.charCodeAt(0).toString(16)+" "})}function Xp(os,Kr,Xr,Ca,Pa,Da,za,Qa){os.name="",za!=null&&typeof za!="function"&&typeof za!="symbol"&&typeof za!="boolean"?os.type=za:os.removeAttribute("type"),Kr!=null?za==="number"?(Kr===0&&os.value===""||os.value!=Kr)&&(os.value=""+kc(Kr)):os.value!==""+kc(Kr)&&(os.value=""+kc(Kr)):za!=="submit"&&za!=="reset"||os.removeAttribute("value"),Kr!=null?ef(os,za,kc(Kr)):Xr!=null?ef(os,za,kc(Xr)):Ca!=null&&os.removeAttribute("value"),Pa==null&&Da!=null&&(os.defaultChecked=!!Da),Pa!=null&&(os.checked=Pa&&typeof Pa!="function"&&typeof Pa!="symbol"),Qa!=null&&typeof Qa!="function"&&typeof Qa!="symbol"&&typeof Qa!="boolean"?os.name=""+kc(Qa):os.removeAttribute("name")}function kj(os,Kr,Xr,Ca,Pa,Da,za,Qa){if(Da!=null&&typeof Da!="function"&&typeof Da!="symbol"&&typeof Da!="boolean"&&(os.type=Da),Kr!=null||Xr!=null){if(!(Da!=="submit"&&Da!=="reset"||Kr!=null)){Wp(os);return}Xr=Xr!=null?""+kc(Xr):"",Kr=Kr!=null?""+kc(Kr):Xr,Qa||Kr===os.value||(os.value=Kr),os.defaultValue=Kr}Ca=Ca??Pa,Ca=typeof Ca!="function"&&typeof Ca!="symbol"&&!!Ca,os.checked=Qa?os.checked:!!Ca,os.defaultChecked=!!Ca,za!=null&&typeof za!="function"&&typeof za!="symbol"&&typeof za!="boolean"&&(os.name=za),Wp(os)}function ef(os,Kr,Xr){Kr==="number"&&$h(os.ownerDocument)===os||os.defaultValue===""+Xr||(os.defaultValue=""+Xr)}function Um(os,Kr,Xr,Ca){if(os=os.options,Kr){Kr={};for(var Pa=0;Pa<Xr.length;Pa++)Kr["$"+Xr[Pa]]=!0;for(Xr=0;Xr<os.length;Xr++)Pa=Kr.hasOwnProperty("$"+os[Xr].value),os[Xr].selected!==Pa&&(os[Xr].selected=Pa),Pa&&Ca&&(os[Xr].defaultSelected=!0)}else{for(Xr=""+kc(Xr),Kr=null,Pa=0;Pa<os.length;Pa++){if(os[Pa].value===Xr){os[Pa].selected=!0,Ca&&(os[Pa].defaultSelected=!0);return}Kr!==null||os[Pa].disabled||(Kr=os[Pa])}Kr!==null&&(Kr.selected=!0)}}function Aj(os,Kr,Xr){if(Kr!=null&&(Kr=""+kc(Kr),Kr!==os.value&&(os.value=Kr),Xr==null)){os.defaultValue!==Kr&&(os.defaultValue=Kr);return}os.defaultValue=Xr!=null?""+kc(Xr):""}function Oj(os,Kr,Xr,Ca){if(Kr==null){if(Ca!=null){if(Xr!=null)throw Error(is(92));if(Tl(Ca)){if(1<Ca.length)throw Error(is(93));Ca=Ca[0]}Xr=Ca}Xr==null&&(Xr=""),Kr=Xr}Xr=kc(Kr),os.defaultValue=Xr,Ca=os.textContent,Ca===Xr&&Ca!==""&&Ca!==null&&(os.value=Ca),Wp(os)}function qm(os,Kr){if(Kr){var Xr=os.firstChild;if(Xr&&Xr===os.lastChild&&Xr.nodeType===3){Xr.nodeValue=Kr;return}}os.textContent=Kr}var Lb=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Ij(os,Kr,Xr){var Ca=Kr.indexOf("--")===0;Xr==null||typeof Xr=="boolean"||Xr===""?Ca?os.setProperty(Kr,""):Kr==="float"?os.cssFloat="":os[Kr]="":Ca?os.setProperty(Kr,Xr):typeof Xr!="number"||Xr===0||Lb.has(Kr)?Kr==="float"?os.cssFloat=Xr:os[Kr]=(""+Xr).trim():os[Kr]=Xr+"px"}function Lj(os,Kr,Xr){if(Kr!=null&&typeof Kr!="object")throw Error(is(62));if(os=os.style,Xr!=null){for(var Ca in Xr)!Xr.hasOwnProperty(Ca)||Kr!=null&&Kr.hasOwnProperty(Ca)||(Ca.indexOf("--")===0?os.setProperty(Ca,""):Ca==="float"?os.cssFloat="":os[Ca]="");for(var Pa in Kr)Ca=Kr[Pa],Kr.hasOwnProperty(Pa)&&Xr[Pa]!==Ca&&Ij(os,Pa,Ca)}else for(var Da in Kr)Kr.hasOwnProperty(Da)&&Ij(os,Da,Kr[Da])}function tf(os){if(os.indexOf("-")===-1)return!1;switch(os){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var $b=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),Pb=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function Ph(os){return Pb.test(""+os)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":os}function rd(){}var sf=null;function nf(os){return os=os.target||os.srcElement||window,os.correspondingUseElement&&(os=os.correspondingUseElement),os.nodeType===3?os.parentNode:os}var Fm=null,zm=null;function $j(os){var Kr=Dm(os);if(Kr&&(os=Kr.stateNode)){var Xr=os[xc]||null;e:switch(os=Kr.stateNode,Kr.type){case"input":if(Xp(os,Xr.value,Xr.defaultValue,Xr.defaultValue,Xr.checked,Xr.defaultChecked,Xr.type,Xr.name),Kr=Xr.name,Xr.type==="radio"&&Kr!=null){for(Xr=os;Xr.parentNode;)Xr=Xr.parentNode;for(Xr=Xr.querySelectorAll('input[name="'+Ac(""+Kr)+'"][type="radio"]'),Kr=0;Kr<Xr.length;Kr++){var Ca=Xr[Kr];if(Ca!==os&&Ca.form===os.form){var Pa=Ca[xc]||null;if(!Pa)throw Error(is(90));Xp(Ca,Pa.value,Pa.defaultValue,Pa.defaultValue,Pa.checked,Pa.defaultChecked,Pa.type,Pa.name)}}for(Kr=0;Kr<Xr.length;Kr++)Ca=Xr[Kr],Ca.form===os.form&&Tj(Ca)}break e;case"textarea":Aj(os,Xr.value,Xr.defaultValue);break e;case"select":Kr=Xr.value,Kr!=null&&Um(os,!!Xr.multiple,Kr,!1)}}}var rf=!1;function Pj(os,Kr,Xr){if(rf)return os(Kr,Xr);rf=!0;try{var Ca=os(Kr);return Ca}finally{if(rf=!1,(Fm!==null||zm!==null)&&(_p(),Fm&&(Kr=Fm,os=zm,zm=Fm=null,$j(Kr),os)))for(Kr=0;Kr<os.length;Kr++)$j(os[Kr])}}function Px(os,Kr){var Xr=os.stateNode;if(Xr===null)return null;var Ca=Xr[xc]||null;if(Ca===null)return null;Xr=Ca[Kr];e:switch(Kr){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(Ca=!Ca.disabled)||(os=os.type,Ca=!(os==="button"||os==="input"||os==="select"||os==="textarea")),os=!Ca;break e;default:os=!1}if(os)return null;if(Xr&&typeof Xr!="function")throw Error(is(231,Kr,typeof Xr));return Xr}var id=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),af=!1;if(id)try{var Dx={};Object.defineProperty(Dx,"passive",{get:function(){af=!0}}),window.addEventListener("test",Dx,Dx),window.removeEventListener("test",Dx,Dx)}catch{af=!1}var Cd=null,of=null,Dh=null;function Dj(){if(Dh)return Dh;var os,Kr=of,Xr=Kr.length,Ca,Pa="value"in Cd?Cd.value:Cd.textContent,Da=Pa.length;for(os=0;os<Xr&&Kr[os]===Pa[os];os++);var za=Xr-os;for(Ca=1;Ca<=za&&Kr[Xr-Ca]===Pa[Da-Ca];Ca++);return Dh=Pa.slice(os,1<Ca?1-Ca:void 0)}function Mh(os){var Kr=os.keyCode;return"charCode"in os?(os=os.charCode,os===0&&Kr===13&&(os=13)):os=Kr,os===10&&(os=13),32<=os||os===13?os:0}function Bh(){return!0}function Mj(){return!1}function hc(os){function Kr(Xr,Ca,Pa,Da,za){this._reactName=Xr,this._targetInst=Pa,this.type=Ca,this.nativeEvent=Da,this.target=za,this.currentTarget=null;for(var Qa in os)os.hasOwnProperty(Qa)&&(Xr=os[Qa],this[Qa]=Xr?Xr(Da):Da[Qa]);return this.isDefaultPrevented=(Da.defaultPrevented!=null?Da.defaultPrevented:Da.returnValue===!1)?Bh:Mj,this.isPropagationStopped=Mj,this}return La(Kr.prototype,{preventDefault:function(){this.defaultPrevented=!0;var Xr=this.nativeEvent;Xr&&(Xr.preventDefault?Xr.preventDefault():typeof Xr.returnValue!="unknown"&&(Xr.returnValue=!1),this.isDefaultPrevented=Bh)},stopPropagation:function(){var Xr=this.nativeEvent;Xr&&(Xr.stopPropagation?Xr.stopPropagation():typeof Xr.cancelBubble!="unknown"&&(Xr.cancelBubble=!0),this.isPropagationStopped=Bh)},persist:function(){},isPersistent:Bh}),Kr}var um={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(os){return os.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Uh=hc(um),Mx=La({},um,{view:0,detail:0}),Db=hc(Mx),lf,uf,Bx,qh=La({},Mx,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:df,button:0,buttons:0,relatedTarget:function(os){return os.relatedTarget===void 0?os.fromElement===os.srcElement?os.toElement:os.fromElement:os.relatedTarget},movementX:function(os){return"movementX"in os?os.movementX:(os!==Bx&&(Bx&&os.type==="mousemove"?(lf=os.screenX-Bx.screenX,uf=os.screenY-Bx.screenY):uf=lf=0,Bx=os),lf)},movementY:function(os){return"movementY"in os?os.movementY:uf}}),Bj=hc(qh),Mb=La({},qh,{dataTransfer:0}),Bb=hc(Mb),Ub=La({},Mx,{relatedTarget:0}),cf=hc(Ub),qb=La({},um,{animationName:0,elapsedTime:0,pseudoElement:0}),Fb=hc(qb),zb=La({},um,{clipboardData:function(os){return"clipboardData"in os?os.clipboardData:window.clipboardData}}),Hb=hc(zb),Kb=La({},um,{data:0}),Uj=hc(Kb),Gb={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Zb={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Vb={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Qb(os){var Kr=this.nativeEvent;return Kr.getModifierState?Kr.getModifierState(os):(os=Vb[os])?!!Kr[os]:!1}function df(){return Qb}var Yb=La({},Mx,{key:function(os){if(os.key){var Kr=Gb[os.key]||os.key;if(Kr!=="Unidentified")return Kr}return os.type==="keypress"?(os=Mh(os),os===13?"Enter":String.fromCharCode(os)):os.type==="keydown"||os.type==="keyup"?Zb[os.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:df,charCode:function(os){return os.type==="keypress"?Mh(os):0},keyCode:function(os){return os.type==="keydown"||os.type==="keyup"?os.keyCode:0},which:function(os){return os.type==="keypress"?Mh(os):os.type==="keydown"||os.type==="keyup"?os.keyCode:0}}),Jb=hc(Yb),Wb=La({},qh,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),qj=hc(Wb),Xb=La({},Mx,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:df}),eR=hc(Xb),tR=La({},um,{propertyName:0,elapsedTime:0,pseudoElement:0}),sR=hc(tR),nR=La({},qh,{deltaX:function(os){return"deltaX"in os?os.deltaX:"wheelDeltaX"in os?-os.wheelDeltaX:0},deltaY:function(os){return"deltaY"in os?os.deltaY:"wheelDeltaY"in os?-os.wheelDeltaY:"wheelDelta"in os?-os.wheelDelta:0},deltaZ:0,deltaMode:0}),rR=hc(nR),iR=La({},um,{newState:0,oldState:0}),aR=hc(iR),oR=[9,13,27,32],mf=id&&"CompositionEvent"in window,Ux=null;id&&"documentMode"in document&&(Ux=document.documentMode);var lR=id&&"TextEvent"in window&&!Ux,Fj=id&&(!mf||Ux&&8<Ux&&11>=Ux),zj=" ",Hj=!1;function Kj(os,Kr){switch(os){case"keyup":return oR.indexOf(Kr.keyCode)!==-1;case"keydown":return Kr.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Gj(os){return os=os.detail,typeof os=="object"&&"data"in os?os.data:null}var Hm=!1;function uR(os,Kr){switch(os){case"compositionend":return Gj(Kr);case"keypress":return Kr.which!==32?null:(Hj=!0,zj);case"textInput":return os=Kr.data,os===zj&&Hj?null:os;default:return null}}function cR(os,Kr){if(Hm)return os==="compositionend"||!mf&&Kj(os,Kr)?(os=Dj(),Dh=of=Cd=null,Hm=!1,os):null;switch(os){case"paste":return null;case"keypress":if(!(Kr.ctrlKey||Kr.altKey||Kr.metaKey)||Kr.ctrlKey&&Kr.altKey){if(Kr.char&&1<Kr.char.length)return Kr.char;if(Kr.which)return String.fromCharCode(Kr.which)}return null;case"compositionend":return Fj&&Kr.locale!=="ko"?null:Kr.data;default:return null}}var dR={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Zj(os){var Kr=os&&os.nodeName&&os.nodeName.toLowerCase();return Kr==="input"?!!dR[os.type]:Kr==="textarea"}function Vj(os,Kr,Xr,Ca){Fm?zm?zm.push(Ca):zm=[Ca]:Fm=Ca,Kr=Ap(Kr,"onChange"),0<Kr.length&&(Xr=new Uh("onChange","change",null,Xr,Ca),os.push({event:Xr,listeners:Kr}))}var qx=null,Fx=null;function mR(os){kE(os,0)}function Fh(os){var Kr=$x(os);if(Tj(Kr))return os}function Qj(os,Kr){if(os==="change")return Kr}var Yj=!1;if(id){var xf;if(id){var hf="oninput"in document;if(!hf){var Jj=document.createElement("div");Jj.setAttribute("oninput","return;"),hf=typeof Jj.oninput=="function"}xf=hf}else xf=!1;Yj=xf&&(!document.documentMode||9<document.documentMode)}function Wj(){qx&&(qx.detachEvent("onpropertychange",Xj),Fx=qx=null)}function Xj(os){if(os.propertyName==="value"&&Fh(Fx)){var Kr=[];Vj(Kr,Fx,os,nf(os)),Pj(mR,Kr)}}function xR(os,Kr,Xr){os==="focusin"?(Wj(),qx=Kr,Fx=Xr,qx.attachEvent("onpropertychange",Xj)):os==="focusout"&&Wj()}function hR(os){if(os==="selectionchange"||os==="keyup"||os==="keydown")return Fh(Fx)}function pR(os,Kr){if(os==="click")return Fh(Kr)}function fR(os,Kr){if(os==="input"||os==="change")return Fh(Kr)}function gR(os,Kr){return os===Kr&&(os!==0||1/os===1/Kr)||os!==os&&Kr!==Kr}var bc=typeof Object.is=="function"?Object.is:gR;function zx(os,Kr){if(bc(os,Kr))return!0;if(typeof os!="object"||os===null||typeof Kr!="object"||Kr===null)return!1;var Xr=Object.keys(os),Ca=Object.keys(Kr);if(Xr.length!==Ca.length)return!1;for(Ca=0;Ca<Xr.length;Ca++){var Pa=Xr[Ca];if(!Bl.call(Kr,Pa)||!bc(os[Pa],Kr[Pa]))return!1}return!0}function ev(os){for(;os&&os.firstChild;)os=os.firstChild;return os}function tv(os,Kr){var Xr=ev(os);os=0;for(var Ca;Xr;){if(Xr.nodeType===3){if(Ca=os+Xr.textContent.length,os<=Kr&&Ca>=Kr)return{node:Xr,offset:Kr-os};os=Ca}e:{for(;Xr;){if(Xr.nextSibling){Xr=Xr.nextSibling;break e}Xr=Xr.parentNode}Xr=void 0}Xr=ev(Xr)}}function sv(os,Kr){return os&&Kr?os===Kr?!0:os&&os.nodeType===3?!1:Kr&&Kr.nodeType===3?sv(os,Kr.parentNode):"contains"in os?os.contains(Kr):os.compareDocumentPosition?!!(os.compareDocumentPosition(Kr)&16):!1:!1}function nv(os){os=os!=null&&os.ownerDocument!=null&&os.ownerDocument.defaultView!=null?os.ownerDocument.defaultView:window;for(var Kr=$h(os.document);Kr instanceof os.HTMLIFrameElement;){try{var Xr=typeof Kr.contentWindow.location.href=="string"}catch{Xr=!1}if(Xr)os=Kr.contentWindow;else break;Kr=$h(os.document)}return Kr}function pf(os){var Kr=os&&os.nodeName&&os.nodeName.toLowerCase();return Kr&&(Kr==="input"&&(os.type==="text"||os.type==="search"||os.type==="tel"||os.type==="url"||os.type==="password")||Kr==="textarea"||os.contentEditable==="true")}var jR=id&&"documentMode"in document&&11>=document.documentMode,Km=null,ff=null,Hx=null,gf=!1;function rv(os,Kr,Xr){var Ca=Xr.window===Xr?Xr.document:Xr.nodeType===9?Xr:Xr.ownerDocument;gf||Km==null||Km!==$h(Ca)||(Ca=Km,"selectionStart"in Ca&&pf(Ca)?Ca={start:Ca.selectionStart,end:Ca.selectionEnd}:(Ca=(Ca.ownerDocument&&Ca.ownerDocument.defaultView||window).getSelection(),Ca={anchorNode:Ca.anchorNode,anchorOffset:Ca.anchorOffset,focusNode:Ca.focusNode,focusOffset:Ca.focusOffset}),Hx&&zx(Hx,Ca)||(Hx=Ca,Ca=Ap(ff,"onSelect"),0<Ca.length&&(Kr=new Uh("onSelect","select",null,Kr,Xr),os.push({event:Kr,listeners:Ca}),Kr.target=Km)))}function cm(os,Kr){var Xr={};return Xr[os.toLowerCase()]=Kr.toLowerCase(),Xr["Webkit"+os]="webkit"+Kr,Xr["Moz"+os]="moz"+Kr,Xr}var Gm={animationend:cm("Animation","AnimationEnd"),animationiteration:cm("Animation","AnimationIteration"),animationstart:cm("Animation","AnimationStart"),transitionrun:cm("Transition","TransitionRun"),transitionstart:cm("Transition","TransitionStart"),transitioncancel:cm("Transition","TransitionCancel"),transitionend:cm("Transition","TransitionEnd")},jf={},iv={};id&&(iv=document.createElement("div").style,"AnimationEvent"in window||(delete Gm.animationend.animation,delete Gm.animationiteration.animation,delete Gm.animationstart.animation),"TransitionEvent"in window||delete Gm.transitionend.transition);function dm(os){if(jf[os])return jf[os];if(!Gm[os])return os;var Kr=Gm[os],Xr;for(Xr in Kr)if(Kr.hasOwnProperty(Xr)&&Xr in iv)return jf[os]=Kr[Xr];return os}var av=dm("animationend"),ov=dm("animationiteration"),lv=dm("animationstart"),vR=dm("transitionrun"),yR=dm("transitionstart"),ER=dm("transitioncancel"),uv=dm("transitionend"),cv=new Map,vf="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");vf.push("scrollEnd");function zc(os,Kr){cv.set(os,Kr),lm(Kr,[os])}var zh=typeof reportError=="function"?reportError:function(os){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var Kr=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof os=="object"&&os!==null&&typeof os.message=="string"?String(os.message):String(os),error:os});if(!window.dispatchEvent(Kr))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",os);return}console.error(os)},Oc=[],Zm=0,yf=0;function Hh(){for(var os=Zm,Kr=yf=Zm=0;Kr<os;){var Xr=Oc[Kr];Oc[Kr++]=null;var Ca=Oc[Kr];Oc[Kr++]=null;var Pa=Oc[Kr];Oc[Kr++]=null;var Da=Oc[Kr];if(Oc[Kr++]=null,Ca!==null&&Pa!==null){var za=Ca.pending;za===null?Pa.next=Pa:(Pa.next=za.next,za.next=Pa),Ca.pending=Pa}Da!==0&&dv(Xr,Pa,Da)}}function Kh(os,Kr,Xr,Ca){Oc[Zm++]=os,Oc[Zm++]=Kr,Oc[Zm++]=Xr,Oc[Zm++]=Ca,yf|=Ca,os.lanes|=Ca,os=os.alternate,os!==null&&(os.lanes|=Ca)}function Ef(os,Kr,Xr,Ca){return Kh(os,Kr,Xr,Ca),Gh(os)}function mm(os,Kr){return Kh(os,null,null,Kr),Gh(os)}function dv(os,Kr,Xr){os.lanes|=Xr;var Ca=os.alternate;Ca!==null&&(Ca.lanes|=Xr);for(var Pa=!1,Da=os.return;Da!==null;)Da.childLanes|=Xr,Ca=Da.alternate,Ca!==null&&(Ca.childLanes|=Xr),Da.tag===22&&(os=Da.stateNode,os===null||os._visibility&1||(Pa=!0)),os=Da,Da=Da.return;return os.tag===3?(Da=os.stateNode,Pa&&Kr!==null&&(Pa=31-Rl(Xr),os=Da.hiddenUpdates,Ca=os[Pa],Ca===null?os[Pa]=[Kr]:Ca.push(Kr),Kr.lane=Xr|536870912),Da):null}function Gh(os){if(50<mh)throw mh=0,kg=null,Error(is(185));for(var Kr=os.return;Kr!==null;)os=Kr,Kr=os.return;return os.tag===3?os.stateNode:null}var Vm={};function bR(os,Kr,Xr,Ca){this.tag=os,this.key=Xr,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=Kr,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=Ca,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Rc(os,Kr,Xr,Ca){return new bR(os,Kr,Xr,Ca)}function bf(os){return os=os.prototype,!(!os||!os.isReactComponent)}function ad(os,Kr){var Xr=os.alternate;return Xr===null?(Xr=Rc(os.tag,Kr,os.key,os.mode),Xr.elementType=os.elementType,Xr.type=os.type,Xr.stateNode=os.stateNode,Xr.alternate=os,os.alternate=Xr):(Xr.pendingProps=Kr,Xr.type=os.type,Xr.flags=0,Xr.subtreeFlags=0,Xr.deletions=null),Xr.flags=os.flags&65011712,Xr.childLanes=os.childLanes,Xr.lanes=os.lanes,Xr.child=os.child,Xr.memoizedProps=os.memoizedProps,Xr.memoizedState=os.memoizedState,Xr.updateQueue=os.updateQueue,Kr=os.dependencies,Xr.dependencies=Kr===null?null:{lanes:Kr.lanes,firstContext:Kr.firstContext},Xr.sibling=os.sibling,Xr.index=os.index,Xr.ref=os.ref,Xr.refCleanup=os.refCleanup,Xr}function mv(os,Kr){os.flags&=65011714;var Xr=os.alternate;return Xr===null?(os.childLanes=0,os.lanes=Kr,os.child=null,os.subtreeFlags=0,os.memoizedProps=null,os.memoizedState=null,os.updateQueue=null,os.dependencies=null,os.stateNode=null):(os.childLanes=Xr.childLanes,os.lanes=Xr.lanes,os.child=Xr.child,os.subtreeFlags=0,os.deletions=null,os.memoizedProps=Xr.memoizedProps,os.memoizedState=Xr.memoizedState,os.updateQueue=Xr.updateQueue,os.type=Xr.type,Kr=Xr.dependencies,os.dependencies=Kr===null?null:{lanes:Kr.lanes,firstContext:Kr.firstContext}),os}function Zh(os,Kr,Xr,Ca,Pa,Da){var za=0;if(Ca=os,typeof os=="function")bf(os)&&(za=1);else if(typeof os=="string")za=S0(os,Xr,Fl.current)?26:os==="html"||os==="head"||os==="body"?27:5;else e:switch(os){case cl:return os=Rc(31,Xr,Kr,Pa),os.elementType=cl,os.lanes=Da,os;case Fa:return xm(Xr.children,Pa,Da,Kr);case Ha:za=8,Pa|=24;break;case Ka:return os=Rc(12,Xr,Kr,Pa|2),os.elementType=Ka,os.lanes=Da,os;case Ya:return os=Rc(13,Xr,Kr,Pa),os.elementType=Ya,os.lanes=Da,os;case el:return os=Rc(19,Xr,Kr,Pa),os.elementType=el,os.lanes=Da,os;default:if(typeof os=="object"&&os!==null)switch(os.$$typeof){case Va:za=10;break e;case Ga:za=9;break e;case Ja:za=11;break e;case tl:za=14;break e;case rl:za=16,Ca=null;break e}za=29,Xr=Error(is(130,os===null?"null":typeof os,"")),Ca=null}return Kr=Rc(za,Xr,Kr,Pa),Kr.elementType=os,Kr.type=Ca,Kr.lanes=Da,Kr}function xm(os,Kr,Xr,Ca){return os=Rc(7,os,Ca,Kr),os.lanes=Xr,os}function Rf(os,Kr,Xr){return os=Rc(6,os,null,Kr),os.lanes=Xr,os}function xv(os){var Kr=Rc(18,null,null,0);return Kr.stateNode=os,Kr}function _f(os,Kr,Xr){return Kr=Rc(4,os.children!==null?os.children:[],os.key,Kr),Kr.lanes=Xr,Kr.stateNode={containerInfo:os.containerInfo,pendingChildren:null,implementation:os.implementation},Kr}var hv=new WeakMap;function Ic(os,Kr){if(typeof os=="object"&&os!==null){var Xr=hv.get(os);return Xr!==void 0?Xr:(Kr={value:os,source:Kr,stack:Iu(Kr)},hv.set(os,Kr),Kr)}return{value:os,source:Kr,stack:Iu(Kr)}}var Qm=[],Ym=0,Vh=null,Kx=0,Lc=[],$c=0,Td=null,Yc=1,Jc="";function od(os,Kr){Qm[Ym++]=Kx,Qm[Ym++]=Vh,Vh=os,Kx=Kr}function pv(os,Kr,Xr){Lc[$c++]=Yc,Lc[$c++]=Jc,Lc[$c++]=Td,Td=os;var Ca=Yc;os=Jc;var Pa=32-Rl(Ca)-1;Ca&=~(1<<Pa),Xr+=1;var Da=32-Rl(Kr)+Pa;if(30<Da){var za=Pa-Pa%5;Da=(Ca&(1<<za)-1).toString(32),Ca>>=za,Pa-=za,Yc=1<<32-Rl(Kr)+Pa|Xr<<Pa|Ca,Jc=Da+os}else Yc=1<<Da|Xr<<Pa|Ca,Jc=os}function wf(os){os.return!==null&&(od(os,1),pv(os,1,0))}function Nf(os){for(;os===Vh;)Vh=Qm[--Ym],Qm[Ym]=null,Kx=Qm[--Ym],Qm[Ym]=null;for(;os===Td;)Td=Lc[--$c],Lc[$c]=null,Jc=Lc[--$c],Lc[$c]=null,Yc=Lc[--$c],Lc[$c]=null}function fv(os,Kr){Lc[$c++]=Yc,Lc[$c++]=Jc,Lc[$c++]=Td,Yc=Kr.id,Jc=Kr.overflow,Td=os}var ec=null,$u=null,hu=!1,kd=null,Pc=!1,Sf=Error(is(519));function Ad(os){var Kr=Error(is(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw Gx(Ic(Kr,os)),Sf}function gv(os){var Kr=os.stateNode,Xr=os.type,Ca=os.memoizedProps;switch(Kr[Xu]=os,Kr[xc]=Ca,Xr){case"dialog":uu("cancel",Kr),uu("close",Kr);break;case"iframe":case"object":case"embed":uu("load",Kr);break;case"video":case"audio":for(Xr=0;Xr<hh.length;Xr++)uu(hh[Xr],Kr);break;case"source":uu("error",Kr);break;case"img":case"image":case"link":uu("error",Kr),uu("load",Kr);break;case"details":uu("toggle",Kr);break;case"input":uu("invalid",Kr),kj(Kr,Ca.value,Ca.defaultValue,Ca.checked,Ca.defaultChecked,Ca.type,Ca.name,!0);break;case"select":uu("invalid",Kr);break;case"textarea":uu("invalid",Kr),Oj(Kr,Ca.value,Ca.defaultValue,Ca.children)}Xr=Ca.children,typeof Xr!="string"&&typeof Xr!="number"&&typeof Xr!="bigint"||Kr.textContent===""+Xr||Ca.suppressHydrationWarning===!0||LE(Kr.textContent,Xr)?(Ca.popover!=null&&(uu("beforetoggle",Kr),uu("toggle",Kr)),Ca.onScroll!=null&&uu("scroll",Kr),Ca.onScrollEnd!=null&&uu("scrollend",Kr),Ca.onClick!=null&&(Kr.onclick=rd),Kr=!0):Kr=!1,Kr||Ad(os,!0)}function jv(os){for(ec=os.return;ec;)switch(ec.tag){case 5:case 31:case 13:Pc=!1;return;case 27:case 3:Pc=!0;return;default:ec=ec.return}}function Jm(os){if(os!==ec)return!1;if(!hu)return jv(os),hu=!0,!1;var Kr=os.tag,Xr;if((Xr=Kr!==3&&Kr!==27)&&((Xr=Kr===5)&&(Xr=os.type,Xr=!(Xr!=="form"&&Xr!=="button")||Kg(os.type,os.memoizedProps)),Xr=!Xr),Xr&&$u&&Ad(os),jv(os),Kr===13){if(os=os.memoizedState,os=os!==null?os.dehydrated:null,!os)throw Error(is(317));$u=zE(os)}else if(Kr===31){if(os=os.memoizedState,os=os!==null?os.dehydrated:null,!os)throw Error(is(317));$u=zE(os)}else Kr===27?(Kr=$u,Kd(os.type)?(os=Yg,Yg=null,$u=os):$u=Kr):$u=ec?Mc(os.stateNode.nextSibling):null;return!0}function hm(){$u=ec=null,hu=!1}function Cf(){var os=kd;return os!==null&&(jc===null?jc=os:jc.push.apply(jc,os),kd=null),os}function Gx(os){kd===null?kd=[os]:kd.push(os)}var Tf=Zl(null),pm=null,ld=null;function Od(os,Kr,Xr){Il(Tf,Kr._currentValue),Kr._currentValue=Xr}function ud(os){os._currentValue=Tf.current,Dl(Tf)}function kf(os,Kr,Xr){for(;os!==null;){var Ca=os.alternate;if((os.childLanes&Kr)!==Kr?(os.childLanes|=Kr,Ca!==null&&(Ca.childLanes|=Kr)):Ca!==null&&(Ca.childLanes&Kr)!==Kr&&(Ca.childLanes|=Kr),os===Xr)break;os=os.return}}function Af(os,Kr,Xr,Ca){var Pa=os.child;for(Pa!==null&&(Pa.return=os);Pa!==null;){var Da=Pa.dependencies;if(Da!==null){var za=Pa.child;Da=Da.firstContext;e:for(;Da!==null;){var Qa=Da;Da=Pa;for(var Xa=0;Xa<Kr.length;Xa++)if(Qa.context===Kr[Xa]){Da.lanes|=Xr,Qa=Da.alternate,Qa!==null&&(Qa.lanes|=Xr),kf(Da.return,Xr,os),Ca||(za=null);break e}Da=Qa.next}}else if(Pa.tag===18){if(za=Pa.return,za===null)throw Error(is(341));za.lanes|=Xr,Da=za.alternate,Da!==null&&(Da.lanes|=Xr),kf(za,Xr,os),za=null}else za=Pa.child;if(za!==null)za.return=Pa;else for(za=Pa;za!==null;){if(za===os){za=null;break}if(Pa=za.sibling,Pa!==null){Pa.return=za.return,za=Pa;break}za=za.return}Pa=za}}function Wm(os,Kr,Xr,Ca){os=null;for(var Pa=Kr,Da=!1;Pa!==null;){if(!Da){if((Pa.flags&524288)!==0)Da=!0;else if((Pa.flags&262144)!==0)break}if(Pa.tag===10){var za=Pa.alternate;if(za===null)throw Error(is(387));if(za=za.memoizedProps,za!==null){var Qa=Pa.type;bc(Pa.pendingProps.value,za.value)||(os!==null?os.push(Qa):os=[Qa])}}else if(Pa===Gl.current){if(za=Pa.alternate,za===null)throw Error(is(387));za.memoizedState.memoizedState!==Pa.memoizedState.memoizedState&&(os!==null?os.push(vh):os=[vh])}Pa=Pa.return}os!==null&&Af(Kr,os,Xr,Ca),Kr.flags|=262144}function Qh(os){for(os=os.firstContext;os!==null;){if(!bc(os.context._currentValue,os.memoizedValue))return!0;os=os.next}return!1}function fm(os){pm=os,ld=null,os=os.dependencies,os!==null&&(os.firstContext=null)}function tc(os){return vv(pm,os)}function Yh(os,Kr){return pm===null&&fm(os),vv(os,Kr)}function vv(os,Kr){var Xr=Kr._currentValue;if(Kr={context:Kr,memoizedValue:Xr,next:null},ld===null){if(os===null)throw Error(is(308));ld=Kr,os.dependencies={lanes:0,firstContext:Kr},os.flags|=524288}else ld=ld.next=Kr;return Xr}var RR=typeof AbortController<"u"?AbortController:function(){var os=[],Kr=this.signal={aborted:!1,addEventListener:function(Xr,Ca){os.push(Ca)}};this.abort=function(){Kr.aborted=!0,os.forEach(function(Xr){return Xr()})}},_R=es.unstable_scheduleCallback,wR=es.unstable_NormalPriority,Hu={$$typeof:Va,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Of(){return{controller:new RR,data:new Map,refCount:0}}function Zx(os){os.refCount--,os.refCount===0&&_R(wR,function(){os.controller.abort()})}var Vx=null,If=0,Xm=0,ex=null;function NR(os,Kr){if(Vx===null){var Xr=Vx=[];If=0,Xm=Pg(),ex={status:"pending",value:void 0,then:function(Ca){Xr.push(Ca)}}}return If++,Kr.then(yv,yv),Kr}function yv(){if(--If===0&&Vx!==null){ex!==null&&(ex.status="fulfilled");var os=Vx;Vx=null,Xm=0,ex=null;for(var Kr=0;Kr<os.length;Kr++)(0,os[Kr])()}}function SR(os,Kr){var Xr=[],Ca={status:"pending",value:null,reason:null,then:function(Pa){Xr.push(Pa)}};return os.then(function(){Ca.status="fulfilled",Ca.value=Kr;for(var Pa=0;Pa<Xr.length;Pa++)(0,Xr[Pa])(Kr)},function(Pa){for(Ca.status="rejected",Ca.reason=Pa,Pa=0;Pa<Xr.length;Pa++)(0,Xr[Pa])(void 0)}),Ca}var Ev=ul.S;ul.S=function(os,Kr){rE=Eu(),typeof Kr=="object"&&Kr!==null&&typeof Kr.then=="function"&&NR(os,Kr),Ev!==null&&Ev(os,Kr)};var gm=Zl(null);function Lf(){var os=gm.current;return os!==null?os:Au.pooledCache}function Jh(os,Kr){Kr===null?Il(gm,gm.current):Il(gm,Kr.pool)}function bv(){var os=Lf();return os===null?null:{parent:Hu._currentValue,pool:os}}var tx=Error(is(460)),$f=Error(is(474)),Wh=Error(is(542)),Xh={then:function(){}};function Rv(os){return os=os.status,os==="fulfilled"||os==="rejected"}function _v(os,Kr,Xr){switch(Xr=os[Xr],Xr===void 0?os.push(Kr):Xr!==Kr&&(Kr.then(rd,rd),Kr=Xr),Kr.status){case"fulfilled":return Kr.value;case"rejected":throw os=Kr.reason,Nv(os),os;default:if(typeof Kr.status=="string")Kr.then(rd,rd);else{if(os=Au,os!==null&&100<os.shellSuspendCounter)throw Error(is(482));os=Kr,os.status="pending",os.then(function(Ca){if(Kr.status==="pending"){var Pa=Kr;Pa.status="fulfilled",Pa.value=Ca}},function(Ca){if(Kr.status==="pending"){var Pa=Kr;Pa.status="rejected",Pa.reason=Ca}})}switch(Kr.status){case"fulfilled":return Kr.value;case"rejected":throw os=Kr.reason,Nv(os),os}throw vm=Kr,tx}}function jm(os){try{var Kr=os._init;return Kr(os._payload)}catch(Xr){throw Xr!==null&&typeof Xr=="object"&&typeof Xr.then=="function"?(vm=Xr,tx):Xr}}var vm=null;function wv(){if(vm===null)throw Error(is(459));var os=vm;return vm=null,os}function Nv(os){if(os===tx||os===Wh)throw Error(is(483))}var sx=null,Qx=0;function ep(os){var Kr=Qx;return Qx+=1,sx===null&&(sx=[]),_v(sx,os,Kr)}function Yx(os,Kr){Kr=Kr.props.ref,os.ref=Kr!==void 0?Kr:null}function tp(os,Kr){throw Kr.$$typeof===Ba?Error(is(525)):(os=Object.prototype.toString.call(Kr),Error(is(31,os==="[object Object]"?"object with keys {"+Object.keys(Kr).join(", ")+"}":os)))}function Sv(os){function Kr(il,sl){if(os){var ml=il.deletions;ml===null?(il.deletions=[sl],il.flags|=16):ml.push(sl)}}function Xr(il,sl){if(!os)return null;for(;sl!==null;)Kr(il,sl),sl=sl.sibling;return null}function Ca(il){for(var sl=new Map;il!==null;)il.key!==null?sl.set(il.key,il):sl.set(il.index,il),il=il.sibling;return sl}function Pa(il,sl){return il=ad(il,sl),il.index=0,il.sibling=null,il}function Da(il,sl,ml){return il.index=ml,os?(ml=il.alternate,ml!==null?(ml=ml.index,ml<sl?(il.flags|=67108866,sl):ml):(il.flags|=67108866,sl)):(il.flags|=1048576,sl)}function za(il){return os&&il.alternate===null&&(il.flags|=67108866),il}function Qa(il,sl,ml,Sl){return sl===null||sl.tag!==6?(sl=Rf(ml,il.mode,Sl),sl.return=il,sl):(sl=Pa(sl,ml),sl.return=il,sl)}function Xa(il,sl,ml,Sl){var Jl=ml.type;return Jl===Fa?wl(il,sl,ml.props.children,Sl,ml.key):sl!==null&&(sl.elementType===Jl||typeof Jl=="object"&&Jl!==null&&Jl.$$typeof===rl&&jm(Jl)===sl.type)?(sl=Pa(sl,ml.props),Yx(sl,ml),sl.return=il,sl):(sl=Zh(ml.type,ml.key,ml.props,null,il.mode,Sl),Yx(sl,ml),sl.return=il,sl)}function xl(il,sl,ml,Sl){return sl===null||sl.tag!==4||sl.stateNode.containerInfo!==ml.containerInfo||sl.stateNode.implementation!==ml.implementation?(sl=_f(ml,il.mode,Sl),sl.return=il,sl):(sl=Pa(sl,ml.children||[]),sl.return=il,sl)}function wl(il,sl,ml,Sl,Jl){return sl===null||sl.tag!==7?(sl=xm(ml,il.mode,Sl,Jl),sl.return=il,sl):(sl=Pa(sl,ml),sl.return=il,sl)}function Cl(il,sl,ml){if(typeof sl=="string"&&sl!==""||typeof sl=="number"||typeof sl=="bigint")return sl=Rf(""+sl,il.mode,ml),sl.return=il,sl;if(typeof sl=="object"&&sl!==null){switch(sl.$$typeof){case Ma:return ml=Zh(sl.type,sl.key,sl.props,null,il.mode,ml),Yx(ml,sl),ml.return=il,ml;case qa:return sl=_f(sl,il.mode,ml),sl.return=il,sl;case rl:return sl=jm(sl),Cl(il,sl,ml)}if(Tl(sl)||nl(sl))return sl=xm(sl,il.mode,ml,null),sl.return=il,sl;if(typeof sl.then=="function")return Cl(il,ep(sl),ml);if(sl.$$typeof===Va)return Cl(il,Yh(il,sl),ml);tp(il,sl)}return null}function gl(il,sl,ml,Sl){var Jl=sl!==null?sl.key:null;if(typeof ml=="string"&&ml!==""||typeof ml=="number"||typeof ml=="bigint")return Jl!==null?null:Qa(il,sl,""+ml,Sl);if(typeof ml=="object"&&ml!==null){switch(ml.$$typeof){case Ma:return ml.key===Jl?Xa(il,sl,ml,Sl):null;case qa:return ml.key===Jl?xl(il,sl,ml,Sl):null;case rl:return ml=jm(ml),gl(il,sl,ml,Sl)}if(Tl(ml)||nl(ml))return Jl!==null?null:wl(il,sl,ml,Sl,null);if(typeof ml.then=="function")return gl(il,sl,ep(ml),Sl);if(ml.$$typeof===Va)return gl(il,sl,Yh(il,ml),Sl);tp(il,ml)}return null}function vl(il,sl,ml,Sl,Jl){if(typeof Sl=="string"&&Sl!==""||typeof Sl=="number"||typeof Sl=="bigint")return il=il.get(ml)||null,Qa(sl,il,""+Sl,Jl);if(typeof Sl=="object"&&Sl!==null){switch(Sl.$$typeof){case Ma:return il=il.get(Sl.key===null?ml:Sl.key)||null,Xa(sl,il,Sl,Jl);case qa:return il=il.get(Sl.key===null?ml:Sl.key)||null,xl(sl,il,Sl,Jl);case rl:return Sl=jm(Sl),vl(il,sl,ml,Sl,Jl)}if(Tl(Sl)||nl(Sl))return il=il.get(ml)||null,wl(sl,il,Sl,Jl,null);if(typeof Sl.then=="function")return vl(il,sl,ml,ep(Sl),Jl);if(Sl.$$typeof===Va)return vl(il,sl,ml,Yh(sl,Sl),Jl);tp(sl,Sl)}return null}function Kl(il,sl,ml,Sl){for(var Jl=null,gu=null,Vl=sl,ou=sl=0,mu=null;Vl!==null&&ou<ml.length;ou++){Vl.index>ou?(mu=Vl,Vl=null):mu=Vl.sibling;var ju=gl(il,Vl,ml[ou],Sl);if(ju===null){Vl===null&&(Vl=mu);break}os&&Vl&&ju.alternate===null&&Kr(il,Vl),sl=Da(ju,sl,ou),gu===null?Jl=ju:gu.sibling=ju,gu=ju,Vl=mu}if(ou===ml.length)return Xr(il,Vl),hu&&od(il,ou),Jl;if(Vl===null){for(;ou<ml.length;ou++)Vl=Cl(il,ml[ou],Sl),Vl!==null&&(sl=Da(Vl,sl,ou),gu===null?Jl=Vl:gu.sibling=Vl,gu=Vl);return hu&&od(il,ou),Jl}for(Vl=Ca(Vl);ou<ml.length;ou++)mu=vl(Vl,il,ou,ml[ou],Sl),mu!==null&&(os&&mu.alternate!==null&&Vl.delete(mu.key===null?ou:mu.key),sl=Da(mu,sl,ou),gu===null?Jl=mu:gu.sibling=mu,gu=mu);return os&&Vl.forEach(function(Yd){return Kr(il,Yd)}),hu&&od(il,ou),Jl}function Wl(il,sl,ml,Sl){if(ml==null)throw Error(is(151));for(var Jl=null,gu=null,Vl=sl,ou=sl=0,mu=null,ju=ml.next();Vl!==null&&!ju.done;ou++,ju=ml.next()){Vl.index>ou?(mu=Vl,Vl=null):mu=Vl.sibling;var Yd=gl(il,Vl,ju.value,Sl);if(Yd===null){Vl===null&&(Vl=mu);break}os&&Vl&&Yd.alternate===null&&Kr(il,Vl),sl=Da(Yd,sl,ou),gu===null?Jl=Yd:gu.sibling=Yd,gu=Yd,Vl=mu}if(ju.done)return Xr(il,Vl),hu&&od(il,ou),Jl;if(Vl===null){for(;!ju.done;ou++,ju=ml.next())ju=Cl(il,ju.value,Sl),ju!==null&&(sl=Da(ju,sl,ou),gu===null?Jl=ju:gu.sibling=ju,gu=ju);return hu&&od(il,ou),Jl}for(Vl=Ca(Vl);!ju.done;ou++,ju=ml.next())ju=vl(Vl,il,ou,ju.value,Sl),ju!==null&&(os&&ju.alternate!==null&&Vl.delete(ju.key===null?ou:ju.key),sl=Da(ju,sl,ou),gu===null?Jl=ju:gu.sibling=ju,gu=ju);return os&&Vl.forEach(function(M0){return Kr(il,M0)}),hu&&od(il,ou),Jl}function Cu(il,sl,ml,Sl){if(typeof ml=="object"&&ml!==null&&ml.type===Fa&&ml.key===null&&(ml=ml.props.children),typeof ml=="object"&&ml!==null){switch(ml.$$typeof){case Ma:e:{for(var Jl=ml.key;sl!==null;){if(sl.key===Jl){if(Jl=ml.type,Jl===Fa){if(sl.tag===7){Xr(il,sl.sibling),Sl=Pa(sl,ml.props.children),Sl.return=il,il=Sl;break e}}else if(sl.elementType===Jl||typeof Jl=="object"&&Jl!==null&&Jl.$$typeof===rl&&jm(Jl)===sl.type){Xr(il,sl.sibling),Sl=Pa(sl,ml.props),Yx(Sl,ml),Sl.return=il,il=Sl;break e}Xr(il,sl);break}else Kr(il,sl);sl=sl.sibling}ml.type===Fa?(Sl=xm(ml.props.children,il.mode,Sl,ml.key),Sl.return=il,il=Sl):(Sl=Zh(ml.type,ml.key,ml.props,null,il.mode,Sl),Yx(Sl,ml),Sl.return=il,il=Sl)}return za(il);case qa:e:{for(Jl=ml.key;sl!==null;){if(sl.key===Jl)if(sl.tag===4&&sl.stateNode.containerInfo===ml.containerInfo&&sl.stateNode.implementation===ml.implementation){Xr(il,sl.sibling),Sl=Pa(sl,ml.children||[]),Sl.return=il,il=Sl;break e}else{Xr(il,sl);break}else Kr(il,sl);sl=sl.sibling}Sl=_f(ml,il.mode,Sl),Sl.return=il,il=Sl}return za(il);case rl:return ml=jm(ml),Cu(il,sl,ml,Sl)}if(Tl(ml))return Kl(il,sl,ml,Sl);if(nl(ml)){if(Jl=nl(ml),typeof Jl!="function")throw Error(is(150));return ml=Jl.call(ml),Wl(il,sl,ml,Sl)}if(typeof ml.then=="function")return Cu(il,sl,ep(ml),Sl);if(ml.$$typeof===Va)return Cu(il,sl,Yh(il,ml),Sl);tp(il,ml)}return typeof ml=="string"&&ml!==""||typeof ml=="number"||typeof ml=="bigint"?(ml=""+ml,sl!==null&&sl.tag===6?(Xr(il,sl.sibling),Sl=Pa(sl,ml),Sl.return=il,il=Sl):(Xr(il,sl),Sl=Rf(ml,il.mode,Sl),Sl.return=il,il=Sl),za(il)):Xr(il,sl)}return function(il,sl,ml,Sl){try{Qx=0;var Jl=Cu(il,sl,ml,Sl);return sx=null,Jl}catch(Vl){if(Vl===tx||Vl===Wh)throw Vl;var gu=Rc(29,Vl,null,il.mode);return gu.lanes=Sl,gu.return=il,gu}finally{}}}var ym=Sv(!0),Cv=Sv(!1),Id=!1;function Pf(os){os.updateQueue={baseState:os.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Df(os,Kr){os=os.updateQueue,Kr.updateQueue===os&&(Kr.updateQueue={baseState:os.baseState,firstBaseUpdate:os.firstBaseUpdate,lastBaseUpdate:os.lastBaseUpdate,shared:os.shared,callbacks:null})}function Ld(os){return{lane:os,tag:0,payload:null,callback:null,next:null}}function $d(os,Kr,Xr){var Ca=os.updateQueue;if(Ca===null)return null;if(Ca=Ca.shared,(vu&2)!==0){var Pa=Ca.pending;return Pa===null?Kr.next=Kr:(Kr.next=Pa.next,Pa.next=Kr),Ca.pending=Kr,Kr=Gh(os),dv(os,null,Xr),Kr}return Kh(os,Ca,Kr,Xr),Gh(os)}function Jx(os,Kr,Xr){if(Kr=Kr.updateQueue,Kr!==null&&(Kr=Kr.shared,(Xr&4194048)!==0)){var Ca=Kr.lanes;Ca&=os.pendingLanes,Xr|=Ca,Kr.lanes=Xr,mc(os,Xr)}}function Mf(os,Kr){var Xr=os.updateQueue,Ca=os.alternate;if(Ca!==null&&(Ca=Ca.updateQueue,Xr===Ca)){var Pa=null,Da=null;if(Xr=Xr.firstBaseUpdate,Xr!==null){do{var za={lane:Xr.lane,tag:Xr.tag,payload:Xr.payload,callback:null,next:null};Da===null?Pa=Da=za:Da=Da.next=za,Xr=Xr.next}while(Xr!==null);Da===null?Pa=Da=Kr:Da=Da.next=Kr}else Pa=Da=Kr;Xr={baseState:Ca.baseState,firstBaseUpdate:Pa,lastBaseUpdate:Da,shared:Ca.shared,callbacks:Ca.callbacks},os.updateQueue=Xr;return}os=Xr.lastBaseUpdate,os===null?Xr.firstBaseUpdate=Kr:os.next=Kr,Xr.lastBaseUpdate=Kr}var Bf=!1;function Wx(){if(Bf){var os=ex;if(os!==null)throw os}}function Xx(os,Kr,Xr,Ca){Bf=!1;var Pa=os.updateQueue;Id=!1;var Da=Pa.firstBaseUpdate,za=Pa.lastBaseUpdate,Qa=Pa.shared.pending;if(Qa!==null){Pa.shared.pending=null;var Xa=Qa,xl=Xa.next;Xa.next=null,za===null?Da=xl:za.next=xl,za=Xa;var wl=os.alternate;wl!==null&&(wl=wl.updateQueue,Qa=wl.lastBaseUpdate,Qa!==za&&(Qa===null?wl.firstBaseUpdate=xl:Qa.next=xl,wl.lastBaseUpdate=Xa))}if(Da!==null){var Cl=Pa.baseState;za=0,wl=xl=Xa=null,Qa=Da;do{var gl=Qa.lane&-536870913,vl=gl!==Qa.lane;if(vl?(du&gl)===gl:(Ca&gl)===gl){gl!==0&&gl===Xm&&(Bf=!0),wl!==null&&(wl=wl.next={lane:0,tag:Qa.tag,payload:Qa.payload,callback:null,next:null});e:{var Kl=os,Wl=Qa;gl=Kr;var Cu=Xr;switch(Wl.tag){case 1:if(Kl=Wl.payload,typeof Kl=="function"){Cl=Kl.call(Cu,Cl,gl);break e}Cl=Kl;break e;case 3:Kl.flags=Kl.flags&-65537|128;case 0:if(Kl=Wl.payload,gl=typeof Kl=="function"?Kl.call(Cu,Cl,gl):Kl,gl==null)break e;Cl=La({},Cl,gl);break e;case 2:Id=!0}}gl=Qa.callback,gl!==null&&(os.flags|=64,vl&&(os.flags|=8192),vl=Pa.callbacks,vl===null?Pa.callbacks=[gl]:vl.push(gl))}else vl={lane:gl,tag:Qa.tag,payload:Qa.payload,callback:Qa.callback,next:null},wl===null?(xl=wl=vl,Xa=Cl):wl=wl.next=vl,za|=gl;if(Qa=Qa.next,Qa===null){if(Qa=Pa.shared.pending,Qa===null)break;vl=Qa,Qa=vl.next,vl.next=null,Pa.lastBaseUpdate=vl,Pa.shared.pending=null}}while(!0);wl===null&&(Xa=Cl),Pa.baseState=Xa,Pa.firstBaseUpdate=xl,Pa.lastBaseUpdate=wl,Da===null&&(Pa.shared.lanes=0),Ud|=za,os.lanes=za,os.memoizedState=Cl}}function Tv(os,Kr){if(typeof os!="function")throw Error(is(191,os));os.call(Kr)}function kv(os,Kr){var Xr=os.callbacks;if(Xr!==null)for(os.callbacks=null,os=0;os<Xr.length;os++)Tv(Xr[os],Kr)}var nx=Zl(null),sp=Zl(0);function Av(os,Kr){os=jd,Il(sp,os),Il(nx,Kr),jd=os|Kr.baseLanes}function Uf(){Il(sp,jd),Il(nx,nx.current)}function qf(){jd=sp.current,Dl(nx),Dl(sp)}var _c=Zl(null),Dc=null;function Pd(os){var Kr=os.alternate;Il(Fu,Fu.current&1),Il(_c,os),Dc===null&&(Kr===null||nx.current!==null||Kr.memoizedState!==null)&&(Dc=os)}function Ff(os){Il(Fu,Fu.current),Il(_c,os),Dc===null&&(Dc=os)}function Ov(os){os.tag===22?(Il(Fu,Fu.current),Il(_c,os),Dc===null&&(Dc=os)):Dd()}function Dd(){Il(Fu,Fu.current),Il(_c,_c.current)}function wc(os){Dl(_c),Dc===os&&(Dc=null),Dl(Fu)}var Fu=Zl(0);function np(os){for(var Kr=os;Kr!==null;){if(Kr.tag===13){var Xr=Kr.memoizedState;if(Xr!==null&&(Xr=Xr.dehydrated,Xr===null||Vg(Xr)||Qg(Xr)))return Kr}else if(Kr.tag===19&&(Kr.memoizedProps.revealOrder==="forwards"||Kr.memoizedProps.revealOrder==="backwards"||Kr.memoizedProps.revealOrder==="unstable_legacy-backwards"||Kr.memoizedProps.revealOrder==="together")){if((Kr.flags&128)!==0)return Kr}else if(Kr.child!==null){Kr.child.return=Kr,Kr=Kr.child;continue}if(Kr===os)break;for(;Kr.sibling===null;){if(Kr.return===null||Kr.return===os)return null;Kr=Kr.return}Kr.sibling.return=Kr.return,Kr=Kr.sibling}return null}var cd=0,iu=null,Nu=null,Ku=null,rp=!1,rx=!1,Em=!1,ip=0,eh=0,ix=null,CR=0;function Bu(){throw Error(is(321))}function zf(os,Kr){if(Kr===null)return!1;for(var Xr=0;Xr<Kr.length&&Xr<os.length;Xr++)if(!bc(os[Xr],Kr[Xr]))return!1;return!0}function Hf(os,Kr,Xr,Ca,Pa,Da){return cd=Da,iu=Kr,Kr.memoizedState=null,Kr.updateQueue=null,Kr.lanes=0,ul.H=os===null||os.memoizedState===null?py:ig,Em=!1,Da=Xr(Ca,Pa),Em=!1,rx&&(Da=Lv(Kr,Xr,Ca,Pa)),Iv(os),Da}function Iv(os){ul.H=nh;var Kr=Nu!==null&&Nu.next!==null;if(cd=0,Ku=Nu=iu=null,rp=!1,eh=0,ix=null,Kr)throw Error(is(300));os===null||Gu||(os=os.dependencies,os!==null&&Qh(os)&&(Gu=!0))}function Lv(os,Kr,Xr,Ca){iu=os;var Pa=0;do{if(rx&&(ix=null),eh=0,rx=!1,25<=Pa)throw Error(is(301));if(Pa+=1,Ku=Nu=null,os.updateQueue!=null){var Da=os.updateQueue;Da.lastEffect=null,Da.events=null,Da.stores=null,Da.memoCache!=null&&(Da.memoCache.index=0)}ul.H=fy,Da=Kr(Xr,Ca)}while(rx);return Da}function TR(){var os=ul.H,Kr=os.useState()[0];return Kr=typeof Kr.then=="function"?th(Kr):Kr,os=os.useState()[0],(Nu!==null?Nu.memoizedState:null)!==os&&(iu.flags|=1024),Kr}function Kf(){var os=ip!==0;return ip=0,os}function Gf(os,Kr,Xr){Kr.updateQueue=os.updateQueue,Kr.flags&=-2053,os.lanes&=~Xr}function Zf(os){if(rp){for(os=os.memoizedState;os!==null;){var Kr=os.queue;Kr!==null&&(Kr.pending=null),os=os.next}rp=!1}cd=0,Ku=Nu=iu=null,rx=!1,eh=ip=0,ix=null}function cc(){var os={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Ku===null?iu.memoizedState=Ku=os:Ku=Ku.next=os,Ku}function zu(){if(Nu===null){var os=iu.alternate;os=os!==null?os.memoizedState:null}else os=Nu.next;var Kr=Ku===null?iu.memoizedState:Ku.next;if(Kr!==null)Ku=Kr,Nu=os;else{if(os===null)throw iu.alternate===null?Error(is(467)):Error(is(310));Nu=os,os={memoizedState:Nu.memoizedState,baseState:Nu.baseState,baseQueue:Nu.baseQueue,queue:Nu.queue,next:null},Ku===null?iu.memoizedState=Ku=os:Ku=Ku.next=os}return Ku}function ap(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function th(os){var Kr=eh;return eh+=1,ix===null&&(ix=[]),os=_v(ix,os,Kr),Kr=iu,(Ku===null?Kr.memoizedState:Ku.next)===null&&(Kr=Kr.alternate,ul.H=Kr===null||Kr.memoizedState===null?py:ig),os}function op(os){if(os!==null&&typeof os=="object"){if(typeof os.then=="function")return th(os);if(os.$$typeof===Va)return tc(os)}throw Error(is(438,String(os)))}function Vf(os){var Kr=null,Xr=iu.updateQueue;if(Xr!==null&&(Kr=Xr.memoCache),Kr==null){var Ca=iu.alternate;Ca!==null&&(Ca=Ca.updateQueue,Ca!==null&&(Ca=Ca.memoCache,Ca!=null&&(Kr={data:Ca.data.map(function(Pa){return Pa.slice()}),index:0})))}if(Kr==null&&(Kr={data:[],index:0}),Xr===null&&(Xr=ap(),iu.updateQueue=Xr),Xr.memoCache=Kr,Xr=Kr.data[Kr.index],Xr===void 0)for(Xr=Kr.data[Kr.index]=Array(os),Ca=0;Ca<os;Ca++)Xr[Ca]=dl;return Kr.index++,Xr}function dd(os,Kr){return typeof Kr=="function"?Kr(os):Kr}function lp(os){var Kr=zu();return Qf(Kr,Nu,os)}function Qf(os,Kr,Xr){var Ca=os.queue;if(Ca===null)throw Error(is(311));Ca.lastRenderedReducer=Xr;var Pa=os.baseQueue,Da=Ca.pending;if(Da!==null){if(Pa!==null){var za=Pa.next;Pa.next=Da.next,Da.next=za}Kr.baseQueue=Pa=Da,Ca.pending=null}if(Da=os.baseState,Pa===null)os.memoizedState=Da;else{Kr=Pa.next;var Qa=za=null,Xa=null,xl=Kr,wl=!1;do{var Cl=xl.lane&-536870913;if(Cl!==xl.lane?(du&Cl)===Cl:(cd&Cl)===Cl){var gl=xl.revertLane;if(gl===0)Xa!==null&&(Xa=Xa.next={lane:0,revertLane:0,gesture:null,action:xl.action,hasEagerState:xl.hasEagerState,eagerState:xl.eagerState,next:null}),Cl===Xm&&(wl=!0);else if((cd&gl)===gl){xl=xl.next,gl===Xm&&(wl=!0);continue}else Cl={lane:0,revertLane:xl.revertLane,gesture:null,action:xl.action,hasEagerState:xl.hasEagerState,eagerState:xl.eagerState,next:null},Xa===null?(Qa=Xa=Cl,za=Da):Xa=Xa.next=Cl,iu.lanes|=gl,Ud|=gl;Cl=xl.action,Em&&Xr(Da,Cl),Da=xl.hasEagerState?xl.eagerState:Xr(Da,Cl)}else gl={lane:Cl,revertLane:xl.revertLane,gesture:xl.gesture,action:xl.action,hasEagerState:xl.hasEagerState,eagerState:xl.eagerState,next:null},Xa===null?(Qa=Xa=gl,za=Da):Xa=Xa.next=gl,iu.lanes|=Cl,Ud|=Cl;xl=xl.next}while(xl!==null&&xl!==Kr);if(Xa===null?za=Da:Xa.next=Qa,!bc(Da,os.memoizedState)&&(Gu=!0,wl&&(Xr=ex,Xr!==null)))throw Xr;os.memoizedState=Da,os.baseState=za,os.baseQueue=Xa,Ca.lastRenderedState=Da}return Pa===null&&(Ca.lanes=0),[os.memoizedState,Ca.dispatch]}function Yf(os){var Kr=zu(),Xr=Kr.queue;if(Xr===null)throw Error(is(311));Xr.lastRenderedReducer=os;var Ca=Xr.dispatch,Pa=Xr.pending,Da=Kr.memoizedState;if(Pa!==null){Xr.pending=null;var za=Pa=Pa.next;do Da=os(Da,za.action),za=za.next;while(za!==Pa);bc(Da,Kr.memoizedState)||(Gu=!0),Kr.memoizedState=Da,Kr.baseQueue===null&&(Kr.baseState=Da),Xr.lastRenderedState=Da}return[Da,Ca]}function $v(os,Kr,Xr){var Ca=iu,Pa=zu(),Da=hu;if(Da){if(Xr===void 0)throw Error(is(407));Xr=Xr()}else Xr=Kr();var za=!bc((Nu||Pa).memoizedState,Xr);if(za&&(Pa.memoizedState=Xr,Gu=!0),Pa=Pa.queue,Xf(Mv.bind(null,Ca,Pa,os),[os]),Pa.getSnapshot!==Kr||za||Ku!==null&&Ku.memoizedState.tag&1){if(Ca.flags|=2048,ax(9,{destroy:void 0},Dv.bind(null,Ca,Pa,Xr,Kr),null),Au===null)throw Error(is(349));Da||(cd&127)!==0||Pv(Ca,Kr,Xr)}return Xr}function Pv(os,Kr,Xr){os.flags|=16384,os={getSnapshot:Kr,value:Xr},Kr=iu.updateQueue,Kr===null?(Kr=ap(),iu.updateQueue=Kr,Kr.stores=[os]):(Xr=Kr.stores,Xr===null?Kr.stores=[os]:Xr.push(os))}function Dv(os,Kr,Xr,Ca){Kr.value=Xr,Kr.getSnapshot=Ca,Bv(Kr)&&Uv(os)}function Mv(os,Kr,Xr){return Xr(function(){Bv(Kr)&&Uv(os)})}function Bv(os){var Kr=os.getSnapshot;os=os.value;try{var Xr=Kr();return!bc(os,Xr)}catch{return!0}}function Uv(os){var Kr=mm(os,2);Kr!==null&&vc(Kr,os,2)}function Jf(os){var Kr=cc();if(typeof os=="function"){var Xr=os;if(os=Xr(),Em){Ol(!0);try{Xr()}finally{Ol(!1)}}}return Kr.memoizedState=Kr.baseState=os,Kr.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:dd,lastRenderedState:os},Kr}function qv(os,Kr,Xr,Ca){return os.baseState=Xr,Qf(os,Nu,typeof Ca=="function"?Ca:dd)}function kR(os,Kr,Xr,Ca,Pa){if(dp(os))throw Error(is(485));if(os=Kr.action,os!==null){var Da={payload:Pa,action:os,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(za){Da.listeners.push(za)}};ul.T!==null?Xr(!0):Da.isTransition=!1,Ca(Da),Xr=Kr.pending,Xr===null?(Da.next=Kr.pending=Da,Fv(Kr,Da)):(Da.next=Xr.next,Kr.pending=Xr.next=Da)}}function Fv(os,Kr){var Xr=Kr.action,Ca=Kr.payload,Pa=os.state;if(Kr.isTransition){var Da=ul.T,za={};ul.T=za;try{var Qa=Xr(Pa,Ca),Xa=ul.S;Xa!==null&&Xa(za,Qa),zv(os,Kr,Qa)}catch(xl){Wf(os,Kr,xl)}finally{Da!==null&&za.types!==null&&(Da.types=za.types),ul.T=Da}}else try{Da=Xr(Pa,Ca),zv(os,Kr,Da)}catch(xl){Wf(os,Kr,xl)}}function zv(os,Kr,Xr){Xr!==null&&typeof Xr=="object"&&typeof Xr.then=="function"?Xr.then(function(Ca){Hv(os,Kr,Ca)},function(Ca){return Wf(os,Kr,Ca)}):Hv(os,Kr,Xr)}function Hv(os,Kr,Xr){Kr.status="fulfilled",Kr.value=Xr,Kv(Kr),os.state=Xr,Kr=os.pending,Kr!==null&&(Xr=Kr.next,Xr===Kr?os.pending=null:(Xr=Xr.next,Kr.next=Xr,Fv(os,Xr)))}function Wf(os,Kr,Xr){var Ca=os.pending;if(os.pending=null,Ca!==null){Ca=Ca.next;do Kr.status="rejected",Kr.reason=Xr,Kv(Kr),Kr=Kr.next;while(Kr!==Ca)}os.action=null}function Kv(os){os=os.listeners;for(var Kr=0;Kr<os.length;Kr++)(0,os[Kr])()}function Gv(os,Kr){return Kr}function Zv(os,Kr){if(hu){var Xr=Au.formState;if(Xr!==null){e:{var Ca=iu;if(hu){if($u){t:{for(var Pa=$u,Da=Pc;Pa.nodeType!==8;){if(!Da){Pa=null;break t}if(Pa=Mc(Pa.nextSibling),Pa===null){Pa=null;break t}}Da=Pa.data,Pa=Da==="F!"||Da==="F"?Pa:null}if(Pa){$u=Mc(Pa.nextSibling),Ca=Pa.data==="F!";break e}}Ad(Ca)}Ca=!1}Ca&&(Kr=Xr[0])}}return Xr=cc(),Xr.memoizedState=Xr.baseState=Kr,Ca={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Gv,lastRenderedState:Kr},Xr.queue=Ca,Xr=my.bind(null,iu,Ca),Ca.dispatch=Xr,Ca=Jf(!1),Da=rg.bind(null,iu,!1,Ca.queue),Ca=cc(),Pa={state:Kr,dispatch:null,action:os,pending:null},Ca.queue=Pa,Xr=kR.bind(null,iu,Pa,Da,Xr),Pa.dispatch=Xr,Ca.memoizedState=os,[Kr,Xr,!1]}function Vv(os){var Kr=zu();return Qv(Kr,Nu,os)}function Qv(os,Kr,Xr){if(Kr=Qf(os,Kr,Gv)[0],os=lp(dd)[0],typeof Kr=="object"&&Kr!==null&&typeof Kr.then=="function")try{var Ca=th(Kr)}catch(za){throw za===tx?Wh:za}else Ca=Kr;Kr=zu();var Pa=Kr.queue,Da=Pa.dispatch;return Xr!==Kr.memoizedState&&(iu.flags|=2048,ax(9,{destroy:void 0},AR.bind(null,Pa,Xr),null)),[Ca,Da,os]}function AR(os,Kr){os.action=Kr}function Yv(os){var Kr=zu(),Xr=Nu;if(Xr!==null)return Qv(Kr,Xr,os);zu(),Kr=Kr.memoizedState,Xr=zu();var Ca=Xr.queue.dispatch;return Xr.memoizedState=os,[Kr,Ca,!1]}function ax(os,Kr,Xr,Ca){return os={tag:os,create:Xr,deps:Ca,inst:Kr,next:null},Kr=iu.updateQueue,Kr===null&&(Kr=ap(),iu.updateQueue=Kr),Xr=Kr.lastEffect,Xr===null?Kr.lastEffect=os.next=os:(Ca=Xr.next,Xr.next=os,os.next=Ca,Kr.lastEffect=os),os}function Jv(){return zu().memoizedState}function up(os,Kr,Xr,Ca){var Pa=cc();iu.flags|=os,Pa.memoizedState=ax(1|Kr,{destroy:void 0},Xr,Ca===void 0?null:Ca)}function cp(os,Kr,Xr,Ca){var Pa=zu();Ca=Ca===void 0?null:Ca;var Da=Pa.memoizedState.inst;Nu!==null&&Ca!==null&&zf(Ca,Nu.memoizedState.deps)?Pa.memoizedState=ax(Kr,Da,Xr,Ca):(iu.flags|=os,Pa.memoizedState=ax(1|Kr,Da,Xr,Ca))}function Wv(os,Kr){up(8390656,8,os,Kr)}function Xf(os,Kr){cp(2048,8,os,Kr)}function OR(os){iu.flags|=4;var Kr=iu.updateQueue;if(Kr===null)Kr=ap(),iu.updateQueue=Kr,Kr.events=[os];else{var Xr=Kr.events;Xr===null?Kr.events=[os]:Xr.push(os)}}function Xv(os){var Kr=zu().memoizedState;return OR({ref:Kr,nextImpl:os}),function(){if((vu&2)!==0)throw Error(is(440));return Kr.impl.apply(void 0,arguments)}}function ey(os,Kr){return cp(4,2,os,Kr)}function ty(os,Kr){return cp(4,4,os,Kr)}function sy(os,Kr){if(typeof Kr=="function"){os=os();var Xr=Kr(os);return function(){typeof Xr=="function"?Xr():Kr(null)}}if(Kr!=null)return os=os(),Kr.current=os,function(){Kr.current=null}}function ny(os,Kr,Xr){Xr=Xr!=null?Xr.concat([os]):null,cp(4,4,sy.bind(null,Kr,os),Xr)}function eg(){}function ry(os,Kr){var Xr=zu();Kr=Kr===void 0?null:Kr;var Ca=Xr.memoizedState;return Kr!==null&&zf(Kr,Ca[1])?Ca[0]:(Xr.memoizedState=[os,Kr],os)}function iy(os,Kr){var Xr=zu();Kr=Kr===void 0?null:Kr;var Ca=Xr.memoizedState;if(Kr!==null&&zf(Kr,Ca[1]))return Ca[0];if(Ca=os(),Em){Ol(!0);try{os()}finally{Ol(!1)}}return Xr.memoizedState=[Ca,Kr],Ca}function tg(os,Kr,Xr){return Xr===void 0||(cd&1073741824)!==0&&(du&261930)===0?os.memoizedState=Kr:(os.memoizedState=Xr,os=aE(),iu.lanes|=os,Ud|=os,Xr)}function ay(os,Kr,Xr,Ca){return bc(Xr,Kr)?Xr:nx.current!==null?(os=tg(os,Xr,Ca),bc(os,Kr)||(Gu=!0),os):(cd&42)===0||(cd&1073741824)!==0&&(du&261930)===0?(Gu=!0,os.memoizedState=Xr):(os=aE(),iu.lanes|=os,Ud|=os,Kr)}function oy(os,Kr,Xr,Ca,Pa){var Da=hl.p;hl.p=Da!==0&&8>Da?Da:8;var za=ul.T,Qa={};ul.T=Qa,rg(os,!1,Kr,Xr);try{var Xa=Pa(),xl=ul.S;if(xl!==null&&xl(Qa,Xa),Xa!==null&&typeof Xa=="object"&&typeof Xa.then=="function"){var wl=SR(Xa,Ca);sh(os,Kr,wl,Cc(os))}else sh(os,Kr,Ca,Cc(os))}catch(Cl){sh(os,Kr,{then:function(){},status:"rejected",reason:Cl},Cc())}finally{hl.p=Da,za!==null&&Qa.types!==null&&(za.types=Qa.types),ul.T=za}}function IR(){}function sg(os,Kr,Xr,Ca){if(os.tag!==5)throw Error(is(476));var Pa=ly(os).queue;oy(os,Pa,Kr,jl,Xr===null?IR:function(){return uy(os),Xr(Ca)})}function ly(os){var Kr=os.memoizedState;if(Kr!==null)return Kr;Kr={memoizedState:jl,baseState:jl,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:dd,lastRenderedState:jl},next:null};var Xr={};return Kr.next={memoizedState:Xr,baseState:Xr,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:dd,lastRenderedState:Xr},next:null},os.memoizedState=Kr,os=os.alternate,os!==null&&(os.memoizedState=Kr),Kr}function uy(os){var Kr=ly(os);Kr.next===null&&(Kr=os.alternate.memoizedState),sh(os,Kr.next.queue,{},Cc())}function ng(){return tc(vh)}function cy(){return zu().memoizedState}function dy(){return zu().memoizedState}function LR(os){for(var Kr=os.return;Kr!==null;){switch(Kr.tag){case 24:case 3:var Xr=Cc();os=Ld(Xr);var Ca=$d(Kr,os,Xr);Ca!==null&&(vc(Ca,Kr,Xr),Jx(Ca,Kr,Xr)),Kr={cache:Of()},os.payload=Kr;return}Kr=Kr.return}}function $R(os,Kr,Xr){var Ca=Cc();Xr={lane:Ca,revertLane:0,gesture:null,action:Xr,hasEagerState:!1,eagerState:null,next:null},dp(os)?xy(Kr,Xr):(Xr=Ef(os,Kr,Xr,Ca),Xr!==null&&(vc(Xr,os,Ca),hy(Xr,Kr,Ca)))}function my(os,Kr,Xr){var Ca=Cc();sh(os,Kr,Xr,Ca)}function sh(os,Kr,Xr,Ca){var Pa={lane:Ca,revertLane:0,gesture:null,action:Xr,hasEagerState:!1,eagerState:null,next:null};if(dp(os))xy(Kr,Pa);else{var Da=os.alternate;if(os.lanes===0&&(Da===null||Da.lanes===0)&&(Da=Kr.lastRenderedReducer,Da!==null))try{var za=Kr.lastRenderedState,Qa=Da(za,Xr);if(Pa.hasEagerState=!0,Pa.eagerState=Qa,bc(Qa,za))return Kh(os,Kr,Pa,0),Au===null&&Hh(),!1}catch{}finally{}if(Xr=Ef(os,Kr,Pa,Ca),Xr!==null)return vc(Xr,os,Ca),hy(Xr,Kr,Ca),!0}return!1}function rg(os,Kr,Xr,Ca){if(Ca={lane:2,revertLane:Pg(),gesture:null,action:Ca,hasEagerState:!1,eagerState:null,next:null},dp(os)){if(Kr)throw Error(is(479))}else Kr=Ef(os,Xr,Ca,2),Kr!==null&&vc(Kr,os,2)}function dp(os){var Kr=os.alternate;return os===iu||Kr!==null&&Kr===iu}function xy(os,Kr){rx=rp=!0;var Xr=os.pending;Xr===null?Kr.next=Kr:(Kr.next=Xr.next,Xr.next=Kr),os.pending=Kr}function hy(os,Kr,Xr){if((Xr&4194048)!==0){var Ca=Kr.lanes;Ca&=os.pendingLanes,Xr|=Ca,Kr.lanes=Xr,mc(os,Xr)}}var nh={readContext:tc,use:op,useCallback:Bu,useContext:Bu,useEffect:Bu,useImperativeHandle:Bu,useLayoutEffect:Bu,useInsertionEffect:Bu,useMemo:Bu,useReducer:Bu,useRef:Bu,useState:Bu,useDebugValue:Bu,useDeferredValue:Bu,useTransition:Bu,useSyncExternalStore:Bu,useId:Bu,useHostTransitionStatus:Bu,useFormState:Bu,useActionState:Bu,useOptimistic:Bu,useMemoCache:Bu,useCacheRefresh:Bu};nh.useEffectEvent=Bu;var py={readContext:tc,use:op,useCallback:function(os,Kr){return cc().memoizedState=[os,Kr===void 0?null:Kr],os},useContext:tc,useEffect:Wv,useImperativeHandle:function(os,Kr,Xr){Xr=Xr!=null?Xr.concat([os]):null,up(4194308,4,sy.bind(null,Kr,os),Xr)},useLayoutEffect:function(os,Kr){return up(4194308,4,os,Kr)},useInsertionEffect:function(os,Kr){up(4,2,os,Kr)},useMemo:function(os,Kr){var Xr=cc();Kr=Kr===void 0?null:Kr;var Ca=os();if(Em){Ol(!0);try{os()}finally{Ol(!1)}}return Xr.memoizedState=[Ca,Kr],Ca},useReducer:function(os,Kr,Xr){var Ca=cc();if(Xr!==void 0){var Pa=Xr(Kr);if(Em){Ol(!0);try{Xr(Kr)}finally{Ol(!1)}}}else Pa=Kr;return Ca.memoizedState=Ca.baseState=Pa,os={pending:null,lanes:0,dispatch:null,lastRenderedReducer:os,lastRenderedState:Pa},Ca.queue=os,os=os.dispatch=$R.bind(null,iu,os),[Ca.memoizedState,os]},useRef:function(os){var Kr=cc();return os={current:os},Kr.memoizedState=os},useState:function(os){os=Jf(os);var Kr=os.queue,Xr=my.bind(null,iu,Kr);return Kr.dispatch=Xr,[os.memoizedState,Xr]},useDebugValue:eg,useDeferredValue:function(os,Kr){var Xr=cc();return tg(Xr,os,Kr)},useTransition:function(){var os=Jf(!1);return os=oy.bind(null,iu,os.queue,!0,!1),cc().memoizedState=os,[!1,os]},useSyncExternalStore:function(os,Kr,Xr){var Ca=iu,Pa=cc();if(hu){if(Xr===void 0)throw Error(is(407));Xr=Xr()}else{if(Xr=Kr(),Au===null)throw Error(is(349));(du&127)!==0||Pv(Ca,Kr,Xr)}Pa.memoizedState=Xr;var Da={value:Xr,getSnapshot:Kr};return Pa.queue=Da,Wv(Mv.bind(null,Ca,Da,os),[os]),Ca.flags|=2048,ax(9,{destroy:void 0},Dv.bind(null,Ca,Da,Xr,Kr),null),Xr},useId:function(){var os=cc(),Kr=Au.identifierPrefix;if(hu){var Xr=Jc,Ca=Yc;Xr=(Ca&~(1<<32-Rl(Ca)-1)).toString(32)+Xr,Kr="_"+Kr+"R_"+Xr,Xr=ip++,0<Xr&&(Kr+="H"+Xr.toString(32)),Kr+="_"}else Xr=CR++,Kr="_"+Kr+"r_"+Xr.toString(32)+"_";return os.memoizedState=Kr},useHostTransitionStatus:ng,useFormState:Zv,useActionState:Zv,useOptimistic:function(os){var Kr=cc();Kr.memoizedState=Kr.baseState=os;var Xr={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return Kr.queue=Xr,Kr=rg.bind(null,iu,!0,Xr),Xr.dispatch=Kr,[os,Kr]},useMemoCache:Vf,useCacheRefresh:function(){return cc().memoizedState=LR.bind(null,iu)},useEffectEvent:function(os){var Kr=cc(),Xr={impl:os};return Kr.memoizedState=Xr,function(){if((vu&2)!==0)throw Error(is(440));return Xr.impl.apply(void 0,arguments)}}},ig={readContext:tc,use:op,useCallback:ry,useContext:tc,useEffect:Xf,useImperativeHandle:ny,useInsertionEffect:ey,useLayoutEffect:ty,useMemo:iy,useReducer:lp,useRef:Jv,useState:function(){return lp(dd)},useDebugValue:eg,useDeferredValue:function(os,Kr){var Xr=zu();return ay(Xr,Nu.memoizedState,os,Kr)},useTransition:function(){var os=lp(dd)[0],Kr=zu().memoizedState;return[typeof os=="boolean"?os:th(os),Kr]},useSyncExternalStore:$v,useId:cy,useHostTransitionStatus:ng,useFormState:Vv,useActionState:Vv,useOptimistic:function(os,Kr){var Xr=zu();return qv(Xr,Nu,os,Kr)},useMemoCache:Vf,useCacheRefresh:dy};ig.useEffectEvent=Xv;var fy={readContext:tc,use:op,useCallback:ry,useContext:tc,useEffect:Xf,useImperativeHandle:ny,useInsertionEffect:ey,useLayoutEffect:ty,useMemo:iy,useReducer:Yf,useRef:Jv,useState:function(){return Yf(dd)},useDebugValue:eg,useDeferredValue:function(os,Kr){var Xr=zu();return Nu===null?tg(Xr,os,Kr):ay(Xr,Nu.memoizedState,os,Kr)},useTransition:function(){var os=Yf(dd)[0],Kr=zu().memoizedState;return[typeof os=="boolean"?os:th(os),Kr]},useSyncExternalStore:$v,useId:cy,useHostTransitionStatus:ng,useFormState:Yv,useActionState:Yv,useOptimistic:function(os,Kr){var Xr=zu();return Nu!==null?qv(Xr,Nu,os,Kr):(Xr.baseState=os,[os,Xr.queue.dispatch])},useMemoCache:Vf,useCacheRefresh:dy};fy.useEffectEvent=Xv;function ag(os,Kr,Xr,Ca){Kr=os.memoizedState,Xr=Xr(Ca,Kr),Xr=Xr==null?Kr:La({},Kr,Xr),os.memoizedState=Xr,os.lanes===0&&(os.updateQueue.baseState=Xr)}var og={enqueueSetState:function(os,Kr,Xr){os=os._reactInternals;var Ca=Cc(),Pa=Ld(Ca);Pa.payload=Kr,Xr!=null&&(Pa.callback=Xr),Kr=$d(os,Pa,Ca),Kr!==null&&(vc(Kr,os,Ca),Jx(Kr,os,Ca))},enqueueReplaceState:function(os,Kr,Xr){os=os._reactInternals;var Ca=Cc(),Pa=Ld(Ca);Pa.tag=1,Pa.payload=Kr,Xr!=null&&(Pa.callback=Xr),Kr=$d(os,Pa,Ca),Kr!==null&&(vc(Kr,os,Ca),Jx(Kr,os,Ca))},enqueueForceUpdate:function(os,Kr){os=os._reactInternals;var Xr=Cc(),Ca=Ld(Xr);Ca.tag=2,Kr!=null&&(Ca.callback=Kr),Kr=$d(os,Ca,Xr),Kr!==null&&(vc(Kr,os,Xr),Jx(Kr,os,Xr))}};function gy(os,Kr,Xr,Ca,Pa,Da,za){return os=os.stateNode,typeof os.shouldComponentUpdate=="function"?os.shouldComponentUpdate(Ca,Da,za):Kr.prototype&&Kr.prototype.isPureReactComponent?!zx(Xr,Ca)||!zx(Pa,Da):!0}function jy(os,Kr,Xr,Ca){os=Kr.state,typeof Kr.componentWillReceiveProps=="function"&&Kr.componentWillReceiveProps(Xr,Ca),typeof Kr.UNSAFE_componentWillReceiveProps=="function"&&Kr.UNSAFE_componentWillReceiveProps(Xr,Ca),Kr.state!==os&&og.enqueueReplaceState(Kr,Kr.state,null)}function bm(os,Kr){var Xr=Kr;if("ref"in Kr){Xr={};for(var Ca in Kr)Ca!=="ref"&&(Xr[Ca]=Kr[Ca])}if(os=os.defaultProps){Xr===Kr&&(Xr=La({},Xr));for(var Pa in os)Xr[Pa]===void 0&&(Xr[Pa]=os[Pa])}return Xr}function vy(os){zh(os)}function yy(os){console.error(os)}function Ey(os){zh(os)}function mp(os,Kr){try{var Xr=os.onUncaughtError;Xr(Kr.value,{componentStack:Kr.stack})}catch(Ca){setTimeout(function(){throw Ca})}}function by(os,Kr,Xr){try{var Ca=os.onCaughtError;Ca(Xr.value,{componentStack:Xr.stack,errorBoundary:Kr.tag===1?Kr.stateNode:null})}catch(Pa){setTimeout(function(){throw Pa})}}function lg(os,Kr,Xr){return Xr=Ld(Xr),Xr.tag=3,Xr.payload={element:null},Xr.callback=function(){mp(os,Kr)},Xr}function Ry(os){return os=Ld(os),os.tag=3,os}function _y(os,Kr,Xr,Ca){var Pa=Xr.type.getDerivedStateFromError;if(typeof Pa=="function"){var Da=Ca.value;os.payload=function(){return Pa(Da)},os.callback=function(){by(Kr,Xr,Ca)}}var za=Xr.stateNode;za!==null&&typeof za.componentDidCatch=="function"&&(os.callback=function(){by(Kr,Xr,Ca),typeof Pa!="function"&&(qd===null?qd=new Set([this]):qd.add(this));var Qa=Ca.stack;this.componentDidCatch(Ca.value,{componentStack:Qa!==null?Qa:""})})}function PR(os,Kr,Xr,Ca,Pa){if(Xr.flags|=32768,Ca!==null&&typeof Ca=="object"&&typeof Ca.then=="function"){if(Kr=Xr.alternate,Kr!==null&&Wm(Kr,Xr,Pa,!0),Xr=_c.current,Xr!==null){switch(Xr.tag){case 31:case 13:return Dc===null?wp():Xr.alternate===null&&Uu===0&&(Uu=3),Xr.flags&=-257,Xr.flags|=65536,Xr.lanes=Pa,Ca===Xh?Xr.flags|=16384:(Kr=Xr.updateQueue,Kr===null?Xr.updateQueue=new Set([Ca]):Kr.add(Ca),Ig(os,Ca,Pa)),!1;case 22:return Xr.flags|=65536,Ca===Xh?Xr.flags|=16384:(Kr=Xr.updateQueue,Kr===null?(Kr={transitions:null,markerInstances:null,retryQueue:new Set([Ca])},Xr.updateQueue=Kr):(Xr=Kr.retryQueue,Xr===null?Kr.retryQueue=new Set([Ca]):Xr.add(Ca)),Ig(os,Ca,Pa)),!1}throw Error(is(435,Xr.tag))}return Ig(os,Ca,Pa),wp(),!1}if(hu)return Kr=_c.current,Kr!==null?((Kr.flags&65536)===0&&(Kr.flags|=256),Kr.flags|=65536,Kr.lanes=Pa,Ca!==Sf&&(os=Error(is(422),{cause:Ca}),Gx(Ic(os,Xr)))):(Ca!==Sf&&(Kr=Error(is(423),{cause:Ca}),Gx(Ic(Kr,Xr))),os=os.current.alternate,os.flags|=65536,Pa&=-Pa,os.lanes|=Pa,Ca=Ic(Ca,Xr),Pa=lg(os.stateNode,Ca,Pa),Mf(os,Pa),Uu!==4&&(Uu=2)),!1;var Da=Error(is(520),{cause:Ca});if(Da=Ic(Da,Xr),dh===null?dh=[Da]:dh.push(Da),Uu!==4&&(Uu=2),Kr===null)return!0;Ca=Ic(Ca,Xr),Xr=Kr;do{switch(Xr.tag){case 3:return Xr.flags|=65536,os=Pa&-Pa,Xr.lanes|=os,os=lg(Xr.stateNode,Ca,os),Mf(Xr,os),!1;case 1:if(Kr=Xr.type,Da=Xr.stateNode,(Xr.flags&128)===0&&(typeof Kr.getDerivedStateFromError=="function"||Da!==null&&typeof Da.componentDidCatch=="function"&&(qd===null||!qd.has(Da))))return Xr.flags|=65536,Pa&=-Pa,Xr.lanes|=Pa,Pa=Ry(Pa),_y(Pa,os,Xr,Ca),Mf(Xr,Pa),!1}Xr=Xr.return}while(Xr!==null);return!1}var ug=Error(is(461)),Gu=!1;function sc(os,Kr,Xr,Ca){Kr.child=os===null?Cv(Kr,null,Xr,Ca):ym(Kr,os.child,Xr,Ca)}function wy(os,Kr,Xr,Ca,Pa){Xr=Xr.render;var Da=Kr.ref;if("ref"in Ca){var za={};for(var Qa in Ca)Qa!=="ref"&&(za[Qa]=Ca[Qa])}else za=Ca;return fm(Kr),Ca=Hf(os,Kr,Xr,za,Da,Pa),Qa=Kf(),os!==null&&!Gu?(Gf(os,Kr,Pa),md(os,Kr,Pa)):(hu&&Qa&&wf(Kr),Kr.flags|=1,sc(os,Kr,Ca,Pa),Kr.child)}function Ny(os,Kr,Xr,Ca,Pa){if(os===null){var Da=Xr.type;return typeof Da=="function"&&!bf(Da)&&Da.defaultProps===void 0&&Xr.compare===null?(Kr.tag=15,Kr.type=Da,Sy(os,Kr,Da,Ca,Pa)):(os=Zh(Xr.type,null,Ca,Kr,Kr.mode,Pa),os.ref=Kr.ref,os.return=Kr,Kr.child=os)}if(Da=os.child,!gg(os,Pa)){var za=Da.memoizedProps;if(Xr=Xr.compare,Xr=Xr!==null?Xr:zx,Xr(za,Ca)&&os.ref===Kr.ref)return md(os,Kr,Pa)}return Kr.flags|=1,os=ad(Da,Ca),os.ref=Kr.ref,os.return=Kr,Kr.child=os}function Sy(os,Kr,Xr,Ca,Pa){if(os!==null){var Da=os.memoizedProps;if(zx(Da,Ca)&&os.ref===Kr.ref)if(Gu=!1,Kr.pendingProps=Ca=Da,gg(os,Pa))(os.flags&131072)!==0&&(Gu=!0);else return Kr.lanes=os.lanes,md(os,Kr,Pa)}return cg(os,Kr,Xr,Ca,Pa)}function Cy(os,Kr,Xr,Ca){var Pa=Ca.children,Da=os!==null?os.memoizedState:null;if(os===null&&Kr.stateNode===null&&(Kr.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),Ca.mode==="hidden"){if((Kr.flags&128)!==0){if(Da=Da!==null?Da.baseLanes|Xr:Xr,os!==null){for(Ca=Kr.child=os.child,Pa=0;Ca!==null;)Pa=Pa|Ca.lanes|Ca.childLanes,Ca=Ca.sibling;Ca=Pa&~Da}else Ca=0,Kr.child=null;return Ty(os,Kr,Da,Xr,Ca)}if((Xr&536870912)!==0)Kr.memoizedState={baseLanes:0,cachePool:null},os!==null&&Jh(Kr,Da!==null?Da.cachePool:null),Da!==null?Av(Kr,Da):Uf(),Ov(Kr);else return Ca=Kr.lanes=536870912,Ty(os,Kr,Da!==null?Da.baseLanes|Xr:Xr,Xr,Ca)}else Da!==null?(Jh(Kr,Da.cachePool),Av(Kr,Da),Dd(),Kr.memoizedState=null):(os!==null&&Jh(Kr,null),Uf(),Dd());return sc(os,Kr,Pa,Xr),Kr.child}function rh(os,Kr){return os!==null&&os.tag===22||Kr.stateNode!==null||(Kr.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),Kr.sibling}function Ty(os,Kr,Xr,Ca,Pa){var Da=Lf();return Da=Da===null?null:{parent:Hu._currentValue,pool:Da},Kr.memoizedState={baseLanes:Xr,cachePool:Da},os!==null&&Jh(Kr,null),Uf(),Ov(Kr),os!==null&&Wm(os,Kr,Ca,!0),Kr.childLanes=Pa,null}function xp(os,Kr){return Kr=fp({mode:Kr.mode,children:Kr.children},os.mode),Kr.ref=os.ref,os.child=Kr,Kr.return=os,Kr}function ky(os,Kr,Xr){return ym(Kr,os.child,null,Xr),os=xp(Kr,Kr.pendingProps),os.flags|=2,wc(Kr),Kr.memoizedState=null,os}function DR(os,Kr,Xr){var Ca=Kr.pendingProps,Pa=(Kr.flags&128)!==0;if(Kr.flags&=-129,os===null){if(hu){if(Ca.mode==="hidden")return os=xp(Kr,Ca),Kr.lanes=536870912,rh(null,os);if(Ff(Kr),(os=$u)?(os=FE(os,Pc),os=os!==null&&os.data==="&"?os:null,os!==null&&(Kr.memoizedState={dehydrated:os,treeContext:Td!==null?{id:Yc,overflow:Jc}:null,retryLane:536870912,hydrationErrors:null},Xr=xv(os),Xr.return=Kr,Kr.child=Xr,ec=Kr,$u=null)):os=null,os===null)throw Ad(Kr);return Kr.lanes=536870912,null}return xp(Kr,Ca)}var Da=os.memoizedState;if(Da!==null){var za=Da.dehydrated;if(Ff(Kr),Pa)if(Kr.flags&256)Kr.flags&=-257,Kr=ky(os,Kr,Xr);else if(Kr.memoizedState!==null)Kr.child=os.child,Kr.flags|=128,Kr=null;else throw Error(is(558));else if(Gu||Wm(os,Kr,Xr,!1),Pa=(Xr&os.childLanes)!==0,Gu||Pa){if(Ca=Au,Ca!==null&&(za=Fc(Ca,Xr),za!==0&&za!==Da.retryLane))throw Da.retryLane=za,mm(os,za),vc(Ca,os,za),ug;wp(),Kr=ky(os,Kr,Xr)}else os=Da.treeContext,$u=Mc(za.nextSibling),ec=Kr,hu=!0,kd=null,Pc=!1,os!==null&&fv(Kr,os),Kr=xp(Kr,Ca),Kr.flags|=4096;return Kr}return os=ad(os.child,{mode:Ca.mode,children:Ca.children}),os.ref=Kr.ref,Kr.child=os,os.return=Kr,os}function hp(os,Kr){var Xr=Kr.ref;if(Xr===null)os!==null&&os.ref!==null&&(Kr.flags|=4194816);else{if(typeof Xr!="function"&&typeof Xr!="object")throw Error(is(284));(os===null||os.ref!==Xr)&&(Kr.flags|=4194816)}}function cg(os,Kr,Xr,Ca,Pa){return fm(Kr),Xr=Hf(os,Kr,Xr,Ca,void 0,Pa),Ca=Kf(),os!==null&&!Gu?(Gf(os,Kr,Pa),md(os,Kr,Pa)):(hu&&Ca&&wf(Kr),Kr.flags|=1,sc(os,Kr,Xr,Pa),Kr.child)}function Ay(os,Kr,Xr,Ca,Pa,Da){return fm(Kr),Kr.updateQueue=null,Xr=Lv(Kr,Ca,Xr,Pa),Iv(os),Ca=Kf(),os!==null&&!Gu?(Gf(os,Kr,Da),md(os,Kr,Da)):(hu&&Ca&&wf(Kr),Kr.flags|=1,sc(os,Kr,Xr,Da),Kr.child)}function Oy(os,Kr,Xr,Ca,Pa){if(fm(Kr),Kr.stateNode===null){var Da=Vm,za=Xr.contextType;typeof za=="object"&&za!==null&&(Da=tc(za)),Da=new Xr(Ca,Da),Kr.memoizedState=Da.state!==null&&Da.state!==void 0?Da.state:null,Da.updater=og,Kr.stateNode=Da,Da._reactInternals=Kr,Da=Kr.stateNode,Da.props=Ca,Da.state=Kr.memoizedState,Da.refs={},Pf(Kr),za=Xr.contextType,Da.context=typeof za=="object"&&za!==null?tc(za):Vm,Da.state=Kr.memoizedState,za=Xr.getDerivedStateFromProps,typeof za=="function"&&(ag(Kr,Xr,za,Ca),Da.state=Kr.memoizedState),typeof Xr.getDerivedStateFromProps=="function"||typeof Da.getSnapshotBeforeUpdate=="function"||typeof Da.UNSAFE_componentWillMount!="function"&&typeof Da.componentWillMount!="function"||(za=Da.state,typeof Da.componentWillMount=="function"&&Da.componentWillMount(),typeof Da.UNSAFE_componentWillMount=="function"&&Da.UNSAFE_componentWillMount(),za!==Da.state&&og.enqueueReplaceState(Da,Da.state,null),Xx(Kr,Ca,Da,Pa),Wx(),Da.state=Kr.memoizedState),typeof Da.componentDidMount=="function"&&(Kr.flags|=4194308),Ca=!0}else if(os===null){Da=Kr.stateNode;var Qa=Kr.memoizedProps,Xa=bm(Xr,Qa);Da.props=Xa;var xl=Da.context,wl=Xr.contextType;za=Vm,typeof wl=="object"&&wl!==null&&(za=tc(wl));var Cl=Xr.getDerivedStateFromProps;wl=typeof Cl=="function"||typeof Da.getSnapshotBeforeUpdate=="function",Qa=Kr.pendingProps!==Qa,wl||typeof Da.UNSAFE_componentWillReceiveProps!="function"&&typeof Da.componentWillReceiveProps!="function"||(Qa||xl!==za)&&jy(Kr,Da,Ca,za),Id=!1;var gl=Kr.memoizedState;Da.state=gl,Xx(Kr,Ca,Da,Pa),Wx(),xl=Kr.memoizedState,Qa||gl!==xl||Id?(typeof Cl=="function"&&(ag(Kr,Xr,Cl,Ca),xl=Kr.memoizedState),(Xa=Id||gy(Kr,Xr,Xa,Ca,gl,xl,za))?(wl||typeof Da.UNSAFE_componentWillMount!="function"&&typeof Da.componentWillMount!="function"||(typeof Da.componentWillMount=="function"&&Da.componentWillMount(),typeof Da.UNSAFE_componentWillMount=="function"&&Da.UNSAFE_componentWillMount()),typeof Da.componentDidMount=="function"&&(Kr.flags|=4194308)):(typeof Da.componentDidMount=="function"&&(Kr.flags|=4194308),Kr.memoizedProps=Ca,Kr.memoizedState=xl),Da.props=Ca,Da.state=xl,Da.context=za,Ca=Xa):(typeof Da.componentDidMount=="function"&&(Kr.flags|=4194308),Ca=!1)}else{Da=Kr.stateNode,Df(os,Kr),za=Kr.memoizedProps,wl=bm(Xr,za),Da.props=wl,Cl=Kr.pendingProps,gl=Da.context,xl=Xr.contextType,Xa=Vm,typeof xl=="object"&&xl!==null&&(Xa=tc(xl)),Qa=Xr.getDerivedStateFromProps,(xl=typeof Qa=="function"||typeof Da.getSnapshotBeforeUpdate=="function")||typeof Da.UNSAFE_componentWillReceiveProps!="function"&&typeof Da.componentWillReceiveProps!="function"||(za!==Cl||gl!==Xa)&&jy(Kr,Da,Ca,Xa),Id=!1,gl=Kr.memoizedState,Da.state=gl,Xx(Kr,Ca,Da,Pa),Wx();var vl=Kr.memoizedState;za!==Cl||gl!==vl||Id||os!==null&&os.dependencies!==null&&Qh(os.dependencies)?(typeof Qa=="function"&&(ag(Kr,Xr,Qa,Ca),vl=Kr.memoizedState),(wl=Id||gy(Kr,Xr,wl,Ca,gl,vl,Xa)||os!==null&&os.dependencies!==null&&Qh(os.dependencies))?(xl||typeof Da.UNSAFE_componentWillUpdate!="function"&&typeof Da.componentWillUpdate!="function"||(typeof Da.componentWillUpdate=="function"&&Da.componentWillUpdate(Ca,vl,Xa),typeof Da.UNSAFE_componentWillUpdate=="function"&&Da.UNSAFE_componentWillUpdate(Ca,vl,Xa)),typeof Da.componentDidUpdate=="function"&&(Kr.flags|=4),typeof Da.getSnapshotBeforeUpdate=="function"&&(Kr.flags|=1024)):(typeof Da.componentDidUpdate!="function"||za===os.memoizedProps&&gl===os.memoizedState||(Kr.flags|=4),typeof Da.getSnapshotBeforeUpdate!="function"||za===os.memoizedProps&&gl===os.memoizedState||(Kr.flags|=1024),Kr.memoizedProps=Ca,Kr.memoizedState=vl),Da.props=Ca,Da.state=vl,Da.context=Xa,Ca=wl):(typeof Da.componentDidUpdate!="function"||za===os.memoizedProps&&gl===os.memoizedState||(Kr.flags|=4),typeof Da.getSnapshotBeforeUpdate!="function"||za===os.memoizedProps&&gl===os.memoizedState||(Kr.flags|=1024),Ca=!1)}return Da=Ca,hp(os,Kr),Ca=(Kr.flags&128)!==0,Da||Ca?(Da=Kr.stateNode,Xr=Ca&&typeof Xr.getDerivedStateFromError!="function"?null:Da.render(),Kr.flags|=1,os!==null&&Ca?(Kr.child=ym(Kr,os.child,null,Pa),Kr.child=ym(Kr,null,Xr,Pa)):sc(os,Kr,Xr,Pa),Kr.memoizedState=Da.state,os=Kr.child):os=md(os,Kr,Pa),os}function Iy(os,Kr,Xr,Ca){return hm(),Kr.flags|=256,sc(os,Kr,Xr,Ca),Kr.child}var dg={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function mg(os){return{baseLanes:os,cachePool:bv()}}function xg(os,Kr,Xr){return os=os!==null?os.childLanes&~Xr:0,Kr&&(os|=Sc),os}function Ly(os,Kr,Xr){var Ca=Kr.pendingProps,Pa=!1,Da=(Kr.flags&128)!==0,za;if((za=Da)||(za=os!==null&&os.memoizedState===null?!1:(Fu.current&2)!==0),za&&(Pa=!0,Kr.flags&=-129),za=(Kr.flags&32)!==0,Kr.flags&=-33,os===null){if(hu){if(Pa?Pd(Kr):Dd(),(os=$u)?(os=FE(os,Pc),os=os!==null&&os.data!=="&"?os:null,os!==null&&(Kr.memoizedState={dehydrated:os,treeContext:Td!==null?{id:Yc,overflow:Jc}:null,retryLane:536870912,hydrationErrors:null},Xr=xv(os),Xr.return=Kr,Kr.child=Xr,ec=Kr,$u=null)):os=null,os===null)throw Ad(Kr);return Qg(os)?Kr.lanes=32:Kr.lanes=536870912,null}var Qa=Ca.children;return Ca=Ca.fallback,Pa?(Dd(),Pa=Kr.mode,Qa=fp({mode:"hidden",children:Qa},Pa),Ca=xm(Ca,Pa,Xr,null),Qa.return=Kr,Ca.return=Kr,Qa.sibling=Ca,Kr.child=Qa,Ca=Kr.child,Ca.memoizedState=mg(Xr),Ca.childLanes=xg(os,za,Xr),Kr.memoizedState=dg,rh(null,Ca)):(Pd(Kr),hg(Kr,Qa))}var Xa=os.memoizedState;if(Xa!==null&&(Qa=Xa.dehydrated,Qa!==null)){if(Da)Kr.flags&256?(Pd(Kr),Kr.flags&=-257,Kr=pg(os,Kr,Xr)):Kr.memoizedState!==null?(Dd(),Kr.child=os.child,Kr.flags|=128,Kr=null):(Dd(),Qa=Ca.fallback,Pa=Kr.mode,Ca=fp({mode:"visible",children:Ca.children},Pa),Qa=xm(Qa,Pa,Xr,null),Qa.flags|=2,Ca.return=Kr,Qa.return=Kr,Ca.sibling=Qa,Kr.child=Ca,ym(Kr,os.child,null,Xr),Ca=Kr.child,Ca.memoizedState=mg(Xr),Ca.childLanes=xg(os,za,Xr),Kr.memoizedState=dg,Kr=rh(null,Ca));else if(Pd(Kr),Qg(Qa)){if(za=Qa.nextSibling&&Qa.nextSibling.dataset,za)var xl=za.dgst;za=xl,Ca=Error(is(419)),Ca.stack="",Ca.digest=za,Gx({value:Ca,source:null,stack:null}),Kr=pg(os,Kr,Xr)}else if(Gu||Wm(os,Kr,Xr,!1),za=(Xr&os.childLanes)!==0,Gu||za){if(za=Au,za!==null&&(Ca=Fc(za,Xr),Ca!==0&&Ca!==Xa.retryLane))throw Xa.retryLane=Ca,mm(os,Ca),vc(za,os,Ca),ug;Vg(Qa)||wp(),Kr=pg(os,Kr,Xr)}else Vg(Qa)?(Kr.flags|=192,Kr.child=os.child,Kr=null):(os=Xa.treeContext,$u=Mc(Qa.nextSibling),ec=Kr,hu=!0,kd=null,Pc=!1,os!==null&&fv(Kr,os),Kr=hg(Kr,Ca.children),Kr.flags|=4096);return Kr}return Pa?(Dd(),Qa=Ca.fallback,Pa=Kr.mode,Xa=os.child,xl=Xa.sibling,Ca=ad(Xa,{mode:"hidden",children:Ca.children}),Ca.subtreeFlags=Xa.subtreeFlags&65011712,xl!==null?Qa=ad(xl,Qa):(Qa=xm(Qa,Pa,Xr,null),Qa.flags|=2),Qa.return=Kr,Ca.return=Kr,Ca.sibling=Qa,Kr.child=Ca,rh(null,Ca),Ca=Kr.child,Qa=os.child.memoizedState,Qa===null?Qa=mg(Xr):(Pa=Qa.cachePool,Pa!==null?(Xa=Hu._currentValue,Pa=Pa.parent!==Xa?{parent:Xa,pool:Xa}:Pa):Pa=bv(),Qa={baseLanes:Qa.baseLanes|Xr,cachePool:Pa}),Ca.memoizedState=Qa,Ca.childLanes=xg(os,za,Xr),Kr.memoizedState=dg,rh(os.child,Ca)):(Pd(Kr),Xr=os.child,os=Xr.sibling,Xr=ad(Xr,{mode:"visible",children:Ca.children}),Xr.return=Kr,Xr.sibling=null,os!==null&&(za=Kr.deletions,za===null?(Kr.deletions=[os],Kr.flags|=16):za.push(os)),Kr.child=Xr,Kr.memoizedState=null,Xr)}function hg(os,Kr){return Kr=fp({mode:"visible",children:Kr},os.mode),Kr.return=os,os.child=Kr}function fp(os,Kr){return os=Rc(22,os,null,Kr),os.lanes=0,os}function pg(os,Kr,Xr){return ym(Kr,os.child,null,Xr),os=hg(Kr,Kr.pendingProps.children),os.flags|=2,Kr.memoizedState=null,os}function $y(os,Kr,Xr){os.lanes|=Kr;var Ca=os.alternate;Ca!==null&&(Ca.lanes|=Kr),kf(os.return,Kr,Xr)}function fg(os,Kr,Xr,Ca,Pa,Da){var za=os.memoizedState;za===null?os.memoizedState={isBackwards:Kr,rendering:null,renderingStartTime:0,last:Ca,tail:Xr,tailMode:Pa,treeForkCount:Da}:(za.isBackwards=Kr,za.rendering=null,za.renderingStartTime=0,za.last=Ca,za.tail=Xr,za.tailMode=Pa,za.treeForkCount=Da)}function Py(os,Kr,Xr){var Ca=Kr.pendingProps,Pa=Ca.revealOrder,Da=Ca.tail;Ca=Ca.children;var za=Fu.current,Qa=(za&2)!==0;if(Qa?(za=za&1|2,Kr.flags|=128):za&=1,Il(Fu,za),sc(os,Kr,Ca,Xr),Ca=hu?Kx:0,!Qa&&os!==null&&(os.flags&128)!==0)e:for(os=Kr.child;os!==null;){if(os.tag===13)os.memoizedState!==null&&$y(os,Xr,Kr);else if(os.tag===19)$y(os,Xr,Kr);else if(os.child!==null){os.child.return=os,os=os.child;continue}if(os===Kr)break e;for(;os.sibling===null;){if(os.return===null||os.return===Kr)break e;os=os.return}os.sibling.return=os.return,os=os.sibling}switch(Pa){case"forwards":for(Xr=Kr.child,Pa=null;Xr!==null;)os=Xr.alternate,os!==null&&np(os)===null&&(Pa=Xr),Xr=Xr.sibling;Xr=Pa,Xr===null?(Pa=Kr.child,Kr.child=null):(Pa=Xr.sibling,Xr.sibling=null),fg(Kr,!1,Pa,Xr,Da,Ca);break;case"backwards":case"unstable_legacy-backwards":for(Xr=null,Pa=Kr.child,Kr.child=null;Pa!==null;){if(os=Pa.alternate,os!==null&&np(os)===null){Kr.child=Pa;break}os=Pa.sibling,Pa.sibling=Xr,Xr=Pa,Pa=os}fg(Kr,!0,Xr,null,Da,Ca);break;case"together":fg(Kr,!1,null,null,void 0,Ca);break;default:Kr.memoizedState=null}return Kr.child}function md(os,Kr,Xr){if(os!==null&&(Kr.dependencies=os.dependencies),Ud|=Kr.lanes,(Xr&Kr.childLanes)===0)if(os!==null){if(Wm(os,Kr,Xr,!1),(Xr&Kr.childLanes)===0)return null}else return null;if(os!==null&&Kr.child!==os.child)throw Error(is(153));if(Kr.child!==null){for(os=Kr.child,Xr=ad(os,os.pendingProps),Kr.child=Xr,Xr.return=Kr;os.sibling!==null;)os=os.sibling,Xr=Xr.sibling=ad(os,os.pendingProps),Xr.return=Kr;Xr.sibling=null}return Kr.child}function gg(os,Kr){return(os.lanes&Kr)!==0?!0:(os=os.dependencies,!!(os!==null&&Qh(os)))}function MR(os,Kr,Xr){switch(Kr.tag){case 3:cu(Kr,Kr.stateNode.containerInfo),Od(Kr,Hu,os.memoizedState.cache),hm();break;case 27:case 5:Ml(Kr);break;case 4:cu(Kr,Kr.stateNode.containerInfo);break;case 10:Od(Kr,Kr.type,Kr.memoizedProps.value);break;case 31:if(Kr.memoizedState!==null)return Kr.flags|=128,Ff(Kr),null;break;case 13:var Ca=Kr.memoizedState;if(Ca!==null)return Ca.dehydrated!==null?(Pd(Kr),Kr.flags|=128,null):(Xr&Kr.child.childLanes)!==0?Ly(os,Kr,Xr):(Pd(Kr),os=md(os,Kr,Xr),os!==null?os.sibling:null);Pd(Kr);break;case 19:var Pa=(os.flags&128)!==0;if(Ca=(Xr&Kr.childLanes)!==0,Ca||(Wm(os,Kr,Xr,!1),Ca=(Xr&Kr.childLanes)!==0),Pa){if(Ca)return Py(os,Kr,Xr);Kr.flags|=128}if(Pa=Kr.memoizedState,Pa!==null&&(Pa.rendering=null,Pa.tail=null,Pa.lastEffect=null),Il(Fu,Fu.current),Ca)break;return null;case 22:return Kr.lanes=0,Cy(os,Kr,Xr,Kr.pendingProps);case 24:Od(Kr,Hu,os.memoizedState.cache)}return md(os,Kr,Xr)}function Dy(os,Kr,Xr){if(os!==null)if(os.memoizedProps!==Kr.pendingProps)Gu=!0;else{if(!gg(os,Xr)&&(Kr.flags&128)===0)return Gu=!1,MR(os,Kr,Xr);Gu=(os.flags&131072)!==0}else Gu=!1,hu&&(Kr.flags&1048576)!==0&&pv(Kr,Kx,Kr.index);switch(Kr.lanes=0,Kr.tag){case 16:e:{var Ca=Kr.pendingProps;if(os=jm(Kr.elementType),Kr.type=os,typeof os=="function")bf(os)?(Ca=bm(os,Ca),Kr.tag=1,Kr=Oy(null,Kr,os,Ca,Xr)):(Kr.tag=0,Kr=cg(null,Kr,os,Ca,Xr));else{if(os!=null){var Pa=os.$$typeof;if(Pa===Ja){Kr.tag=11,Kr=wy(null,Kr,os,Ca,Xr);break e}else if(Pa===tl){Kr.tag=14,Kr=Ny(null,Kr,os,Ca,Xr);break e}}throw Kr=pl(os)||os,Error(is(306,Kr,""))}}return Kr;case 0:return cg(os,Kr,Kr.type,Kr.pendingProps,Xr);case 1:return Ca=Kr.type,Pa=bm(Ca,Kr.pendingProps),Oy(os,Kr,Ca,Pa,Xr);case 3:e:{if(cu(Kr,Kr.stateNode.containerInfo),os===null)throw Error(is(387));Ca=Kr.pendingProps;var Da=Kr.memoizedState;Pa=Da.element,Df(os,Kr),Xx(Kr,Ca,null,Xr);var za=Kr.memoizedState;if(Ca=za.cache,Od(Kr,Hu,Ca),Ca!==Da.cache&&Af(Kr,[Hu],Xr,!0),Wx(),Ca=za.element,Da.isDehydrated)if(Da={element:Ca,isDehydrated:!1,cache:za.cache},Kr.updateQueue.baseState=Da,Kr.memoizedState=Da,Kr.flags&256){Kr=Iy(os,Kr,Ca,Xr);break e}else if(Ca!==Pa){Pa=Ic(Error(is(424)),Kr),Gx(Pa),Kr=Iy(os,Kr,Ca,Xr);break e}else{switch(os=Kr.stateNode.containerInfo,os.nodeType){case 9:os=os.body;break;default:os=os.nodeName==="HTML"?os.ownerDocument.body:os}for($u=Mc(os.firstChild),ec=Kr,hu=!0,kd=null,Pc=!0,Xr=Cv(Kr,null,Ca,Xr),Kr.child=Xr;Xr;)Xr.flags=Xr.flags&-3|4096,Xr=Xr.sibling}else{if(hm(),Ca===Pa){Kr=md(os,Kr,Xr);break e}sc(os,Kr,Ca,Xr)}Kr=Kr.child}return Kr;case 26:return hp(os,Kr),os===null?(Xr=VE(Kr.type,null,Kr.pendingProps,null))?Kr.memoizedState=Xr:hu||(Xr=Kr.type,os=Kr.pendingProps,Ca=Op(nu.current).createElement(Xr),Ca[Xu]=Kr,Ca[xc]=os,nc(Ca,Xr,os),Qu(Ca),Kr.stateNode=Ca):Kr.memoizedState=VE(Kr.type,os.memoizedProps,Kr.pendingProps,os.memoizedState),null;case 27:return Ml(Kr),os===null&&hu&&(Ca=Kr.stateNode=KE(Kr.type,Kr.pendingProps,nu.current),ec=Kr,Pc=!0,Pa=$u,Kd(Kr.type)?(Yg=Pa,$u=Mc(Ca.firstChild)):$u=Pa),sc(os,Kr,Kr.pendingProps.children,Xr),hp(os,Kr),os===null&&(Kr.flags|=4194304),Kr.child;case 5:return os===null&&hu&&((Pa=Ca=$u)&&(Ca=h0(Ca,Kr.type,Kr.pendingProps,Pc),Ca!==null?(Kr.stateNode=Ca,ec=Kr,$u=Mc(Ca.firstChild),Pc=!1,Pa=!0):Pa=!1),Pa||Ad(Kr)),Ml(Kr),Pa=Kr.type,Da=Kr.pendingProps,za=os!==null?os.memoizedProps:null,Ca=Da.children,Kg(Pa,Da)?Ca=null:za!==null&&Kg(Pa,za)&&(Kr.flags|=32),Kr.memoizedState!==null&&(Pa=Hf(os,Kr,TR,null,null,Xr),vh._currentValue=Pa),hp(os,Kr),sc(os,Kr,Ca,Xr),Kr.child;case 6:return os===null&&hu&&((os=Xr=$u)&&(Xr=p0(Xr,Kr.pendingProps,Pc),Xr!==null?(Kr.stateNode=Xr,ec=Kr,$u=null,os=!0):os=!1),os||Ad(Kr)),null;case 13:return Ly(os,Kr,Xr);case 4:return cu(Kr,Kr.stateNode.containerInfo),Ca=Kr.pendingProps,os===null?Kr.child=ym(Kr,null,Ca,Xr):sc(os,Kr,Ca,Xr),Kr.child;case 11:return wy(os,Kr,Kr.type,Kr.pendingProps,Xr);case 7:return sc(os,Kr,Kr.pendingProps,Xr),Kr.child;case 8:return sc(os,Kr,Kr.pendingProps.children,Xr),Kr.child;case 12:return sc(os,Kr,Kr.pendingProps.children,Xr),Kr.child;case 10:return Ca=Kr.pendingProps,Od(Kr,Kr.type,Ca.value),sc(os,Kr,Ca.children,Xr),Kr.child;case 9:return Pa=Kr.type._context,Ca=Kr.pendingProps.children,fm(Kr),Pa=tc(Pa),Ca=Ca(Pa),Kr.flags|=1,sc(os,Kr,Ca,Xr),Kr.child;case 14:return Ny(os,Kr,Kr.type,Kr.pendingProps,Xr);case 15:return Sy(os,Kr,Kr.type,Kr.pendingProps,Xr);case 19:return Py(os,Kr,Xr);case 31:return DR(os,Kr,Xr);case 22:return Cy(os,Kr,Xr,Kr.pendingProps);case 24:return fm(Kr),Ca=tc(Hu),os===null?(Pa=Lf(),Pa===null&&(Pa=Au,Da=Of(),Pa.pooledCache=Da,Da.refCount++,Da!==null&&(Pa.pooledCacheLanes|=Xr),Pa=Da),Kr.memoizedState={parent:Ca,cache:Pa},Pf(Kr),Od(Kr,Hu,Pa)):((os.lanes&Xr)!==0&&(Df(os,Kr),Xx(Kr,null,null,Xr),Wx()),Pa=os.memoizedState,Da=Kr.memoizedState,Pa.parent!==Ca?(Pa={parent:Ca,cache:Ca},Kr.memoizedState=Pa,Kr.lanes===0&&(Kr.memoizedState=Kr.updateQueue.baseState=Pa),Od(Kr,Hu,Ca)):(Ca=Da.cache,Od(Kr,Hu,Ca),Ca!==Pa.cache&&Af(Kr,[Hu],Xr,!0))),sc(os,Kr,Kr.pendingProps.children,Xr),Kr.child;case 29:throw Kr.pendingProps}throw Error(is(156,Kr.tag))}function xd(os){os.flags|=4}function jg(os,Kr,Xr,Ca,Pa){if((Kr=(os.mode&32)!==0)&&(Kr=!1),Kr){if(os.flags|=16777216,(Pa&335544128)===Pa)if(os.stateNode.complete)os.flags|=8192;else if(cE())os.flags|=8192;else throw vm=Xh,$f}else os.flags&=-16777217}function My(os,Kr){if(Kr.type!=="stylesheet"||(Kr.state.loading&4)!==0)os.flags&=-16777217;else if(os.flags|=16777216,!XE(Kr))if(cE())os.flags|=8192;else throw vm=Xh,$f}function gp(os,Kr){Kr!==null&&(os.flags|=4),os.flags&16384&&(Kr=os.tag!==22?ku():536870912,os.lanes|=Kr,cx|=Kr)}function ih(os,Kr){if(!hu)switch(os.tailMode){case"hidden":Kr=os.tail;for(var Xr=null;Kr!==null;)Kr.alternate!==null&&(Xr=Kr),Kr=Kr.sibling;Xr===null?os.tail=null:Xr.sibling=null;break;case"collapsed":Xr=os.tail;for(var Ca=null;Xr!==null;)Xr.alternate!==null&&(Ca=Xr),Xr=Xr.sibling;Ca===null?Kr||os.tail===null?os.tail=null:os.tail.sibling=null:Ca.sibling=null}}function Pu(os){var Kr=os.alternate!==null&&os.alternate.child===os.child,Xr=0,Ca=0;if(Kr)for(var Pa=os.child;Pa!==null;)Xr|=Pa.lanes|Pa.childLanes,Ca|=Pa.subtreeFlags&65011712,Ca|=Pa.flags&65011712,Pa.return=os,Pa=Pa.sibling;else for(Pa=os.child;Pa!==null;)Xr|=Pa.lanes|Pa.childLanes,Ca|=Pa.subtreeFlags,Ca|=Pa.flags,Pa.return=os,Pa=Pa.sibling;return os.subtreeFlags|=Ca,os.childLanes=Xr,Kr}function BR(os,Kr,Xr){var Ca=Kr.pendingProps;switch(Nf(Kr),Kr.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Pu(Kr),null;case 1:return Pu(Kr),null;case 3:return Xr=Kr.stateNode,Ca=null,os!==null&&(Ca=os.memoizedState.cache),Kr.memoizedState.cache!==Ca&&(Kr.flags|=2048),ud(Hu),Al(),Xr.pendingContext&&(Xr.context=Xr.pendingContext,Xr.pendingContext=null),(os===null||os.child===null)&&(Jm(Kr)?xd(Kr):os===null||os.memoizedState.isDehydrated&&(Kr.flags&256)===0||(Kr.flags|=1024,Cf())),Pu(Kr),null;case 26:var Pa=Kr.type,Da=Kr.memoizedState;return os===null?(xd(Kr),Da!==null?(Pu(Kr),My(Kr,Da)):(Pu(Kr),jg(Kr,Pa,null,Ca,Xr))):Da?Da!==os.memoizedState?(xd(Kr),Pu(Kr),My(Kr,Da)):(Pu(Kr),Kr.flags&=-16777217):(os=os.memoizedProps,os!==Ca&&xd(Kr),Pu(Kr),jg(Kr,Pa,os,Ca,Xr)),null;case 27:if(Ql(Kr),Xr=nu.current,Pa=Kr.type,os!==null&&Kr.stateNode!=null)os.memoizedProps!==Ca&&xd(Kr);else{if(!Ca){if(Kr.stateNode===null)throw Error(is(166));return Pu(Kr),null}os=Fl.current,Jm(Kr)?gv(Kr):(os=KE(Pa,Ca,Xr),Kr.stateNode=os,xd(Kr))}return Pu(Kr),null;case 5:if(Ql(Kr),Pa=Kr.type,os!==null&&Kr.stateNode!=null)os.memoizedProps!==Ca&&xd(Kr);else{if(!Ca){if(Kr.stateNode===null)throw Error(is(166));return Pu(Kr),null}if(Da=Fl.current,Jm(Kr))gv(Kr);else{var za=Op(nu.current);switch(Da){case 1:Da=za.createElementNS("http://www.w3.org/2000/svg",Pa);break;case 2:Da=za.createElementNS("http://www.w3.org/1998/Math/MathML",Pa);break;default:switch(Pa){case"svg":Da=za.createElementNS("http://www.w3.org/2000/svg",Pa);break;case"math":Da=za.createElementNS("http://www.w3.org/1998/Math/MathML",Pa);break;case"script":Da=za.createElement("div"),Da.innerHTML="<script><\/script>",Da=Da.removeChild(Da.firstChild);break;case"select":Da=typeof Ca.is=="string"?za.createElement("select",{is:Ca.is}):za.createElement("select"),Ca.multiple?Da.multiple=!0:Ca.size&&(Da.size=Ca.size);break;default:Da=typeof Ca.is=="string"?za.createElement(Pa,{is:Ca.is}):za.createElement(Pa)}}Da[Xu]=Kr,Da[xc]=Ca;e:for(za=Kr.child;za!==null;){if(za.tag===5||za.tag===6)Da.appendChild(za.stateNode);else if(za.tag!==4&&za.tag!==27&&za.child!==null){za.child.return=za,za=za.child;continue}if(za===Kr)break e;for(;za.sibling===null;){if(za.return===null||za.return===Kr)break e;za=za.return}za.sibling.return=za.return,za=za.sibling}Kr.stateNode=Da;e:switch(nc(Da,Pa,Ca),Pa){case"button":case"input":case"select":case"textarea":Ca=!!Ca.autoFocus;break e;case"img":Ca=!0;break e;default:Ca=!1}Ca&&xd(Kr)}}return Pu(Kr),jg(Kr,Kr.type,os===null?null:os.memoizedProps,Kr.pendingProps,Xr),null;case 6:if(os&&Kr.stateNode!=null)os.memoizedProps!==Ca&&xd(Kr);else{if(typeof Ca!="string"&&Kr.stateNode===null)throw Error(is(166));if(os=nu.current,Jm(Kr)){if(os=Kr.stateNode,Xr=Kr.memoizedProps,Ca=null,Pa=ec,Pa!==null)switch(Pa.tag){case 27:case 5:Ca=Pa.memoizedProps}os[Xu]=Kr,os=!!(os.nodeValue===Xr||Ca!==null&&Ca.suppressHydrationWarning===!0||LE(os.nodeValue,Xr)),os||Ad(Kr,!0)}else os=Op(os).createTextNode(Ca),os[Xu]=Kr,Kr.stateNode=os}return Pu(Kr),null;case 31:if(Xr=Kr.memoizedState,os===null||os.memoizedState!==null){if(Ca=Jm(Kr),Xr!==null){if(os===null){if(!Ca)throw Error(is(318));if(os=Kr.memoizedState,os=os!==null?os.dehydrated:null,!os)throw Error(is(557));os[Xu]=Kr}else hm(),(Kr.flags&128)===0&&(Kr.memoizedState=null),Kr.flags|=4;Pu(Kr),os=!1}else Xr=Cf(),os!==null&&os.memoizedState!==null&&(os.memoizedState.hydrationErrors=Xr),os=!0;if(!os)return Kr.flags&256?(wc(Kr),Kr):(wc(Kr),null);if((Kr.flags&128)!==0)throw Error(is(558))}return Pu(Kr),null;case 13:if(Ca=Kr.memoizedState,os===null||os.memoizedState!==null&&os.memoizedState.dehydrated!==null){if(Pa=Jm(Kr),Ca!==null&&Ca.dehydrated!==null){if(os===null){if(!Pa)throw Error(is(318));if(Pa=Kr.memoizedState,Pa=Pa!==null?Pa.dehydrated:null,!Pa)throw Error(is(317));Pa[Xu]=Kr}else hm(),(Kr.flags&128)===0&&(Kr.memoizedState=null),Kr.flags|=4;Pu(Kr),Pa=!1}else Pa=Cf(),os!==null&&os.memoizedState!==null&&(os.memoizedState.hydrationErrors=Pa),Pa=!0;if(!Pa)return Kr.flags&256?(wc(Kr),Kr):(wc(Kr),null)}return wc(Kr),(Kr.flags&128)!==0?(Kr.lanes=Xr,Kr):(Xr=Ca!==null,os=os!==null&&os.memoizedState!==null,Xr&&(Ca=Kr.child,Pa=null,Ca.alternate!==null&&Ca.alternate.memoizedState!==null&&Ca.alternate.memoizedState.cachePool!==null&&(Pa=Ca.alternate.memoizedState.cachePool.pool),Da=null,Ca.memoizedState!==null&&Ca.memoizedState.cachePool!==null&&(Da=Ca.memoizedState.cachePool.pool),Da!==Pa&&(Ca.flags|=2048)),Xr!==os&&Xr&&(Kr.child.flags|=8192),gp(Kr,Kr.updateQueue),Pu(Kr),null);case 4:return Al(),os===null&&Ug(Kr.stateNode.containerInfo),Pu(Kr),null;case 10:return ud(Kr.type),Pu(Kr),null;case 19:if(Dl(Fu),Ca=Kr.memoizedState,Ca===null)return Pu(Kr),null;if(Pa=(Kr.flags&128)!==0,Da=Ca.rendering,Da===null)if(Pa)ih(Ca,!1);else{if(Uu!==0||os!==null&&(os.flags&128)!==0)for(os=Kr.child;os!==null;){if(Da=np(os),Da!==null){for(Kr.flags|=128,ih(Ca,!1),os=Da.updateQueue,Kr.updateQueue=os,gp(Kr,os),Kr.subtreeFlags=0,os=Xr,Xr=Kr.child;Xr!==null;)mv(Xr,os),Xr=Xr.sibling;return Il(Fu,Fu.current&1|2),hu&&od(Kr,Ca.treeForkCount),Kr.child}os=os.sibling}Ca.tail!==null&&Eu()>bp&&(Kr.flags|=128,Pa=!0,ih(Ca,!1),Kr.lanes=4194304)}else{if(!Pa)if(os=np(Da),os!==null){if(Kr.flags|=128,Pa=!0,os=os.updateQueue,Kr.updateQueue=os,gp(Kr,os),ih(Ca,!0),Ca.tail===null&&Ca.tailMode==="hidden"&&!Da.alternate&&!hu)return Pu(Kr),null}else 2*Eu()-Ca.renderingStartTime>bp&&Xr!==536870912&&(Kr.flags|=128,Pa=!0,ih(Ca,!1),Kr.lanes=4194304);Ca.isBackwards?(Da.sibling=Kr.child,Kr.child=Da):(os=Ca.last,os!==null?os.sibling=Da:Kr.child=Da,Ca.last=Da)}return Ca.tail!==null?(os=Ca.tail,Ca.rendering=os,Ca.tail=os.sibling,Ca.renderingStartTime=Eu(),os.sibling=null,Xr=Fu.current,Il(Fu,Pa?Xr&1|2:Xr&1),hu&&od(Kr,Ca.treeForkCount),os):(Pu(Kr),null);case 22:case 23:return wc(Kr),qf(),Ca=Kr.memoizedState!==null,os!==null?os.memoizedState!==null!==Ca&&(Kr.flags|=8192):Ca&&(Kr.flags|=8192),Ca?(Xr&536870912)!==0&&(Kr.flags&128)===0&&(Pu(Kr),Kr.subtreeFlags&6&&(Kr.flags|=8192)):Pu(Kr),Xr=Kr.updateQueue,Xr!==null&&gp(Kr,Xr.retryQueue),Xr=null,os!==null&&os.memoizedState!==null&&os.memoizedState.cachePool!==null&&(Xr=os.memoizedState.cachePool.pool),Ca=null,Kr.memoizedState!==null&&Kr.memoizedState.cachePool!==null&&(Ca=Kr.memoizedState.cachePool.pool),Ca!==Xr&&(Kr.flags|=2048),os!==null&&Dl(gm),null;case 24:return Xr=null,os!==null&&(Xr=os.memoizedState.cache),Kr.memoizedState.cache!==Xr&&(Kr.flags|=2048),ud(Hu),Pu(Kr),null;case 25:return null;case 30:return null}throw Error(is(156,Kr.tag))}function UR(os,Kr){switch(Nf(Kr),Kr.tag){case 1:return os=Kr.flags,os&65536?(Kr.flags=os&-65537|128,Kr):null;case 3:return ud(Hu),Al(),os=Kr.flags,(os&65536)!==0&&(os&128)===0?(Kr.flags=os&-65537|128,Kr):null;case 26:case 27:case 5:return Ql(Kr),null;case 31:if(Kr.memoizedState!==null){if(wc(Kr),Kr.alternate===null)throw Error(is(340));hm()}return os=Kr.flags,os&65536?(Kr.flags=os&-65537|128,Kr):null;case 13:if(wc(Kr),os=Kr.memoizedState,os!==null&&os.dehydrated!==null){if(Kr.alternate===null)throw Error(is(340));hm()}return os=Kr.flags,os&65536?(Kr.flags=os&-65537|128,Kr):null;case 19:return Dl(Fu),null;case 4:return Al(),null;case 10:return ud(Kr.type),null;case 22:case 23:return wc(Kr),qf(),os!==null&&Dl(gm),os=Kr.flags,os&65536?(Kr.flags=os&-65537|128,Kr):null;case 24:return ud(Hu),null;case 25:return null;default:return null}}function By(os,Kr){switch(Nf(Kr),Kr.tag){case 3:ud(Hu),Al();break;case 26:case 27:case 5:Ql(Kr);break;case 4:Al();break;case 31:Kr.memoizedState!==null&&wc(Kr);break;case 13:wc(Kr);break;case 19:Dl(Fu);break;case 10:ud(Kr.type);break;case 22:case 23:wc(Kr),qf(),os!==null&&Dl(gm);break;case 24:ud(Hu)}}function ah(os,Kr){try{var Xr=Kr.updateQueue,Ca=Xr!==null?Xr.lastEffect:null;if(Ca!==null){var Pa=Ca.next;Xr=Pa;do{if((Xr.tag&os)===os){Ca=void 0;var Da=Xr.create,za=Xr.inst;Ca=Da(),za.destroy=Ca}Xr=Xr.next}while(Xr!==Pa)}}catch(Qa){wu(Kr,Kr.return,Qa)}}function Md(os,Kr,Xr){try{var Ca=Kr.updateQueue,Pa=Ca!==null?Ca.lastEffect:null;if(Pa!==null){var Da=Pa.next;Ca=Da;do{if((Ca.tag&os)===os){var za=Ca.inst,Qa=za.destroy;if(Qa!==void 0){za.destroy=void 0,Pa=Kr;var Xa=Xr,xl=Qa;try{xl()}catch(wl){wu(Pa,Xa,wl)}}}Ca=Ca.next}while(Ca!==Da)}}catch(wl){wu(Kr,Kr.return,wl)}}function Uy(os){var Kr=os.updateQueue;if(Kr!==null){var Xr=os.stateNode;try{kv(Kr,Xr)}catch(Ca){wu(os,os.return,Ca)}}}function qy(os,Kr,Xr){Xr.props=bm(os.type,os.memoizedProps),Xr.state=os.memoizedState;try{Xr.componentWillUnmount()}catch(Ca){wu(os,Kr,Ca)}}function oh(os,Kr){try{var Xr=os.ref;if(Xr!==null){switch(os.tag){case 26:case 27:case 5:var Ca=os.stateNode;break;case 30:Ca=os.stateNode;break;default:Ca=os.stateNode}typeof Xr=="function"?os.refCleanup=Xr(Ca):Xr.current=Ca}}catch(Pa){wu(os,Kr,Pa)}}function Wc(os,Kr){var Xr=os.ref,Ca=os.refCleanup;if(Xr!==null)if(typeof Ca=="function")try{Ca()}catch(Pa){wu(os,Kr,Pa)}finally{os.refCleanup=null,os=os.alternate,os!=null&&(os.refCleanup=null)}else if(typeof Xr=="function")try{Xr(null)}catch(Pa){wu(os,Kr,Pa)}else Xr.current=null}function Fy(os){var Kr=os.type,Xr=os.memoizedProps,Ca=os.stateNode;try{e:switch(Kr){case"button":case"input":case"select":case"textarea":Xr.autoFocus&&Ca.focus();break e;case"img":Xr.src?Ca.src=Xr.src:Xr.srcSet&&(Ca.srcset=Xr.srcSet)}}catch(Pa){wu(os,os.return,Pa)}}function vg(os,Kr,Xr){try{var Ca=os.stateNode;l0(Ca,os.type,Xr,Kr),Ca[xc]=Kr}catch(Pa){wu(os,os.return,Pa)}}function zy(os){return os.tag===5||os.tag===3||os.tag===26||os.tag===27&&Kd(os.type)||os.tag===4}function yg(os){e:for(;;){for(;os.sibling===null;){if(os.return===null||zy(os.return))return null;os=os.return}for(os.sibling.return=os.return,os=os.sibling;os.tag!==5&&os.tag!==6&&os.tag!==18;){if(os.tag===27&&Kd(os.type)||os.flags&2||os.child===null||os.tag===4)continue e;os.child.return=os,os=os.child}if(!(os.flags&2))return os.stateNode}}function Eg(os,Kr,Xr){var Ca=os.tag;if(Ca===5||Ca===6)os=os.stateNode,Kr?(Xr.nodeType===9?Xr.body:Xr.nodeName==="HTML"?Xr.ownerDocument.body:Xr).insertBefore(os,Kr):(Kr=Xr.nodeType===9?Xr.body:Xr.nodeName==="HTML"?Xr.ownerDocument.body:Xr,Kr.appendChild(os),Xr=Xr._reactRootContainer,Xr!=null||Kr.onclick!==null||(Kr.onclick=rd));else if(Ca!==4&&(Ca===27&&Kd(os.type)&&(Xr=os.stateNode,Kr=null),os=os.child,os!==null))for(Eg(os,Kr,Xr),os=os.sibling;os!==null;)Eg(os,Kr,Xr),os=os.sibling}function jp(os,Kr,Xr){var Ca=os.tag;if(Ca===5||Ca===6)os=os.stateNode,Kr?Xr.insertBefore(os,Kr):Xr.appendChild(os);else if(Ca!==4&&(Ca===27&&Kd(os.type)&&(Xr=os.stateNode),os=os.child,os!==null))for(jp(os,Kr,Xr),os=os.sibling;os!==null;)jp(os,Kr,Xr),os=os.sibling}function Hy(os){var Kr=os.stateNode,Xr=os.memoizedProps;try{for(var Ca=os.type,Pa=Kr.attributes;Pa.length;)Kr.removeAttributeNode(Pa[0]);nc(Kr,Ca,Xr),Kr[Xu]=os,Kr[xc]=Xr}catch(Da){wu(os,os.return,Da)}}var hd=!1,Zu=!1,bg=!1,Ky=typeof WeakSet=="function"?WeakSet:Set,Yu=null;function qR(os,Kr){if(os=os.containerInfo,zg=Bp,os=nv(os),pf(os)){if("selectionStart"in os)var Xr={start:os.selectionStart,end:os.selectionEnd};else e:{Xr=(Xr=os.ownerDocument)&&Xr.defaultView||window;var Ca=Xr.getSelection&&Xr.getSelection();if(Ca&&Ca.rangeCount!==0){Xr=Ca.anchorNode;var Pa=Ca.anchorOffset,Da=Ca.focusNode;Ca=Ca.focusOffset;try{Xr.nodeType,Da.nodeType}catch{Xr=null;break e}var za=0,Qa=-1,Xa=-1,xl=0,wl=0,Cl=os,gl=null;t:for(;;){for(var vl;Cl!==Xr||Pa!==0&&Cl.nodeType!==3||(Qa=za+Pa),Cl!==Da||Ca!==0&&Cl.nodeType!==3||(Xa=za+Ca),Cl.nodeType===3&&(za+=Cl.nodeValue.length),(vl=Cl.firstChild)!==null;)gl=Cl,Cl=vl;for(;;){if(Cl===os)break t;if(gl===Xr&&++xl===Pa&&(Qa=za),gl===Da&&++wl===Ca&&(Xa=za),(vl=Cl.nextSibling)!==null)break;Cl=gl,gl=Cl.parentNode}Cl=vl}Xr=Qa===-1||Xa===-1?null:{start:Qa,end:Xa}}else Xr=null}Xr=Xr||{start:0,end:0}}else Xr=null;for(Hg={focusedElem:os,selectionRange:Xr},Bp=!1,Yu=Kr;Yu!==null;)if(Kr=Yu,os=Kr.child,(Kr.subtreeFlags&1028)!==0&&os!==null)os.return=Kr,Yu=os;else for(;Yu!==null;){switch(Kr=Yu,Da=Kr.alternate,os=Kr.flags,Kr.tag){case 0:if((os&4)!==0&&(os=Kr.updateQueue,os=os!==null?os.events:null,os!==null))for(Xr=0;Xr<os.length;Xr++)Pa=os[Xr],Pa.ref.impl=Pa.nextImpl;break;case 11:case 15:break;case 1:if((os&1024)!==0&&Da!==null){os=void 0,Xr=Kr,Pa=Da.memoizedProps,Da=Da.memoizedState,Ca=Xr.stateNode;try{var Kl=bm(Xr.type,Pa);os=Ca.getSnapshotBeforeUpdate(Kl,Da),Ca.__reactInternalSnapshotBeforeUpdate=os}catch(Wl){wu(Xr,Xr.return,Wl)}}break;case 3:if((os&1024)!==0){if(os=Kr.stateNode.containerInfo,Xr=os.nodeType,Xr===9)Zg(os);else if(Xr===1)switch(os.nodeName){case"HEAD":case"HTML":case"BODY":Zg(os);break;default:os.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((os&1024)!==0)throw Error(is(163))}if(os=Kr.sibling,os!==null){os.return=Kr.return,Yu=os;break}Yu=Kr.return}}function Gy(os,Kr,Xr){var Ca=Xr.flags;switch(Xr.tag){case 0:case 11:case 15:fd(os,Xr),Ca&4&&ah(5,Xr);break;case 1:if(fd(os,Xr),Ca&4)if(os=Xr.stateNode,Kr===null)try{os.componentDidMount()}catch(za){wu(Xr,Xr.return,za)}else{var Pa=bm(Xr.type,Kr.memoizedProps);Kr=Kr.memoizedState;try{os.componentDidUpdate(Pa,Kr,os.__reactInternalSnapshotBeforeUpdate)}catch(za){wu(Xr,Xr.return,za)}}Ca&64&&Uy(Xr),Ca&512&&oh(Xr,Xr.return);break;case 3:if(fd(os,Xr),Ca&64&&(os=Xr.updateQueue,os!==null)){if(Kr=null,Xr.child!==null)switch(Xr.child.tag){case 27:case 5:Kr=Xr.child.stateNode;break;case 1:Kr=Xr.child.stateNode}try{kv(os,Kr)}catch(za){wu(Xr,Xr.return,za)}}break;case 27:Kr===null&&Ca&4&&Hy(Xr);case 26:case 5:fd(os,Xr),Kr===null&&Ca&4&&Fy(Xr),Ca&512&&oh(Xr,Xr.return);break;case 12:fd(os,Xr);break;case 31:fd(os,Xr),Ca&4&&Qy(os,Xr);break;case 13:fd(os,Xr),Ca&4&&Yy(os,Xr),Ca&64&&(os=Xr.memoizedState,os!==null&&(os=os.dehydrated,os!==null&&(Xr=YR.bind(null,Xr),f0(os,Xr))));break;case 22:if(Ca=Xr.memoizedState!==null||hd,!Ca){Kr=Kr!==null&&Kr.memoizedState!==null||Zu,Pa=hd;var Da=Zu;hd=Ca,(Zu=Kr)&&!Da?gd(os,Xr,(Xr.subtreeFlags&8772)!==0):fd(os,Xr),hd=Pa,Zu=Da}break;case 30:break;default:fd(os,Xr)}}function Zy(os){var Kr=os.alternate;Kr!==null&&(os.alternate=null,Zy(Kr)),os.child=null,os.deletions=null,os.sibling=null,os.tag===5&&(Kr=os.stateNode,Kr!==null&&Jp(Kr)),os.stateNode=null,os.return=null,os.dependencies=null,os.memoizedProps=null,os.memoizedState=null,os.pendingProps=null,os.stateNode=null,os.updateQueue=null}var Du=null,pc=!1;function pd(os,Kr,Xr){for(Xr=Xr.child;Xr!==null;)Vy(os,Kr,Xr),Xr=Xr.sibling}function Vy(os,Kr,Xr){if(_l&&typeof _l.onCommitFiberUnmount=="function")try{_l.onCommitFiberUnmount(bl,Xr)}catch{}switch(Xr.tag){case 26:Zu||Wc(Xr,Kr),pd(os,Kr,Xr),Xr.memoizedState?Xr.memoizedState.count--:Xr.stateNode&&(Xr=Xr.stateNode,Xr.parentNode.removeChild(Xr));break;case 27:Zu||Wc(Xr,Kr);var Ca=Du,Pa=pc;Kd(Xr.type)&&(Du=Xr.stateNode,pc=!1),pd(os,Kr,Xr),fh(Xr.stateNode),Du=Ca,pc=Pa;break;case 5:Zu||Wc(Xr,Kr);case 6:if(Ca=Du,Pa=pc,Du=null,pd(os,Kr,Xr),Du=Ca,pc=Pa,Du!==null)if(pc)try{(Du.nodeType===9?Du.body:Du.nodeName==="HTML"?Du.ownerDocument.body:Du).removeChild(Xr.stateNode)}catch(Da){wu(Xr,Kr,Da)}else try{Du.removeChild(Xr.stateNode)}catch(Da){wu(Xr,Kr,Da)}break;case 18:Du!==null&&(pc?(os=Du,UE(os.nodeType===9?os.body:os.nodeName==="HTML"?os.ownerDocument.body:os,Xr.stateNode),jx(os)):UE(Du,Xr.stateNode));break;case 4:Ca=Du,Pa=pc,Du=Xr.stateNode.containerInfo,pc=!0,pd(os,Kr,Xr),Du=Ca,pc=Pa;break;case 0:case 11:case 14:case 15:Md(2,Xr,Kr),Zu||Md(4,Xr,Kr),pd(os,Kr,Xr);break;case 1:Zu||(Wc(Xr,Kr),Ca=Xr.stateNode,typeof Ca.componentWillUnmount=="function"&&qy(Xr,Kr,Ca)),pd(os,Kr,Xr);break;case 21:pd(os,Kr,Xr);break;case 22:Zu=(Ca=Zu)||Xr.memoizedState!==null,pd(os,Kr,Xr),Zu=Ca;break;default:pd(os,Kr,Xr)}}function Qy(os,Kr){if(Kr.memoizedState===null&&(os=Kr.alternate,os!==null&&(os=os.memoizedState,os!==null))){os=os.dehydrated;try{jx(os)}catch(Xr){wu(Kr,Kr.return,Xr)}}}function Yy(os,Kr){if(Kr.memoizedState===null&&(os=Kr.alternate,os!==null&&(os=os.memoizedState,os!==null&&(os=os.dehydrated,os!==null))))try{jx(os)}catch(Xr){wu(Kr,Kr.return,Xr)}}function FR(os){switch(os.tag){case 31:case 13:case 19:var Kr=os.stateNode;return Kr===null&&(Kr=os.stateNode=new Ky),Kr;case 22:return os=os.stateNode,Kr=os._retryCache,Kr===null&&(Kr=os._retryCache=new Ky),Kr;default:throw Error(is(435,os.tag))}}function vp(os,Kr){var Xr=FR(os);Kr.forEach(function(Ca){if(!Xr.has(Ca)){Xr.add(Ca);var Pa=JR.bind(null,os,Ca);Ca.then(Pa,Pa)}})}function fc(os,Kr){var Xr=Kr.deletions;if(Xr!==null)for(var Ca=0;Ca<Xr.length;Ca++){var Pa=Xr[Ca],Da=os,za=Kr,Qa=za;e:for(;Qa!==null;){switch(Qa.tag){case 27:if(Kd(Qa.type)){Du=Qa.stateNode,pc=!1;break e}break;case 5:Du=Qa.stateNode,pc=!1;break e;case 3:case 4:Du=Qa.stateNode.containerInfo,pc=!0;break e}Qa=Qa.return}if(Du===null)throw Error(is(160));Vy(Da,za,Pa),Du=null,pc=!1,Da=Pa.alternate,Da!==null&&(Da.return=null),Pa.return=null}if(Kr.subtreeFlags&13886)for(Kr=Kr.child;Kr!==null;)Jy(Kr,os),Kr=Kr.sibling}var Hc=null;function Jy(os,Kr){var Xr=os.alternate,Ca=os.flags;switch(os.tag){case 0:case 11:case 14:case 15:fc(Kr,os),gc(os),Ca&4&&(Md(3,os,os.return),ah(3,os),Md(5,os,os.return));break;case 1:fc(Kr,os),gc(os),Ca&512&&(Zu||Xr===null||Wc(Xr,Xr.return)),Ca&64&&hd&&(os=os.updateQueue,os!==null&&(Ca=os.callbacks,Ca!==null&&(Xr=os.shared.hiddenCallbacks,os.shared.hiddenCallbacks=Xr===null?Ca:Xr.concat(Ca))));break;case 26:var Pa=Hc;if(fc(Kr,os),gc(os),Ca&512&&(Zu||Xr===null||Wc(Xr,Xr.return)),Ca&4){var Da=Xr!==null?Xr.memoizedState:null;if(Ca=os.memoizedState,Xr===null)if(Ca===null)if(os.stateNode===null){e:{Ca=os.type,Xr=os.memoizedProps,Pa=Pa.ownerDocument||Pa;t:switch(Ca){case"title":Da=Pa.getElementsByTagName("title")[0],(!Da||Da[Lx]||Da[Xu]||Da.namespaceURI==="http://www.w3.org/2000/svg"||Da.hasAttribute("itemprop"))&&(Da=Pa.createElement(Ca),Pa.head.insertBefore(Da,Pa.querySelector("head > title"))),nc(Da,Ca,Xr),Da[Xu]=os,Qu(Da),Ca=Da;break e;case"link":var za=JE("link","href",Pa).get(Ca+(Xr.href||""));if(za){for(var Qa=0;Qa<za.length;Qa++)if(Da=za[Qa],Da.getAttribute("href")===(Xr.href==null||Xr.href===""?null:Xr.href)&&Da.getAttribute("rel")===(Xr.rel==null?null:Xr.rel)&&Da.getAttribute("title")===(Xr.title==null?null:Xr.title)&&Da.getAttribute("crossorigin")===(Xr.crossOrigin==null?null:Xr.crossOrigin)){za.splice(Qa,1);break t}}Da=Pa.createElement(Ca),nc(Da,Ca,Xr),Pa.head.appendChild(Da);break;case"meta":if(za=JE("meta","content",Pa).get(Ca+(Xr.content||""))){for(Qa=0;Qa<za.length;Qa++)if(Da=za[Qa],Da.getAttribute("content")===(Xr.content==null?null:""+Xr.content)&&Da.getAttribute("name")===(Xr.name==null?null:Xr.name)&&Da.getAttribute("property")===(Xr.property==null?null:Xr.property)&&Da.getAttribute("http-equiv")===(Xr.httpEquiv==null?null:Xr.httpEquiv)&&Da.getAttribute("charset")===(Xr.charSet==null?null:Xr.charSet)){za.splice(Qa,1);break t}}Da=Pa.createElement(Ca),nc(Da,Ca,Xr),Pa.head.appendChild(Da);break;default:throw Error(is(468,Ca))}Da[Xu]=os,Qu(Da),Ca=Da}os.stateNode=Ca}else WE(Pa,os.type,os.stateNode);else os.stateNode=YE(Pa,Ca,os.memoizedProps);else Da!==Ca?(Da===null?Xr.stateNode!==null&&(Xr=Xr.stateNode,Xr.parentNode.removeChild(Xr)):Da.count--,Ca===null?WE(Pa,os.type,os.stateNode):YE(Pa,Ca,os.memoizedProps)):Ca===null&&os.stateNode!==null&&vg(os,os.memoizedProps,Xr.memoizedProps)}break;case 27:fc(Kr,os),gc(os),Ca&512&&(Zu||Xr===null||Wc(Xr,Xr.return)),Xr!==null&&Ca&4&&vg(os,os.memoizedProps,Xr.memoizedProps);break;case 5:if(fc(Kr,os),gc(os),Ca&512&&(Zu||Xr===null||Wc(Xr,Xr.return)),os.flags&32){Pa=os.stateNode;try{qm(Pa,"")}catch(Kl){wu(os,os.return,Kl)}}Ca&4&&os.stateNode!=null&&(Pa=os.memoizedProps,vg(os,Pa,Xr!==null?Xr.memoizedProps:Pa)),Ca&1024&&(bg=!0);break;case 6:if(fc(Kr,os),gc(os),Ca&4){if(os.stateNode===null)throw Error(is(162));Ca=os.memoizedProps,Xr=os.stateNode;try{Xr.nodeValue=Ca}catch(Kl){wu(os,os.return,Kl)}}break;case 3:if($p=null,Pa=Hc,Hc=Ip(Kr.containerInfo),fc(Kr,os),Hc=Pa,gc(os),Ca&4&&Xr!==null&&Xr.memoizedState.isDehydrated)try{jx(Kr.containerInfo)}catch(Kl){wu(os,os.return,Kl)}bg&&(bg=!1,Wy(os));break;case 4:Ca=Hc,Hc=Ip(os.stateNode.containerInfo),fc(Kr,os),gc(os),Hc=Ca;break;case 12:fc(Kr,os),gc(os);break;case 31:fc(Kr,os),gc(os),Ca&4&&(Ca=os.updateQueue,Ca!==null&&(os.updateQueue=null,vp(os,Ca)));break;case 13:fc(Kr,os),gc(os),os.child.flags&8192&&os.memoizedState!==null!=(Xr!==null&&Xr.memoizedState!==null)&&(Ep=Eu()),Ca&4&&(Ca=os.updateQueue,Ca!==null&&(os.updateQueue=null,vp(os,Ca)));break;case 22:Pa=os.memoizedState!==null;var Xa=Xr!==null&&Xr.memoizedState!==null,xl=hd,wl=Zu;if(hd=xl||Pa,Zu=wl||Xa,fc(Kr,os),Zu=wl,hd=xl,gc(os),Ca&8192)e:for(Kr=os.stateNode,Kr._visibility=Pa?Kr._visibility&-2:Kr._visibility|1,Pa&&(Xr===null||Xa||hd||Zu||Rm(os)),Xr=null,Kr=os;;){if(Kr.tag===5||Kr.tag===26){if(Xr===null){Xa=Xr=Kr;try{if(Da=Xa.stateNode,Pa)za=Da.style,typeof za.setProperty=="function"?za.setProperty("display","none","important"):za.display="none";else{Qa=Xa.stateNode;var Cl=Xa.memoizedProps.style,gl=Cl!=null&&Cl.hasOwnProperty("display")?Cl.display:null;Qa.style.display=gl==null||typeof gl=="boolean"?"":(""+gl).trim()}}catch(Kl){wu(Xa,Xa.return,Kl)}}}else if(Kr.tag===6){if(Xr===null){Xa=Kr;try{Xa.stateNode.nodeValue=Pa?"":Xa.memoizedProps}catch(Kl){wu(Xa,Xa.return,Kl)}}}else if(Kr.tag===18){if(Xr===null){Xa=Kr;try{var vl=Xa.stateNode;Pa?qE(vl,!0):qE(Xa.stateNode,!1)}catch(Kl){wu(Xa,Xa.return,Kl)}}}else if((Kr.tag!==22&&Kr.tag!==23||Kr.memoizedState===null||Kr===os)&&Kr.child!==null){Kr.child.return=Kr,Kr=Kr.child;continue}if(Kr===os)break e;for(;Kr.sibling===null;){if(Kr.return===null||Kr.return===os)break e;Xr===Kr&&(Xr=null),Kr=Kr.return}Xr===Kr&&(Xr=null),Kr.sibling.return=Kr.return,Kr=Kr.sibling}Ca&4&&(Ca=os.updateQueue,Ca!==null&&(Xr=Ca.retryQueue,Xr!==null&&(Ca.retryQueue=null,vp(os,Xr))));break;case 19:fc(Kr,os),gc(os),Ca&4&&(Ca=os.updateQueue,Ca!==null&&(os.updateQueue=null,vp(os,Ca)));break;case 30:break;case 21:break;default:fc(Kr,os),gc(os)}}function gc(os){var Kr=os.flags;if(Kr&2){try{for(var Xr,Ca=os.return;Ca!==null;){if(zy(Ca)){Xr=Ca;break}Ca=Ca.return}if(Xr==null)throw Error(is(160));switch(Xr.tag){case 27:var Pa=Xr.stateNode,Da=yg(os);jp(os,Da,Pa);break;case 5:var za=Xr.stateNode;Xr.flags&32&&(qm(za,""),Xr.flags&=-33);var Qa=yg(os);jp(os,Qa,za);break;case 3:case 4:var Xa=Xr.stateNode.containerInfo,xl=yg(os);Eg(os,xl,Xa);break;default:throw Error(is(161))}}catch(wl){wu(os,os.return,wl)}os.flags&=-3}Kr&4096&&(os.flags&=-4097)}function Wy(os){if(os.subtreeFlags&1024)for(os=os.child;os!==null;){var Kr=os;Wy(Kr),Kr.tag===5&&Kr.flags&1024&&Kr.stateNode.reset(),os=os.sibling}}function fd(os,Kr){if(Kr.subtreeFlags&8772)for(Kr=Kr.child;Kr!==null;)Gy(os,Kr.alternate,Kr),Kr=Kr.sibling}function Rm(os){for(os=os.child;os!==null;){var Kr=os;switch(Kr.tag){case 0:case 11:case 14:case 15:Md(4,Kr,Kr.return),Rm(Kr);break;case 1:Wc(Kr,Kr.return);var Xr=Kr.stateNode;typeof Xr.componentWillUnmount=="function"&&qy(Kr,Kr.return,Xr),Rm(Kr);break;case 27:fh(Kr.stateNode);case 26:case 5:Wc(Kr,Kr.return),Rm(Kr);break;case 22:Kr.memoizedState===null&&Rm(Kr);break;case 30:Rm(Kr);break;default:Rm(Kr)}os=os.sibling}}function gd(os,Kr,Xr){for(Xr=Xr&&(Kr.subtreeFlags&8772)!==0,Kr=Kr.child;Kr!==null;){var Ca=Kr.alternate,Pa=os,Da=Kr,za=Da.flags;switch(Da.tag){case 0:case 11:case 15:gd(Pa,Da,Xr),ah(4,Da);break;case 1:if(gd(Pa,Da,Xr),Ca=Da,Pa=Ca.stateNode,typeof Pa.componentDidMount=="function")try{Pa.componentDidMount()}catch(xl){wu(Ca,Ca.return,xl)}if(Ca=Da,Pa=Ca.updateQueue,Pa!==null){var Qa=Ca.stateNode;try{var Xa=Pa.shared.hiddenCallbacks;if(Xa!==null)for(Pa.shared.hiddenCallbacks=null,Pa=0;Pa<Xa.length;Pa++)Tv(Xa[Pa],Qa)}catch(xl){wu(Ca,Ca.return,xl)}}Xr&&za&64&&Uy(Da),oh(Da,Da.return);break;case 27:Hy(Da);case 26:case 5:gd(Pa,Da,Xr),Xr&&Ca===null&&za&4&&Fy(Da),oh(Da,Da.return);break;case 12:gd(Pa,Da,Xr);break;case 31:gd(Pa,Da,Xr),Xr&&za&4&&Qy(Pa,Da);break;case 13:gd(Pa,Da,Xr),Xr&&za&4&&Yy(Pa,Da);break;case 22:Da.memoizedState===null&&gd(Pa,Da,Xr),oh(Da,Da.return);break;case 30:break;default:gd(Pa,Da,Xr)}Kr=Kr.sibling}}function Rg(os,Kr){var Xr=null;os!==null&&os.memoizedState!==null&&os.memoizedState.cachePool!==null&&(Xr=os.memoizedState.cachePool.pool),os=null,Kr.memoizedState!==null&&Kr.memoizedState.cachePool!==null&&(os=Kr.memoizedState.cachePool.pool),os!==Xr&&(os!=null&&os.refCount++,Xr!=null&&Zx(Xr))}function _g(os,Kr){os=null,Kr.alternate!==null&&(os=Kr.alternate.memoizedState.cache),Kr=Kr.memoizedState.cache,Kr!==os&&(Kr.refCount++,os!=null&&Zx(os))}function Kc(os,Kr,Xr,Ca){if(Kr.subtreeFlags&10256)for(Kr=Kr.child;Kr!==null;)Xy(os,Kr,Xr,Ca),Kr=Kr.sibling}function Xy(os,Kr,Xr,Ca){var Pa=Kr.flags;switch(Kr.tag){case 0:case 11:case 15:Kc(os,Kr,Xr,Ca),Pa&2048&&ah(9,Kr);break;case 1:Kc(os,Kr,Xr,Ca);break;case 3:Kc(os,Kr,Xr,Ca),Pa&2048&&(os=null,Kr.alternate!==null&&(os=Kr.alternate.memoizedState.cache),Kr=Kr.memoizedState.cache,Kr!==os&&(Kr.refCount++,os!=null&&Zx(os)));break;case 12:if(Pa&2048){Kc(os,Kr,Xr,Ca),os=Kr.stateNode;try{var Da=Kr.memoizedProps,za=Da.id,Qa=Da.onPostCommit;typeof Qa=="function"&&Qa(za,Kr.alternate===null?"mount":"update",os.passiveEffectDuration,-0)}catch(Xa){wu(Kr,Kr.return,Xa)}}else Kc(os,Kr,Xr,Ca);break;case 31:Kc(os,Kr,Xr,Ca);break;case 13:Kc(os,Kr,Xr,Ca);break;case 23:break;case 22:Da=Kr.stateNode,za=Kr.alternate,Kr.memoizedState!==null?Da._visibility&2?Kc(os,Kr,Xr,Ca):lh(os,Kr):Da._visibility&2?Kc(os,Kr,Xr,Ca):(Da._visibility|=2,ox(os,Kr,Xr,Ca,(Kr.subtreeFlags&10256)!==0||!1)),Pa&2048&&Rg(za,Kr);break;case 24:Kc(os,Kr,Xr,Ca),Pa&2048&&_g(Kr.alternate,Kr);break;default:Kc(os,Kr,Xr,Ca)}}function ox(os,Kr,Xr,Ca,Pa){for(Pa=Pa&&((Kr.subtreeFlags&10256)!==0||!1),Kr=Kr.child;Kr!==null;){var Da=os,za=Kr,Qa=Xr,Xa=Ca,xl=za.flags;switch(za.tag){case 0:case 11:case 15:ox(Da,za,Qa,Xa,Pa),ah(8,za);break;case 23:break;case 22:var wl=za.stateNode;za.memoizedState!==null?wl._visibility&2?ox(Da,za,Qa,Xa,Pa):lh(Da,za):(wl._visibility|=2,ox(Da,za,Qa,Xa,Pa)),Pa&&xl&2048&&Rg(za.alternate,za);break;case 24:ox(Da,za,Qa,Xa,Pa),Pa&&xl&2048&&_g(za.alternate,za);break;default:ox(Da,za,Qa,Xa,Pa)}Kr=Kr.sibling}}function lh(os,Kr){if(Kr.subtreeFlags&10256)for(Kr=Kr.child;Kr!==null;){var Xr=os,Ca=Kr,Pa=Ca.flags;switch(Ca.tag){case 22:lh(Xr,Ca),Pa&2048&&Rg(Ca.alternate,Ca);break;case 24:lh(Xr,Ca),Pa&2048&&_g(Ca.alternate,Ca);break;default:lh(Xr,Ca)}Kr=Kr.sibling}}var uh=8192;function lx(os,Kr,Xr){if(os.subtreeFlags&uh)for(os=os.child;os!==null;)eE(os,Kr,Xr),os=os.sibling}function eE(os,Kr,Xr){switch(os.tag){case 26:lx(os,Kr,Xr),os.flags&uh&&os.memoizedState!==null&&C0(Xr,Hc,os.memoizedState,os.memoizedProps);break;case 5:lx(os,Kr,Xr);break;case 3:case 4:var Ca=Hc;Hc=Ip(os.stateNode.containerInfo),lx(os,Kr,Xr),Hc=Ca;break;case 22:os.memoizedState===null&&(Ca=os.alternate,Ca!==null&&Ca.memoizedState!==null?(Ca=uh,uh=16777216,lx(os,Kr,Xr),uh=Ca):lx(os,Kr,Xr));break;default:lx(os,Kr,Xr)}}function tE(os){var Kr=os.alternate;if(Kr!==null&&(os=Kr.child,os!==null)){Kr.child=null;do Kr=os.sibling,os.sibling=null,os=Kr;while(os!==null)}}function ch(os){var Kr=os.deletions;if((os.flags&16)!==0){if(Kr!==null)for(var Xr=0;Xr<Kr.length;Xr++){var Ca=Kr[Xr];Yu=Ca,nE(Ca,os)}tE(os)}if(os.subtreeFlags&10256)for(os=os.child;os!==null;)sE(os),os=os.sibling}function sE(os){switch(os.tag){case 0:case 11:case 15:ch(os),os.flags&2048&&Md(9,os,os.return);break;case 3:ch(os);break;case 12:ch(os);break;case 22:var Kr=os.stateNode;os.memoizedState!==null&&Kr._visibility&2&&(os.return===null||os.return.tag!==13)?(Kr._visibility&=-3,yp(os)):ch(os);break;default:ch(os)}}function yp(os){var Kr=os.deletions;if((os.flags&16)!==0){if(Kr!==null)for(var Xr=0;Xr<Kr.length;Xr++){var Ca=Kr[Xr];Yu=Ca,nE(Ca,os)}tE(os)}for(os=os.child;os!==null;){switch(Kr=os,Kr.tag){case 0:case 11:case 15:Md(8,Kr,Kr.return),yp(Kr);break;case 22:Xr=Kr.stateNode,Xr._visibility&2&&(Xr._visibility&=-3,yp(Kr));break;default:yp(Kr)}os=os.sibling}}function nE(os,Kr){for(;Yu!==null;){var Xr=Yu;switch(Xr.tag){case 0:case 11:case 15:Md(8,Xr,Kr);break;case 23:case 22:if(Xr.memoizedState!==null&&Xr.memoizedState.cachePool!==null){var Ca=Xr.memoizedState.cachePool.pool;Ca!=null&&Ca.refCount++}break;case 24:Zx(Xr.memoizedState.cache)}if(Ca=Xr.child,Ca!==null)Ca.return=Xr,Yu=Ca;else e:for(Xr=os;Yu!==null;){Ca=Yu;var Pa=Ca.sibling,Da=Ca.return;if(Zy(Ca),Ca===Xr){Yu=null;break e}if(Pa!==null){Pa.return=Da,Yu=Pa;break e}Yu=Da}}}var zR={getCacheForType:function(os){var Kr=tc(Hu),Xr=Kr.data.get(os);return Xr===void 0&&(Xr=os(),Kr.data.set(os,Xr)),Xr},cacheSignal:function(){return tc(Hu).controller.signal}},HR=typeof WeakMap=="function"?WeakMap:Map,vu=0,Au=null,lu=null,du=0,_u=0,Nc=null,Bd=!1,ux=!1,wg=!1,jd=0,Uu=0,Ud=0,_m=0,Ng=0,Sc=0,cx=0,dh=null,jc=null,Sg=!1,Ep=0,rE=0,bp=1/0,Rp=null,qd=null,Vu=0,Fd=null,dx=null,vd=0,Cg=0,Tg=null,iE=null,mh=0,kg=null;function Cc(){return(vu&2)!==0&&du!==0?du&-du:ul.T!==null?Pg():Ej()}function aE(){if(Sc===0)if((du&536870912)===0||hu){var os=su;su<<=1,(su&3932160)===0&&(su=262144),Sc=os}else Sc=536870912;return os=_c.current,os!==null&&(os.flags|=32),Sc}function vc(os,Kr,Xr){(os===Au&&(_u===2||_u===9)||os.cancelPendingCommit!==null)&&(mx(os,0),zd(os,du,Sc,!1)),Wu(os,Xr),((vu&2)===0||os!==Au)&&(os===Au&&((vu&2)===0&&(_m|=Xr),Uu===4&&zd(os,du,Sc,!1)),Xc(os))}function oE(os,Kr,Xr){if((vu&6)!==0)throw Error(is(327));var Ca=!Xr&&(Kr&127)===0&&(Kr&os.expiredLanes)===0||tu(os,Kr),Pa=Ca?ZR(os,Kr):Og(os,Kr,!0),Da=Ca;do{if(Pa===0){ux&&!Ca&&zd(os,Kr,0,!1);break}else{if(Xr=os.current.alternate,Da&&!KR(Xr)){Pa=Og(os,Kr,!1),Da=!1;continue}if(Pa===2){if(Da=Kr,os.errorRecoveryDisabledLanes&Da)var za=0;else za=os.pendingLanes&-536870913,za=za!==0?za:za&536870912?536870912:0;if(za!==0){Kr=za;e:{var Qa=os;Pa=dh;var Xa=Qa.current.memoizedState.isDehydrated;if(Xa&&(mx(Qa,za).flags|=256),za=Og(Qa,za,!1),za!==2){if(wg&&!Xa){Qa.errorRecoveryDisabledLanes|=Da,_m|=Da,Pa=4;break e}Da=jc,jc=Pa,Da!==null&&(jc===null?jc=Da:jc.push.apply(jc,Da))}Pa=za}if(Da=!1,Pa!==2)continue}}if(Pa===1){mx(os,0),zd(os,Kr,0,!0);break}e:{switch(Ca=os,Da=Pa,Da){case 0:case 1:throw Error(is(345));case 4:if((Kr&4194048)!==Kr)break;case 6:zd(Ca,Kr,Sc,!Bd);break e;case 2:jc=null;break;case 3:case 5:break;default:throw Error(is(329))}if((Kr&62914560)===Kr&&(Pa=Ep+300-Eu(),10<Pa)){if(zd(Ca,Kr,Sc,!Bd),Lm(Ca,0,!0)!==0)break e;vd=Kr,Ca.timeoutHandle=ME(lE.bind(null,Ca,Xr,jc,Rp,Sg,Kr,Sc,_m,cx,Bd,Da,"Throttled",-0,0),Pa);break e}lE(Ca,Xr,jc,Rp,Sg,Kr,Sc,_m,cx,Bd,Da,null,-0,0)}}break}while(!0);Xc(os)}function lE(os,Kr,Xr,Ca,Pa,Da,za,Qa,Xa,xl,wl,Cl,gl,vl){if(os.timeoutHandle=-1,Cl=Kr.subtreeFlags,Cl&8192||(Cl&16785408)===16785408){Cl={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:rd},eE(Kr,Da,Cl);var Kl=(Da&62914560)===Da?Ep-Eu():(Da&4194048)===Da?rE-Eu():0;if(Kl=T0(Cl,Kl),Kl!==null){vd=Da,os.cancelPendingCommit=Kl(fE.bind(null,os,Kr,Da,Xr,Ca,Pa,za,Qa,Xa,wl,Cl,null,gl,vl)),zd(os,Da,za,!xl);return}}fE(os,Kr,Da,Xr,Ca,Pa,za,Qa,Xa)}function KR(os){for(var Kr=os;;){var Xr=Kr.tag;if((Xr===0||Xr===11||Xr===15)&&Kr.flags&16384&&(Xr=Kr.updateQueue,Xr!==null&&(Xr=Xr.stores,Xr!==null)))for(var Ca=0;Ca<Xr.length;Ca++){var Pa=Xr[Ca],Da=Pa.getSnapshot;Pa=Pa.value;try{if(!bc(Da(),Pa))return!1}catch{return!1}}if(Xr=Kr.child,Kr.subtreeFlags&16384&&Xr!==null)Xr.return=Kr,Kr=Xr;else{if(Kr===os)break;for(;Kr.sibling===null;){if(Kr.return===null||Kr.return===os)return!0;Kr=Kr.return}Kr.sibling.return=Kr.return,Kr=Kr.sibling}}return!0}function zd(os,Kr,Xr,Ca){Kr&=~Ng,Kr&=~_m,os.suspendedLanes|=Kr,os.pingedLanes&=~Kr,Ca&&(os.warmLanes|=Kr),Ca=os.expirationTimes;for(var Pa=Kr;0<Pa;){var Da=31-Rl(Pa),za=1<<Da;Ca[Da]=-1,Pa&=~za}Xr!==0&&Qc(os,Xr,Kr)}function _p(){return(vu&6)===0?(xh(0),!1):!0}function Ag(){if(lu!==null){if(_u===0)var os=lu.return;else os=lu,ld=pm=null,Zf(os),sx=null,Qx=0,os=lu;for(;os!==null;)By(os.alternate,os),os=os.return;lu=null}}function mx(os,Kr){var Xr=os.timeoutHandle;Xr!==-1&&(os.timeoutHandle=-1,d0(Xr)),Xr=os.cancelPendingCommit,Xr!==null&&(os.cancelPendingCommit=null,Xr()),vd=0,Ag(),Au=os,lu=Xr=ad(os.current,null),du=Kr,_u=0,Nc=null,Bd=!1,ux=tu(os,Kr),wg=!1,cx=Sc=Ng=_m=Ud=Uu=0,jc=dh=null,Sg=!1,(Kr&8)!==0&&(Kr|=Kr&32);var Ca=os.entangledLanes;if(Ca!==0)for(os=os.entanglements,Ca&=Kr;0<Ca;){var Pa=31-Rl(Ca),Da=1<<Pa;Kr|=os[Pa],Ca&=~Da}return jd=Kr,Hh(),Xr}function uE(os,Kr){iu=null,ul.H=nh,Kr===tx||Kr===Wh?(Kr=wv(),_u=3):Kr===$f?(Kr=wv(),_u=4):_u=Kr===ug?8:Kr!==null&&typeof Kr=="object"&&typeof Kr.then=="function"?6:1,Nc=Kr,lu===null&&(Uu=1,mp(os,Ic(Kr,os.current)))}function cE(){var os=_c.current;return os===null?!0:(du&4194048)===du?Dc===null:(du&62914560)===du||(du&536870912)!==0?os===Dc:!1}function dE(){var os=ul.H;return ul.H=nh,os===null?nh:os}function mE(){var os=ul.A;return ul.A=zR,os}function wp(){Uu=4,Bd||(du&4194048)!==du&&_c.current!==null||(ux=!0),(Ud&134217727)===0&&(_m&134217727)===0||Au===null||zd(Au,du,Sc,!1)}function Og(os,Kr,Xr){var Ca=vu;vu|=2;var Pa=dE(),Da=mE();(Au!==os||du!==Kr)&&(Rp=null,mx(os,Kr)),Kr=!1;var za=Uu;e:do try{if(_u!==0&&lu!==null){var Qa=lu,Xa=Nc;switch(_u){case 8:Ag(),za=6;break e;case 3:case 2:case 9:case 6:_c.current===null&&(Kr=!0);var xl=_u;if(_u=0,Nc=null,xx(os,Qa,Xa,xl),Xr&&ux){za=0;break e}break;default:xl=_u,_u=0,Nc=null,xx(os,Qa,Xa,xl)}}GR(),za=Uu;break}catch(wl){uE(os,wl)}while(!0);return Kr&&os.shellSuspendCounter++,ld=pm=null,vu=Ca,ul.H=Pa,ul.A=Da,lu===null&&(Au=null,du=0,Hh()),za}function GR(){for(;lu!==null;)xE(lu)}function ZR(os,Kr){var Xr=vu;vu|=2;var Ca=dE(),Pa=mE();Au!==os||du!==Kr?(Rp=null,bp=Eu()+500,mx(os,Kr)):ux=tu(os,Kr);e:do try{if(_u!==0&&lu!==null){Kr=lu;var Da=Nc;t:switch(_u){case 1:_u=0,Nc=null,xx(os,Kr,Da,1);break;case 2:case 9:if(Rv(Da)){_u=0,Nc=null,hE(Kr);break}Kr=function(){_u!==2&&_u!==9||Au!==os||(_u=7),Xc(os)},Da.then(Kr,Kr);break e;case 3:_u=7;break e;case 4:_u=5;break e;case 7:Rv(Da)?(_u=0,Nc=null,hE(Kr)):(_u=0,Nc=null,xx(os,Kr,Da,7));break;case 5:var za=null;switch(lu.tag){case 26:za=lu.memoizedState;case 5:case 27:var Qa=lu;if(za?XE(za):Qa.stateNode.complete){_u=0,Nc=null;var Xa=Qa.sibling;if(Xa!==null)lu=Xa;else{var xl=Qa.return;xl!==null?(lu=xl,Np(xl)):lu=null}break t}}_u=0,Nc=null,xx(os,Kr,Da,5);break;case 6:_u=0,Nc=null,xx(os,Kr,Da,6);break;case 8:Ag(),Uu=6;break e;default:throw Error(is(462))}}VR();break}catch(wl){uE(os,wl)}while(!0);return ld=pm=null,ul.H=Ca,ul.A=Pa,vu=Xr,lu!==null?0:(Au=null,du=0,Hh(),Uu)}function VR(){for(;lu!==null&&!lc();)xE(lu)}function xE(os){var Kr=Dy(os.alternate,os,jd);os.memoizedProps=os.pendingProps,Kr===null?Np(os):lu=Kr}function hE(os){var Kr=os,Xr=Kr.alternate;switch(Kr.tag){case 15:case 0:Kr=Ay(Xr,Kr,Kr.pendingProps,Kr.type,void 0,du);break;case 11:Kr=Ay(Xr,Kr,Kr.pendingProps,Kr.type.render,Kr.ref,du);break;case 5:Zf(Kr);default:By(Xr,Kr),Kr=lu=mv(Kr,jd),Kr=Dy(Xr,Kr,jd)}os.memoizedProps=os.pendingProps,Kr===null?Np(os):lu=Kr}function xx(os,Kr,Xr,Ca){ld=pm=null,Zf(Kr),sx=null,Qx=0;var Pa=Kr.return;try{if(PR(os,Pa,Kr,Xr,du)){Uu=1,mp(os,Ic(Xr,os.current)),lu=null;return}}catch(Da){if(Pa!==null)throw lu=Pa,Da;Uu=1,mp(os,Ic(Xr,os.current)),lu=null;return}Kr.flags&32768?(hu||Ca===1?os=!0:ux||(du&536870912)!==0?os=!1:(Bd=os=!0,(Ca===2||Ca===9||Ca===3||Ca===6)&&(Ca=_c.current,Ca!==null&&Ca.tag===13&&(Ca.flags|=16384))),pE(Kr,os)):Np(Kr)}function Np(os){var Kr=os;do{if((Kr.flags&32768)!==0){pE(Kr,Bd);return}os=Kr.return;var Xr=BR(Kr.alternate,Kr,jd);if(Xr!==null){lu=Xr;return}if(Kr=Kr.sibling,Kr!==null){lu=Kr;return}lu=Kr=os}while(Kr!==null);Uu===0&&(Uu=5)}function pE(os,Kr){do{var Xr=UR(os.alternate,os);if(Xr!==null){Xr.flags&=32767,lu=Xr;return}if(Xr=os.return,Xr!==null&&(Xr.flags|=32768,Xr.subtreeFlags=0,Xr.deletions=null),!Kr&&(os=os.sibling,os!==null)){lu=os;return}lu=os=Xr}while(os!==null);Uu=6,lu=null}function fE(os,Kr,Xr,Ca,Pa,Da,za,Qa,Xa){os.cancelPendingCommit=null;do Sp();while(Vu!==0);if((vu&6)!==0)throw Error(is(327));if(Kr!==null){if(Kr===os.current)throw Error(is(177));if(Da=Kr.lanes|Kr.childLanes,Da|=yf,Vc(os,Xr,Da,za,Qa,Xa),os===Au&&(lu=Au=null,du=0),dx=Kr,Fd=os,vd=Xr,Cg=Da,Tg=Pa,iE=Ca,(Kr.subtreeFlags&10256)!==0||(Kr.flags&10256)!==0?(os.callbackNode=null,os.callbackPriority=0,WR($l,function(){return EE(),null})):(os.callbackNode=null,os.callbackPriority=0),Ca=(Kr.flags&13878)!==0,(Kr.subtreeFlags&13878)!==0||Ca){Ca=ul.T,ul.T=null,Pa=hl.p,hl.p=2,za=vu,vu|=4;try{qR(os,Kr,Xr)}finally{vu=za,hl.p=Pa,ul.T=Ca}}Vu=1,gE(),jE(),vE()}}function gE(){if(Vu===1){Vu=0;var os=Fd,Kr=dx,Xr=(Kr.flags&13878)!==0;if((Kr.subtreeFlags&13878)!==0||Xr){Xr=ul.T,ul.T=null;var Ca=hl.p;hl.p=2;var Pa=vu;vu|=4;try{Jy(Kr,os);var Da=Hg,za=nv(os.containerInfo),Qa=Da.focusedElem,Xa=Da.selectionRange;if(za!==Qa&&Qa&&Qa.ownerDocument&&sv(Qa.ownerDocument.documentElement,Qa)){if(Xa!==null&&pf(Qa)){var xl=Xa.start,wl=Xa.end;if(wl===void 0&&(wl=xl),"selectionStart"in Qa)Qa.selectionStart=xl,Qa.selectionEnd=Math.min(wl,Qa.value.length);else{var Cl=Qa.ownerDocument||document,gl=Cl&&Cl.defaultView||window;if(gl.getSelection){var vl=gl.getSelection(),Kl=Qa.textContent.length,Wl=Math.min(Xa.start,Kl),Cu=Xa.end===void 0?Wl:Math.min(Xa.end,Kl);!vl.extend&&Wl>Cu&&(za=Cu,Cu=Wl,Wl=za);var il=tv(Qa,Wl),sl=tv(Qa,Cu);if(il&&sl&&(vl.rangeCount!==1||vl.anchorNode!==il.node||vl.anchorOffset!==il.offset||vl.focusNode!==sl.node||vl.focusOffset!==sl.offset)){var ml=Cl.createRange();ml.setStart(il.node,il.offset),vl.removeAllRanges(),Wl>Cu?(vl.addRange(ml),vl.extend(sl.node,sl.offset)):(ml.setEnd(sl.node,sl.offset),vl.addRange(ml))}}}}for(Cl=[],vl=Qa;vl=vl.parentNode;)vl.nodeType===1&&Cl.push({element:vl,left:vl.scrollLeft,top:vl.scrollTop});for(typeof Qa.focus=="function"&&Qa.focus(),Qa=0;Qa<Cl.length;Qa++){var Sl=Cl[Qa];Sl.element.scrollLeft=Sl.left,Sl.element.scrollTop=Sl.top}}Bp=!!zg,Hg=zg=null}finally{vu=Pa,hl.p=Ca,ul.T=Xr}}os.current=Kr,Vu=2}}function jE(){if(Vu===2){Vu=0;var os=Fd,Kr=dx,Xr=(Kr.flags&8772)!==0;if((Kr.subtreeFlags&8772)!==0||Xr){Xr=ul.T,ul.T=null;var Ca=hl.p;hl.p=2;var Pa=vu;vu|=4;try{Gy(os,Kr.alternate,Kr)}finally{vu=Pa,hl.p=Ca,ul.T=Xr}}Vu=3}}function vE(){if(Vu===4||Vu===3){Vu=0,Tu();var os=Fd,Kr=dx,Xr=vd,Ca=iE;(Kr.subtreeFlags&10256)!==0||(Kr.flags&10256)!==0?Vu=5:(Vu=0,dx=Fd=null,yE(os,os.pendingLanes));var Pa=os.pendingLanes;if(Pa===0&&(qd=null),Qp(Xr),Kr=Kr.stateNode,_l&&typeof _l.onCommitFiberRoot=="function")try{_l.onCommitFiberRoot(bl,Kr,void 0,(Kr.current.flags&128)===128)}catch{}if(Ca!==null){Kr=ul.T,Pa=hl.p,hl.p=2,ul.T=null;try{for(var Da=os.onRecoverableError,za=0;za<Ca.length;za++){var Qa=Ca[za];Da(Qa.value,{componentStack:Qa.stack})}}finally{ul.T=Kr,hl.p=Pa}}(vd&3)!==0&&Sp(),Xc(os),Pa=os.pendingLanes,(Xr&261930)!==0&&(Pa&42)!==0?os===kg?mh++:(mh=0,kg=os):mh=0,xh(0)}}function yE(os,Kr){(os.pooledCacheLanes&=Kr)===0&&(Kr=os.pooledCache,Kr!=null&&(os.pooledCache=null,Zx(Kr)))}function Sp(){return gE(),jE(),vE(),EE()}function EE(){if(Vu!==5)return!1;var os=Fd,Kr=Cg;Cg=0;var Xr=Qp(vd),Ca=ul.T,Pa=hl.p;try{hl.p=32>Xr?32:Xr,ul.T=null,Xr=Tg,Tg=null;var Da=Fd,za=vd;if(Vu=0,dx=Fd=null,vd=0,(vu&6)!==0)throw Error(is(331));var Qa=vu;if(vu|=4,sE(Da.current),Xy(Da,Da.current,za,Xr),vu=Qa,xh(0,!1),_l&&typeof _l.onPostCommitFiberRoot=="function")try{_l.onPostCommitFiberRoot(bl,Da)}catch{}return!0}finally{hl.p=Pa,ul.T=Ca,yE(os,Kr)}}function bE(os,Kr,Xr){Kr=Ic(Xr,Kr),Kr=lg(os.stateNode,Kr,2),os=$d(os,Kr,2),os!==null&&(Wu(os,2),Xc(os))}function wu(os,Kr,Xr){if(os.tag===3)bE(os,os,Xr);else for(;Kr!==null;){if(Kr.tag===3){bE(Kr,os,Xr);break}else if(Kr.tag===1){var Ca=Kr.stateNode;if(typeof Kr.type.getDerivedStateFromError=="function"||typeof Ca.componentDidCatch=="function"&&(qd===null||!qd.has(Ca))){os=Ic(Xr,os),Xr=Ry(2),Ca=$d(Kr,Xr,2),Ca!==null&&(_y(Xr,Ca,Kr,os),Wu(Ca,2),Xc(Ca));break}}Kr=Kr.return}}function Ig(os,Kr,Xr){var Ca=os.pingCache;if(Ca===null){Ca=os.pingCache=new HR;var Pa=new Set;Ca.set(Kr,Pa)}else Pa=Ca.get(Kr),Pa===void 0&&(Pa=new Set,Ca.set(Kr,Pa));Pa.has(Xr)||(wg=!0,Pa.add(Xr),os=QR.bind(null,os,Kr,Xr),Kr.then(os,os))}function QR(os,Kr,Xr){var Ca=os.pingCache;Ca!==null&&Ca.delete(Kr),os.pingedLanes|=os.suspendedLanes&Xr,os.warmLanes&=~Xr,Au===os&&(du&Xr)===Xr&&(Uu===4||Uu===3&&(du&62914560)===du&&300>Eu()-Ep?(vu&2)===0&&mx(os,0):Ng|=Xr,cx===du&&(cx=0)),Xc(os)}function RE(os,Kr){Kr===0&&(Kr=ku()),os=mm(os,Kr),os!==null&&(Wu(os,Kr),Xc(os))}function YR(os){var Kr=os.memoizedState,Xr=0;Kr!==null&&(Xr=Kr.retryLane),RE(os,Xr)}function JR(os,Kr){var Xr=0;switch(os.tag){case 31:case 13:var Ca=os.stateNode,Pa=os.memoizedState;Pa!==null&&(Xr=Pa.retryLane);break;case 19:Ca=os.stateNode;break;case 22:Ca=os.stateNode._retryCache;break;default:throw Error(is(314))}Ca!==null&&Ca.delete(Kr),RE(os,Xr)}function WR(os,Kr){return ru(os,Kr)}var Cp=null,hx=null,Lg=!1,Tp=!1,$g=!1,Hd=0;function Xc(os){os!==hx&&os.next===null&&(hx===null?Cp=hx=os:hx=hx.next=os),Tp=!0,Lg||(Lg=!0,e0())}function xh(os,Kr){if(!$g&&Tp){$g=!0;do for(var Xr=!1,Ca=Cp;Ca!==null;){if(os!==0){var Pa=Ca.pendingLanes;if(Pa===0)var Da=0;else{var za=Ca.suspendedLanes,Qa=Ca.pingedLanes;Da=(1<<31-Rl(42|os)+1)-1,Da&=Pa&~(za&~Qa),Da=Da&201326741?Da&201326741|1:Da?Da|2:0}Da!==0&&(Xr=!0,SE(Ca,Da))}else Da=du,Da=Lm(Ca,Ca===Au?Da:0,Ca.cancelPendingCommit!==null||Ca.timeoutHandle!==-1),(Da&3)===0||tu(Ca,Da)||(Xr=!0,SE(Ca,Da));Ca=Ca.next}while(Xr);$g=!1}}function XR(){_E()}function _E(){Tp=Lg=!1;var os=0;Hd!==0&&c0()&&(os=Hd);for(var Kr=Eu(),Xr=null,Ca=Cp;Ca!==null;){var Pa=Ca.next,Da=wE(Ca,Kr);Da===0?(Ca.next=null,Xr===null?Cp=Pa:Xr.next=Pa,Pa===null&&(hx=Xr)):(Xr=Ca,(os!==0||(Da&3)!==0)&&(Tp=!0)),Ca=Pa}Vu!==0&&Vu!==5||xh(os),Hd!==0&&(Hd=0)}function wE(os,Kr){for(var Xr=os.suspendedLanes,Ca=os.pingedLanes,Pa=os.expirationTimes,Da=os.pendingLanes&-62914561;0<Da;){var za=31-Rl(Da),Qa=1<<za,Xa=Pa[za];Xa===-1?((Qa&Xr)===0||(Qa&Ca)!==0)&&(Pa[za]=bu(Qa,Kr)):Xa<=Kr&&(os.expiredLanes|=Qa),Da&=~Qa}if(Kr=Au,Xr=du,Xr=Lm(os,os===Kr?Xr:0,os.cancelPendingCommit!==null||os.timeoutHandle!==-1),Ca=os.callbackNode,Xr===0||os===Kr&&(_u===2||_u===9)||os.cancelPendingCommit!==null)return Ca!==null&&Ca!==null&&Mu(Ca),os.callbackNode=null,os.callbackPriority=0;if((Xr&3)===0||tu(os,Xr)){if(Kr=Xr&-Xr,Kr===os.callbackPriority)return Kr;switch(Ca!==null&&Mu(Ca),Qp(Xr)){case 2:case 8:Xr=yl;break;case 32:Xr=$l;break;case 268435456:Xr=Za;break;default:Xr=$l}return Ca=NE.bind(null,os),Xr=ru(Xr,Ca),os.callbackPriority=Kr,os.callbackNode=Xr,Kr}return Ca!==null&&Ca!==null&&Mu(Ca),os.callbackPriority=2,os.callbackNode=null,2}function NE(os,Kr){if(Vu!==0&&Vu!==5)return os.callbackNode=null,os.callbackPriority=0,null;var Xr=os.callbackNode;if(Sp()&&os.callbackNode!==Xr)return null;var Ca=du;return Ca=Lm(os,os===Au?Ca:0,os.cancelPendingCommit!==null||os.timeoutHandle!==-1),Ca===0?null:(oE(os,Ca,Kr),wE(os,Eu()),os.callbackNode!=null&&os.callbackNode===Xr?NE.bind(null,os):null)}function SE(os,Kr){if(Sp())return null;oE(os,Kr,!0)}function e0(){m0(function(){(vu&6)!==0?ru(ll,XR):_E()})}function Pg(){if(Hd===0){var os=Xm;os===0&&(os=au,au<<=1,(au&261888)===0&&(au=256)),Hd=os}return Hd}function CE(os){return os==null||typeof os=="symbol"||typeof os=="boolean"?null:typeof os=="function"?os:Ph(""+os)}function TE(os,Kr){var Xr=Kr.ownerDocument.createElement("input");return Xr.name=Kr.name,Xr.value=Kr.value,os.id&&Xr.setAttribute("form",os.id),Kr.parentNode.insertBefore(Xr,Kr),os=new FormData(os),Xr.parentNode.removeChild(Xr),os}function t0(os,Kr,Xr,Ca,Pa){if(Kr==="submit"&&Xr&&Xr.stateNode===Pa){var Da=CE((Pa[xc]||null).action),za=Ca.submitter;za&&(Kr=(Kr=za[xc]||null)?CE(Kr.formAction):za.getAttribute("formAction"),Kr!==null&&(Da=Kr,za=null));var Qa=new Uh("action","action",null,Ca,Pa);os.push({event:Qa,listeners:[{instance:null,listener:function(){if(Ca.defaultPrevented){if(Hd!==0){var Xa=za?TE(Pa,za):new FormData(Pa);sg(Xr,{pending:!0,data:Xa,method:Pa.method,action:Da},null,Xa)}}else typeof Da=="function"&&(Qa.preventDefault(),Xa=za?TE(Pa,za):new FormData(Pa),sg(Xr,{pending:!0,data:Xa,method:Pa.method,action:Da},Da,Xa))},currentTarget:Pa}]})}}for(var Dg=0;Dg<vf.length;Dg++){var Mg=vf[Dg],s0=Mg.toLowerCase(),n0=Mg[0].toUpperCase()+Mg.slice(1);zc(s0,"on"+n0)}zc(av,"onAnimationEnd"),zc(ov,"onAnimationIteration"),zc(lv,"onAnimationStart"),zc("dblclick","onDoubleClick"),zc("focusin","onFocus"),zc("focusout","onBlur"),zc(vR,"onTransitionRun"),zc(yR,"onTransitionStart"),zc(ER,"onTransitionCancel"),zc(uv,"onTransitionEnd"),Bm("onMouseEnter",["mouseout","mouseover"]),Bm("onMouseLeave",["mouseout","mouseover"]),Bm("onPointerEnter",["pointerout","pointerover"]),Bm("onPointerLeave",["pointerout","pointerover"]),lm("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),lm("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),lm("onBeforeInput",["compositionend","keypress","textInput","paste"]),lm("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),lm("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),lm("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var hh="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),r0=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(hh));function kE(os,Kr){Kr=(Kr&4)!==0;for(var Xr=0;Xr<os.length;Xr++){var Ca=os[Xr],Pa=Ca.event;Ca=Ca.listeners;e:{var Da=void 0;if(Kr)for(var za=Ca.length-1;0<=za;za--){var Qa=Ca[za],Xa=Qa.instance,xl=Qa.currentTarget;if(Qa=Qa.listener,Xa!==Da&&Pa.isPropagationStopped())break e;Da=Qa,Pa.currentTarget=xl;try{Da(Pa)}catch(wl){zh(wl)}Pa.currentTarget=null,Da=Xa}else for(za=0;za<Ca.length;za++){if(Qa=Ca[za],Xa=Qa.instance,xl=Qa.currentTarget,Qa=Qa.listener,Xa!==Da&&Pa.isPropagationStopped())break e;Da=Qa,Pa.currentTarget=xl;try{Da(Pa)}catch(wl){zh(wl)}Pa.currentTarget=null,Da=Xa}}}}function uu(os,Kr){var Xr=Kr[Yp];Xr===void 0&&(Xr=Kr[Yp]=new Set);var Ca=os+"__bubble";Xr.has(Ca)||(AE(Kr,os,2,!1),Xr.add(Ca))}function Bg(os,Kr,Xr){var Ca=0;Kr&&(Ca|=4),AE(Xr,os,Ca,Kr)}var kp="_reactListening"+Math.random().toString(36).slice(2);function Ug(os){if(!os[kp]){os[kp]=!0,_j.forEach(function(Xr){Xr!=="selectionchange"&&(r0.has(Xr)||Bg(Xr,!1,os),Bg(Xr,!0,os))});var Kr=os.nodeType===9?os:os.ownerDocument;Kr===null||Kr[kp]||(Kr[kp]=!0,Bg("selectionchange",!1,Kr))}}function AE(os,Kr,Xr,Ca){switch(ab(Kr)){case 2:var Pa=O0;break;case 8:Pa=I0;break;default:Pa=tj}Xr=Pa.bind(null,Kr,Xr,os),Pa=void 0,!af||Kr!=="touchstart"&&Kr!=="touchmove"&&Kr!=="wheel"||(Pa=!0),Ca?Pa!==void 0?os.addEventListener(Kr,Xr,{capture:!0,passive:Pa}):os.addEventListener(Kr,Xr,!0):Pa!==void 0?os.addEventListener(Kr,Xr,{passive:Pa}):os.addEventListener(Kr,Xr,!1)}function qg(os,Kr,Xr,Ca,Pa){var Da=Ca;if((Kr&1)===0&&(Kr&2)===0&&Ca!==null)e:for(;;){if(Ca===null)return;var za=Ca.tag;if(za===3||za===4){var Qa=Ca.stateNode.containerInfo;if(Qa===Pa)break;if(za===4)for(za=Ca.return;za!==null;){var Xa=za.tag;if((Xa===3||Xa===4)&&za.stateNode.containerInfo===Pa)return;za=za.return}for(;Qa!==null;){if(za=Pm(Qa),za===null)return;if(Xa=za.tag,Xa===5||Xa===6||Xa===26||Xa===27){Ca=Da=za;continue e}Qa=Qa.parentNode}}Ca=Ca.return}Pj(function(){var xl=Da,wl=nf(Xr),Cl=[];e:{var gl=cv.get(os);if(gl!==void 0){var vl=Uh,Kl=os;switch(os){case"keypress":if(Mh(Xr)===0)break e;case"keydown":case"keyup":vl=Jb;break;case"focusin":Kl="focus",vl=cf;break;case"focusout":Kl="blur",vl=cf;break;case"beforeblur":case"afterblur":vl=cf;break;case"click":if(Xr.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":vl=Bj;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":vl=Bb;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":vl=eR;break;case av:case ov:case lv:vl=Fb;break;case uv:vl=sR;break;case"scroll":case"scrollend":vl=Db;break;case"wheel":vl=rR;break;case"copy":case"cut":case"paste":vl=Hb;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":vl=qj;break;case"toggle":case"beforetoggle":vl=aR}var Wl=(Kr&4)!==0,Cu=!Wl&&(os==="scroll"||os==="scrollend"),il=Wl?gl!==null?gl+"Capture":null:gl;Wl=[];for(var sl=xl,ml;sl!==null;){var Sl=sl;if(ml=Sl.stateNode,Sl=Sl.tag,Sl!==5&&Sl!==26&&Sl!==27||ml===null||il===null||(Sl=Px(sl,il),Sl!=null&&Wl.push(ph(sl,Sl,ml))),Cu)break;sl=sl.return}0<Wl.length&&(gl=new vl(gl,Kl,null,Xr,wl),Cl.push({event:gl,listeners:Wl}))}}if((Kr&7)===0){e:{if(gl=os==="mouseover"||os==="pointerover",vl=os==="mouseout"||os==="pointerout",gl&&Xr!==sf&&(Kl=Xr.relatedTarget||Xr.fromElement)&&(Pm(Kl)||Kl[$m]))break e;if((vl||gl)&&(gl=wl.window===wl?wl:(gl=wl.ownerDocument)?gl.defaultView||gl.parentWindow:window,vl?(Kl=Xr.relatedTarget||Xr.toElement,vl=xl,Kl=Kl?Pm(Kl):null,Kl!==null&&(Cu=Qr(Kl),Wl=Kl.tag,Kl!==Cu||Wl!==5&&Wl!==27&&Wl!==6)&&(Kl=null)):(vl=null,Kl=xl),vl!==Kl)){if(Wl=Bj,Sl="onMouseLeave",il="onMouseEnter",sl="mouse",(os==="pointerout"||os==="pointerover")&&(Wl=qj,Sl="onPointerLeave",il="onPointerEnter",sl="pointer"),Cu=vl==null?gl:$x(vl),ml=Kl==null?gl:$x(Kl),gl=new Wl(Sl,sl+"leave",vl,Xr,wl),gl.target=Cu,gl.relatedTarget=ml,Sl=null,Pm(wl)===xl&&(Wl=new Wl(il,sl+"enter",Kl,Xr,wl),Wl.target=ml,Wl.relatedTarget=Cu,Sl=Wl),Cu=Sl,vl&&Kl)t:{for(Wl=i0,il=vl,sl=Kl,ml=0,Sl=il;Sl;Sl=Wl(Sl))ml++;Sl=0;for(var Jl=sl;Jl;Jl=Wl(Jl))Sl++;for(;0<ml-Sl;)il=Wl(il),ml--;for(;0<Sl-ml;)sl=Wl(sl),Sl--;for(;ml--;){if(il===sl||sl!==null&&il===sl.alternate){Wl=il;break t}il=Wl(il),sl=Wl(sl)}Wl=null}else Wl=null;vl!==null&&OE(Cl,gl,vl,Wl,!1),Kl!==null&&Cu!==null&&OE(Cl,Cu,Kl,Wl,!0)}}e:{if(gl=xl?$x(xl):window,vl=gl.nodeName&&gl.nodeName.toLowerCase(),vl==="select"||vl==="input"&&gl.type==="file")var gu=Qj;else if(Zj(gl))if(Yj)gu=fR;else{gu=hR;var Vl=xR}else vl=gl.nodeName,!vl||vl.toLowerCase()!=="input"||gl.type!=="checkbox"&&gl.type!=="radio"?xl&&tf(xl.elementType)&&(gu=Qj):gu=pR;if(gu&&(gu=gu(os,xl))){Vj(Cl,gu,Xr,wl);break e}Vl&&Vl(os,gl,xl),os==="focusout"&&xl&&gl.type==="number"&&xl.memoizedProps.value!=null&&ef(gl,"number",gl.value)}switch(Vl=xl?$x(xl):window,os){case"focusin":(Zj(Vl)||Vl.contentEditable==="true")&&(Km=Vl,ff=xl,Hx=null);break;case"focusout":Hx=ff=Km=null;break;case"mousedown":gf=!0;break;case"contextmenu":case"mouseup":case"dragend":gf=!1,rv(Cl,Xr,wl);break;case"selectionchange":if(jR)break;case"keydown":case"keyup":rv(Cl,Xr,wl)}var ou;if(mf)e:{switch(os){case"compositionstart":var mu="onCompositionStart";break e;case"compositionend":mu="onCompositionEnd";break e;case"compositionupdate":mu="onCompositionUpdate";break e}mu=void 0}else Hm?Kj(os,Xr)&&(mu="onCompositionEnd"):os==="keydown"&&Xr.keyCode===229&&(mu="onCompositionStart");mu&&(Fj&&Xr.locale!=="ko"&&(Hm||mu!=="onCompositionStart"?mu==="onCompositionEnd"&&Hm&&(ou=Dj()):(Cd=wl,of="value"in Cd?Cd.value:Cd.textContent,Hm=!0)),Vl=Ap(xl,mu),0<Vl.length&&(mu=new Uj(mu,os,null,Xr,wl),Cl.push({event:mu,listeners:Vl}),ou?mu.data=ou:(ou=Gj(Xr),ou!==null&&(mu.data=ou)))),(ou=lR?uR(os,Xr):cR(os,Xr))&&(mu=Ap(xl,"onBeforeInput"),0<mu.length&&(Vl=new Uj("onBeforeInput","beforeinput",null,Xr,wl),Cl.push({event:Vl,listeners:mu}),Vl.data=ou)),t0(Cl,os,xl,Xr,wl)}kE(Cl,Kr)})}function ph(os,Kr,Xr){return{instance:os,listener:Kr,currentTarget:Xr}}function Ap(os,Kr){for(var Xr=Kr+"Capture",Ca=[];os!==null;){var Pa=os,Da=Pa.stateNode;if(Pa=Pa.tag,Pa!==5&&Pa!==26&&Pa!==27||Da===null||(Pa=Px(os,Xr),Pa!=null&&Ca.unshift(ph(os,Pa,Da)),Pa=Px(os,Kr),Pa!=null&&Ca.push(ph(os,Pa,Da))),os.tag===3)return Ca;os=os.return}return[]}function i0(os){if(os===null)return null;do os=os.return;while(os&&os.tag!==5&&os.tag!==27);return os||null}function OE(os,Kr,Xr,Ca,Pa){for(var Da=Kr._reactName,za=[];Xr!==null&&Xr!==Ca;){var Qa=Xr,Xa=Qa.alternate,xl=Qa.stateNode;if(Qa=Qa.tag,Xa!==null&&Xa===Ca)break;Qa!==5&&Qa!==26&&Qa!==27||xl===null||(Xa=xl,Pa?(xl=Px(Xr,Da),xl!=null&&za.unshift(ph(Xr,xl,Xa))):Pa||(xl=Px(Xr,Da),xl!=null&&za.push(ph(Xr,xl,Xa)))),Xr=Xr.return}za.length!==0&&os.push({event:Kr,listeners:za})}var a0=/\r\n?/g,o0=/\u0000|\uFFFD/g;function IE(os){return(typeof os=="string"?os:""+os).replace(a0,`
|
|
25
|
+
`).replace(o0,"")}function LE(os,Kr){return Kr=IE(Kr),IE(os)===Kr}function Su(os,Kr,Xr,Ca,Pa,Da){switch(Xr){case"children":typeof Ca=="string"?Kr==="body"||Kr==="textarea"&&Ca===""||qm(os,Ca):(typeof Ca=="number"||typeof Ca=="bigint")&&Kr!=="body"&&qm(os,""+Ca);break;case"className":Lh(os,"class",Ca);break;case"tabIndex":Lh(os,"tabindex",Ca);break;case"dir":case"role":case"viewBox":case"width":case"height":Lh(os,Xr,Ca);break;case"style":Lj(os,Ca,Da);break;case"data":if(Kr!=="object"){Lh(os,"data",Ca);break}case"src":case"href":if(Ca===""&&(Kr!=="a"||Xr!=="href")){os.removeAttribute(Xr);break}if(Ca==null||typeof Ca=="function"||typeof Ca=="symbol"||typeof Ca=="boolean"){os.removeAttribute(Xr);break}Ca=Ph(""+Ca),os.setAttribute(Xr,Ca);break;case"action":case"formAction":if(typeof Ca=="function"){os.setAttribute(Xr,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof Da=="function"&&(Xr==="formAction"?(Kr!=="input"&&Su(os,Kr,"name",Pa.name,Pa,null),Su(os,Kr,"formEncType",Pa.formEncType,Pa,null),Su(os,Kr,"formMethod",Pa.formMethod,Pa,null),Su(os,Kr,"formTarget",Pa.formTarget,Pa,null)):(Su(os,Kr,"encType",Pa.encType,Pa,null),Su(os,Kr,"method",Pa.method,Pa,null),Su(os,Kr,"target",Pa.target,Pa,null)));if(Ca==null||typeof Ca=="symbol"||typeof Ca=="boolean"){os.removeAttribute(Xr);break}Ca=Ph(""+Ca),os.setAttribute(Xr,Ca);break;case"onClick":Ca!=null&&(os.onclick=rd);break;case"onScroll":Ca!=null&&uu("scroll",os);break;case"onScrollEnd":Ca!=null&&uu("scrollend",os);break;case"dangerouslySetInnerHTML":if(Ca!=null){if(typeof Ca!="object"||!("__html"in Ca))throw Error(is(61));if(Xr=Ca.__html,Xr!=null){if(Pa.children!=null)throw Error(is(60));os.innerHTML=Xr}}break;case"multiple":os.multiple=Ca&&typeof Ca!="function"&&typeof Ca!="symbol";break;case"muted":os.muted=Ca&&typeof Ca!="function"&&typeof Ca!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(Ca==null||typeof Ca=="function"||typeof Ca=="boolean"||typeof Ca=="symbol"){os.removeAttribute("xlink:href");break}Xr=Ph(""+Ca),os.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",Xr);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":Ca!=null&&typeof Ca!="function"&&typeof Ca!="symbol"?os.setAttribute(Xr,""+Ca):os.removeAttribute(Xr);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":Ca&&typeof Ca!="function"&&typeof Ca!="symbol"?os.setAttribute(Xr,""):os.removeAttribute(Xr);break;case"capture":case"download":Ca===!0?os.setAttribute(Xr,""):Ca!==!1&&Ca!=null&&typeof Ca!="function"&&typeof Ca!="symbol"?os.setAttribute(Xr,Ca):os.removeAttribute(Xr);break;case"cols":case"rows":case"size":case"span":Ca!=null&&typeof Ca!="function"&&typeof Ca!="symbol"&&!isNaN(Ca)&&1<=Ca?os.setAttribute(Xr,Ca):os.removeAttribute(Xr);break;case"rowSpan":case"start":Ca==null||typeof Ca=="function"||typeof Ca=="symbol"||isNaN(Ca)?os.removeAttribute(Xr):os.setAttribute(Xr,Ca);break;case"popover":uu("beforetoggle",os),uu("toggle",os),Ih(os,"popover",Ca);break;case"xlinkActuate":nd(os,"http://www.w3.org/1999/xlink","xlink:actuate",Ca);break;case"xlinkArcrole":nd(os,"http://www.w3.org/1999/xlink","xlink:arcrole",Ca);break;case"xlinkRole":nd(os,"http://www.w3.org/1999/xlink","xlink:role",Ca);break;case"xlinkShow":nd(os,"http://www.w3.org/1999/xlink","xlink:show",Ca);break;case"xlinkTitle":nd(os,"http://www.w3.org/1999/xlink","xlink:title",Ca);break;case"xlinkType":nd(os,"http://www.w3.org/1999/xlink","xlink:type",Ca);break;case"xmlBase":nd(os,"http://www.w3.org/XML/1998/namespace","xml:base",Ca);break;case"xmlLang":nd(os,"http://www.w3.org/XML/1998/namespace","xml:lang",Ca);break;case"xmlSpace":nd(os,"http://www.w3.org/XML/1998/namespace","xml:space",Ca);break;case"is":Ih(os,"is",Ca);break;case"innerText":case"textContent":break;default:(!(2<Xr.length)||Xr[0]!=="o"&&Xr[0]!=="O"||Xr[1]!=="n"&&Xr[1]!=="N")&&(Xr=$b.get(Xr)||Xr,Ih(os,Xr,Ca))}}function Fg(os,Kr,Xr,Ca,Pa,Da){switch(Xr){case"style":Lj(os,Ca,Da);break;case"dangerouslySetInnerHTML":if(Ca!=null){if(typeof Ca!="object"||!("__html"in Ca))throw Error(is(61));if(Xr=Ca.__html,Xr!=null){if(Pa.children!=null)throw Error(is(60));os.innerHTML=Xr}}break;case"children":typeof Ca=="string"?qm(os,Ca):(typeof Ca=="number"||typeof Ca=="bigint")&&qm(os,""+Ca);break;case"onScroll":Ca!=null&&uu("scroll",os);break;case"onScrollEnd":Ca!=null&&uu("scrollend",os);break;case"onClick":Ca!=null&&(os.onclick=rd);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!wj.hasOwnProperty(Xr))e:{if(Xr[0]==="o"&&Xr[1]==="n"&&(Pa=Xr.endsWith("Capture"),Kr=Xr.slice(2,Pa?Xr.length-7:void 0),Da=os[xc]||null,Da=Da!=null?Da[Xr]:null,typeof Da=="function"&&os.removeEventListener(Kr,Da,Pa),typeof Ca=="function")){typeof Da!="function"&&Da!==null&&(Xr in os?os[Xr]=null:os.hasAttribute(Xr)&&os.removeAttribute(Xr)),os.addEventListener(Kr,Ca,Pa);break e}Xr in os?os[Xr]=Ca:Ca===!0?os.setAttribute(Xr,""):Ih(os,Xr,Ca)}}}function nc(os,Kr,Xr){switch(Kr){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":uu("error",os),uu("load",os);var Ca=!1,Pa=!1,Da;for(Da in Xr)if(Xr.hasOwnProperty(Da)){var za=Xr[Da];if(za!=null)switch(Da){case"src":Ca=!0;break;case"srcSet":Pa=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(is(137,Kr));default:Su(os,Kr,Da,za,Xr,null)}}Pa&&Su(os,Kr,"srcSet",Xr.srcSet,Xr,null),Ca&&Su(os,Kr,"src",Xr.src,Xr,null);return;case"input":uu("invalid",os);var Qa=Da=za=Pa=null,Xa=null,xl=null;for(Ca in Xr)if(Xr.hasOwnProperty(Ca)){var wl=Xr[Ca];if(wl!=null)switch(Ca){case"name":Pa=wl;break;case"type":za=wl;break;case"checked":Xa=wl;break;case"defaultChecked":xl=wl;break;case"value":Da=wl;break;case"defaultValue":Qa=wl;break;case"children":case"dangerouslySetInnerHTML":if(wl!=null)throw Error(is(137,Kr));break;default:Su(os,Kr,Ca,wl,Xr,null)}}kj(os,Da,Qa,Xa,xl,za,Pa,!1);return;case"select":uu("invalid",os),Ca=za=Da=null;for(Pa in Xr)if(Xr.hasOwnProperty(Pa)&&(Qa=Xr[Pa],Qa!=null))switch(Pa){case"value":Da=Qa;break;case"defaultValue":za=Qa;break;case"multiple":Ca=Qa;default:Su(os,Kr,Pa,Qa,Xr,null)}Kr=Da,Xr=za,os.multiple=!!Ca,Kr!=null?Um(os,!!Ca,Kr,!1):Xr!=null&&Um(os,!!Ca,Xr,!0);return;case"textarea":uu("invalid",os),Da=Pa=Ca=null;for(za in Xr)if(Xr.hasOwnProperty(za)&&(Qa=Xr[za],Qa!=null))switch(za){case"value":Ca=Qa;break;case"defaultValue":Pa=Qa;break;case"children":Da=Qa;break;case"dangerouslySetInnerHTML":if(Qa!=null)throw Error(is(91));break;default:Su(os,Kr,za,Qa,Xr,null)}Oj(os,Ca,Pa,Da);return;case"option":for(Xa in Xr)if(Xr.hasOwnProperty(Xa)&&(Ca=Xr[Xa],Ca!=null))switch(Xa){case"selected":os.selected=Ca&&typeof Ca!="function"&&typeof Ca!="symbol";break;default:Su(os,Kr,Xa,Ca,Xr,null)}return;case"dialog":uu("beforetoggle",os),uu("toggle",os),uu("cancel",os),uu("close",os);break;case"iframe":case"object":uu("load",os);break;case"video":case"audio":for(Ca=0;Ca<hh.length;Ca++)uu(hh[Ca],os);break;case"image":uu("error",os),uu("load",os);break;case"details":uu("toggle",os);break;case"embed":case"source":case"link":uu("error",os),uu("load",os);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(xl in Xr)if(Xr.hasOwnProperty(xl)&&(Ca=Xr[xl],Ca!=null))switch(xl){case"children":case"dangerouslySetInnerHTML":throw Error(is(137,Kr));default:Su(os,Kr,xl,Ca,Xr,null)}return;default:if(tf(Kr)){for(wl in Xr)Xr.hasOwnProperty(wl)&&(Ca=Xr[wl],Ca!==void 0&&Fg(os,Kr,wl,Ca,Xr,void 0));return}}for(Qa in Xr)Xr.hasOwnProperty(Qa)&&(Ca=Xr[Qa],Ca!=null&&Su(os,Kr,Qa,Ca,Xr,null))}function l0(os,Kr,Xr,Ca){switch(Kr){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var Pa=null,Da=null,za=null,Qa=null,Xa=null,xl=null,wl=null;for(vl in Xr){var Cl=Xr[vl];if(Xr.hasOwnProperty(vl)&&Cl!=null)switch(vl){case"checked":break;case"value":break;case"defaultValue":Xa=Cl;default:Ca.hasOwnProperty(vl)||Su(os,Kr,vl,null,Ca,Cl)}}for(var gl in Ca){var vl=Ca[gl];if(Cl=Xr[gl],Ca.hasOwnProperty(gl)&&(vl!=null||Cl!=null))switch(gl){case"type":Da=vl;break;case"name":Pa=vl;break;case"checked":xl=vl;break;case"defaultChecked":wl=vl;break;case"value":za=vl;break;case"defaultValue":Qa=vl;break;case"children":case"dangerouslySetInnerHTML":if(vl!=null)throw Error(is(137,Kr));break;default:vl!==Cl&&Su(os,Kr,gl,vl,Ca,Cl)}}Xp(os,za,Qa,Xa,xl,wl,Da,Pa);return;case"select":vl=za=Qa=gl=null;for(Da in Xr)if(Xa=Xr[Da],Xr.hasOwnProperty(Da)&&Xa!=null)switch(Da){case"value":break;case"multiple":vl=Xa;default:Ca.hasOwnProperty(Da)||Su(os,Kr,Da,null,Ca,Xa)}for(Pa in Ca)if(Da=Ca[Pa],Xa=Xr[Pa],Ca.hasOwnProperty(Pa)&&(Da!=null||Xa!=null))switch(Pa){case"value":gl=Da;break;case"defaultValue":Qa=Da;break;case"multiple":za=Da;default:Da!==Xa&&Su(os,Kr,Pa,Da,Ca,Xa)}Kr=Qa,Xr=za,Ca=vl,gl!=null?Um(os,!!Xr,gl,!1):!!Ca!=!!Xr&&(Kr!=null?Um(os,!!Xr,Kr,!0):Um(os,!!Xr,Xr?[]:"",!1));return;case"textarea":vl=gl=null;for(Qa in Xr)if(Pa=Xr[Qa],Xr.hasOwnProperty(Qa)&&Pa!=null&&!Ca.hasOwnProperty(Qa))switch(Qa){case"value":break;case"children":break;default:Su(os,Kr,Qa,null,Ca,Pa)}for(za in Ca)if(Pa=Ca[za],Da=Xr[za],Ca.hasOwnProperty(za)&&(Pa!=null||Da!=null))switch(za){case"value":gl=Pa;break;case"defaultValue":vl=Pa;break;case"children":break;case"dangerouslySetInnerHTML":if(Pa!=null)throw Error(is(91));break;default:Pa!==Da&&Su(os,Kr,za,Pa,Ca,Da)}Aj(os,gl,vl);return;case"option":for(var Kl in Xr)if(gl=Xr[Kl],Xr.hasOwnProperty(Kl)&&gl!=null&&!Ca.hasOwnProperty(Kl))switch(Kl){case"selected":os.selected=!1;break;default:Su(os,Kr,Kl,null,Ca,gl)}for(Xa in Ca)if(gl=Ca[Xa],vl=Xr[Xa],Ca.hasOwnProperty(Xa)&&gl!==vl&&(gl!=null||vl!=null))switch(Xa){case"selected":os.selected=gl&&typeof gl!="function"&&typeof gl!="symbol";break;default:Su(os,Kr,Xa,gl,Ca,vl)}return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var Wl in Xr)gl=Xr[Wl],Xr.hasOwnProperty(Wl)&&gl!=null&&!Ca.hasOwnProperty(Wl)&&Su(os,Kr,Wl,null,Ca,gl);for(xl in Ca)if(gl=Ca[xl],vl=Xr[xl],Ca.hasOwnProperty(xl)&&gl!==vl&&(gl!=null||vl!=null))switch(xl){case"children":case"dangerouslySetInnerHTML":if(gl!=null)throw Error(is(137,Kr));break;default:Su(os,Kr,xl,gl,Ca,vl)}return;default:if(tf(Kr)){for(var Cu in Xr)gl=Xr[Cu],Xr.hasOwnProperty(Cu)&&gl!==void 0&&!Ca.hasOwnProperty(Cu)&&Fg(os,Kr,Cu,void 0,Ca,gl);for(wl in Ca)gl=Ca[wl],vl=Xr[wl],!Ca.hasOwnProperty(wl)||gl===vl||gl===void 0&&vl===void 0||Fg(os,Kr,wl,gl,Ca,vl);return}}for(var il in Xr)gl=Xr[il],Xr.hasOwnProperty(il)&&gl!=null&&!Ca.hasOwnProperty(il)&&Su(os,Kr,il,null,Ca,gl);for(Cl in Ca)gl=Ca[Cl],vl=Xr[Cl],!Ca.hasOwnProperty(Cl)||gl===vl||gl==null&&vl==null||Su(os,Kr,Cl,gl,Ca,vl)}function $E(os){switch(os){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function u0(){if(typeof performance.getEntriesByType=="function"){for(var os=0,Kr=0,Xr=performance.getEntriesByType("resource"),Ca=0;Ca<Xr.length;Ca++){var Pa=Xr[Ca],Da=Pa.transferSize,za=Pa.initiatorType,Qa=Pa.duration;if(Da&&Qa&&$E(za)){for(za=0,Qa=Pa.responseEnd,Ca+=1;Ca<Xr.length;Ca++){var Xa=Xr[Ca],xl=Xa.startTime;if(xl>Qa)break;var wl=Xa.transferSize,Cl=Xa.initiatorType;wl&&$E(Cl)&&(Xa=Xa.responseEnd,za+=wl*(Xa<Qa?1:(Qa-xl)/(Xa-xl)))}if(--Ca,Kr+=8*(Da+za)/(Pa.duration/1e3),os++,10<os)break}}if(0<os)return Kr/os/1e6}return navigator.connection&&(os=navigator.connection.downlink,typeof os=="number")?os:5}var zg=null,Hg=null;function Op(os){return os.nodeType===9?os:os.ownerDocument}function PE(os){switch(os){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function DE(os,Kr){if(os===0)switch(Kr){case"svg":return 1;case"math":return 2;default:return 0}return os===1&&Kr==="foreignObject"?0:os}function Kg(os,Kr){return os==="textarea"||os==="noscript"||typeof Kr.children=="string"||typeof Kr.children=="number"||typeof Kr.children=="bigint"||typeof Kr.dangerouslySetInnerHTML=="object"&&Kr.dangerouslySetInnerHTML!==null&&Kr.dangerouslySetInnerHTML.__html!=null}var Gg=null;function c0(){var os=window.event;return os&&os.type==="popstate"?os===Gg?!1:(Gg=os,!0):(Gg=null,!1)}var ME=typeof setTimeout=="function"?setTimeout:void 0,d0=typeof clearTimeout=="function"?clearTimeout:void 0,BE=typeof Promise=="function"?Promise:void 0,m0=typeof queueMicrotask=="function"?queueMicrotask:typeof BE<"u"?function(os){return BE.resolve(null).then(os).catch(x0)}:ME;function x0(os){setTimeout(function(){throw os})}function Kd(os){return os==="head"}function UE(os,Kr){var Xr=Kr,Ca=0;do{var Pa=Xr.nextSibling;if(os.removeChild(Xr),Pa&&Pa.nodeType===8)if(Xr=Pa.data,Xr==="/$"||Xr==="/&"){if(Ca===0){os.removeChild(Pa),jx(Kr);return}Ca--}else if(Xr==="$"||Xr==="$?"||Xr==="$~"||Xr==="$!"||Xr==="&")Ca++;else if(Xr==="html")fh(os.ownerDocument.documentElement);else if(Xr==="head"){Xr=os.ownerDocument.head,fh(Xr);for(var Da=Xr.firstChild;Da;){var za=Da.nextSibling,Qa=Da.nodeName;Da[Lx]||Qa==="SCRIPT"||Qa==="STYLE"||Qa==="LINK"&&Da.rel.toLowerCase()==="stylesheet"||Xr.removeChild(Da),Da=za}}else Xr==="body"&&fh(os.ownerDocument.body);Xr=Pa}while(Xr);jx(Kr)}function qE(os,Kr){var Xr=os;os=0;do{var Ca=Xr.nextSibling;if(Xr.nodeType===1?Kr?(Xr._stashedDisplay=Xr.style.display,Xr.style.display="none"):(Xr.style.display=Xr._stashedDisplay||"",Xr.getAttribute("style")===""&&Xr.removeAttribute("style")):Xr.nodeType===3&&(Kr?(Xr._stashedText=Xr.nodeValue,Xr.nodeValue=""):Xr.nodeValue=Xr._stashedText||""),Ca&&Ca.nodeType===8)if(Xr=Ca.data,Xr==="/$"){if(os===0)break;os--}else Xr!=="$"&&Xr!=="$?"&&Xr!=="$~"&&Xr!=="$!"||os++;Xr=Ca}while(Xr)}function Zg(os){var Kr=os.firstChild;for(Kr&&Kr.nodeType===10&&(Kr=Kr.nextSibling);Kr;){var Xr=Kr;switch(Kr=Kr.nextSibling,Xr.nodeName){case"HTML":case"HEAD":case"BODY":Zg(Xr),Jp(Xr);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(Xr.rel.toLowerCase()==="stylesheet")continue}os.removeChild(Xr)}}function h0(os,Kr,Xr,Ca){for(;os.nodeType===1;){var Pa=Xr;if(os.nodeName.toLowerCase()!==Kr.toLowerCase()){if(!Ca&&(os.nodeName!=="INPUT"||os.type!=="hidden"))break}else if(Ca){if(!os[Lx])switch(Kr){case"meta":if(!os.hasAttribute("itemprop"))break;return os;case"link":if(Da=os.getAttribute("rel"),Da==="stylesheet"&&os.hasAttribute("data-precedence"))break;if(Da!==Pa.rel||os.getAttribute("href")!==(Pa.href==null||Pa.href===""?null:Pa.href)||os.getAttribute("crossorigin")!==(Pa.crossOrigin==null?null:Pa.crossOrigin)||os.getAttribute("title")!==(Pa.title==null?null:Pa.title))break;return os;case"style":if(os.hasAttribute("data-precedence"))break;return os;case"script":if(Da=os.getAttribute("src"),(Da!==(Pa.src==null?null:Pa.src)||os.getAttribute("type")!==(Pa.type==null?null:Pa.type)||os.getAttribute("crossorigin")!==(Pa.crossOrigin==null?null:Pa.crossOrigin))&&Da&&os.hasAttribute("async")&&!os.hasAttribute("itemprop"))break;return os;default:return os}}else if(Kr==="input"&&os.type==="hidden"){var Da=Pa.name==null?null:""+Pa.name;if(Pa.type==="hidden"&&os.getAttribute("name")===Da)return os}else return os;if(os=Mc(os.nextSibling),os===null)break}return null}function p0(os,Kr,Xr){if(Kr==="")return null;for(;os.nodeType!==3;)if((os.nodeType!==1||os.nodeName!=="INPUT"||os.type!=="hidden")&&!Xr||(os=Mc(os.nextSibling),os===null))return null;return os}function FE(os,Kr){for(;os.nodeType!==8;)if((os.nodeType!==1||os.nodeName!=="INPUT"||os.type!=="hidden")&&!Kr||(os=Mc(os.nextSibling),os===null))return null;return os}function Vg(os){return os.data==="$?"||os.data==="$~"}function Qg(os){return os.data==="$!"||os.data==="$?"&&os.ownerDocument.readyState!=="loading"}function f0(os,Kr){var Xr=os.ownerDocument;if(os.data==="$~")os._reactRetry=Kr;else if(os.data!=="$?"||Xr.readyState!=="loading")Kr();else{var Ca=function(){Kr(),Xr.removeEventListener("DOMContentLoaded",Ca)};Xr.addEventListener("DOMContentLoaded",Ca),os._reactRetry=Ca}}function Mc(os){for(;os!=null;os=os.nextSibling){var Kr=os.nodeType;if(Kr===1||Kr===3)break;if(Kr===8){if(Kr=os.data,Kr==="$"||Kr==="$!"||Kr==="$?"||Kr==="$~"||Kr==="&"||Kr==="F!"||Kr==="F")break;if(Kr==="/$"||Kr==="/&")return null}}return os}var Yg=null;function zE(os){os=os.nextSibling;for(var Kr=0;os;){if(os.nodeType===8){var Xr=os.data;if(Xr==="/$"||Xr==="/&"){if(Kr===0)return Mc(os.nextSibling);Kr--}else Xr!=="$"&&Xr!=="$!"&&Xr!=="$?"&&Xr!=="$~"&&Xr!=="&"||Kr++}os=os.nextSibling}return null}function HE(os){os=os.previousSibling;for(var Kr=0;os;){if(os.nodeType===8){var Xr=os.data;if(Xr==="$"||Xr==="$!"||Xr==="$?"||Xr==="$~"||Xr==="&"){if(Kr===0)return os;Kr--}else Xr!=="/$"&&Xr!=="/&"||Kr++}os=os.previousSibling}return null}function KE(os,Kr,Xr){switch(Kr=Op(Xr),os){case"html":if(os=Kr.documentElement,!os)throw Error(is(452));return os;case"head":if(os=Kr.head,!os)throw Error(is(453));return os;case"body":if(os=Kr.body,!os)throw Error(is(454));return os;default:throw Error(is(451))}}function fh(os){for(var Kr=os.attributes;Kr.length;)os.removeAttributeNode(Kr[0]);Jp(os)}var Bc=new Map,GE=new Set;function Ip(os){return typeof os.getRootNode=="function"?os.getRootNode():os.nodeType===9?os:os.ownerDocument}var yd=hl.d;hl.d={f:g0,r:j0,D:v0,C:y0,L:E0,m:b0,X:_0,S:R0,M:w0};function g0(){var os=yd.f(),Kr=_p();return os||Kr}function j0(os){var Kr=Dm(os);Kr!==null&&Kr.tag===5&&Kr.type==="form"?uy(Kr):yd.r(os)}var px=typeof document>"u"?null:document;function ZE(os,Kr,Xr){var Ca=px;if(Ca&&typeof Kr=="string"&&Kr){var Pa=Ac(Kr);Pa='link[rel="'+os+'"][href="'+Pa+'"]',typeof Xr=="string"&&(Pa+='[crossorigin="'+Xr+'"]'),GE.has(Pa)||(GE.add(Pa),os={rel:os,crossOrigin:Xr,href:Kr},Ca.querySelector(Pa)===null&&(Kr=Ca.createElement("link"),nc(Kr,"link",os),Qu(Kr),Ca.head.appendChild(Kr)))}}function v0(os){yd.D(os),ZE("dns-prefetch",os,null)}function y0(os,Kr){yd.C(os,Kr),ZE("preconnect",os,Kr)}function E0(os,Kr,Xr){yd.L(os,Kr,Xr);var Ca=px;if(Ca&&os&&Kr){var Pa='link[rel="preload"][as="'+Ac(Kr)+'"]';Kr==="image"&&Xr&&Xr.imageSrcSet?(Pa+='[imagesrcset="'+Ac(Xr.imageSrcSet)+'"]',typeof Xr.imageSizes=="string"&&(Pa+='[imagesizes="'+Ac(Xr.imageSizes)+'"]')):Pa+='[href="'+Ac(os)+'"]';var Da=Pa;switch(Kr){case"style":Da=fx(os);break;case"script":Da=gx(os)}Bc.has(Da)||(os=La({rel:"preload",href:Kr==="image"&&Xr&&Xr.imageSrcSet?void 0:os,as:Kr},Xr),Bc.set(Da,os),Ca.querySelector(Pa)!==null||Kr==="style"&&Ca.querySelector(gh(Da))||Kr==="script"&&Ca.querySelector(jh(Da))||(Kr=Ca.createElement("link"),nc(Kr,"link",os),Qu(Kr),Ca.head.appendChild(Kr)))}}function b0(os,Kr){yd.m(os,Kr);var Xr=px;if(Xr&&os){var Ca=Kr&&typeof Kr.as=="string"?Kr.as:"script",Pa='link[rel="modulepreload"][as="'+Ac(Ca)+'"][href="'+Ac(os)+'"]',Da=Pa;switch(Ca){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":Da=gx(os)}if(!Bc.has(Da)&&(os=La({rel:"modulepreload",href:os},Kr),Bc.set(Da,os),Xr.querySelector(Pa)===null)){switch(Ca){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(Xr.querySelector(jh(Da)))return}Ca=Xr.createElement("link"),nc(Ca,"link",os),Qu(Ca),Xr.head.appendChild(Ca)}}}function R0(os,Kr,Xr){yd.S(os,Kr,Xr);var Ca=px;if(Ca&&os){var Pa=Mm(Ca).hoistableStyles,Da=fx(os);Kr=Kr||"default";var za=Pa.get(Da);if(!za){var Qa={loading:0,preload:null};if(za=Ca.querySelector(gh(Da)))Qa.loading=5;else{os=La({rel:"stylesheet",href:os,"data-precedence":Kr},Xr),(Xr=Bc.get(Da))&&Jg(os,Xr);var Xa=za=Ca.createElement("link");Qu(Xa),nc(Xa,"link",os),Xa._p=new Promise(function(xl,wl){Xa.onload=xl,Xa.onerror=wl}),Xa.addEventListener("load",function(){Qa.loading|=1}),Xa.addEventListener("error",function(){Qa.loading|=2}),Qa.loading|=4,Lp(za,Kr,Ca)}za={type:"stylesheet",instance:za,count:1,state:Qa},Pa.set(Da,za)}}}function _0(os,Kr){yd.X(os,Kr);var Xr=px;if(Xr&&os){var Ca=Mm(Xr).hoistableScripts,Pa=gx(os),Da=Ca.get(Pa);Da||(Da=Xr.querySelector(jh(Pa)),Da||(os=La({src:os,async:!0},Kr),(Kr=Bc.get(Pa))&&Wg(os,Kr),Da=Xr.createElement("script"),Qu(Da),nc(Da,"link",os),Xr.head.appendChild(Da)),Da={type:"script",instance:Da,count:1,state:null},Ca.set(Pa,Da))}}function w0(os,Kr){yd.M(os,Kr);var Xr=px;if(Xr&&os){var Ca=Mm(Xr).hoistableScripts,Pa=gx(os),Da=Ca.get(Pa);Da||(Da=Xr.querySelector(jh(Pa)),Da||(os=La({src:os,async:!0,type:"module"},Kr),(Kr=Bc.get(Pa))&&Wg(os,Kr),Da=Xr.createElement("script"),Qu(Da),nc(Da,"link",os),Xr.head.appendChild(Da)),Da={type:"script",instance:Da,count:1,state:null},Ca.set(Pa,Da))}}function VE(os,Kr,Xr,Ca){var Pa=(Pa=nu.current)?Ip(Pa):null;if(!Pa)throw Error(is(446));switch(os){case"meta":case"title":return null;case"style":return typeof Xr.precedence=="string"&&typeof Xr.href=="string"?(Kr=fx(Xr.href),Xr=Mm(Pa).hoistableStyles,Ca=Xr.get(Kr),Ca||(Ca={type:"style",instance:null,count:0,state:null},Xr.set(Kr,Ca)),Ca):{type:"void",instance:null,count:0,state:null};case"link":if(Xr.rel==="stylesheet"&&typeof Xr.href=="string"&&typeof Xr.precedence=="string"){os=fx(Xr.href);var Da=Mm(Pa).hoistableStyles,za=Da.get(os);if(za||(Pa=Pa.ownerDocument||Pa,za={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},Da.set(os,za),(Da=Pa.querySelector(gh(os)))&&!Da._p&&(za.instance=Da,za.state.loading=5),Bc.has(os)||(Xr={rel:"preload",as:"style",href:Xr.href,crossOrigin:Xr.crossOrigin,integrity:Xr.integrity,media:Xr.media,hrefLang:Xr.hrefLang,referrerPolicy:Xr.referrerPolicy},Bc.set(os,Xr),Da||N0(Pa,os,Xr,za.state))),Kr&&Ca===null)throw Error(is(528,""));return za}if(Kr&&Ca!==null)throw Error(is(529,""));return null;case"script":return Kr=Xr.async,Xr=Xr.src,typeof Xr=="string"&&Kr&&typeof Kr!="function"&&typeof Kr!="symbol"?(Kr=gx(Xr),Xr=Mm(Pa).hoistableScripts,Ca=Xr.get(Kr),Ca||(Ca={type:"script",instance:null,count:0,state:null},Xr.set(Kr,Ca)),Ca):{type:"void",instance:null,count:0,state:null};default:throw Error(is(444,os))}}function fx(os){return'href="'+Ac(os)+'"'}function gh(os){return'link[rel="stylesheet"]['+os+"]"}function QE(os){return La({},os,{"data-precedence":os.precedence,precedence:null})}function N0(os,Kr,Xr,Ca){os.querySelector('link[rel="preload"][as="style"]['+Kr+"]")?Ca.loading=1:(Kr=os.createElement("link"),Ca.preload=Kr,Kr.addEventListener("load",function(){return Ca.loading|=1}),Kr.addEventListener("error",function(){return Ca.loading|=2}),nc(Kr,"link",Xr),Qu(Kr),os.head.appendChild(Kr))}function gx(os){return'[src="'+Ac(os)+'"]'}function jh(os){return"script[async]"+os}function YE(os,Kr,Xr){if(Kr.count++,Kr.instance===null)switch(Kr.type){case"style":var Ca=os.querySelector('style[data-href~="'+Ac(Xr.href)+'"]');if(Ca)return Kr.instance=Ca,Qu(Ca),Ca;var Pa=La({},Xr,{"data-href":Xr.href,"data-precedence":Xr.precedence,href:null,precedence:null});return Ca=(os.ownerDocument||os).createElement("style"),Qu(Ca),nc(Ca,"style",Pa),Lp(Ca,Xr.precedence,os),Kr.instance=Ca;case"stylesheet":Pa=fx(Xr.href);var Da=os.querySelector(gh(Pa));if(Da)return Kr.state.loading|=4,Kr.instance=Da,Qu(Da),Da;Ca=QE(Xr),(Pa=Bc.get(Pa))&&Jg(Ca,Pa),Da=(os.ownerDocument||os).createElement("link"),Qu(Da);var za=Da;return za._p=new Promise(function(Qa,Xa){za.onload=Qa,za.onerror=Xa}),nc(Da,"link",Ca),Kr.state.loading|=4,Lp(Da,Xr.precedence,os),Kr.instance=Da;case"script":return Da=gx(Xr.src),(Pa=os.querySelector(jh(Da)))?(Kr.instance=Pa,Qu(Pa),Pa):(Ca=Xr,(Pa=Bc.get(Da))&&(Ca=La({},Xr),Wg(Ca,Pa)),os=os.ownerDocument||os,Pa=os.createElement("script"),Qu(Pa),nc(Pa,"link",Ca),os.head.appendChild(Pa),Kr.instance=Pa);case"void":return null;default:throw Error(is(443,Kr.type))}else Kr.type==="stylesheet"&&(Kr.state.loading&4)===0&&(Ca=Kr.instance,Kr.state.loading|=4,Lp(Ca,Xr.precedence,os));return Kr.instance}function Lp(os,Kr,Xr){for(var Ca=Xr.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),Pa=Ca.length?Ca[Ca.length-1]:null,Da=Pa,za=0;za<Ca.length;za++){var Qa=Ca[za];if(Qa.dataset.precedence===Kr)Da=Qa;else if(Da!==Pa)break}Da?Da.parentNode.insertBefore(os,Da.nextSibling):(Kr=Xr.nodeType===9?Xr.head:Xr,Kr.insertBefore(os,Kr.firstChild))}function Jg(os,Kr){os.crossOrigin==null&&(os.crossOrigin=Kr.crossOrigin),os.referrerPolicy==null&&(os.referrerPolicy=Kr.referrerPolicy),os.title==null&&(os.title=Kr.title)}function Wg(os,Kr){os.crossOrigin==null&&(os.crossOrigin=Kr.crossOrigin),os.referrerPolicy==null&&(os.referrerPolicy=Kr.referrerPolicy),os.integrity==null&&(os.integrity=Kr.integrity)}var $p=null;function JE(os,Kr,Xr){if($p===null){var Ca=new Map,Pa=$p=new Map;Pa.set(Xr,Ca)}else Pa=$p,Ca=Pa.get(Xr),Ca||(Ca=new Map,Pa.set(Xr,Ca));if(Ca.has(os))return Ca;for(Ca.set(os,null),Xr=Xr.getElementsByTagName(os),Pa=0;Pa<Xr.length;Pa++){var Da=Xr[Pa];if(!(Da[Lx]||Da[Xu]||os==="link"&&Da.getAttribute("rel")==="stylesheet")&&Da.namespaceURI!=="http://www.w3.org/2000/svg"){var za=Da.getAttribute(Kr)||"";za=os+za;var Qa=Ca.get(za);Qa?Qa.push(Da):Ca.set(za,[Da])}}return Ca}function WE(os,Kr,Xr){os=os.ownerDocument||os,os.head.insertBefore(Xr,Kr==="title"?os.querySelector("head > title"):null)}function S0(os,Kr,Xr){if(Xr===1||Kr.itemProp!=null)return!1;switch(os){case"meta":case"title":return!0;case"style":if(typeof Kr.precedence!="string"||typeof Kr.href!="string"||Kr.href==="")break;return!0;case"link":if(typeof Kr.rel!="string"||typeof Kr.href!="string"||Kr.href===""||Kr.onLoad||Kr.onError)break;switch(Kr.rel){case"stylesheet":return os=Kr.disabled,typeof Kr.precedence=="string"&&os==null;default:return!0}case"script":if(Kr.async&&typeof Kr.async!="function"&&typeof Kr.async!="symbol"&&!Kr.onLoad&&!Kr.onError&&Kr.src&&typeof Kr.src=="string")return!0}return!1}function XE(os){return!(os.type==="stylesheet"&&(os.state.loading&3)===0)}function C0(os,Kr,Xr,Ca){if(Xr.type==="stylesheet"&&(typeof Ca.media!="string"||matchMedia(Ca.media).matches!==!1)&&(Xr.state.loading&4)===0){if(Xr.instance===null){var Pa=fx(Ca.href),Da=Kr.querySelector(gh(Pa));if(Da){Kr=Da._p,Kr!==null&&typeof Kr=="object"&&typeof Kr.then=="function"&&(os.count++,os=Pp.bind(os),Kr.then(os,os)),Xr.state.loading|=4,Xr.instance=Da,Qu(Da);return}Da=Kr.ownerDocument||Kr,Ca=QE(Ca),(Pa=Bc.get(Pa))&&Jg(Ca,Pa),Da=Da.createElement("link"),Qu(Da);var za=Da;za._p=new Promise(function(Qa,Xa){za.onload=Qa,za.onerror=Xa}),nc(Da,"link",Ca),Xr.instance=Da}os.stylesheets===null&&(os.stylesheets=new Map),os.stylesheets.set(Xr,Kr),(Kr=Xr.state.preload)&&(Xr.state.loading&3)===0&&(os.count++,Xr=Pp.bind(os),Kr.addEventListener("load",Xr),Kr.addEventListener("error",Xr))}}var Xg=0;function T0(os,Kr){return os.stylesheets&&os.count===0&&Mp(os,os.stylesheets),0<os.count||0<os.imgCount?function(Xr){var Ca=setTimeout(function(){if(os.stylesheets&&Mp(os,os.stylesheets),os.unsuspend){var Da=os.unsuspend;os.unsuspend=null,Da()}},6e4+Kr);0<os.imgBytes&&Xg===0&&(Xg=62500*u0());var Pa=setTimeout(function(){if(os.waitingForImages=!1,os.count===0&&(os.stylesheets&&Mp(os,os.stylesheets),os.unsuspend)){var Da=os.unsuspend;os.unsuspend=null,Da()}},(os.imgBytes>Xg?50:800)+Kr);return os.unsuspend=Xr,function(){os.unsuspend=null,clearTimeout(Ca),clearTimeout(Pa)}}:null}function Pp(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Mp(this,this.stylesheets);else if(this.unsuspend){var os=this.unsuspend;this.unsuspend=null,os()}}}var Dp=null;function Mp(os,Kr){os.stylesheets=null,os.unsuspend!==null&&(os.count++,Dp=new Map,Kr.forEach(k0,os),Dp=null,Pp.call(os))}function k0(os,Kr){if(!(Kr.state.loading&4)){var Xr=Dp.get(os);if(Xr)var Ca=Xr.get(null);else{Xr=new Map,Dp.set(os,Xr);for(var Pa=os.querySelectorAll("link[data-precedence],style[data-precedence]"),Da=0;Da<Pa.length;Da++){var za=Pa[Da];(za.nodeName==="LINK"||za.getAttribute("media")!=="not all")&&(Xr.set(za.dataset.precedence,za),Ca=za)}Ca&&Xr.set(null,Ca)}Pa=Kr.instance,za=Pa.getAttribute("data-precedence"),Da=Xr.get(za)||Ca,Da===Ca&&Xr.set(null,Pa),Xr.set(za,Pa),this.count++,Ca=Pp.bind(this),Pa.addEventListener("load",Ca),Pa.addEventListener("error",Ca),Da?Da.parentNode.insertBefore(Pa,Da.nextSibling):(os=os.nodeType===9?os.head:os,os.insertBefore(Pa,os.firstChild)),Kr.state.loading|=4}}var vh={$$typeof:Va,Provider:null,Consumer:null,_currentValue:jl,_currentValue2:jl,_threadCount:0};function A0(os,Kr,Xr,Ca,Pa,Da,za,Qa,Xa){this.tag=1,this.containerInfo=os,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=uc(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=uc(0),this.hiddenUpdates=uc(null),this.identifierPrefix=Ca,this.onUncaughtError=Pa,this.onCaughtError=Da,this.onRecoverableError=za,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=Xa,this.incompleteTransitions=new Map}function eb(os,Kr,Xr,Ca,Pa,Da,za,Qa,Xa,xl,wl,Cl){return os=new A0(os,Kr,Xr,za,Xa,xl,wl,Cl,Qa),Kr=1,Da===!0&&(Kr|=24),Da=Rc(3,null,null,Kr),os.current=Da,Da.stateNode=os,Kr=Of(),Kr.refCount++,os.pooledCache=Kr,Kr.refCount++,Da.memoizedState={element:Ca,isDehydrated:Xr,cache:Kr},Pf(Da),os}function tb(os){return os?(os=Vm,os):Vm}function sb(os,Kr,Xr,Ca,Pa,Da){Pa=tb(Pa),Ca.context===null?Ca.context=Pa:Ca.pendingContext=Pa,Ca=Ld(Kr),Ca.payload={element:Xr},Da=Da===void 0?null:Da,Da!==null&&(Ca.callback=Da),Xr=$d(os,Ca,Kr),Xr!==null&&(vc(Xr,os,Kr),Jx(Xr,os,Kr))}function nb(os,Kr){if(os=os.memoizedState,os!==null&&os.dehydrated!==null){var Xr=os.retryLane;os.retryLane=Xr!==0&&Xr<Kr?Xr:Kr}}function ej(os,Kr){nb(os,Kr),(os=os.alternate)&&nb(os,Kr)}function rb(os){if(os.tag===13||os.tag===31){var Kr=mm(os,67108864);Kr!==null&&vc(Kr,os,67108864),ej(os,67108864)}}function ib(os){if(os.tag===13||os.tag===31){var Kr=Cc();Kr=Vp(Kr);var Xr=mm(os,Kr);Xr!==null&&vc(Xr,os,Kr),ej(os,Kr)}}var Bp=!0;function O0(os,Kr,Xr,Ca){var Pa=ul.T;ul.T=null;var Da=hl.p;try{hl.p=2,tj(os,Kr,Xr,Ca)}finally{hl.p=Da,ul.T=Pa}}function I0(os,Kr,Xr,Ca){var Pa=ul.T;ul.T=null;var Da=hl.p;try{hl.p=8,tj(os,Kr,Xr,Ca)}finally{hl.p=Da,ul.T=Pa}}function tj(os,Kr,Xr,Ca){if(Bp){var Pa=sj(Ca);if(Pa===null)qg(os,Kr,Ca,Up,Xr),ob(os,Ca);else if($0(Pa,os,Kr,Xr,Ca))Ca.stopPropagation();else if(ob(os,Ca),Kr&4&&-1<L0.indexOf(os)){for(;Pa!==null;){var Da=Dm(Pa);if(Da!==null)switch(Da.tag){case 3:if(Da=Da.stateNode,Da.current.memoizedState.isDehydrated){var za=ac(Da.pendingLanes);if(za!==0){var Qa=Da;for(Qa.pendingLanes|=2,Qa.entangledLanes|=2;za;){var Xa=1<<31-Rl(za);Qa.entanglements[1]|=Xa,za&=~Xa}Xc(Da),(vu&6)===0&&(bp=Eu()+500,xh(0))}}break;case 31:case 13:Qa=mm(Da,2),Qa!==null&&vc(Qa,Da,2),_p(),ej(Da,2)}if(Da=sj(Ca),Da===null&&qg(os,Kr,Ca,Up,Xr),Da===Pa)break;Pa=Da}Pa!==null&&Ca.stopPropagation()}else qg(os,Kr,Ca,null,Xr)}}function sj(os){return os=nf(os),nj(os)}var Up=null;function nj(os){if(Up=null,os=Pm(os),os!==null){var Kr=Qr(os);if(Kr===null)os=null;else{var Xr=Kr.tag;if(Xr===13){if(os=ja(Kr),os!==null)return os;os=null}else if(Xr===31){if(os=Na(Kr),os!==null)return os;os=null}else if(Xr===3){if(Kr.stateNode.current.memoizedState.isDehydrated)return Kr.tag===3?Kr.stateNode.containerInfo:null;os=null}else Kr!==os&&(os=null)}}return Up=os,null}function ab(os){switch(os){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(Ua()){case ll:return 2;case yl:return 8;case $l:case kl:return 32;case Za:return 268435456;default:return 32}default:return 32}}var rj=!1,Gd=null,Zd=null,Vd=null,yh=new Map,Eh=new Map,Qd=[],L0="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function ob(os,Kr){switch(os){case"focusin":case"focusout":Gd=null;break;case"dragenter":case"dragleave":Zd=null;break;case"mouseover":case"mouseout":Vd=null;break;case"pointerover":case"pointerout":yh.delete(Kr.pointerId);break;case"gotpointercapture":case"lostpointercapture":Eh.delete(Kr.pointerId)}}function bh(os,Kr,Xr,Ca,Pa,Da){return os===null||os.nativeEvent!==Da?(os={blockedOn:Kr,domEventName:Xr,eventSystemFlags:Ca,nativeEvent:Da,targetContainers:[Pa]},Kr!==null&&(Kr=Dm(Kr),Kr!==null&&rb(Kr)),os):(os.eventSystemFlags|=Ca,Kr=os.targetContainers,Pa!==null&&Kr.indexOf(Pa)===-1&&Kr.push(Pa),os)}function $0(os,Kr,Xr,Ca,Pa){switch(Kr){case"focusin":return Gd=bh(Gd,os,Kr,Xr,Ca,Pa),!0;case"dragenter":return Zd=bh(Zd,os,Kr,Xr,Ca,Pa),!0;case"mouseover":return Vd=bh(Vd,os,Kr,Xr,Ca,Pa),!0;case"pointerover":var Da=Pa.pointerId;return yh.set(Da,bh(yh.get(Da)||null,os,Kr,Xr,Ca,Pa)),!0;case"gotpointercapture":return Da=Pa.pointerId,Eh.set(Da,bh(Eh.get(Da)||null,os,Kr,Xr,Ca,Pa)),!0}return!1}function lb(os){var Kr=Pm(os.target);if(Kr!==null){var Xr=Qr(Kr);if(Xr!==null){if(Kr=Xr.tag,Kr===13){if(Kr=ja(Xr),Kr!==null){os.blockedOn=Kr,bj(os.priority,function(){ib(Xr)});return}}else if(Kr===31){if(Kr=Na(Xr),Kr!==null){os.blockedOn=Kr,bj(os.priority,function(){ib(Xr)});return}}else if(Kr===3&&Xr.stateNode.current.memoizedState.isDehydrated){os.blockedOn=Xr.tag===3?Xr.stateNode.containerInfo:null;return}}}os.blockedOn=null}function qp(os){if(os.blockedOn!==null)return!1;for(var Kr=os.targetContainers;0<Kr.length;){var Xr=sj(os.nativeEvent);if(Xr===null){Xr=os.nativeEvent;var Ca=new Xr.constructor(Xr.type,Xr);sf=Ca,Xr.target.dispatchEvent(Ca),sf=null}else return Kr=Dm(Xr),Kr!==null&&rb(Kr),os.blockedOn=Xr,!1;Kr.shift()}return!0}function ub(os,Kr,Xr){qp(os)&&Xr.delete(Kr)}function P0(){rj=!1,Gd!==null&&qp(Gd)&&(Gd=null),Zd!==null&&qp(Zd)&&(Zd=null),Vd!==null&&qp(Vd)&&(Vd=null),yh.forEach(ub),Eh.forEach(ub)}function Fp(os,Kr){os.blockedOn===Kr&&(os.blockedOn=null,rj||(rj=!0,es.unstable_scheduleCallback(es.unstable_NormalPriority,P0)))}var zp=null;function cb(os){zp!==os&&(zp=os,es.unstable_scheduleCallback(es.unstable_NormalPriority,function(){zp===os&&(zp=null);for(var Kr=0;Kr<os.length;Kr+=3){var Xr=os[Kr],Ca=os[Kr+1],Pa=os[Kr+2];if(typeof Ca!="function"){if(nj(Ca||Xr)===null)continue;break}var Da=Dm(Xr);Da!==null&&(os.splice(Kr,3),Kr-=3,sg(Da,{pending:!0,data:Pa,method:Xr.method,action:Ca},Ca,Pa))}}))}function jx(os){function Kr(Xa){return Fp(Xa,os)}Gd!==null&&Fp(Gd,os),Zd!==null&&Fp(Zd,os),Vd!==null&&Fp(Vd,os),yh.forEach(Kr),Eh.forEach(Kr);for(var Xr=0;Xr<Qd.length;Xr++){var Ca=Qd[Xr];Ca.blockedOn===os&&(Ca.blockedOn=null)}for(;0<Qd.length&&(Xr=Qd[0],Xr.blockedOn===null);)lb(Xr),Xr.blockedOn===null&&Qd.shift();if(Xr=(os.ownerDocument||os).$$reactFormReplay,Xr!=null)for(Ca=0;Ca<Xr.length;Ca+=3){var Pa=Xr[Ca],Da=Xr[Ca+1],za=Pa[xc]||null;if(typeof Da=="function")za||cb(Xr);else if(za){var Qa=null;if(Da&&Da.hasAttribute("formAction")){if(Pa=Da,za=Da[xc]||null)Qa=za.formAction;else if(nj(Pa)!==null)continue}else Qa=za.action;typeof Qa=="function"?Xr[Ca+1]=Qa:(Xr.splice(Ca,3),Ca-=3),cb(Xr)}}}function db(){function os(Da){Da.canIntercept&&Da.info==="react-transition"&&Da.intercept({handler:function(){return new Promise(function(za){return Pa=za})},focusReset:"manual",scroll:"manual"})}function Kr(){Pa!==null&&(Pa(),Pa=null),Ca||setTimeout(Xr,20)}function Xr(){if(!Ca&&!navigation.transition){var Da=navigation.currentEntry;Da&&Da.url!=null&&navigation.navigate(Da.url,{state:Da.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var Ca=!1,Pa=null;return navigation.addEventListener("navigate",os),navigation.addEventListener("navigatesuccess",Kr),navigation.addEventListener("navigateerror",Kr),setTimeout(Xr,100),function(){Ca=!0,navigation.removeEventListener("navigate",os),navigation.removeEventListener("navigatesuccess",Kr),navigation.removeEventListener("navigateerror",Kr),Pa!==null&&(Pa(),Pa=null)}}}function ij(os){this._internalRoot=os}Hp.prototype.render=ij.prototype.render=function(os){var Kr=this._internalRoot;if(Kr===null)throw Error(is(409));var Xr=Kr.current,Ca=Cc();sb(Xr,Ca,os,Kr,null,null)},Hp.prototype.unmount=ij.prototype.unmount=function(){var os=this._internalRoot;if(os!==null){this._internalRoot=null;var Kr=os.containerInfo;sb(os.current,2,null,os,null,null),_p(),Kr[$m]=null}};function Hp(os){this._internalRoot=os}Hp.prototype.unstable_scheduleHydration=function(os){if(os){var Kr=Ej();os={blockedOn:null,target:os,priority:Kr};for(var Xr=0;Xr<Qd.length&&Kr!==0&&Kr<Qd[Xr].priority;Xr++);Qd.splice(Xr,0,os),Xr===0&&lb(os)}};var mb=$.version;if(mb!=="19.2.4")throw Error(is(527,mb,"19.2.4"));hl.findDOMNode=function(os){var Kr=os._reactInternals;if(Kr===void 0)throw typeof os.render=="function"?Error(is(188)):(os=Object.keys(os).join(","),Error(is(268,os)));return os=Oa(Kr),os=os!==null?Ia(os):null,os=os===null?null:os.stateNode,os};var D0={bundleType:0,version:"19.2.4",rendererPackageName:"react-dom",currentDispatcherRef:ul,reconcilerVersion:"19.2.4"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Kp=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Kp.isDisabled&&Kp.supportsFiber)try{bl=Kp.inject(D0),_l=Kp}catch{}}return reactDomClient_production.createRoot=function(os,Kr){if(!cs(os))throw Error(is(299));var Xr=!1,Ca="",Pa=vy,Da=yy,za=Ey;return Kr!=null&&(Kr.unstable_strictMode===!0&&(Xr=!0),Kr.identifierPrefix!==void 0&&(Ca=Kr.identifierPrefix),Kr.onUncaughtError!==void 0&&(Pa=Kr.onUncaughtError),Kr.onCaughtError!==void 0&&(Da=Kr.onCaughtError),Kr.onRecoverableError!==void 0&&(za=Kr.onRecoverableError)),Kr=eb(os,1,!1,null,null,Xr,Ca,null,Pa,Da,za,db),os[$m]=Kr.current,Ug(os),new ij(Kr)},reactDomClient_production.hydrateRoot=function(os,Kr,Xr){if(!cs(os))throw Error(is(299));var Ca=!1,Pa="",Da=vy,za=yy,Qa=Ey,Xa=null;return Xr!=null&&(Xr.unstable_strictMode===!0&&(Ca=!0),Xr.identifierPrefix!==void 0&&(Pa=Xr.identifierPrefix),Xr.onUncaughtError!==void 0&&(Da=Xr.onUncaughtError),Xr.onCaughtError!==void 0&&(za=Xr.onCaughtError),Xr.onRecoverableError!==void 0&&(Qa=Xr.onRecoverableError),Xr.formState!==void 0&&(Xa=Xr.formState)),Kr=eb(os,1,!0,Kr,Xr??null,Ca,Pa,Xa,Da,za,Qa,db),Kr.context=tb(null),Xr=Kr.current,Ca=Cc(),Ca=Vp(Ca),Pa=Ld(Ca),Pa.callback=null,$d(Xr,Pa,Ca),Xr=Ca,Kr.current.lanes=Xr,Wu(Kr,Xr),Xc(Kr),os[$m]=Kr.current,Ug(os),new Hp(Kr)},reactDomClient_production.version="19.2.4",reactDomClient_production}var hasRequiredClient;function requireClient(){if(hasRequiredClient)return client.exports;hasRequiredClient=1;function es(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(es)}catch($){console.error($)}}return es(),client.exports=requireReactDomClient_production(),client.exports}var clientExports=requireClient(),Subscribable=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(es){return this.listeners.add(es),this.onSubscribe(),()=>{this.listeners.delete(es),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},defaultTimeoutProvider={setTimeout:(es,$)=>setTimeout(es,$),clearTimeout:es=>clearTimeout(es),setInterval:(es,$)=>setInterval(es,$),clearInterval:es=>clearInterval(es)},Wd,yj,hb,TimeoutManager=(hb=class{constructor(){Hl(this,Wd,defaultTimeoutProvider);Hl(this,yj,!1)}setTimeoutProvider(es){Pl(this,Wd,es)}setTimeout(es,$){return Wa(this,Wd).setTimeout(es,$)}clearTimeout(es){Wa(this,Wd).clearTimeout(es)}setInterval(es,$){return Wa(this,Wd).setInterval(es,$)}clearInterval(es){Wa(this,Wd).clearInterval(es)}},Wd=new WeakMap,yj=new WeakMap,hb),timeoutManager=new TimeoutManager;function systemSetTimeoutZero(es){setTimeout(es,0)}var isServer=typeof window>"u"||"Deno"in globalThis;function noop$2(){}function functionalUpdate(es,$){return typeof es=="function"?es($):es}function isValidTimeout(es){return typeof es=="number"&&es>=0&&es!==1/0}function timeUntilStale(es,$){return Math.max(es+($||0)-Date.now(),0)}function resolveStaleTime(es,$){return typeof es=="function"?es($):es}function resolveEnabled(es,$){return typeof es=="function"?es($):es}function matchQuery(es,$){const{type:ts="all",exact:is,fetchStatus:cs,predicate:Qr,queryKey:ja,stale:Na}=es;if(ja){if(is){if($.queryHash!==hashQueryKeyByOptions(ja,$.options))return!1}else if(!partialMatchKey($.queryKey,ja))return!1}if(ts!=="all"){const Aa=$.isActive();if(ts==="active"&&!Aa||ts==="inactive"&&Aa)return!1}return!(typeof Na=="boolean"&&$.isStale()!==Na||cs&&cs!==$.state.fetchStatus||Qr&&!Qr($))}function matchMutation(es,$){const{exact:ts,status:is,predicate:cs,mutationKey:Qr}=es;if(Qr){if(!$.options.mutationKey)return!1;if(ts){if(hashKey($.options.mutationKey)!==hashKey(Qr))return!1}else if(!partialMatchKey($.options.mutationKey,Qr))return!1}return!(is&&$.state.status!==is||cs&&!cs($))}function hashQueryKeyByOptions(es,$){return(($==null?void 0:$.queryKeyHashFn)||hashKey)(es)}function hashKey(es){return JSON.stringify(es,($,ts)=>isPlainObject$1(ts)?Object.keys(ts).sort().reduce((is,cs)=>(is[cs]=ts[cs],is),{}):ts)}function partialMatchKey(es,$){return es===$?!0:typeof es!=typeof $?!1:es&&$&&typeof es=="object"&&typeof $=="object"?Object.keys($).every(ts=>partialMatchKey(es[ts],$[ts])):!1}var hasOwn=Object.prototype.hasOwnProperty;function replaceEqualDeep(es,$,ts=0){if(es===$)return es;if(ts>500)return $;const is=isPlainArray(es)&&isPlainArray($);if(!is&&!(isPlainObject$1(es)&&isPlainObject$1($)))return $;const Qr=(is?es:Object.keys(es)).length,ja=is?$:Object.keys($),Na=ja.length,Aa=is?new Array(Na):{};let Oa=0;for(let Ia=0;Ia<Na;Ia++){const La=is?Ia:ja[Ia],Ba=es[La],Ma=$[La];if(Ba===Ma){Aa[La]=Ba,(is?Ia<Qr:hasOwn.call(es,La))&&Oa++;continue}if(Ba===null||Ma===null||typeof Ba!="object"||typeof Ma!="object"){Aa[La]=Ma;continue}const qa=replaceEqualDeep(Ba,Ma,ts+1);Aa[La]=qa,qa===Ba&&Oa++}return Qr===Na&&Oa===Qr?es:Aa}function shallowEqualObjects(es,$){if(!$||Object.keys(es).length!==Object.keys($).length)return!1;for(const ts in es)if(es[ts]!==$[ts])return!1;return!0}function isPlainArray(es){return Array.isArray(es)&&es.length===Object.keys(es).length}function isPlainObject$1(es){if(!hasObjectPrototype(es))return!1;const $=es.constructor;if($===void 0)return!0;const ts=$.prototype;return!(!hasObjectPrototype(ts)||!ts.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(es)!==Object.prototype)}function hasObjectPrototype(es){return Object.prototype.toString.call(es)==="[object Object]"}function sleep$1(es){return new Promise($=>{timeoutManager.setTimeout($,es)})}function replaceData(es,$,ts){return typeof ts.structuralSharing=="function"?ts.structuralSharing(es,$):ts.structuralSharing!==!1?replaceEqualDeep(es,$):$}function addToEnd(es,$,ts=0){const is=[...es,$];return ts&&is.length>ts?is.slice(1):is}function addToStart(es,$,ts=0){const is=[$,...es];return ts&&is.length>ts?is.slice(0,-1):is}var skipToken=Symbol();function ensureQueryFn(es,$){return!es.queryFn&&($!=null&&$.initialPromise)?()=>$.initialPromise:!es.queryFn||es.queryFn===skipToken?()=>Promise.reject(new Error(`Missing queryFn: '${es.queryHash}'`)):es.queryFn}function shouldThrowError(es,$){return typeof es=="function"?es(...$):!!es}function addConsumeAwareSignal(es,$,ts){let is=!1,cs;return Object.defineProperty(es,"signal",{enumerable:!0,get:()=>(cs??(cs=$()),is||(is=!0,cs.aborted?ts():cs.addEventListener("abort",ts,{once:!0})),cs)}),es}var wm,Xd,vx,pb,FocusManager=(pb=class extends Subscribable{constructor(){super();Hl(this,wm);Hl(this,Xd);Hl(this,vx);Pl(this,vx,$=>{if(!isServer&&window.addEventListener){const ts=()=>$();return window.addEventListener("visibilitychange",ts,!1),()=>{window.removeEventListener("visibilitychange",ts)}}})}onSubscribe(){Wa(this,Xd)||this.setEventListener(Wa(this,vx))}onUnsubscribe(){var $;this.hasListeners()||(($=Wa(this,Xd))==null||$.call(this),Pl(this,Xd,void 0))}setEventListener($){var ts;Pl(this,vx,$),(ts=Wa(this,Xd))==null||ts.call(this),Pl(this,Xd,$(is=>{typeof is=="boolean"?this.setFocused(is):this.onFocus()}))}setFocused($){Wa(this,wm)!==$&&(Pl(this,wm,$),this.onFocus())}onFocus(){const $=this.isFocused();this.listeners.forEach(ts=>{ts($)})}isFocused(){var $;return typeof Wa(this,wm)=="boolean"?Wa(this,wm):(($=globalThis.document)==null?void 0:$.visibilityState)!=="hidden"}},wm=new WeakMap,Xd=new WeakMap,vx=new WeakMap,pb),focusManager=new FocusManager;function pendingThenable(){let es,$;const ts=new Promise((cs,Qr)=>{es=cs,$=Qr});ts.status="pending",ts.catch(()=>{});function is(cs){Object.assign(ts,cs),delete ts.resolve,delete ts.reject}return ts.resolve=cs=>{is({status:"fulfilled",value:cs}),es(cs)},ts.reject=cs=>{is({status:"rejected",reason:cs}),$(cs)},ts}var defaultScheduler=systemSetTimeoutZero;function createNotifyManager(){let es=[],$=0,ts=Na=>{Na()},is=Na=>{Na()},cs=defaultScheduler;const Qr=Na=>{$?es.push(Na):cs(()=>{ts(Na)})},ja=()=>{const Na=es;es=[],Na.length&&cs(()=>{is(()=>{Na.forEach(Aa=>{ts(Aa)})})})};return{batch:Na=>{let Aa;$++;try{Aa=Na()}finally{$--,$||ja()}return Aa},batchCalls:Na=>(...Aa)=>{Qr(()=>{Na(...Aa)})},schedule:Qr,setNotifyFunction:Na=>{ts=Na},setBatchNotifyFunction:Na=>{is=Na},setScheduler:Na=>{cs=Na}}}var notifyManager=createNotifyManager(),yx,em,Ex,fb,OnlineManager=(fb=class extends Subscribable{constructor(){super();Hl(this,yx,!0);Hl(this,em);Hl(this,Ex);Pl(this,Ex,$=>{if(!isServer&&window.addEventListener){const ts=()=>$(!0),is=()=>$(!1);return window.addEventListener("online",ts,!1),window.addEventListener("offline",is,!1),()=>{window.removeEventListener("online",ts),window.removeEventListener("offline",is)}}})}onSubscribe(){Wa(this,em)||this.setEventListener(Wa(this,Ex))}onUnsubscribe(){var $;this.hasListeners()||(($=Wa(this,em))==null||$.call(this),Pl(this,em,void 0))}setEventListener($){var ts;Pl(this,Ex,$),(ts=Wa(this,em))==null||ts.call(this),Pl(this,em,$(this.setOnline.bind(this)))}setOnline($){Wa(this,yx)!==$&&(Pl(this,yx,$),this.listeners.forEach(is=>{is($)}))}isOnline(){return Wa(this,yx)}},yx=new WeakMap,em=new WeakMap,Ex=new WeakMap,fb),onlineManager=new OnlineManager;function defaultRetryDelay(es){return Math.min(1e3*2**es,3e4)}function canFetch(es){return(es??"online")==="online"?onlineManager.isOnline():!0}var CancelledError=class extends Error{constructor(es){super("CancelledError"),this.revert=es==null?void 0:es.revert,this.silent=es==null?void 0:es.silent}};function createRetryer(es){let $=!1,ts=0,is;const cs=pendingThenable(),Qr=()=>cs.status!=="pending",ja=Fa=>{var Ha;if(!Qr()){const Ka=new CancelledError(Fa);Ba(Ka),(Ha=es.onCancel)==null||Ha.call(es,Ka)}},Na=()=>{$=!0},Aa=()=>{$=!1},Oa=()=>focusManager.isFocused()&&(es.networkMode==="always"||onlineManager.isOnline())&&es.canRun(),Ia=()=>canFetch(es.networkMode)&&es.canRun(),La=Fa=>{Qr()||(is==null||is(),cs.resolve(Fa))},Ba=Fa=>{Qr()||(is==null||is(),cs.reject(Fa))},Ma=()=>new Promise(Fa=>{var Ha;is=Ka=>{(Qr()||Oa())&&Fa(Ka)},(Ha=es.onPause)==null||Ha.call(es)}).then(()=>{var Fa;is=void 0,Qr()||(Fa=es.onContinue)==null||Fa.call(es)}),qa=()=>{if(Qr())return;let Fa;const Ha=ts===0?es.initialPromise:void 0;try{Fa=Ha??es.fn()}catch(Ka){Fa=Promise.reject(Ka)}Promise.resolve(Fa).then(La).catch(Ka=>{var el;if(Qr())return;const Ga=es.retry??(isServer?0:3),Va=es.retryDelay??defaultRetryDelay,Ja=typeof Va=="function"?Va(ts,Ka):Va,Ya=Ga===!0||typeof Ga=="number"&&ts<Ga||typeof Ga=="function"&&Ga(ts,Ka);if($||!Ya){Ba(Ka);return}ts++,(el=es.onFail)==null||el.call(es,ts,Ka),sleep$1(Ja).then(()=>Oa()?void 0:Ma()).then(()=>{$?Ba(Ka):qa()})})};return{promise:cs,status:()=>cs.status,cancel:ja,continue:()=>(is==null||is(),cs),cancelRetry:Na,continueRetry:Aa,canStart:Ia,start:()=>(Ia()?qa():Ma().then(qa),cs)}}var Nm,gb,Removable=(gb=class{constructor(){Hl(this,Nm)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),isValidTimeout(this.gcTime)&&Pl(this,Nm,timeoutManager.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(es){this.gcTime=Math.max(this.gcTime||0,es??(isServer?1/0:300*1e3))}clearGcTimeout(){Wa(this,Nm)&&(timeoutManager.clearTimeout(Wa(this,Nm)),Pl(this,Nm,void 0))}},Nm=new WeakMap,gb),Sm,bx,Uc,Cm,Ju,_h,Tm,Gc,Ed,jb,Query=(jb=class extends Removable{constructor($){super();Hl(this,Gc);Hl(this,Sm);Hl(this,bx);Hl(this,Uc);Hl(this,Cm);Hl(this,Ju);Hl(this,_h);Hl(this,Tm);Pl(this,Tm,!1),Pl(this,_h,$.defaultOptions),this.setOptions($.options),this.observers=[],Pl(this,Cm,$.client),Pl(this,Uc,Wa(this,Cm).getQueryCache()),this.queryKey=$.queryKey,this.queryHash=$.queryHash,Pl(this,Sm,getDefaultState$1(this.options)),this.state=$.state??Wa(this,Sm),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var $;return($=Wa(this,Ju))==null?void 0:$.promise}setOptions($){if(this.options={...Wa(this,_h),...$},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const ts=getDefaultState$1(this.options);ts.data!==void 0&&(this.setState(successState(ts.data,ts.dataUpdatedAt)),Pl(this,Sm,ts))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Wa(this,Uc).remove(this)}setData($,ts){const is=replaceData(this.state.data,$,this.options);return Xl(this,Gc,Ed).call(this,{data:is,type:"success",dataUpdatedAt:ts==null?void 0:ts.updatedAt,manual:ts==null?void 0:ts.manual}),is}setState($,ts){Xl(this,Gc,Ed).call(this,{type:"setState",state:$,setStateOptions:ts})}cancel($){var is,cs;const ts=(is=Wa(this,Ju))==null?void 0:is.promise;return(cs=Wa(this,Ju))==null||cs.cancel($),ts?ts.then(noop$2).catch(noop$2):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Wa(this,Sm))}isActive(){return this.observers.some($=>resolveEnabled($.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===skipToken||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some($=>resolveStaleTime($.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some($=>$.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime($=0){return this.state.data===void 0?!0:$==="static"?!1:this.state.isInvalidated?!0:!timeUntilStale(this.state.dataUpdatedAt,$)}onFocus(){var ts;const $=this.observers.find(is=>is.shouldFetchOnWindowFocus());$==null||$.refetch({cancelRefetch:!1}),(ts=Wa(this,Ju))==null||ts.continue()}onOnline(){var ts;const $=this.observers.find(is=>is.shouldFetchOnReconnect());$==null||$.refetch({cancelRefetch:!1}),(ts=Wa(this,Ju))==null||ts.continue()}addObserver($){this.observers.includes($)||(this.observers.push($),this.clearGcTimeout(),Wa(this,Uc).notify({type:"observerAdded",query:this,observer:$}))}removeObserver($){this.observers.includes($)&&(this.observers=this.observers.filter(ts=>ts!==$),this.observers.length||(Wa(this,Ju)&&(Wa(this,Tm)?Wa(this,Ju).cancel({revert:!0}):Wa(this,Ju).cancelRetry()),this.scheduleGc()),Wa(this,Uc).notify({type:"observerRemoved",query:this,observer:$}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Xl(this,Gc,Ed).call(this,{type:"invalidate"})}async fetch($,ts){var Aa,Oa,Ia,La,Ba,Ma,qa,Fa,Ha,Ka,Ga,Va;if(this.state.fetchStatus!=="idle"&&((Aa=Wa(this,Ju))==null?void 0:Aa.status())!=="rejected"){if(this.state.data!==void 0&&(ts!=null&&ts.cancelRefetch))this.cancel({silent:!0});else if(Wa(this,Ju))return Wa(this,Ju).continueRetry(),Wa(this,Ju).promise}if($&&this.setOptions($),!this.options.queryFn){const Ja=this.observers.find(Ya=>Ya.options.queryFn);Ja&&this.setOptions(Ja.options)}const is=new AbortController,cs=Ja=>{Object.defineProperty(Ja,"signal",{enumerable:!0,get:()=>(Pl(this,Tm,!0),is.signal)})},Qr=()=>{const Ja=ensureQueryFn(this.options,ts),el=(()=>{const tl={client:Wa(this,Cm),queryKey:this.queryKey,meta:this.meta};return cs(tl),tl})();return Pl(this,Tm,!1),this.options.persister?this.options.persister(Ja,el,this):Ja(el)},Na=(()=>{const Ja={fetchOptions:ts,options:this.options,queryKey:this.queryKey,client:Wa(this,Cm),state:this.state,fetchFn:Qr};return cs(Ja),Ja})();(Oa=this.options.behavior)==null||Oa.onFetch(Na,this),Pl(this,bx,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((Ia=Na.fetchOptions)==null?void 0:Ia.meta))&&Xl(this,Gc,Ed).call(this,{type:"fetch",meta:(La=Na.fetchOptions)==null?void 0:La.meta}),Pl(this,Ju,createRetryer({initialPromise:ts==null?void 0:ts.initialPromise,fn:Na.fetchFn,onCancel:Ja=>{Ja instanceof CancelledError&&Ja.revert&&this.setState({...Wa(this,bx),fetchStatus:"idle"}),is.abort()},onFail:(Ja,Ya)=>{Xl(this,Gc,Ed).call(this,{type:"failed",failureCount:Ja,error:Ya})},onPause:()=>{Xl(this,Gc,Ed).call(this,{type:"pause"})},onContinue:()=>{Xl(this,Gc,Ed).call(this,{type:"continue"})},retry:Na.options.retry,retryDelay:Na.options.retryDelay,networkMode:Na.options.networkMode,canRun:()=>!0}));try{const Ja=await Wa(this,Ju).start();if(Ja===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(Ja),(Ma=(Ba=Wa(this,Uc).config).onSuccess)==null||Ma.call(Ba,Ja,this),(Fa=(qa=Wa(this,Uc).config).onSettled)==null||Fa.call(qa,Ja,this.state.error,this),Ja}catch(Ja){if(Ja instanceof CancelledError){if(Ja.silent)return Wa(this,Ju).promise;if(Ja.revert){if(this.state.data===void 0)throw Ja;return this.state.data}}throw Xl(this,Gc,Ed).call(this,{type:"error",error:Ja}),(Ka=(Ha=Wa(this,Uc).config).onError)==null||Ka.call(Ha,Ja,this),(Va=(Ga=Wa(this,Uc).config).onSettled)==null||Va.call(Ga,this.state.data,Ja,this),Ja}finally{this.scheduleGc()}}},Sm=new WeakMap,bx=new WeakMap,Uc=new WeakMap,Cm=new WeakMap,Ju=new WeakMap,_h=new WeakMap,Tm=new WeakMap,Gc=new WeakSet,Ed=function($){const ts=is=>{switch($.type){case"failed":return{...is,fetchFailureCount:$.failureCount,fetchFailureReason:$.error};case"pause":return{...is,fetchStatus:"paused"};case"continue":return{...is,fetchStatus:"fetching"};case"fetch":return{...is,...fetchState(is.data,this.options),fetchMeta:$.meta??null};case"success":const cs={...is,...successState($.data,$.dataUpdatedAt),dataUpdateCount:is.dataUpdateCount+1,...!$.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Pl(this,bx,$.manual?cs:void 0),cs;case"error":const Qr=$.error;return{...is,error:Qr,errorUpdateCount:is.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:is.fetchFailureCount+1,fetchFailureReason:Qr,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...is,isInvalidated:!0};case"setState":return{...is,...$.state}}};this.state=ts(this.state),notifyManager.batch(()=>{this.observers.forEach(is=>{is.onQueryUpdate()}),Wa(this,Uc).notify({query:this,type:"updated",action:$})})},jb);function fetchState(es,$){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:canFetch($.networkMode)?"fetching":"paused",...es===void 0&&{error:null,status:"pending"}}}function successState(es,$){return{data:es,dataUpdatedAt:$??Date.now(),error:null,isInvalidated:!1,status:"success"}}function getDefaultState$1(es){const $=typeof es.initialData=="function"?es.initialData():es.initialData,ts=$!==void 0,is=ts?typeof es.initialDataUpdatedAt=="function"?es.initialDataUpdatedAt():es.initialDataUpdatedAt:0;return{data:$,dataUpdateCount:0,dataUpdatedAt:ts?is??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:ts?"success":"pending",fetchStatus:"idle"}}var yc,pu,wh,dc,km,Rx,bd,tm,Nh,_x,wx,Am,Om,sm,Nx,Ru,Rh,oj,lj,uj,cj,dj,mj,xj,Nb,vb,QueryObserver=(vb=class extends Subscribable{constructor($,ts){super();Hl(this,Ru);Hl(this,yc);Hl(this,pu);Hl(this,wh);Hl(this,dc);Hl(this,km);Hl(this,Rx);Hl(this,bd);Hl(this,tm);Hl(this,Nh);Hl(this,_x);Hl(this,wx);Hl(this,Am);Hl(this,Om);Hl(this,sm);Hl(this,Nx,new Set);this.options=ts,Pl(this,yc,$),Pl(this,tm,null),Pl(this,bd,pendingThenable()),this.bindMethods(),this.setOptions(ts)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Wa(this,pu).addObserver(this),shouldFetchOnMount(Wa(this,pu),this.options)?Xl(this,Ru,Rh).call(this):this.updateResult(),Xl(this,Ru,cj).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return shouldFetchOn(Wa(this,pu),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return shouldFetchOn(Wa(this,pu),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Xl(this,Ru,dj).call(this),Xl(this,Ru,mj).call(this),Wa(this,pu).removeObserver(this)}setOptions($){const ts=this.options,is=Wa(this,pu);if(this.options=Wa(this,yc).defaultQueryOptions($),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof resolveEnabled(this.options.enabled,Wa(this,pu))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Xl(this,Ru,xj).call(this),Wa(this,pu).setOptions(this.options),ts._defaulted&&!shallowEqualObjects(this.options,ts)&&Wa(this,yc).getQueryCache().notify({type:"observerOptionsUpdated",query:Wa(this,pu),observer:this});const cs=this.hasListeners();cs&&shouldFetchOptionally(Wa(this,pu),is,this.options,ts)&&Xl(this,Ru,Rh).call(this),this.updateResult(),cs&&(Wa(this,pu)!==is||resolveEnabled(this.options.enabled,Wa(this,pu))!==resolveEnabled(ts.enabled,Wa(this,pu))||resolveStaleTime(this.options.staleTime,Wa(this,pu))!==resolveStaleTime(ts.staleTime,Wa(this,pu)))&&Xl(this,Ru,oj).call(this);const Qr=Xl(this,Ru,lj).call(this);cs&&(Wa(this,pu)!==is||resolveEnabled(this.options.enabled,Wa(this,pu))!==resolveEnabled(ts.enabled,Wa(this,pu))||Qr!==Wa(this,sm))&&Xl(this,Ru,uj).call(this,Qr)}getOptimisticResult($){const ts=Wa(this,yc).getQueryCache().build(Wa(this,yc),$),is=this.createResult(ts,$);return shouldAssignObserverCurrentProperties(this,is)&&(Pl(this,dc,is),Pl(this,Rx,this.options),Pl(this,km,Wa(this,pu).state)),is}getCurrentResult(){return Wa(this,dc)}trackResult($,ts){return new Proxy($,{get:(is,cs)=>(this.trackProp(cs),ts==null||ts(cs),cs==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&Wa(this,bd).status==="pending"&&Wa(this,bd).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(is,cs))})}trackProp($){Wa(this,Nx).add($)}getCurrentQuery(){return Wa(this,pu)}refetch({...$}={}){return this.fetch({...$})}fetchOptimistic($){const ts=Wa(this,yc).defaultQueryOptions($),is=Wa(this,yc).getQueryCache().build(Wa(this,yc),ts);return is.fetch().then(()=>this.createResult(is,ts))}fetch($){return Xl(this,Ru,Rh).call(this,{...$,cancelRefetch:$.cancelRefetch??!0}).then(()=>(this.updateResult(),Wa(this,dc)))}createResult($,ts){var cl;const is=Wa(this,pu),cs=this.options,Qr=Wa(this,dc),ja=Wa(this,km),Na=Wa(this,Rx),Oa=$!==is?$.state:Wa(this,wh),{state:Ia}=$;let La={...Ia},Ba=!1,Ma;if(ts._optimisticResults){const dl=this.hasListeners(),fl=!dl&&shouldFetchOnMount($,ts),nl=dl&&shouldFetchOptionally($,is,ts,cs);(fl||nl)&&(La={...La,...fetchState(Ia.data,$.options)}),ts._optimisticResults==="isRestoring"&&(La.fetchStatus="idle")}let{error:qa,errorUpdatedAt:Fa,status:Ha}=La;Ma=La.data;let Ka=!1;if(ts.placeholderData!==void 0&&Ma===void 0&&Ha==="pending"){let dl;Qr!=null&&Qr.isPlaceholderData&&ts.placeholderData===(Na==null?void 0:Na.placeholderData)?(dl=Qr.data,Ka=!0):dl=typeof ts.placeholderData=="function"?ts.placeholderData((cl=Wa(this,wx))==null?void 0:cl.state.data,Wa(this,wx)):ts.placeholderData,dl!==void 0&&(Ha="success",Ma=replaceData(Qr==null?void 0:Qr.data,dl,ts),Ba=!0)}if(ts.select&&Ma!==void 0&&!Ka)if(Qr&&Ma===(ja==null?void 0:ja.data)&&ts.select===Wa(this,Nh))Ma=Wa(this,_x);else try{Pl(this,Nh,ts.select),Ma=ts.select(Ma),Ma=replaceData(Qr==null?void 0:Qr.data,Ma,ts),Pl(this,_x,Ma),Pl(this,tm,null)}catch(dl){Pl(this,tm,dl)}Wa(this,tm)&&(qa=Wa(this,tm),Ma=Wa(this,_x),Fa=Date.now(),Ha="error");const Ga=La.fetchStatus==="fetching",Va=Ha==="pending",Ja=Ha==="error",Ya=Va&&Ga,el=Ma!==void 0,rl={status:Ha,fetchStatus:La.fetchStatus,isPending:Va,isSuccess:Ha==="success",isError:Ja,isInitialLoading:Ya,isLoading:Ya,data:Ma,dataUpdatedAt:La.dataUpdatedAt,error:qa,errorUpdatedAt:Fa,failureCount:La.fetchFailureCount,failureReason:La.fetchFailureReason,errorUpdateCount:La.errorUpdateCount,isFetched:La.dataUpdateCount>0||La.errorUpdateCount>0,isFetchedAfterMount:La.dataUpdateCount>Oa.dataUpdateCount||La.errorUpdateCount>Oa.errorUpdateCount,isFetching:Ga,isRefetching:Ga&&!Va,isLoadingError:Ja&&!el,isPaused:La.fetchStatus==="paused",isPlaceholderData:Ba,isRefetchError:Ja&&el,isStale:isStale($,ts),refetch:this.refetch,promise:Wa(this,bd),isEnabled:resolveEnabled(ts.enabled,$)!==!1};if(this.options.experimental_prefetchInRender){const dl=rl.data!==void 0,fl=rl.status==="error"&&!dl,nl=Tl=>{fl?Tl.reject(rl.error):dl&&Tl.resolve(rl.data)},ol=()=>{const Tl=Pl(this,bd,rl.promise=pendingThenable());nl(Tl)},pl=Wa(this,bd);switch(pl.status){case"pending":$.queryHash===is.queryHash&&nl(pl);break;case"fulfilled":(fl||rl.data!==pl.value)&&ol();break;case"rejected":(!fl||rl.error!==pl.reason)&&ol();break}}return rl}updateResult(){const $=Wa(this,dc),ts=this.createResult(Wa(this,pu),this.options);if(Pl(this,km,Wa(this,pu).state),Pl(this,Rx,this.options),Wa(this,km).data!==void 0&&Pl(this,wx,Wa(this,pu)),shallowEqualObjects(ts,$))return;Pl(this,dc,ts);const is=()=>{if(!$)return!0;const{notifyOnChangeProps:cs}=this.options,Qr=typeof cs=="function"?cs():cs;if(Qr==="all"||!Qr&&!Wa(this,Nx).size)return!0;const ja=new Set(Qr??Wa(this,Nx));return this.options.throwOnError&&ja.add("error"),Object.keys(Wa(this,dc)).some(Na=>{const Aa=Na;return Wa(this,dc)[Aa]!==$[Aa]&&ja.has(Aa)})};Xl(this,Ru,Nb).call(this,{listeners:is()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Xl(this,Ru,cj).call(this)}},yc=new WeakMap,pu=new WeakMap,wh=new WeakMap,dc=new WeakMap,km=new WeakMap,Rx=new WeakMap,bd=new WeakMap,tm=new WeakMap,Nh=new WeakMap,_x=new WeakMap,wx=new WeakMap,Am=new WeakMap,Om=new WeakMap,sm=new WeakMap,Nx=new WeakMap,Ru=new WeakSet,Rh=function($){Xl(this,Ru,xj).call(this);let ts=Wa(this,pu).fetch(this.options,$);return $!=null&&$.throwOnError||(ts=ts.catch(noop$2)),ts},oj=function(){Xl(this,Ru,dj).call(this);const $=resolveStaleTime(this.options.staleTime,Wa(this,pu));if(isServer||Wa(this,dc).isStale||!isValidTimeout($))return;const is=timeUntilStale(Wa(this,dc).dataUpdatedAt,$)+1;Pl(this,Am,timeoutManager.setTimeout(()=>{Wa(this,dc).isStale||this.updateResult()},is))},lj=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Wa(this,pu)):this.options.refetchInterval)??!1},uj=function($){Xl(this,Ru,mj).call(this),Pl(this,sm,$),!(isServer||resolveEnabled(this.options.enabled,Wa(this,pu))===!1||!isValidTimeout(Wa(this,sm))||Wa(this,sm)===0)&&Pl(this,Om,timeoutManager.setInterval(()=>{(this.options.refetchIntervalInBackground||focusManager.isFocused())&&Xl(this,Ru,Rh).call(this)},Wa(this,sm)))},cj=function(){Xl(this,Ru,oj).call(this),Xl(this,Ru,uj).call(this,Xl(this,Ru,lj).call(this))},dj=function(){Wa(this,Am)&&(timeoutManager.clearTimeout(Wa(this,Am)),Pl(this,Am,void 0))},mj=function(){Wa(this,Om)&&(timeoutManager.clearInterval(Wa(this,Om)),Pl(this,Om,void 0))},xj=function(){const $=Wa(this,yc).getQueryCache().build(Wa(this,yc),this.options);if($===Wa(this,pu))return;const ts=Wa(this,pu);Pl(this,pu,$),Pl(this,wh,$.state),this.hasListeners()&&(ts==null||ts.removeObserver(this),$.addObserver(this))},Nb=function($){notifyManager.batch(()=>{$.listeners&&this.listeners.forEach(ts=>{ts(Wa(this,dc))}),Wa(this,yc).getQueryCache().notify({query:Wa(this,pu),type:"observerResultsUpdated"})})},vb);function shouldLoadOnMount(es,$){return resolveEnabled($.enabled,es)!==!1&&es.state.data===void 0&&!(es.state.status==="error"&&$.retryOnMount===!1)}function shouldFetchOnMount(es,$){return shouldLoadOnMount(es,$)||es.state.data!==void 0&&shouldFetchOn(es,$,$.refetchOnMount)}function shouldFetchOn(es,$,ts){if(resolveEnabled($.enabled,es)!==!1&&resolveStaleTime($.staleTime,es)!=="static"){const is=typeof ts=="function"?ts(es):ts;return is==="always"||is!==!1&&isStale(es,$)}return!1}function shouldFetchOptionally(es,$,ts,is){return(es!==$||resolveEnabled(is.enabled,es)===!1)&&(!ts.suspense||es.state.status!=="error")&&isStale(es,ts)}function isStale(es,$){return resolveEnabled($.enabled,es)!==!1&&es.isStaleByTime(resolveStaleTime($.staleTime,es))}function shouldAssignObserverCurrentProperties(es,$){return!shallowEqualObjects(es.getCurrentResult(),$)}function infiniteQueryBehavior(es){return{onFetch:($,ts)=>{var Ia,La,Ba,Ma,qa;const is=$.options,cs=(Ba=(La=(Ia=$.fetchOptions)==null?void 0:Ia.meta)==null?void 0:La.fetchMore)==null?void 0:Ba.direction,Qr=((Ma=$.state.data)==null?void 0:Ma.pages)||[],ja=((qa=$.state.data)==null?void 0:qa.pageParams)||[];let Na={pages:[],pageParams:[]},Aa=0;const Oa=async()=>{let Fa=!1;const Ha=Va=>{addConsumeAwareSignal(Va,()=>$.signal,()=>Fa=!0)},Ka=ensureQueryFn($.options,$.fetchOptions),Ga=async(Va,Ja,Ya)=>{if(Fa)return Promise.reject();if(Ja==null&&Va.pages.length)return Promise.resolve(Va);const tl=(()=>{const fl={client:$.client,queryKey:$.queryKey,pageParam:Ja,direction:Ya?"backward":"forward",meta:$.options.meta};return Ha(fl),fl})(),rl=await Ka(tl),{maxPages:cl}=$.options,dl=Ya?addToStart:addToEnd;return{pages:dl(Va.pages,rl,cl),pageParams:dl(Va.pageParams,Ja,cl)}};if(cs&&Qr.length){const Va=cs==="backward",Ja=Va?getPreviousPageParam:getNextPageParam,Ya={pages:Qr,pageParams:ja},el=Ja(is,Ya);Na=await Ga(Ya,el,Va)}else{const Va=es??Qr.length;do{const Ja=Aa===0?ja[0]??is.initialPageParam:getNextPageParam(is,Na);if(Aa>0&&Ja==null)break;Na=await Ga(Na,Ja),Aa++}while(Aa<Va)}return Na};$.options.persister?$.fetchFn=()=>{var Fa,Ha;return(Ha=(Fa=$.options).persister)==null?void 0:Ha.call(Fa,Oa,{client:$.client,queryKey:$.queryKey,meta:$.options.meta,signal:$.signal},ts)}:$.fetchFn=Oa}}}function getNextPageParam(es,{pages:$,pageParams:ts}){const is=$.length-1;return $.length>0?es.getNextPageParam($[is],$,ts[is],ts):void 0}function getPreviousPageParam(es,{pages:$,pageParams:ts}){var is;return $.length>0?(is=es.getPreviousPageParam)==null?void 0:is.call(es,$[0],$,ts[0],ts):void 0}function hasNextPage(es,$){return $?getNextPageParam(es,$)!=null:!1}function hasPreviousPage(es,$){return!$||!es.getPreviousPageParam?!1:getPreviousPageParam(es,$)!=null}var InfiniteQueryObserver=class extends QueryObserver{constructor(es,$){super(es,$)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(es){super.setOptions({...es,behavior:infiniteQueryBehavior()})}getOptimisticResult(es){return es.behavior=infiniteQueryBehavior(),super.getOptimisticResult(es)}fetchNextPage(es){return this.fetch({...es,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(es){return this.fetch({...es,meta:{fetchMore:{direction:"backward"}}})}createResult(es,$){var qa,Fa;const{state:ts}=es,is=super.createResult(es,$),{isFetching:cs,isRefetching:Qr,isError:ja,isRefetchError:Na}=is,Aa=(Fa=(qa=ts.fetchMeta)==null?void 0:qa.fetchMore)==null?void 0:Fa.direction,Oa=ja&&Aa==="forward",Ia=cs&&Aa==="forward",La=ja&&Aa==="backward",Ba=cs&&Aa==="backward";return{...is,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:hasNextPage($,ts.data),hasPreviousPage:hasPreviousPage($,ts.data),isFetchNextPageError:Oa,isFetchingNextPage:Ia,isFetchPreviousPageError:La,isFetchingPreviousPage:Ba,isRefetchError:Na&&!Oa&&!La,isRefetching:Qr&&!Ia&&!Ba}}},Sh,ed,oc,Im,td,Jd,yb,Mutation=(yb=class extends Removable{constructor($){super();Hl(this,td);Hl(this,Sh);Hl(this,ed);Hl(this,oc);Hl(this,Im);Pl(this,Sh,$.client),this.mutationId=$.mutationId,Pl(this,oc,$.mutationCache),Pl(this,ed,[]),this.state=$.state||getDefaultState(),this.setOptions($.options),this.scheduleGc()}setOptions($){this.options=$,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver($){Wa(this,ed).includes($)||(Wa(this,ed).push($),this.clearGcTimeout(),Wa(this,oc).notify({type:"observerAdded",mutation:this,observer:$}))}removeObserver($){Pl(this,ed,Wa(this,ed).filter(ts=>ts!==$)),this.scheduleGc(),Wa(this,oc).notify({type:"observerRemoved",mutation:this,observer:$})}optionalRemove(){Wa(this,ed).length||(this.state.status==="pending"?this.scheduleGc():Wa(this,oc).remove(this))}continue(){var $;return(($=Wa(this,Im))==null?void 0:$.continue())??this.execute(this.state.variables)}async execute($){var ja,Na,Aa,Oa,Ia,La,Ba,Ma,qa,Fa,Ha,Ka,Ga,Va,Ja,Ya,el,tl;const ts=()=>{Xl(this,td,Jd).call(this,{type:"continue"})},is={client:Wa(this,Sh),meta:this.options.meta,mutationKey:this.options.mutationKey};Pl(this,Im,createRetryer({fn:()=>this.options.mutationFn?this.options.mutationFn($,is):Promise.reject(new Error("No mutationFn found")),onFail:(rl,cl)=>{Xl(this,td,Jd).call(this,{type:"failed",failureCount:rl,error:cl})},onPause:()=>{Xl(this,td,Jd).call(this,{type:"pause"})},onContinue:ts,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Wa(this,oc).canRun(this)}));const cs=this.state.status==="pending",Qr=!Wa(this,Im).canStart();try{if(cs)ts();else{Xl(this,td,Jd).call(this,{type:"pending",variables:$,isPaused:Qr}),Wa(this,oc).config.onMutate&&await Wa(this,oc).config.onMutate($,this,is);const cl=await((Na=(ja=this.options).onMutate)==null?void 0:Na.call(ja,$,is));cl!==this.state.context&&Xl(this,td,Jd).call(this,{type:"pending",context:cl,variables:$,isPaused:Qr})}const rl=await Wa(this,Im).start();return await((Oa=(Aa=Wa(this,oc).config).onSuccess)==null?void 0:Oa.call(Aa,rl,$,this.state.context,this,is)),await((La=(Ia=this.options).onSuccess)==null?void 0:La.call(Ia,rl,$,this.state.context,is)),await((Ma=(Ba=Wa(this,oc).config).onSettled)==null?void 0:Ma.call(Ba,rl,null,this.state.variables,this.state.context,this,is)),await((Fa=(qa=this.options).onSettled)==null?void 0:Fa.call(qa,rl,null,$,this.state.context,is)),Xl(this,td,Jd).call(this,{type:"success",data:rl}),rl}catch(rl){try{await((Ka=(Ha=Wa(this,oc).config).onError)==null?void 0:Ka.call(Ha,rl,$,this.state.context,this,is))}catch(cl){Promise.reject(cl)}try{await((Va=(Ga=this.options).onError)==null?void 0:Va.call(Ga,rl,$,this.state.context,is))}catch(cl){Promise.reject(cl)}try{await((Ya=(Ja=Wa(this,oc).config).onSettled)==null?void 0:Ya.call(Ja,void 0,rl,this.state.variables,this.state.context,this,is))}catch(cl){Promise.reject(cl)}try{await((tl=(el=this.options).onSettled)==null?void 0:tl.call(el,void 0,rl,$,this.state.context,is))}catch(cl){Promise.reject(cl)}throw Xl(this,td,Jd).call(this,{type:"error",error:rl}),rl}finally{Wa(this,oc).runNext(this)}}},Sh=new WeakMap,ed=new WeakMap,oc=new WeakMap,Im=new WeakMap,td=new WeakSet,Jd=function($){const ts=is=>{switch($.type){case"failed":return{...is,failureCount:$.failureCount,failureReason:$.error};case"pause":return{...is,isPaused:!0};case"continue":return{...is,isPaused:!1};case"pending":return{...is,context:$.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:$.isPaused,status:"pending",variables:$.variables,submittedAt:Date.now()};case"success":return{...is,data:$.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...is,data:void 0,error:$.error,failureCount:is.failureCount+1,failureReason:$.error,isPaused:!1,status:"error"}}};this.state=ts(this.state),notifyManager.batch(()=>{Wa(this,ed).forEach(is=>{is.onMutationUpdate($)}),Wa(this,oc).notify({mutation:this,type:"updated",action:$})})},yb);function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Rd,Zc,Ch,Eb,MutationCache=(Eb=class extends Subscribable{constructor($={}){super();Hl(this,Rd);Hl(this,Zc);Hl(this,Ch);this.config=$,Pl(this,Rd,new Set),Pl(this,Zc,new Map),Pl(this,Ch,0)}build($,ts,is){const cs=new Mutation({client:$,mutationCache:this,mutationId:++Gp(this,Ch)._,options:$.defaultMutationOptions(ts),state:is});return this.add(cs),cs}add($){Wa(this,Rd).add($);const ts=scopeFor($);if(typeof ts=="string"){const is=Wa(this,Zc).get(ts);is?is.push($):Wa(this,Zc).set(ts,[$])}this.notify({type:"added",mutation:$})}remove($){if(Wa(this,Rd).delete($)){const ts=scopeFor($);if(typeof ts=="string"){const is=Wa(this,Zc).get(ts);if(is)if(is.length>1){const cs=is.indexOf($);cs!==-1&&is.splice(cs,1)}else is[0]===$&&Wa(this,Zc).delete(ts)}}this.notify({type:"removed",mutation:$})}canRun($){const ts=scopeFor($);if(typeof ts=="string"){const is=Wa(this,Zc).get(ts),cs=is==null?void 0:is.find(Qr=>Qr.state.status==="pending");return!cs||cs===$}else return!0}runNext($){var is;const ts=scopeFor($);if(typeof ts=="string"){const cs=(is=Wa(this,Zc).get(ts))==null?void 0:is.find(Qr=>Qr!==$&&Qr.state.isPaused);return(cs==null?void 0:cs.continue())??Promise.resolve()}else return Promise.resolve()}clear(){notifyManager.batch(()=>{Wa(this,Rd).forEach($=>{this.notify({type:"removed",mutation:$})}),Wa(this,Rd).clear(),Wa(this,Zc).clear()})}getAll(){return Array.from(Wa(this,Rd))}find($){const ts={exact:!0,...$};return this.getAll().find(is=>matchMutation(ts,is))}findAll($={}){return this.getAll().filter(ts=>matchMutation($,ts))}notify($){notifyManager.batch(()=>{this.listeners.forEach(ts=>{ts($)})})}resumePausedMutations(){const $=this.getAll().filter(ts=>ts.state.isPaused);return notifyManager.batch(()=>Promise.all($.map(ts=>ts.continue().catch(noop$2))))}},Rd=new WeakMap,Zc=new WeakMap,Ch=new WeakMap,Eb);function scopeFor(es){var $;return($=es.options.scope)==null?void 0:$.id}var _d,nm,Ec,wd,Nd,Zp,hj,bb,MutationObserver$1=(bb=class extends Subscribable{constructor(ts,is){super();Hl(this,Nd);Hl(this,_d);Hl(this,nm);Hl(this,Ec);Hl(this,wd);Pl(this,_d,ts),this.setOptions(is),this.bindMethods(),Xl(this,Nd,Zp).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(ts){var cs;const is=this.options;this.options=Wa(this,_d).defaultMutationOptions(ts),shallowEqualObjects(this.options,is)||Wa(this,_d).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Wa(this,Ec),observer:this}),is!=null&&is.mutationKey&&this.options.mutationKey&&hashKey(is.mutationKey)!==hashKey(this.options.mutationKey)?this.reset():((cs=Wa(this,Ec))==null?void 0:cs.state.status)==="pending"&&Wa(this,Ec).setOptions(this.options)}onUnsubscribe(){var ts;this.hasListeners()||(ts=Wa(this,Ec))==null||ts.removeObserver(this)}onMutationUpdate(ts){Xl(this,Nd,Zp).call(this),Xl(this,Nd,hj).call(this,ts)}getCurrentResult(){return Wa(this,nm)}reset(){var ts;(ts=Wa(this,Ec))==null||ts.removeObserver(this),Pl(this,Ec,void 0),Xl(this,Nd,Zp).call(this),Xl(this,Nd,hj).call(this)}mutate(ts,is){var cs;return Pl(this,wd,is),(cs=Wa(this,Ec))==null||cs.removeObserver(this),Pl(this,Ec,Wa(this,_d).getMutationCache().build(Wa(this,_d),this.options)),Wa(this,Ec).addObserver(this),Wa(this,Ec).execute(ts)}},_d=new WeakMap,nm=new WeakMap,Ec=new WeakMap,wd=new WeakMap,Nd=new WeakSet,Zp=function(){var is;const ts=((is=Wa(this,Ec))==null?void 0:is.state)??getDefaultState();Pl(this,nm,{...ts,isPending:ts.status==="pending",isSuccess:ts.status==="success",isError:ts.status==="error",isIdle:ts.status==="idle",mutate:this.mutate,reset:this.reset})},hj=function(ts){notifyManager.batch(()=>{var is,cs,Qr,ja,Na,Aa,Oa,Ia;if(Wa(this,wd)&&this.hasListeners()){const La=Wa(this,nm).variables,Ba=Wa(this,nm).context,Ma={client:Wa(this,_d),meta:this.options.meta,mutationKey:this.options.mutationKey};if((ts==null?void 0:ts.type)==="success"){try{(cs=(is=Wa(this,wd)).onSuccess)==null||cs.call(is,ts.data,La,Ba,Ma)}catch(qa){Promise.reject(qa)}try{(ja=(Qr=Wa(this,wd)).onSettled)==null||ja.call(Qr,ts.data,null,La,Ba,Ma)}catch(qa){Promise.reject(qa)}}else if((ts==null?void 0:ts.type)==="error"){try{(Aa=(Na=Wa(this,wd)).onError)==null||Aa.call(Na,ts.error,La,Ba,Ma)}catch(qa){Promise.reject(qa)}try{(Ia=(Oa=Wa(this,wd)).onSettled)==null||Ia.call(Oa,void 0,ts.error,La,Ba,Ma)}catch(qa){Promise.reject(qa)}}}this.listeners.forEach(La=>{La(Wa(this,nm))})})},bb);function difference(es,$){const ts=new Set($);return es.filter(is=>!ts.has(is))}function replaceAt(es,$,ts){const is=es.slice(0);return is[$]=ts,is}var Sx,Tc,Cx,Tx,qc,rm,Th,kh,Ah,Oh,rc,pj,fj,gj,jj,vj,Rb,QueriesObserver=(Rb=class extends Subscribable{constructor($,ts,is){super();Hl(this,rc);Hl(this,Sx);Hl(this,Tc);Hl(this,Cx);Hl(this,Tx);Hl(this,qc);Hl(this,rm);Hl(this,Th);Hl(this,kh);Hl(this,Ah);Hl(this,Oh,[]);Pl(this,Sx,$),Pl(this,Tx,is),Pl(this,Cx,[]),Pl(this,qc,[]),Pl(this,Tc,[]),this.setQueries(ts)}onSubscribe(){this.listeners.size===1&&Wa(this,qc).forEach($=>{$.subscribe(ts=>{Xl(this,rc,jj).call(this,$,ts)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,Wa(this,qc).forEach($=>{$.destroy()})}setQueries($,ts){Pl(this,Cx,$),Pl(this,Tx,ts),notifyManager.batch(()=>{const is=Wa(this,qc),cs=Xl(this,rc,gj).call(this,Wa(this,Cx));cs.forEach(La=>La.observer.setOptions(La.defaultedQueryOptions));const Qr=cs.map(La=>La.observer),ja=Qr.map(La=>La.getCurrentResult()),Na=is.length!==Qr.length,Aa=Qr.some((La,Ba)=>La!==is[Ba]),Oa=Na||Aa,Ia=Oa?!0:ja.some((La,Ba)=>{const Ma=Wa(this,Tc)[Ba];return!Ma||!shallowEqualObjects(La,Ma)});!Oa&&!Ia||(Oa&&(Pl(this,Oh,cs),Pl(this,qc,Qr)),Pl(this,Tc,ja),this.hasListeners()&&(Oa&&(difference(is,Qr).forEach(La=>{La.destroy()}),difference(Qr,is).forEach(La=>{La.subscribe(Ba=>{Xl(this,rc,jj).call(this,La,Ba)})})),Xl(this,rc,vj).call(this)))})}getCurrentResult(){return Wa(this,Tc)}getQueries(){return Wa(this,qc).map($=>$.getCurrentQuery())}getObservers(){return Wa(this,qc)}getOptimisticResult($,ts){const is=Xl(this,rc,gj).call(this,$),cs=is.map(ja=>ja.observer.getOptimisticResult(ja.defaultedQueryOptions)),Qr=is.map(ja=>ja.defaultedQueryOptions.queryHash);return[cs,ja=>Xl(this,rc,fj).call(this,ja??cs,ts,Qr),()=>Xl(this,rc,pj).call(this,cs,is)]}},Sx=new WeakMap,Tc=new WeakMap,Cx=new WeakMap,Tx=new WeakMap,qc=new WeakMap,rm=new WeakMap,Th=new WeakMap,kh=new WeakMap,Ah=new WeakMap,Oh=new WeakMap,rc=new WeakSet,pj=function($,ts){return ts.map((is,cs)=>{const Qr=$[cs];return is.defaultedQueryOptions.notifyOnChangeProps?Qr:is.observer.trackResult(Qr,ja=>{ts.forEach(Na=>{Na.observer.trackProp(ja)})})})},fj=function($,ts,is){if(ts){const cs=Wa(this,Ah),Qr=is!==void 0&&cs!==void 0&&(cs.length!==is.length||is.some((ja,Na)=>ja!==cs[Na]));return(!Wa(this,rm)||Wa(this,Tc)!==Wa(this,kh)||Qr||ts!==Wa(this,Th))&&(Pl(this,Th,ts),Pl(this,kh,Wa(this,Tc)),is!==void 0&&Pl(this,Ah,is),Pl(this,rm,replaceEqualDeep(Wa(this,rm),ts($)))),Wa(this,rm)}return $},gj=function($){const ts=new Map;Wa(this,qc).forEach(cs=>{const Qr=cs.options.queryHash;if(!Qr)return;const ja=ts.get(Qr);ja?ja.push(cs):ts.set(Qr,[cs])});const is=[];return $.forEach(cs=>{var Aa;const Qr=Wa(this,Sx).defaultQueryOptions(cs),Na=((Aa=ts.get(Qr.queryHash))==null?void 0:Aa.shift())??new QueryObserver(Wa(this,Sx),Qr);is.push({defaultedQueryOptions:Qr,observer:Na})}),is},jj=function($,ts){const is=Wa(this,qc).indexOf($);is!==-1&&(Pl(this,Tc,replaceAt(Wa(this,Tc),is,ts)),Xl(this,rc,vj).call(this))},vj=function(){var $;if(this.hasListeners()){const ts=Wa(this,rm),is=Xl(this,rc,pj).call(this,Wa(this,Tc),Wa(this,Oh)),cs=Xl(this,rc,fj).call(this,is,($=Wa(this,Tx))==null?void 0:$.combine);ts!==cs&¬ifyManager.batch(()=>{this.listeners.forEach(Qr=>{Qr(Wa(this,Tc))})})}},Rb),sd,_b,QueryCache=(_b=class extends Subscribable{constructor($={}){super();Hl(this,sd);this.config=$,Pl(this,sd,new Map)}build($,ts,is){const cs=ts.queryKey,Qr=ts.queryHash??hashQueryKeyByOptions(cs,ts);let ja=this.get(Qr);return ja||(ja=new Query({client:$,queryKey:cs,queryHash:Qr,options:$.defaultQueryOptions(ts),state:is,defaultOptions:$.getQueryDefaults(cs)}),this.add(ja)),ja}add($){Wa(this,sd).has($.queryHash)||(Wa(this,sd).set($.queryHash,$),this.notify({type:"added",query:$}))}remove($){const ts=Wa(this,sd).get($.queryHash);ts&&($.destroy(),ts===$&&Wa(this,sd).delete($.queryHash),this.notify({type:"removed",query:$}))}clear(){notifyManager.batch(()=>{this.getAll().forEach($=>{this.remove($)})})}get($){return Wa(this,sd).get($)}getAll(){return[...Wa(this,sd).values()]}find($){const ts={exact:!0,...$};return this.getAll().find(is=>matchQuery(ts,is))}findAll($={}){const ts=this.getAll();return Object.keys($).length>0?ts.filter(is=>matchQuery($,is)):ts}notify($){notifyManager.batch(()=>{this.listeners.forEach(ts=>{ts($)})})}onFocus(){notifyManager.batch(()=>{this.getAll().forEach($=>{$.onFocus()})})}onOnline(){notifyManager.batch(()=>{this.getAll().forEach($=>{$.onOnline()})})}},sd=new WeakMap,_b),qu,im,am,kx,Ax,om,Ox,Ix,wb,QueryClient=(wb=class{constructor(es={}){Hl(this,qu);Hl(this,im);Hl(this,am);Hl(this,kx);Hl(this,Ax);Hl(this,om);Hl(this,Ox);Hl(this,Ix);Pl(this,qu,es.queryCache||new QueryCache),Pl(this,im,es.mutationCache||new MutationCache),Pl(this,am,es.defaultOptions||{}),Pl(this,kx,new Map),Pl(this,Ax,new Map),Pl(this,om,0)}mount(){Gp(this,om)._++,Wa(this,om)===1&&(Pl(this,Ox,focusManager.subscribe(async es=>{es&&(await this.resumePausedMutations(),Wa(this,qu).onFocus())})),Pl(this,Ix,onlineManager.subscribe(async es=>{es&&(await this.resumePausedMutations(),Wa(this,qu).onOnline())})))}unmount(){var es,$;Gp(this,om)._--,Wa(this,om)===0&&((es=Wa(this,Ox))==null||es.call(this),Pl(this,Ox,void 0),($=Wa(this,Ix))==null||$.call(this),Pl(this,Ix,void 0))}isFetching(es){return Wa(this,qu).findAll({...es,fetchStatus:"fetching"}).length}isMutating(es){return Wa(this,im).findAll({...es,status:"pending"}).length}getQueryData(es){var ts;const $=this.defaultQueryOptions({queryKey:es});return(ts=Wa(this,qu).get($.queryHash))==null?void 0:ts.state.data}ensureQueryData(es){const $=this.defaultQueryOptions(es),ts=Wa(this,qu).build(this,$),is=ts.state.data;return is===void 0?this.fetchQuery(es):(es.revalidateIfStale&&ts.isStaleByTime(resolveStaleTime($.staleTime,ts))&&this.prefetchQuery($),Promise.resolve(is))}getQueriesData(es){return Wa(this,qu).findAll(es).map(({queryKey:$,state:ts})=>{const is=ts.data;return[$,is]})}setQueryData(es,$,ts){const is=this.defaultQueryOptions({queryKey:es}),cs=Wa(this,qu).get(is.queryHash),Qr=cs==null?void 0:cs.state.data,ja=functionalUpdate($,Qr);if(ja!==void 0)return Wa(this,qu).build(this,is).setData(ja,{...ts,manual:!0})}setQueriesData(es,$,ts){return notifyManager.batch(()=>Wa(this,qu).findAll(es).map(({queryKey:is})=>[is,this.setQueryData(is,$,ts)]))}getQueryState(es){var ts;const $=this.defaultQueryOptions({queryKey:es});return(ts=Wa(this,qu).get($.queryHash))==null?void 0:ts.state}removeQueries(es){const $=Wa(this,qu);notifyManager.batch(()=>{$.findAll(es).forEach(ts=>{$.remove(ts)})})}resetQueries(es,$){const ts=Wa(this,qu);return notifyManager.batch(()=>(ts.findAll(es).forEach(is=>{is.reset()}),this.refetchQueries({type:"active",...es},$)))}cancelQueries(es,$={}){const ts={revert:!0,...$},is=notifyManager.batch(()=>Wa(this,qu).findAll(es).map(cs=>cs.cancel(ts)));return Promise.all(is).then(noop$2).catch(noop$2)}invalidateQueries(es,$={}){return notifyManager.batch(()=>(Wa(this,qu).findAll(es).forEach(ts=>{ts.invalidate()}),(es==null?void 0:es.refetchType)==="none"?Promise.resolve():this.refetchQueries({...es,type:(es==null?void 0:es.refetchType)??(es==null?void 0:es.type)??"active"},$)))}refetchQueries(es,$={}){const ts={...$,cancelRefetch:$.cancelRefetch??!0},is=notifyManager.batch(()=>Wa(this,qu).findAll(es).filter(cs=>!cs.isDisabled()&&!cs.isStatic()).map(cs=>{let Qr=cs.fetch(void 0,ts);return ts.throwOnError||(Qr=Qr.catch(noop$2)),cs.state.fetchStatus==="paused"?Promise.resolve():Qr}));return Promise.all(is).then(noop$2)}fetchQuery(es){const $=this.defaultQueryOptions(es);$.retry===void 0&&($.retry=!1);const ts=Wa(this,qu).build(this,$);return ts.isStaleByTime(resolveStaleTime($.staleTime,ts))?ts.fetch($):Promise.resolve(ts.state.data)}prefetchQuery(es){return this.fetchQuery(es).then(noop$2).catch(noop$2)}fetchInfiniteQuery(es){return es.behavior=infiniteQueryBehavior(es.pages),this.fetchQuery(es)}prefetchInfiniteQuery(es){return this.fetchInfiniteQuery(es).then(noop$2).catch(noop$2)}ensureInfiniteQueryData(es){return es.behavior=infiniteQueryBehavior(es.pages),this.ensureQueryData(es)}resumePausedMutations(){return onlineManager.isOnline()?Wa(this,im).resumePausedMutations():Promise.resolve()}getQueryCache(){return Wa(this,qu)}getMutationCache(){return Wa(this,im)}getDefaultOptions(){return Wa(this,am)}setDefaultOptions(es){Pl(this,am,es)}setQueryDefaults(es,$){Wa(this,kx).set(hashKey(es),{queryKey:es,defaultOptions:$})}getQueryDefaults(es){const $=[...Wa(this,kx).values()],ts={};return $.forEach(is=>{partialMatchKey(es,is.queryKey)&&Object.assign(ts,is.defaultOptions)}),ts}setMutationDefaults(es,$){Wa(this,Ax).set(hashKey(es),{mutationKey:es,defaultOptions:$})}getMutationDefaults(es){const $=[...Wa(this,Ax).values()],ts={};return $.forEach(is=>{partialMatchKey(es,is.mutationKey)&&Object.assign(ts,is.defaultOptions)}),ts}defaultQueryOptions(es){if(es._defaulted)return es;const $={...Wa(this,am).queries,...this.getQueryDefaults(es.queryKey),...es,_defaulted:!0};return $.queryHash||($.queryHash=hashQueryKeyByOptions($.queryKey,$)),$.refetchOnReconnect===void 0&&($.refetchOnReconnect=$.networkMode!=="always"),$.throwOnError===void 0&&($.throwOnError=!!$.suspense),!$.networkMode&&$.persister&&($.networkMode="offlineFirst"),$.queryFn===skipToken&&($.enabled=!1),$}defaultMutationOptions(es){return es!=null&&es._defaulted?es:{...Wa(this,am).mutations,...(es==null?void 0:es.mutationKey)&&this.getMutationDefaults(es.mutationKey),...es,_defaulted:!0}}clear(){Wa(this,qu).clear(),Wa(this,im).clear()}},qu=new WeakMap,im=new WeakMap,am=new WeakMap,kx=new WeakMap,Ax=new WeakMap,om=new WeakMap,Ox=new WeakMap,Ix=new WeakMap,wb),QueryClientContext=reactExports.createContext(void 0),useQueryClient=es=>{const $=reactExports.useContext(QueryClientContext);if(!$)throw new Error("No QueryClient set, use QueryClientProvider to set one");return $},QueryClientProvider=({client:es,children:$})=>(reactExports.useEffect(()=>(es.mount(),()=>{es.unmount()}),[es]),jsxRuntimeExports.jsx(QueryClientContext.Provider,{value:es,children:$})),IsRestoringContext=reactExports.createContext(!1),useIsRestoring=()=>reactExports.useContext(IsRestoringContext);IsRestoringContext.Provider;function createValue(){let es=!1;return{clearReset:()=>{es=!1},reset:()=>{es=!0},isReset:()=>es}}var QueryErrorResetBoundaryContext=reactExports.createContext(createValue()),useQueryErrorResetBoundary=()=>reactExports.useContext(QueryErrorResetBoundaryContext),ensurePreventErrorBoundaryRetry=(es,$,ts)=>{const is=ts!=null&&ts.state.error&&typeof es.throwOnError=="function"?shouldThrowError(es.throwOnError,[ts.state.error,ts]):es.throwOnError;(es.suspense||es.experimental_prefetchInRender||is)&&($.isReset()||(es.retryOnMount=!1))},useClearResetErrorBoundary=es=>{reactExports.useEffect(()=>{es.clearReset()},[es])},getHasError=({result:es,errorResetBoundary:$,throwOnError:ts,query:is,suspense:cs})=>es.isError&&!$.isReset()&&!es.isFetching&&is&&(cs&&es.data===void 0||shouldThrowError(ts,[es.error,is])),ensureSuspenseTimers=es=>{if(es.suspense){const ts=cs=>cs==="static"?cs:Math.max(cs??1e3,1e3),is=es.staleTime;es.staleTime=typeof is=="function"?(...cs)=>ts(is(...cs)):ts(is),typeof es.gcTime=="number"&&(es.gcTime=Math.max(es.gcTime,1e3))}},willFetch=(es,$)=>es.isLoading&&es.isFetching&&!$,shouldSuspend=(es,$)=>(es==null?void 0:es.suspense)&&$.isPending,fetchOptimistic=(es,$,ts)=>$.fetchOptimistic(es).catch(()=>{ts.clearReset()});function useQueries({queries:es,...$},ts){const is=useQueryClient(),cs=useIsRestoring(),Qr=useQueryErrorResetBoundary(),ja=reactExports.useMemo(()=>es.map(Fa=>{const Ha=is.defaultQueryOptions(Fa);return Ha._optimisticResults=cs?"isRestoring":"optimistic",Ha}),[es,is,cs]);ja.forEach(Fa=>{ensureSuspenseTimers(Fa);const Ha=is.getQueryCache().get(Fa.queryHash);ensurePreventErrorBoundaryRetry(Fa,Qr,Ha)}),useClearResetErrorBoundary(Qr);const[Na]=reactExports.useState(()=>new QueriesObserver(is,ja,$)),[Aa,Oa,Ia]=Na.getOptimisticResult(ja,$.combine),La=!cs&&$.subscribed!==!1;reactExports.useSyncExternalStore(reactExports.useCallback(Fa=>La?Na.subscribe(notifyManager.batchCalls(Fa)):noop$2,[Na,La]),()=>Na.getCurrentResult(),()=>Na.getCurrentResult()),reactExports.useEffect(()=>{Na.setQueries(ja,$)},[ja,$,Na]);const Ma=Aa.some((Fa,Ha)=>shouldSuspend(ja[Ha],Fa))?Aa.flatMap((Fa,Ha)=>{const Ka=ja[Ha];if(Ka&&shouldSuspend(Ka,Fa)){const Ga=new QueryObserver(is,Ka);return fetchOptimistic(Ka,Ga,Qr)}return[]}):[];if(Ma.length>0)throw Promise.all(Ma);const qa=Aa.find((Fa,Ha)=>{const Ka=ja[Ha];return Ka&&getHasError({result:Fa,errorResetBoundary:Qr,throwOnError:Ka.throwOnError,query:is.getQueryCache().get(Ka.queryHash),suspense:Ka.suspense})});if(qa!=null&&qa.error)throw qa.error;return Oa(Ia())}function useBaseQuery(es,$,ts){var Ba,Ma,qa,Fa;const is=useIsRestoring(),cs=useQueryErrorResetBoundary(),Qr=useQueryClient(),ja=Qr.defaultQueryOptions(es);(Ma=(Ba=Qr.getDefaultOptions().queries)==null?void 0:Ba._experimental_beforeQuery)==null||Ma.call(Ba,ja);const Na=Qr.getQueryCache().get(ja.queryHash);ja._optimisticResults=is?"isRestoring":"optimistic",ensureSuspenseTimers(ja),ensurePreventErrorBoundaryRetry(ja,cs,Na),useClearResetErrorBoundary(cs);const Aa=!Qr.getQueryCache().get(ja.queryHash),[Oa]=reactExports.useState(()=>new $(Qr,ja)),Ia=Oa.getOptimisticResult(ja),La=!is&&es.subscribed!==!1;if(reactExports.useSyncExternalStore(reactExports.useCallback(Ha=>{const Ka=La?Oa.subscribe(notifyManager.batchCalls(Ha)):noop$2;return Oa.updateResult(),Ka},[Oa,La]),()=>Oa.getCurrentResult(),()=>Oa.getCurrentResult()),reactExports.useEffect(()=>{Oa.setOptions(ja)},[ja,Oa]),shouldSuspend(ja,Ia))throw fetchOptimistic(ja,Oa,cs);if(getHasError({result:Ia,errorResetBoundary:cs,throwOnError:ja.throwOnError,query:Na,suspense:ja.suspense}))throw Ia.error;if((Fa=(qa=Qr.getDefaultOptions().queries)==null?void 0:qa._experimental_afterQuery)==null||Fa.call(qa,ja,Ia),ja.experimental_prefetchInRender&&!isServer&&willFetch(Ia,is)){const Ha=Aa?fetchOptimistic(ja,Oa,cs):Na==null?void 0:Na.promise;Ha==null||Ha.catch(noop$2).finally(()=>{Oa.updateResult()})}return ja.notifyOnChangeProps?Ia:Oa.trackResult(Ia)}function useQuery(es,$){return useBaseQuery(es,QueryObserver)}function useMutation(es,$){const ts=useQueryClient(),[is]=reactExports.useState(()=>new MutationObserver$1(ts,es));reactExports.useEffect(()=>{is.setOptions(es)},[is,es]);const cs=reactExports.useSyncExternalStore(reactExports.useCallback(ja=>is.subscribe(notifyManager.batchCalls(ja)),[is]),()=>is.getCurrentResult(),()=>is.getCurrentResult()),Qr=reactExports.useCallback((ja,Na)=>{is.mutate(ja,Na).catch(noop$2)},[is]);if(cs.error&&shouldThrowError(is.options.throwOnError,[cs.error]))throw cs.error;return{...cs,mutate:Qr,mutateAsync:cs.mutate}}function useInfiniteQuery(es,$){return useBaseQuery(es,InfiniteQueryObserver)}var M$2=(es,$,ts,is,cs,Qr,ja,Na)=>{let Aa=document.documentElement,Oa=["light","dark"];function Ia(Ma){(Array.isArray(es)?es:[es]).forEach(qa=>{let Fa=qa==="class",Ha=Fa&&Qr?cs.map(Ka=>Qr[Ka]||Ka):cs;Fa?(Aa.classList.remove(...Ha),Aa.classList.add(Qr&&Qr[Ma]?Qr[Ma]:Ma)):Aa.setAttribute(qa,Ma)}),La(Ma)}function La(Ma){Na&&Oa.includes(Ma)&&(Aa.style.colorScheme=Ma)}function Ba(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(is)Ia(is);else try{let Ma=localStorage.getItem($)||ts,qa=ja&&Ma==="system"?Ba():Ma;Ia(qa)}catch{}},x$1=reactExports.createContext(void 0),U$1={setTheme:es=>{},themes:[]},z$1=()=>{var es;return(es=reactExports.useContext(x$1))!=null?es:U$1};reactExports.memo(({forcedTheme:es,storageKey:$,attribute:ts,enableSystem:is,enableColorScheme:cs,defaultTheme:Qr,value:ja,themes:Na,nonce:Aa,scriptProps:Oa})=>{let Ia=JSON.stringify([ts,$,Qr,es,Na,ja,is,cs]).slice(1,-1);return reactExports.createElement("script",{...Oa,suppressHydrationWarning:!0,nonce:typeof window>"u"?Aa:"",dangerouslySetInnerHTML:{__html:`(${M$2.toString()})(${Ia})`}})});var jt$1=es=>{switch(es){case"success":return ee$1;case"info":return ae$1;case"warning":return oe$1;case"error":return se$1;default:return null}},te$1=Array(12).fill(0),Yt$1=({visible:es,className:$})=>React.createElement("div",{className:["sonner-loading-wrapper",$].filter(Boolean).join(" "),"data-visible":es},React.createElement("div",{className:"sonner-spinner"},te$1.map((ts,is)=>React.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${is}`})))),ee$1=React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},React.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"})),oe$1=React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},React.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"})),ae$1=React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},React.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"})),se$1=React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},React.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"})),Ot$1=React.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"},React.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),React.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Ft$1=()=>{let[es,$]=React.useState(document.hidden);return React.useEffect(()=>{let ts=()=>{$(document.hidden)};return document.addEventListener("visibilitychange",ts),()=>window.removeEventListener("visibilitychange",ts)},[]),es},bt$1=1,yt$1=class{constructor(){this.subscribe=$=>(this.subscribers.push($),()=>{let ts=this.subscribers.indexOf($);this.subscribers.splice(ts,1)}),this.publish=$=>{this.subscribers.forEach(ts=>ts($))},this.addToast=$=>{this.publish($),this.toasts=[...this.toasts,$]},this.create=$=>{var ts;let{message:is,...cs}=$,Qr=typeof($==null?void 0:$.id)=="number"||((ts=$.id)==null?void 0:ts.length)>0?$.id:bt$1++,ja=this.toasts.find(Aa=>Aa.id===Qr),Na=$.dismissible===void 0?!0:$.dismissible;return this.dismissedToasts.has(Qr)&&this.dismissedToasts.delete(Qr),ja?this.toasts=this.toasts.map(Aa=>Aa.id===Qr?(this.publish({...Aa,...$,id:Qr,title:is}),{...Aa,...$,id:Qr,dismissible:Na,title:is}):Aa):this.addToast({title:is,...cs,dismissible:Na,id:Qr}),Qr},this.dismiss=$=>(this.dismissedToasts.add($),$||this.toasts.forEach(ts=>{this.subscribers.forEach(is=>is({id:ts.id,dismiss:!0}))}),this.subscribers.forEach(ts=>ts({id:$,dismiss:!0})),$),this.message=($,ts)=>this.create({...ts,message:$}),this.error=($,ts)=>this.create({...ts,message:$,type:"error"}),this.success=($,ts)=>this.create({...ts,type:"success",message:$}),this.info=($,ts)=>this.create({...ts,type:"info",message:$}),this.warning=($,ts)=>this.create({...ts,type:"warning",message:$}),this.loading=($,ts)=>this.create({...ts,type:"loading",message:$}),this.promise=($,ts)=>{if(!ts)return;let is;ts.loading!==void 0&&(is=this.create({...ts,promise:$,type:"loading",message:ts.loading,description:typeof ts.description!="function"?ts.description:void 0}));let cs=$ instanceof Promise?$:$(),Qr=is!==void 0,ja,Na=cs.then(async Oa=>{if(ja=["resolve",Oa],React.isValidElement(Oa))Qr=!1,this.create({id:is,type:"default",message:Oa});else if(ie$1(Oa)&&!Oa.ok){Qr=!1;let Ia=typeof ts.error=="function"?await ts.error(`HTTP error! status: ${Oa.status}`):ts.error,La=typeof ts.description=="function"?await ts.description(`HTTP error! status: ${Oa.status}`):ts.description;this.create({id:is,type:"error",message:Ia,description:La})}else if(ts.success!==void 0){Qr=!1;let Ia=typeof ts.success=="function"?await ts.success(Oa):ts.success,La=typeof ts.description=="function"?await ts.description(Oa):ts.description;this.create({id:is,type:"success",message:Ia,description:La})}}).catch(async Oa=>{if(ja=["reject",Oa],ts.error!==void 0){Qr=!1;let Ia=typeof ts.error=="function"?await ts.error(Oa):ts.error,La=typeof ts.description=="function"?await ts.description(Oa):ts.description;this.create({id:is,type:"error",message:Ia,description:La})}}).finally(()=>{var Oa;Qr&&(this.dismiss(is),is=void 0),(Oa=ts.finally)==null||Oa.call(ts)}),Aa=()=>new Promise((Oa,Ia)=>Na.then(()=>ja[0]==="reject"?Ia(ja[1]):Oa(ja[1])).catch(Ia));return typeof is!="string"&&typeof is!="number"?{unwrap:Aa}:Object.assign(is,{unwrap:Aa})},this.custom=($,ts)=>{let is=(ts==null?void 0:ts.id)||bt$1++;return this.create({jsx:$(is),id:is,...ts}),is},this.getActiveToasts=()=>this.toasts.filter($=>!this.dismissedToasts.has($.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},v$1=new yt$1,ne$1=(es,$)=>{let ts=($==null?void 0:$.id)||bt$1++;return v$1.addToast({title:es,...$,id:ts}),ts},ie$1=es=>es&&typeof es=="object"&&"ok"in es&&typeof es.ok=="boolean"&&"status"in es&&typeof es.status=="number",le$1=ne$1,ce$1=()=>v$1.toasts,de$1=()=>v$1.getActiveToasts(),ue$1=Object.assign(le$1,{success:v$1.success,info:v$1.info,warning:v$1.warning,error:v$1.error,custom:v$1.custom,message:v$1.message,promise:v$1.promise,dismiss:v$1.dismiss,loading:v$1.loading},{getHistory:ce$1,getToasts:de$1});function wt$1(es,{insertAt:$}={}){if(typeof document>"u")return;let ts=document.head||document.getElementsByTagName("head")[0],is=document.createElement("style");is.type="text/css",$==="top"&&ts.firstChild?ts.insertBefore(is,ts.firstChild):ts.appendChild(is),is.styleSheet?is.styleSheet.cssText=es:is.appendChild(document.createTextNode(es))}wt$1(`:where(html[dir="ltr"]),:where([data-sonner-toaster][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%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][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%)}:where([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:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([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);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([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 #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([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)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([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;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([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);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-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([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}:where([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}:where([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, 0px)) translate(var(--swipe-amount-x, 0px));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{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{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{0%{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-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--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-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-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-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, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--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-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-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],[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],[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],[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],[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:nth-child(1){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)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{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%)}
|
|
26
|
+
`);function tt$1(es){return es.label!==void 0}var pe$1=3,me$1="32px",ge$1="16px",Wt$1=4e3,he$1=356,be$1=14,ye$1=20,we$1=200;function M$1(...es){return es.filter(Boolean).join(" ")}function xe$1(es){let[$,ts]=es.split("-"),is=[];return $&&is.push($),ts&&is.push(ts),is}var ve$1=es=>{var $,ts,is,cs,Qr,ja,Na,Aa,Oa,Ia,La;let{invert:Ba,toast:Ma,unstyled:qa,interacting:Fa,setHeights:Ha,visibleToasts:Ka,heights:Ga,index:Va,toasts:Ja,expanded:Ya,removeToast:el,defaultRichColors:tl,closeButton:rl,style:cl,cancelButtonStyle:dl,actionButtonStyle:fl,className:nl="",descriptionClassName:ol="",duration:pl,position:Tl,gap:ul,loadingIcon:hl,expandByDefault:jl,classNames:Nl,icons:zl,closeButtonAriaLabel:Zl="Close toast",pauseWhenPageIsHidden:Dl}=es,[Il,Fl]=React.useState(null),[ql,nu]=React.useState(null),[Gl,cu]=React.useState(!1),[Al,Ml]=React.useState(!1),[Ql,eu]=React.useState(!1),[xu,fu]=React.useState(!1),[Ou,yu]=React.useState(!1),[ic,Iu]=React.useState(0),[Bl,ru]=React.useState(0),Mu=React.useRef(Ma.duration||pl||Wt$1),lc=React.useRef(null),Tu=React.useRef(null),Eu=Va===0,Ua=Va+1<=Ka,ll=Ma.type,yl=Ma.dismissible!==!1,$l=Ma.className||"",kl=Ma.descriptionClassName||"",Za=React.useMemo(()=>Ga.findIndex(tu=>tu.toastId===Ma.id)||0,[Ga,Ma.id]),al=React.useMemo(()=>{var tu;return(tu=Ma.closeButton)!=null?tu:rl},[Ma.closeButton,rl]),El=React.useMemo(()=>Ma.duration||pl||Wt$1,[Ma.duration,pl]),bl=React.useRef(0),_l=React.useRef(0),Ol=React.useRef(0),Rl=React.useRef(null),[Ul,Ll]=Tl.split("-"),Yl=React.useMemo(()=>Ga.reduce((tu,bu,ku)=>ku>=Za?tu:tu+bu.height,0),[Ga,Za]),au=Ft$1(),su=Ma.invert||Ba,Lu=ll==="loading";_l.current=React.useMemo(()=>Za*ul+Yl,[Za,Yl]),React.useEffect(()=>{Mu.current=El},[El]),React.useEffect(()=>{cu(!0)},[]),React.useEffect(()=>{let tu=Tu.current;if(tu){let bu=tu.getBoundingClientRect().height;return ru(bu),Ha(ku=>[{toastId:Ma.id,height:bu,position:Ma.position},...ku]),()=>Ha(ku=>ku.filter(uc=>uc.toastId!==Ma.id))}},[Ha,Ma.id]),React.useLayoutEffect(()=>{if(!Gl)return;let tu=Tu.current,bu=tu.style.height;tu.style.height="auto";let ku=tu.getBoundingClientRect().height;tu.style.height=bu,ru(ku),Ha(uc=>uc.find(Wu=>Wu.toastId===Ma.id)?uc.map(Wu=>Wu.toastId===Ma.id?{...Wu,height:ku}:Wu):[{toastId:Ma.id,height:ku,position:Ma.position},...uc])},[Gl,Ma.title,Ma.description,Ha,Ma.id]);let ac=React.useCallback(()=>{Ml(!0),Iu(_l.current),Ha(tu=>tu.filter(bu=>bu.toastId!==Ma.id)),setTimeout(()=>{el(Ma)},we$1)},[Ma,el,Ha,_l]);React.useEffect(()=>{if(Ma.promise&&ll==="loading"||Ma.duration===1/0||Ma.type==="loading")return;let tu;return Ya||Fa||Dl&&au?(()=>{if(Ol.current<bl.current){let bu=new Date().getTime()-bl.current;Mu.current=Mu.current-bu}Ol.current=new Date().getTime()})():Mu.current!==1/0&&(bl.current=new Date().getTime(),tu=setTimeout(()=>{var bu;(bu=Ma.onAutoClose)==null||bu.call(Ma,Ma),ac()},Mu.current)),()=>clearTimeout(tu)},[Ya,Fa,Ma,ll,Dl,au,ac]),React.useEffect(()=>{Ma.delete&&ac()},[ac,Ma.delete]);function Lm(){var tu,bu,ku;return zl!=null&&zl.loading?React.createElement("div",{className:M$1(Nl==null?void 0:Nl.loader,(tu=Ma==null?void 0:Ma.classNames)==null?void 0:tu.loader,"sonner-loader"),"data-visible":ll==="loading"},zl.loading):hl?React.createElement("div",{className:M$1(Nl==null?void 0:Nl.loader,(bu=Ma==null?void 0:Ma.classNames)==null?void 0:bu.loader,"sonner-loader"),"data-visible":ll==="loading"},hl):React.createElement(Yt$1,{className:M$1(Nl==null?void 0:Nl.loader,(ku=Ma==null?void 0:Ma.classNames)==null?void 0:ku.loader),visible:ll==="loading"})}return React.createElement("li",{tabIndex:0,ref:Tu,className:M$1(nl,$l,Nl==null?void 0:Nl.toast,($=Ma==null?void 0:Ma.classNames)==null?void 0:$.toast,Nl==null?void 0:Nl.default,Nl==null?void 0:Nl[ll],(ts=Ma==null?void 0:Ma.classNames)==null?void 0:ts[ll]),"data-sonner-toast":"","data-rich-colors":(is=Ma.richColors)!=null?is:tl,"data-styled":!(Ma.jsx||Ma.unstyled||qa),"data-mounted":Gl,"data-promise":!!Ma.promise,"data-swiped":Ou,"data-removed":Al,"data-visible":Ua,"data-y-position":Ul,"data-x-position":Ll,"data-index":Va,"data-front":Eu,"data-swiping":Ql,"data-dismissible":yl,"data-type":ll,"data-invert":su,"data-swipe-out":xu,"data-swipe-direction":ql,"data-expanded":!!(Ya||jl&&Gl),style:{"--index":Va,"--toasts-before":Va,"--z-index":Ja.length-Va,"--offset":`${Al?ic:_l.current}px`,"--initial-height":jl?"auto":`${Bl}px`,...cl,...Ma.style},onDragEnd:()=>{eu(!1),Fl(null),Rl.current=null},onPointerDown:tu=>{Lu||!yl||(lc.current=new Date,Iu(_l.current),tu.target.setPointerCapture(tu.pointerId),tu.target.tagName!=="BUTTON"&&(eu(!0),Rl.current={x:tu.clientX,y:tu.clientY}))},onPointerUp:()=>{var tu,bu,ku,uc;if(xu||!yl)return;Rl.current=null;let Wu=Number(((tu=Tu.current)==null?void 0:tu.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Vc=Number(((bu=Tu.current)==null?void 0:bu.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Qc=new Date().getTime()-((ku=lc.current)==null?void 0:ku.getTime()),mc=Il==="x"?Wu:Vc,Fc=Math.abs(mc)/Qc;if(Math.abs(mc)>=ye$1||Fc>.11){Iu(_l.current),(uc=Ma.onDismiss)==null||uc.call(Ma,Ma),nu(Il==="x"?Wu>0?"right":"left":Vc>0?"down":"up"),ac(),fu(!0),yu(!1);return}eu(!1),Fl(null)},onPointerMove:tu=>{var bu,ku,uc,Wu;if(!Rl.current||!yl||((bu=window.getSelection())==null?void 0:bu.toString().length)>0)return;let Vc=tu.clientY-Rl.current.y,Qc=tu.clientX-Rl.current.x,mc=(ku=es.swipeDirections)!=null?ku:xe$1(Tl);!Il&&(Math.abs(Qc)>1||Math.abs(Vc)>1)&&Fl(Math.abs(Qc)>Math.abs(Vc)?"x":"y");let Fc={x:0,y:0};Il==="y"?(mc.includes("top")||mc.includes("bottom"))&&(mc.includes("top")&&Vc<0||mc.includes("bottom")&&Vc>0)&&(Fc.y=Vc):Il==="x"&&(mc.includes("left")||mc.includes("right"))&&(mc.includes("left")&&Qc<0||mc.includes("right")&&Qc>0)&&(Fc.x=Qc),(Math.abs(Fc.x)>0||Math.abs(Fc.y)>0)&&yu(!0),(uc=Tu.current)==null||uc.style.setProperty("--swipe-amount-x",`${Fc.x}px`),(Wu=Tu.current)==null||Wu.style.setProperty("--swipe-amount-y",`${Fc.y}px`)}},al&&!Ma.jsx?React.createElement("button",{"aria-label":Zl,"data-disabled":Lu,"data-close-button":!0,onClick:Lu||!yl?()=>{}:()=>{var tu;ac(),(tu=Ma.onDismiss)==null||tu.call(Ma,Ma)},className:M$1(Nl==null?void 0:Nl.closeButton,(cs=Ma==null?void 0:Ma.classNames)==null?void 0:cs.closeButton)},(Qr=zl==null?void 0:zl.close)!=null?Qr:Ot$1):null,Ma.jsx||reactExports.isValidElement(Ma.title)?Ma.jsx?Ma.jsx:typeof Ma.title=="function"?Ma.title():Ma.title:React.createElement(React.Fragment,null,ll||Ma.icon||Ma.promise?React.createElement("div",{"data-icon":"",className:M$1(Nl==null?void 0:Nl.icon,(ja=Ma==null?void 0:Ma.classNames)==null?void 0:ja.icon)},Ma.promise||Ma.type==="loading"&&!Ma.icon?Ma.icon||Lm():null,Ma.type!=="loading"?Ma.icon||(zl==null?void 0:zl[ll])||jt$1(ll):null):null,React.createElement("div",{"data-content":"",className:M$1(Nl==null?void 0:Nl.content,(Na=Ma==null?void 0:Ma.classNames)==null?void 0:Na.content)},React.createElement("div",{"data-title":"",className:M$1(Nl==null?void 0:Nl.title,(Aa=Ma==null?void 0:Ma.classNames)==null?void 0:Aa.title)},typeof Ma.title=="function"?Ma.title():Ma.title),Ma.description?React.createElement("div",{"data-description":"",className:M$1(ol,kl,Nl==null?void 0:Nl.description,(Oa=Ma==null?void 0:Ma.classNames)==null?void 0:Oa.description)},typeof Ma.description=="function"?Ma.description():Ma.description):null),reactExports.isValidElement(Ma.cancel)?Ma.cancel:Ma.cancel&&tt$1(Ma.cancel)?React.createElement("button",{"data-button":!0,"data-cancel":!0,style:Ma.cancelButtonStyle||dl,onClick:tu=>{var bu,ku;tt$1(Ma.cancel)&&yl&&((ku=(bu=Ma.cancel).onClick)==null||ku.call(bu,tu),ac())},className:M$1(Nl==null?void 0:Nl.cancelButton,(Ia=Ma==null?void 0:Ma.classNames)==null?void 0:Ia.cancelButton)},Ma.cancel.label):null,reactExports.isValidElement(Ma.action)?Ma.action:Ma.action&&tt$1(Ma.action)?React.createElement("button",{"data-button":!0,"data-action":!0,style:Ma.actionButtonStyle||fl,onClick:tu=>{var bu,ku;tt$1(Ma.action)&&((ku=(bu=Ma.action).onClick)==null||ku.call(bu,tu),!tu.defaultPrevented&&ac())},className:M$1(Nl==null?void 0:Nl.actionButton,(La=Ma==null?void 0:Ma.classNames)==null?void 0:La.actionButton)},Ma.action.label):null))};function _t$1(){if(typeof window>"u"||typeof document>"u")return"ltr";let es=document.documentElement.getAttribute("dir");return es==="auto"||!es?window.getComputedStyle(document.documentElement).direction:es}function Te$1(es,$){let ts={};return[es,$].forEach((is,cs)=>{let Qr=cs===1,ja=Qr?"--mobile-offset":"--offset",Na=Qr?ge$1:me$1;function Aa(Oa){["top","right","bottom","left"].forEach(Ia=>{ts[`${ja}-${Ia}`]=typeof Oa=="number"?`${Oa}px`:Oa})}typeof is=="number"||typeof is=="string"?Aa(is):typeof is=="object"?["top","right","bottom","left"].forEach(Oa=>{is[Oa]===void 0?ts[`${ja}-${Oa}`]=Na:ts[`${ja}-${Oa}`]=typeof is[Oa]=="number"?`${is[Oa]}px`:is[Oa]}):Aa(Na)}),ts}var $e$1=reactExports.forwardRef(function(es,$){let{invert:ts,position:is="bottom-right",hotkey:cs=["altKey","KeyT"],expand:Qr,closeButton:ja,className:Na,offset:Aa,mobileOffset:Oa,theme:Ia="light",richColors:La,duration:Ba,style:Ma,visibleToasts:qa=pe$1,toastOptions:Fa,dir:Ha=_t$1(),gap:Ka=be$1,loadingIcon:Ga,icons:Va,containerAriaLabel:Ja="Notifications",pauseWhenPageIsHidden:Ya}=es,[el,tl]=React.useState([]),rl=React.useMemo(()=>Array.from(new Set([is].concat(el.filter(Dl=>Dl.position).map(Dl=>Dl.position)))),[el,is]),[cl,dl]=React.useState([]),[fl,nl]=React.useState(!1),[ol,pl]=React.useState(!1),[Tl,ul]=React.useState(Ia!=="system"?Ia:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),hl=React.useRef(null),jl=cs.join("+").replace(/Key/g,"").replace(/Digit/g,""),Nl=React.useRef(null),zl=React.useRef(!1),Zl=React.useCallback(Dl=>{tl(Il=>{var Fl;return(Fl=Il.find(ql=>ql.id===Dl.id))!=null&&Fl.delete||v$1.dismiss(Dl.id),Il.filter(({id:ql})=>ql!==Dl.id)})},[]);return React.useEffect(()=>v$1.subscribe(Dl=>{if(Dl.dismiss){tl(Il=>Il.map(Fl=>Fl.id===Dl.id?{...Fl,delete:!0}:Fl));return}setTimeout(()=>{ReactDOM.flushSync(()=>{tl(Il=>{let Fl=Il.findIndex(ql=>ql.id===Dl.id);return Fl!==-1?[...Il.slice(0,Fl),{...Il[Fl],...Dl},...Il.slice(Fl+1)]:[Dl,...Il]})})})}),[]),React.useEffect(()=>{if(Ia!=="system"){ul(Ia);return}if(Ia==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ul("dark"):ul("light")),typeof window>"u")return;let Dl=window.matchMedia("(prefers-color-scheme: dark)");try{Dl.addEventListener("change",({matches:Il})=>{ul(Il?"dark":"light")})}catch{Dl.addListener(({matches:Fl})=>{try{ul(Fl?"dark":"light")}catch(ql){console.error(ql)}})}},[Ia]),React.useEffect(()=>{el.length<=1&&nl(!1)},[el]),React.useEffect(()=>{let Dl=Il=>{var Fl,ql;cs.every(nu=>Il[nu]||Il.code===nu)&&(nl(!0),(Fl=hl.current)==null||Fl.focus()),Il.code==="Escape"&&(document.activeElement===hl.current||(ql=hl.current)!=null&&ql.contains(document.activeElement))&&nl(!1)};return document.addEventListener("keydown",Dl),()=>document.removeEventListener("keydown",Dl)},[cs]),React.useEffect(()=>{if(hl.current)return()=>{Nl.current&&(Nl.current.focus({preventScroll:!0}),Nl.current=null,zl.current=!1)}},[hl.current]),React.createElement("section",{ref:$,"aria-label":`${Ja} ${jl}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},rl.map((Dl,Il)=>{var Fl;let[ql,nu]=Dl.split("-");return el.length?React.createElement("ol",{key:Dl,dir:Ha==="auto"?_t$1():Ha,tabIndex:-1,ref:hl,className:Na,"data-sonner-toaster":!0,"data-theme":Tl,"data-y-position":ql,"data-lifted":fl&&el.length>1&&!Qr,"data-x-position":nu,style:{"--front-toast-height":`${((Fl=cl[0])==null?void 0:Fl.height)||0}px`,"--width":`${he$1}px`,"--gap":`${Ka}px`,...Ma,...Te$1(Aa,Oa)},onBlur:Gl=>{zl.current&&!Gl.currentTarget.contains(Gl.relatedTarget)&&(zl.current=!1,Nl.current&&(Nl.current.focus({preventScroll:!0}),Nl.current=null))},onFocus:Gl=>{Gl.target instanceof HTMLElement&&Gl.target.dataset.dismissible==="false"||zl.current||(zl.current=!0,Nl.current=Gl.relatedTarget)},onMouseEnter:()=>nl(!0),onMouseMove:()=>nl(!0),onMouseLeave:()=>{ol||nl(!1)},onDragEnd:()=>nl(!1),onPointerDown:Gl=>{Gl.target instanceof HTMLElement&&Gl.target.dataset.dismissible==="false"||pl(!0)},onPointerUp:()=>pl(!1)},el.filter(Gl=>!Gl.position&&Il===0||Gl.position===Dl).map((Gl,cu)=>{var Al,Ml;return React.createElement(ve$1,{key:Gl.id,icons:Va,index:cu,toast:Gl,defaultRichColors:La,duration:(Al=Fa==null?void 0:Fa.duration)!=null?Al:Ba,className:Fa==null?void 0:Fa.className,descriptionClassName:Fa==null?void 0:Fa.descriptionClassName,invert:ts,visibleToasts:qa,closeButton:(Ml=Fa==null?void 0:Fa.closeButton)!=null?Ml:ja,interacting:ol,position:Dl,style:Fa==null?void 0:Fa.style,unstyled:Fa==null?void 0:Fa.unstyled,classNames:Fa==null?void 0:Fa.classNames,cancelButtonStyle:Fa==null?void 0:Fa.cancelButtonStyle,actionButtonStyle:Fa==null?void 0:Fa.actionButtonStyle,removeToast:Zl,toasts:el.filter(Ql=>Ql.position==Gl.position),heights:cl.filter(Ql=>Ql.position==Gl.position),setHeights:dl,expandByDefault:Qr,gap:Ka,loadingIcon:Ga,expanded:fl,pauseWhenPageIsHidden:Ya,swipeDirections:es.swipeDirections})})):null}))});const Toaster=({...es})=>{const{theme:$="system"}=z$1();return jsxRuntimeExports.jsx($e$1,{theme:$,className:"toaster group",icons:{success:jsxRuntimeExports.jsx(CircleCheck,{className:"size-4"}),info:jsxRuntimeExports.jsx(Info,{className:"size-4"}),warning:jsxRuntimeExports.jsx(TriangleAlert,{className:"size-4"}),error:jsxRuntimeExports.jsx(OctagonX,{className:"size-4"}),loading:jsxRuntimeExports.jsx(LoaderCircle,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},...es})};function captureException(es,$){}class ErrorBoundary extends reactExports.Component{constructor($){super($),this.state={hasError:!1,error:null}}static getDerivedStateFromError($){return{hasError:!0,error:$}}componentDidCatch($,ts){ts.componentStack}render(){var $;return this.state.hasError?jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:jsxRuntimeExports.jsxs("div",{className:"max-w-md text-center space-y-4",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Something went wrong"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:(($=this.state.error)==null?void 0:$.message)??"An unexpected error occurred."}),jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>{this.setState({hasError:!1,error:null}),window.location.href="/dashboard"},children:"Go to Dashboard"})]})}):this.props.children}}const resolveFetch$3=es=>es?(...$)=>es(...$):(...$)=>fetch(...$);class FunctionsError extends Error{constructor($,ts="FunctionsError",is){super($),this.name=ts,this.context=is}}class FunctionsFetchError extends FunctionsError{constructor($){super("Failed to send a request to the Edge Function","FunctionsFetchError",$)}}class FunctionsRelayError extends FunctionsError{constructor($){super("Relay Error invoking the Edge Function","FunctionsRelayError",$)}}class FunctionsHttpError extends FunctionsError{constructor($){super("Edge Function returned a non-2xx status code","FunctionsHttpError",$)}}var FunctionRegion;(function(es){es.Any="any",es.ApNortheast1="ap-northeast-1",es.ApNortheast2="ap-northeast-2",es.ApSouth1="ap-south-1",es.ApSoutheast1="ap-southeast-1",es.ApSoutheast2="ap-southeast-2",es.CaCentral1="ca-central-1",es.EuCentral1="eu-central-1",es.EuWest1="eu-west-1",es.EuWest2="eu-west-2",es.EuWest3="eu-west-3",es.SaEast1="sa-east-1",es.UsEast1="us-east-1",es.UsWest1="us-west-1",es.UsWest2="us-west-2"})(FunctionRegion||(FunctionRegion={}));class FunctionsClient{constructor($,{headers:ts={},customFetch:is,region:cs=FunctionRegion.Any}={}){this.url=$,this.headers=ts,this.region=cs,this.fetch=resolveFetch$3(is)}setAuth($){this.headers.Authorization=`Bearer ${$}`}invoke($){return __awaiter(this,arguments,void 0,function*(ts,is={}){var cs;let Qr,ja;try{const{headers:Na,method:Aa,body:Oa,signal:Ia,timeout:La}=is;let Ba={},{region:Ma}=is;Ma||(Ma=this.region);const qa=new URL(`${this.url}/${ts}`);Ma&&Ma!=="any"&&(Ba["x-region"]=Ma,qa.searchParams.set("forceFunctionRegion",Ma));let Fa;Oa&&(Na&&!Object.prototype.hasOwnProperty.call(Na,"Content-Type")||!Na)?typeof Blob<"u"&&Oa instanceof Blob||Oa instanceof ArrayBuffer?(Ba["Content-Type"]="application/octet-stream",Fa=Oa):typeof Oa=="string"?(Ba["Content-Type"]="text/plain",Fa=Oa):typeof FormData<"u"&&Oa instanceof FormData?Fa=Oa:(Ba["Content-Type"]="application/json",Fa=JSON.stringify(Oa)):Oa&&typeof Oa!="string"&&!(typeof Blob<"u"&&Oa instanceof Blob)&&!(Oa instanceof ArrayBuffer)&&!(typeof FormData<"u"&&Oa instanceof FormData)?Fa=JSON.stringify(Oa):Fa=Oa;let Ha=Ia;La&&(ja=new AbortController,Qr=setTimeout(()=>ja.abort(),La),Ia?(Ha=ja.signal,Ia.addEventListener("abort",()=>ja.abort())):Ha=ja.signal);const Ka=yield this.fetch(qa.toString(),{method:Aa||"POST",headers:Object.assign(Object.assign(Object.assign({},Ba),this.headers),Na),body:Fa,signal:Ha}).catch(Ya=>{throw new FunctionsFetchError(Ya)}),Ga=Ka.headers.get("x-relay-error");if(Ga&&Ga==="true")throw new FunctionsRelayError(Ka);if(!Ka.ok)throw new FunctionsHttpError(Ka);let Va=((cs=Ka.headers.get("Content-Type"))!==null&&cs!==void 0?cs:"text/plain").split(";")[0].trim(),Ja;return Va==="application/json"?Ja=yield Ka.json():Va==="application/octet-stream"||Va==="application/pdf"?Ja=yield Ka.blob():Va==="text/event-stream"?Ja=Ka:Va==="multipart/form-data"?Ja=yield Ka.formData():Ja=yield Ka.text(),{data:Ja,error:null,response:Ka}}catch(Na){return{data:null,error:Na,response:Na instanceof FunctionsHttpError||Na instanceof FunctionsRelayError?Na.context:void 0}}finally{Qr&&clearTimeout(Qr)}})}}var PostgrestError=class extends Error{constructor(es){super(es.message),this.name="PostgrestError",this.details=es.details,this.hint=es.hint,this.code=es.code}},PostgrestBuilder=class{constructor(es){var $,ts,is;this.shouldThrowOnError=!1,this.method=es.method,this.url=es.url,this.headers=new Headers(es.headers),this.schema=es.schema,this.body=es.body,this.shouldThrowOnError=($=es.shouldThrowOnError)!==null&&$!==void 0?$:!1,this.signal=es.signal,this.isMaybeSingle=(ts=es.isMaybeSingle)!==null&&ts!==void 0?ts:!1,this.urlLengthLimit=(is=es.urlLengthLimit)!==null&&is!==void 0?is:8e3,es.fetch?this.fetch=es.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(es,$){return this.headers=new Headers(this.headers),this.headers.set(es,$),this}then(es,$){var ts=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const is=this.fetch;let cs=is(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async Qr=>{let ja=null,Na=null,Aa=null,Oa=Qr.status,Ia=Qr.statusText;if(Qr.ok){var La,Ba;if(ts.method!=="HEAD"){var Ma;const Ka=await Qr.text();Ka===""||(ts.headers.get("Accept")==="text/csv"||ts.headers.get("Accept")&&(!((Ma=ts.headers.get("Accept"))===null||Ma===void 0)&&Ma.includes("application/vnd.pgrst.plan+text"))?Na=Ka:Na=JSON.parse(Ka))}const Fa=(La=ts.headers.get("Prefer"))===null||La===void 0?void 0:La.match(/count=(exact|planned|estimated)/),Ha=(Ba=Qr.headers.get("content-range"))===null||Ba===void 0?void 0:Ba.split("/");Fa&&Ha&&Ha.length>1&&(Aa=parseInt(Ha[1])),ts.isMaybeSingle&&ts.method==="GET"&&Array.isArray(Na)&&(Na.length>1?(ja={code:"PGRST116",details:`Results contain ${Na.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},Na=null,Aa=null,Oa=406,Ia="Not Acceptable"):Na.length===1?Na=Na[0]:Na=null)}else{var qa;const Fa=await Qr.text();try{ja=JSON.parse(Fa),Array.isArray(ja)&&Qr.status===404&&(Na=[],ja=null,Oa=200,Ia="OK")}catch{Qr.status===404&&Fa===""?(Oa=204,Ia="No Content"):ja={message:Fa}}if(ja&&ts.isMaybeSingle&&(!(ja==null||(qa=ja.details)===null||qa===void 0)&&qa.includes("0 rows"))&&(ja=null,Oa=200,Ia="OK"),ja&&ts.shouldThrowOnError)throw new PostgrestError(ja)}return{error:ja,data:Na,count:Aa,status:Oa,statusText:Ia}});return this.shouldThrowOnError||(cs=cs.catch(Qr=>{var ja;let Na="",Aa="",Oa="";const Ia=Qr==null?void 0:Qr.cause;if(Ia){var La,Ba,Ma,qa;const Ka=(La=Ia==null?void 0:Ia.message)!==null&&La!==void 0?La:"",Ga=(Ba=Ia==null?void 0:Ia.code)!==null&&Ba!==void 0?Ba:"";Na=`${(Ma=Qr==null?void 0:Qr.name)!==null&&Ma!==void 0?Ma:"FetchError"}: ${Qr==null?void 0:Qr.message}`,Na+=`
|
|
27
|
+
|
|
28
|
+
Caused by: ${(qa=Ia==null?void 0:Ia.name)!==null&&qa!==void 0?qa:"Error"}: ${Ka}`,Ga&&(Na+=` (${Ga})`),Ia!=null&&Ia.stack&&(Na+=`
|
|
29
|
+
${Ia.stack}`)}else{var Fa;Na=(Fa=Qr==null?void 0:Qr.stack)!==null&&Fa!==void 0?Fa:""}const Ha=this.url.toString().length;return(Qr==null?void 0:Qr.name)==="AbortError"||(Qr==null?void 0:Qr.code)==="ABORT_ERR"?(Oa="",Aa="Request was aborted (timeout or manual cancellation)",Ha>this.urlLengthLimit&&(Aa+=`. Note: Your request URL is ${Ha} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((Ia==null?void 0:Ia.name)==="HeadersOverflowError"||(Ia==null?void 0:Ia.code)==="UND_ERR_HEADERS_OVERFLOW")&&(Oa="",Aa="HTTP headers exceeded server limits (typically 16KB)",Ha>this.urlLengthLimit&&(Aa+=`. Your request URL is ${Ha} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(ja=Qr==null?void 0:Qr.name)!==null&&ja!==void 0?ja:"FetchError"}: ${Qr==null?void 0:Qr.message}`,details:Na,hint:Aa,code:Oa},data:null,count:null,status:0,statusText:""}})),cs.then(es,$)}returns(){return this}overrideTypes(){return this}},PostgrestTransformBuilder=class extends PostgrestBuilder{select(es){let $=!1;const ts=(es??"*").split("").map(is=>/\s/.test(is)&&!$?"":(is==='"'&&($=!$),is)).join("");return this.url.searchParams.set("select",ts),this.headers.append("Prefer","return=representation"),this}order(es,{ascending:$=!0,nullsFirst:ts,foreignTable:is,referencedTable:cs=is}={}){const Qr=cs?`${cs}.order`:"order",ja=this.url.searchParams.get(Qr);return this.url.searchParams.set(Qr,`${ja?`${ja},`:""}${es}.${$?"asc":"desc"}${ts===void 0?"":ts?".nullsfirst":".nullslast"}`),this}limit(es,{foreignTable:$,referencedTable:ts=$}={}){const is=typeof ts>"u"?"limit":`${ts}.limit`;return this.url.searchParams.set(is,`${es}`),this}range(es,$,{foreignTable:ts,referencedTable:is=ts}={}){const cs=typeof is>"u"?"offset":`${is}.offset`,Qr=typeof is>"u"?"limit":`${is}.limit`;return this.url.searchParams.set(cs,`${es}`),this.url.searchParams.set(Qr,`${$-es+1}`),this}abortSignal(es){return this.signal=es,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:es=!1,verbose:$=!1,settings:ts=!1,buffers:is=!1,wal:cs=!1,format:Qr="text"}={}){var ja;const Na=[es?"analyze":null,$?"verbose":null,ts?"settings":null,is?"buffers":null,cs?"wal":null].filter(Boolean).join("|"),Aa=(ja=this.headers.get("Accept"))!==null&&ja!==void 0?ja:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${Qr}; for="${Aa}"; options=${Na};`),Qr==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(es){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${es}`),this}};const PostgrestReservedCharsRegexp=new RegExp("[,()]");var PostgrestFilterBuilder=class extends PostgrestTransformBuilder{eq(es,$){return this.url.searchParams.append(es,`eq.${$}`),this}neq(es,$){return this.url.searchParams.append(es,`neq.${$}`),this}gt(es,$){return this.url.searchParams.append(es,`gt.${$}`),this}gte(es,$){return this.url.searchParams.append(es,`gte.${$}`),this}lt(es,$){return this.url.searchParams.append(es,`lt.${$}`),this}lte(es,$){return this.url.searchParams.append(es,`lte.${$}`),this}like(es,$){return this.url.searchParams.append(es,`like.${$}`),this}likeAllOf(es,$){return this.url.searchParams.append(es,`like(all).{${$.join(",")}}`),this}likeAnyOf(es,$){return this.url.searchParams.append(es,`like(any).{${$.join(",")}}`),this}ilike(es,$){return this.url.searchParams.append(es,`ilike.${$}`),this}ilikeAllOf(es,$){return this.url.searchParams.append(es,`ilike(all).{${$.join(",")}}`),this}ilikeAnyOf(es,$){return this.url.searchParams.append(es,`ilike(any).{${$.join(",")}}`),this}regexMatch(es,$){return this.url.searchParams.append(es,`match.${$}`),this}regexIMatch(es,$){return this.url.searchParams.append(es,`imatch.${$}`),this}is(es,$){return this.url.searchParams.append(es,`is.${$}`),this}isDistinct(es,$){return this.url.searchParams.append(es,`isdistinct.${$}`),this}in(es,$){const ts=Array.from(new Set($)).map(is=>typeof is=="string"&&PostgrestReservedCharsRegexp.test(is)?`"${is}"`:`${is}`).join(",");return this.url.searchParams.append(es,`in.(${ts})`),this}notIn(es,$){const ts=Array.from(new Set($)).map(is=>typeof is=="string"&&PostgrestReservedCharsRegexp.test(is)?`"${is}"`:`${is}`).join(",");return this.url.searchParams.append(es,`not.in.(${ts})`),this}contains(es,$){return typeof $=="string"?this.url.searchParams.append(es,`cs.${$}`):Array.isArray($)?this.url.searchParams.append(es,`cs.{${$.join(",")}}`):this.url.searchParams.append(es,`cs.${JSON.stringify($)}`),this}containedBy(es,$){return typeof $=="string"?this.url.searchParams.append(es,`cd.${$}`):Array.isArray($)?this.url.searchParams.append(es,`cd.{${$.join(",")}}`):this.url.searchParams.append(es,`cd.${JSON.stringify($)}`),this}rangeGt(es,$){return this.url.searchParams.append(es,`sr.${$}`),this}rangeGte(es,$){return this.url.searchParams.append(es,`nxl.${$}`),this}rangeLt(es,$){return this.url.searchParams.append(es,`sl.${$}`),this}rangeLte(es,$){return this.url.searchParams.append(es,`nxr.${$}`),this}rangeAdjacent(es,$){return this.url.searchParams.append(es,`adj.${$}`),this}overlaps(es,$){return typeof $=="string"?this.url.searchParams.append(es,`ov.${$}`):this.url.searchParams.append(es,`ov.{${$.join(",")}}`),this}textSearch(es,$,{config:ts,type:is}={}){let cs="";is==="plain"?cs="pl":is==="phrase"?cs="ph":is==="websearch"&&(cs="w");const Qr=ts===void 0?"":`(${ts})`;return this.url.searchParams.append(es,`${cs}fts${Qr}.${$}`),this}match(es){return Object.entries(es).forEach(([$,ts])=>{this.url.searchParams.append($,`eq.${ts}`)}),this}not(es,$,ts){return this.url.searchParams.append(es,`not.${$}.${ts}`),this}or(es,{foreignTable:$,referencedTable:ts=$}={}){const is=ts?`${ts}.or`:"or";return this.url.searchParams.append(is,`(${es})`),this}filter(es,$,ts){return this.url.searchParams.append(es,`${$}.${ts}`),this}},PostgrestQueryBuilder=class{constructor(es,{headers:$={},schema:ts,fetch:is,urlLengthLimit:cs=8e3}){this.url=es,this.headers=new Headers($),this.schema=ts,this.fetch=is,this.urlLengthLimit=cs}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(es,$){const{head:ts=!1,count:is}=$??{},cs=ts?"HEAD":"GET";let Qr=!1;const ja=(es??"*").split("").map(Oa=>/\s/.test(Oa)&&!Qr?"":(Oa==='"'&&(Qr=!Qr),Oa)).join(""),{url:Na,headers:Aa}=this.cloneRequestState();return Na.searchParams.set("select",ja),is&&Aa.append("Prefer",`count=${is}`),new PostgrestFilterBuilder({method:cs,url:Na,headers:Aa,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(es,{count:$,defaultToNull:ts=!0}={}){var is;const cs="POST",{url:Qr,headers:ja}=this.cloneRequestState();if($&&ja.append("Prefer",`count=${$}`),ts||ja.append("Prefer","missing=default"),Array.isArray(es)){const Na=es.reduce((Aa,Oa)=>Aa.concat(Object.keys(Oa)),[]);if(Na.length>0){const Aa=[...new Set(Na)].map(Oa=>`"${Oa}"`);Qr.searchParams.set("columns",Aa.join(","))}}return new PostgrestFilterBuilder({method:cs,url:Qr,headers:ja,schema:this.schema,body:es,fetch:(is=this.fetch)!==null&&is!==void 0?is:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(es,{onConflict:$,ignoreDuplicates:ts=!1,count:is,defaultToNull:cs=!0}={}){var Qr;const ja="POST",{url:Na,headers:Aa}=this.cloneRequestState();if(Aa.append("Prefer",`resolution=${ts?"ignore":"merge"}-duplicates`),$!==void 0&&Na.searchParams.set("on_conflict",$),is&&Aa.append("Prefer",`count=${is}`),cs||Aa.append("Prefer","missing=default"),Array.isArray(es)){const Oa=es.reduce((Ia,La)=>Ia.concat(Object.keys(La)),[]);if(Oa.length>0){const Ia=[...new Set(Oa)].map(La=>`"${La}"`);Na.searchParams.set("columns",Ia.join(","))}}return new PostgrestFilterBuilder({method:ja,url:Na,headers:Aa,schema:this.schema,body:es,fetch:(Qr=this.fetch)!==null&&Qr!==void 0?Qr:fetch,urlLengthLimit:this.urlLengthLimit})}update(es,{count:$}={}){var ts;const is="PATCH",{url:cs,headers:Qr}=this.cloneRequestState();return $&&Qr.append("Prefer",`count=${$}`),new PostgrestFilterBuilder({method:is,url:cs,headers:Qr,schema:this.schema,body:es,fetch:(ts=this.fetch)!==null&&ts!==void 0?ts:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:es}={}){var $;const ts="DELETE",{url:is,headers:cs}=this.cloneRequestState();return es&&cs.append("Prefer",`count=${es}`),new PostgrestFilterBuilder({method:ts,url:is,headers:cs,schema:this.schema,fetch:($=this.fetch)!==null&&$!==void 0?$:fetch,urlLengthLimit:this.urlLengthLimit})}};function _typeof$2(es){"@babel/helpers - typeof";return _typeof$2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},_typeof$2(es)}function toPrimitive$2(es,$){if(_typeof$2(es)!="object"||!es)return es;var ts=es[Symbol.toPrimitive];if(ts!==void 0){var is=ts.call(es,$);if(_typeof$2(is)!="object")return is;throw new TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(es)}function toPropertyKey$2(es){var $=toPrimitive$2(es,"string");return _typeof$2($)=="symbol"?$:$+""}function _defineProperty$2(es,$,ts){return($=toPropertyKey$2($))in es?Object.defineProperty(es,$,{value:ts,enumerable:!0,configurable:!0,writable:!0}):es[$]=ts,es}function ownKeys$2(es,$){var ts=Object.keys(es);if(Object.getOwnPropertySymbols){var is=Object.getOwnPropertySymbols(es);$&&(is=is.filter(function(cs){return Object.getOwnPropertyDescriptor(es,cs).enumerable})),ts.push.apply(ts,is)}return ts}function _objectSpread2$2(es){for(var $=1;$<arguments.length;$++){var ts=arguments[$]!=null?arguments[$]:{};$%2?ownKeys$2(Object(ts),!0).forEach(function(is){_defineProperty$2(es,is,ts[is])}):Object.getOwnPropertyDescriptors?Object.defineProperties(es,Object.getOwnPropertyDescriptors(ts)):ownKeys$2(Object(ts)).forEach(function(is){Object.defineProperty(es,is,Object.getOwnPropertyDescriptor(ts,is))})}return es}var PostgrestClient=class Sb{constructor($,{headers:ts={},schema:is,fetch:cs,timeout:Qr,urlLengthLimit:ja=8e3}={}){this.url=$,this.headers=new Headers(ts),this.schemaName=is,this.urlLengthLimit=ja;const Na=cs??globalThis.fetch;Qr!==void 0&&Qr>0?this.fetch=(Aa,Oa)=>{const Ia=new AbortController,La=setTimeout(()=>Ia.abort(),Qr),Ba=Oa==null?void 0:Oa.signal;if(Ba){if(Ba.aborted)return clearTimeout(La),Na(Aa,Oa);const Ma=()=>{clearTimeout(La),Ia.abort()};return Ba.addEventListener("abort",Ma,{once:!0}),Na(Aa,_objectSpread2$2(_objectSpread2$2({},Oa),{},{signal:Ia.signal})).finally(()=>{clearTimeout(La),Ba.removeEventListener("abort",Ma)})}return Na(Aa,_objectSpread2$2(_objectSpread2$2({},Oa),{},{signal:Ia.signal})).finally(()=>clearTimeout(La))}:this.fetch=Na}from($){if(!$||typeof $!="string"||$.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new PostgrestQueryBuilder(new URL(`${this.url}/${$}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema($){return new Sb(this.url,{headers:this.headers,schema:$,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc($,ts={},{head:is=!1,get:cs=!1,count:Qr}={}){var ja;let Na;const Aa=new URL(`${this.url}/rpc/${$}`);let Oa;const Ia=Ma=>Ma!==null&&typeof Ma=="object"&&(!Array.isArray(Ma)||Ma.some(Ia)),La=is&&Object.values(ts).some(Ia);La?(Na="POST",Oa=ts):is||cs?(Na=is?"HEAD":"GET",Object.entries(ts).filter(([Ma,qa])=>qa!==void 0).map(([Ma,qa])=>[Ma,Array.isArray(qa)?`{${qa.join(",")}}`:`${qa}`]).forEach(([Ma,qa])=>{Aa.searchParams.append(Ma,qa)})):(Na="POST",Oa=ts);const Ba=new Headers(this.headers);return La?Ba.set("Prefer",Qr?`count=${Qr},return=minimal`:"return=minimal"):Qr&&Ba.set("Prefer",`count=${Qr}`),new PostgrestFilterBuilder({method:Na,url:Aa,headers:Ba,schema:this.schemaName,body:Oa,fetch:(ja=this.fetch)!==null&&ja!==void 0?ja:fetch,urlLengthLimit:this.urlLengthLimit})}};class WebSocketFactory{constructor(){}static detectEnvironment(){var $;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!(($=navigator.userAgent)===null||$===void 0)&&$.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const ts=globalThis.process;if(ts){const is=ts.versions;if(is&&is.node){const cs=is.node,Qr=parseInt(cs.replace(/^v/,"").split(".")[0]);return Qr>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${Qr} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${Qr} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
30
|
+
import ws from "ws"
|
|
31
|
+
new RealtimeClient(url, { transport: ws })`}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const $=this.detectEnvironment();if($.constructor)return $.constructor;let ts=$.error||"WebSocket not supported in this environment.";throw $.workaround&&(ts+=`
|
|
32
|
+
|
|
33
|
+
Suggested solution: ${$.workaround}`),new Error(ts)}static createWebSocket($,ts){const is=this.getWebSocketConstructor();return new is($,ts)}static isWebSocketSupported(){try{const $=this.detectEnvironment();return $.type==="native"||$.type==="ws"}catch{return!1}}}const version$3="2.95.3",DEFAULT_VERSION=`realtime-js/${version$3}`,VSN_1_0_0="1.0.0",VSN_2_0_0="2.0.0",DEFAULT_VSN=VSN_2_0_0,DEFAULT_TIMEOUT=1e4,WS_CLOSE_NORMAL=1e3,MAX_PUSH_BUFFER_SIZE=100;var SOCKET_STATES;(function(es){es[es.connecting=0]="connecting",es[es.open=1]="open",es[es.closing=2]="closing",es[es.closed=3]="closed"})(SOCKET_STATES||(SOCKET_STATES={}));var CHANNEL_STATES;(function(es){es.closed="closed",es.errored="errored",es.joined="joined",es.joining="joining",es.leaving="leaving"})(CHANNEL_STATES||(CHANNEL_STATES={}));var CHANNEL_EVENTS;(function(es){es.close="phx_close",es.error="phx_error",es.join="phx_join",es.reply="phx_reply",es.leave="phx_leave",es.access_token="access_token"})(CHANNEL_EVENTS||(CHANNEL_EVENTS={}));var TRANSPORTS;(function(es){es.websocket="websocket"})(TRANSPORTS||(TRANSPORTS={}));var CONNECTION_STATE;(function(es){es.Connecting="connecting",es.Open="open",es.Closing="closing",es.Closed="closed"})(CONNECTION_STATE||(CONNECTION_STATE={}));class Serializer{constructor($){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=$??[]}encode($,ts){if($.event===this.BROADCAST_EVENT&&!($.payload instanceof ArrayBuffer)&&typeof $.payload.event=="string")return ts(this._binaryEncodeUserBroadcastPush($));let is=[$.join_ref,$.ref,$.topic,$.event,$.payload];return ts(JSON.stringify(is))}_binaryEncodeUserBroadcastPush($){var ts;return this._isArrayBuffer((ts=$.payload)===null||ts===void 0?void 0:ts.payload)?this._encodeBinaryUserBroadcastPush($):this._encodeJsonUserBroadcastPush($)}_encodeBinaryUserBroadcastPush($){var ts,is;const cs=(is=(ts=$.payload)===null||ts===void 0?void 0:ts.payload)!==null&&is!==void 0?is:new ArrayBuffer(0);return this._encodeUserBroadcastPush($,this.BINARY_ENCODING,cs)}_encodeJsonUserBroadcastPush($){var ts,is;const cs=(is=(ts=$.payload)===null||ts===void 0?void 0:ts.payload)!==null&&is!==void 0?is:{},ja=new TextEncoder().encode(JSON.stringify(cs)).buffer;return this._encodeUserBroadcastPush($,this.JSON_ENCODING,ja)}_encodeUserBroadcastPush($,ts,is){var cs,Qr;const ja=$.topic,Na=(cs=$.ref)!==null&&cs!==void 0?cs:"",Aa=(Qr=$.join_ref)!==null&&Qr!==void 0?Qr:"",Oa=$.payload.event,Ia=this.allowedMetadataKeys?this._pick($.payload,this.allowedMetadataKeys):{},La=Object.keys(Ia).length===0?"":JSON.stringify(Ia);if(Aa.length>255)throw new Error(`joinRef length ${Aa.length} exceeds maximum of 255`);if(Na.length>255)throw new Error(`ref length ${Na.length} exceeds maximum of 255`);if(ja.length>255)throw new Error(`topic length ${ja.length} exceeds maximum of 255`);if(Oa.length>255)throw new Error(`userEvent length ${Oa.length} exceeds maximum of 255`);if(La.length>255)throw new Error(`metadata length ${La.length} exceeds maximum of 255`);const Ba=this.USER_BROADCAST_PUSH_META_LENGTH+Aa.length+Na.length+ja.length+Oa.length+La.length,Ma=new ArrayBuffer(this.HEADER_LENGTH+Ba);let qa=new DataView(Ma),Fa=0;qa.setUint8(Fa++,this.KINDS.userBroadcastPush),qa.setUint8(Fa++,Aa.length),qa.setUint8(Fa++,Na.length),qa.setUint8(Fa++,ja.length),qa.setUint8(Fa++,Oa.length),qa.setUint8(Fa++,La.length),qa.setUint8(Fa++,ts),Array.from(Aa,Ka=>qa.setUint8(Fa++,Ka.charCodeAt(0))),Array.from(Na,Ka=>qa.setUint8(Fa++,Ka.charCodeAt(0))),Array.from(ja,Ka=>qa.setUint8(Fa++,Ka.charCodeAt(0))),Array.from(Oa,Ka=>qa.setUint8(Fa++,Ka.charCodeAt(0))),Array.from(La,Ka=>qa.setUint8(Fa++,Ka.charCodeAt(0)));var Ha=new Uint8Array(Ma.byteLength+is.byteLength);return Ha.set(new Uint8Array(Ma),0),Ha.set(new Uint8Array(is),Ma.byteLength),Ha.buffer}decode($,ts){if(this._isArrayBuffer($)){let is=this._binaryDecode($);return ts(is)}if(typeof $=="string"){const is=JSON.parse($),[cs,Qr,ja,Na,Aa]=is;return ts({join_ref:cs,ref:Qr,topic:ja,event:Na,payload:Aa})}return ts({})}_binaryDecode($){const ts=new DataView($),is=ts.getUint8(0),cs=new TextDecoder;switch(is){case this.KINDS.userBroadcast:return this._decodeUserBroadcast($,ts,cs)}}_decodeUserBroadcast($,ts,is){const cs=ts.getUint8(1),Qr=ts.getUint8(2),ja=ts.getUint8(3),Na=ts.getUint8(4);let Aa=this.HEADER_LENGTH+4;const Oa=is.decode($.slice(Aa,Aa+cs));Aa=Aa+cs;const Ia=is.decode($.slice(Aa,Aa+Qr));Aa=Aa+Qr;const La=is.decode($.slice(Aa,Aa+ja));Aa=Aa+ja;const Ba=$.slice(Aa,$.byteLength),Ma=Na===this.JSON_ENCODING?JSON.parse(is.decode(Ba)):Ba,qa={type:this.BROADCAST_EVENT,event:Ia,payload:Ma};return ja>0&&(qa.meta=JSON.parse(La)),{join_ref:null,ref:null,topic:Oa,event:this.BROADCAST_EVENT,payload:qa}}_isArrayBuffer($){var ts;return $ instanceof ArrayBuffer||((ts=$==null?void 0:$.constructor)===null||ts===void 0?void 0:ts.name)==="ArrayBuffer"}_pick($,ts){return!$||typeof $!="object"?{}:Object.fromEntries(Object.entries($).filter(([is])=>ts.includes(is)))}}class Timer{constructor($,ts){this.callback=$,this.timerCalc=ts,this.timer=void 0,this.tries=0,this.callback=$,this.timerCalc=ts}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var PostgresTypes;(function(es){es.abstime="abstime",es.bool="bool",es.date="date",es.daterange="daterange",es.float4="float4",es.float8="float8",es.int2="int2",es.int4="int4",es.int4range="int4range",es.int8="int8",es.int8range="int8range",es.json="json",es.jsonb="jsonb",es.money="money",es.numeric="numeric",es.oid="oid",es.reltime="reltime",es.text="text",es.time="time",es.timestamp="timestamp",es.timestamptz="timestamptz",es.timetz="timetz",es.tsrange="tsrange",es.tstzrange="tstzrange"})(PostgresTypes||(PostgresTypes={}));const convertChangeData=(es,$,ts={})=>{var is;const cs=(is=ts.skipTypes)!==null&&is!==void 0?is:[];return $?Object.keys($).reduce((Qr,ja)=>(Qr[ja]=convertColumn(ja,es,$,cs),Qr),{}):{}},convertColumn=(es,$,ts,is)=>{const cs=$.find(Na=>Na.name===es),Qr=cs==null?void 0:cs.type,ja=ts[es];return Qr&&!is.includes(Qr)?convertCell(Qr,ja):noop$1(ja)},convertCell=(es,$)=>{if(es.charAt(0)==="_"){const ts=es.slice(1,es.length);return toArray($,ts)}switch(es){case PostgresTypes.bool:return toBoolean($);case PostgresTypes.float4:case PostgresTypes.float8:case PostgresTypes.int2:case PostgresTypes.int4:case PostgresTypes.int8:case PostgresTypes.numeric:case PostgresTypes.oid:return toNumber($);case PostgresTypes.json:case PostgresTypes.jsonb:return toJson($);case PostgresTypes.timestamp:return toTimestampString($);case PostgresTypes.abstime:case PostgresTypes.date:case PostgresTypes.daterange:case PostgresTypes.int4range:case PostgresTypes.int8range:case PostgresTypes.money:case PostgresTypes.reltime:case PostgresTypes.text:case PostgresTypes.time:case PostgresTypes.timestamptz:case PostgresTypes.timetz:case PostgresTypes.tsrange:case PostgresTypes.tstzrange:return noop$1($);default:return noop$1($)}},noop$1=es=>es,toBoolean=es=>{switch(es){case"t":return!0;case"f":return!1;default:return es}},toNumber=es=>{if(typeof es=="string"){const $=parseFloat(es);if(!Number.isNaN($))return $}return es},toJson=es=>{if(typeof es=="string")try{return JSON.parse(es)}catch{return es}return es},toArray=(es,$)=>{if(typeof es!="string")return es;const ts=es.length-1,is=es[ts];if(es[0]==="{"&&is==="}"){let Qr;const ja=es.slice(1,ts);try{Qr=JSON.parse("["+ja+"]")}catch{Qr=ja?ja.split(","):[]}return Qr.map(Na=>convertCell($,Na))}return es},toTimestampString=es=>typeof es=="string"?es.replace(" ","T"):es,httpEndpointURL=es=>{const $=new URL(es);return $.protocol=$.protocol.replace(/^ws/i,"http"),$.pathname=$.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),$.pathname===""||$.pathname==="/"?$.pathname="/api/broadcast":$.pathname=$.pathname+"/api/broadcast",$.href};class Push{constructor($,ts,is={},cs=DEFAULT_TIMEOUT){this.channel=$,this.event=ts,this.payload=is,this.timeout=cs,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend($){this.timeout=$,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload($){this.payload=Object.assign(Object.assign({},this.payload),$)}receive($,ts){var is;return this._hasReceived($)&&ts((is=this.receivedResp)===null||is===void 0?void 0:is.response),this.recHooks.push({status:$,callback:ts}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const $=ts=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=ts,this._matchReceive(ts)};this.channel._on(this.refEvent,{},$),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger($,ts){this.refEvent&&this.channel._trigger(this.refEvent,{status:$,response:ts})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:$,response:ts}){this.recHooks.filter(is=>is.status===$).forEach(is=>is.callback(ts))}_hasReceived($){return this.receivedResp&&this.receivedResp.status===$}}var REALTIME_PRESENCE_LISTEN_EVENTS;(function(es){es.SYNC="sync",es.JOIN="join",es.LEAVE="leave"})(REALTIME_PRESENCE_LISTEN_EVENTS||(REALTIME_PRESENCE_LISTEN_EVENTS={}));class RealtimePresence{constructor($,ts){this.channel=$,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const is=(ts==null?void 0:ts.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(is.state,{},cs=>{const{onJoin:Qr,onLeave:ja,onSync:Na}=this.caller;this.joinRef=this.channel._joinRef(),this.state=RealtimePresence.syncState(this.state,cs,Qr,ja),this.pendingDiffs.forEach(Aa=>{this.state=RealtimePresence.syncDiff(this.state,Aa,Qr,ja)}),this.pendingDiffs=[],Na()}),this.channel._on(is.diff,{},cs=>{const{onJoin:Qr,onLeave:ja,onSync:Na}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(cs):(this.state=RealtimePresence.syncDiff(this.state,cs,Qr,ja),Na())}),this.onJoin((cs,Qr,ja)=>{this.channel._trigger("presence",{event:"join",key:cs,currentPresences:Qr,newPresences:ja})}),this.onLeave((cs,Qr,ja)=>{this.channel._trigger("presence",{event:"leave",key:cs,currentPresences:Qr,leftPresences:ja})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState($,ts,is,cs){const Qr=this.cloneDeep($),ja=this.transformState(ts),Na={},Aa={};return this.map(Qr,(Oa,Ia)=>{ja[Oa]||(Aa[Oa]=Ia)}),this.map(ja,(Oa,Ia)=>{const La=Qr[Oa];if(La){const Ba=Ia.map(Ha=>Ha.presence_ref),Ma=La.map(Ha=>Ha.presence_ref),qa=Ia.filter(Ha=>Ma.indexOf(Ha.presence_ref)<0),Fa=La.filter(Ha=>Ba.indexOf(Ha.presence_ref)<0);qa.length>0&&(Na[Oa]=qa),Fa.length>0&&(Aa[Oa]=Fa)}else Na[Oa]=Ia}),this.syncDiff(Qr,{joins:Na,leaves:Aa},is,cs)}static syncDiff($,ts,is,cs){const{joins:Qr,leaves:ja}={joins:this.transformState(ts.joins),leaves:this.transformState(ts.leaves)};return is||(is=()=>{}),cs||(cs=()=>{}),this.map(Qr,(Na,Aa)=>{var Oa;const Ia=(Oa=$[Na])!==null&&Oa!==void 0?Oa:[];if($[Na]=this.cloneDeep(Aa),Ia.length>0){const La=$[Na].map(Ma=>Ma.presence_ref),Ba=Ia.filter(Ma=>La.indexOf(Ma.presence_ref)<0);$[Na].unshift(...Ba)}is(Na,Ia,Aa)}),this.map(ja,(Na,Aa)=>{let Oa=$[Na];if(!Oa)return;const Ia=Aa.map(La=>La.presence_ref);Oa=Oa.filter(La=>Ia.indexOf(La.presence_ref)<0),$[Na]=Oa,cs(Na,Oa,Aa),Oa.length===0&&delete $[Na]}),$}static map($,ts){return Object.getOwnPropertyNames($).map(is=>ts(is,$[is]))}static transformState($){return $=this.cloneDeep($),Object.getOwnPropertyNames($).reduce((ts,is)=>{const cs=$[is];return"metas"in cs?ts[is]=cs.metas.map(Qr=>(Qr.presence_ref=Qr.phx_ref,delete Qr.phx_ref,delete Qr.phx_ref_prev,Qr)):ts[is]=cs,ts},{})}static cloneDeep($){return JSON.parse(JSON.stringify($))}onJoin($){this.caller.onJoin=$}onLeave($){this.caller.onLeave=$}onSync($){this.caller.onSync=$}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT;(function(es){es.ALL="*",es.INSERT="INSERT",es.UPDATE="UPDATE",es.DELETE="DELETE"})(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT||(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT={}));var REALTIME_LISTEN_TYPES;(function(es){es.BROADCAST="broadcast",es.PRESENCE="presence",es.POSTGRES_CHANGES="postgres_changes",es.SYSTEM="system"})(REALTIME_LISTEN_TYPES||(REALTIME_LISTEN_TYPES={}));var REALTIME_SUBSCRIBE_STATES;(function(es){es.SUBSCRIBED="SUBSCRIBED",es.TIMED_OUT="TIMED_OUT",es.CLOSED="CLOSED",es.CHANNEL_ERROR="CHANNEL_ERROR"})(REALTIME_SUBSCRIBE_STATES||(REALTIME_SUBSCRIBE_STATES={}));class RealtimeChannel{constructor($,ts={config:{}},is){var cs,Qr;if(this.topic=$,this.params=ts,this.socket=is,this.bindings={},this.state=CHANNEL_STATES.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=$.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},ts.config),this.timeout=this.socket.timeout,this.joinPush=new Push(this,CHANNEL_EVENTS.join,this.params,this.timeout),this.rejoinTimer=new Timer(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=CHANNEL_STATES.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(ja=>ja.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=CHANNEL_STATES.closed,this.socket._remove(this)}),this._onError(ja=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,ja),this.state=CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",ja=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,ja),this.state=CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this._on(CHANNEL_EVENTS.reply,{},(ja,Na)=>{this._trigger(this._replyEventName(Na),ja)}),this.presence=new RealtimePresence(this),this.broadcastEndpointURL=httpEndpointURL(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((Qr=(cs=this.params.config)===null||cs===void 0?void 0:cs.broadcast)===null||Qr===void 0)&&Qr.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe($,ts=this.timeout){var is,cs,Qr;if(this.socket.isConnected()||this.socket.connect(),this.state==CHANNEL_STATES.closed){const{config:{broadcast:ja,presence:Na,private:Aa}}=this.params,Oa=(cs=(is=this.bindings.postgres_changes)===null||is===void 0?void 0:is.map(Ma=>Ma.filter))!==null&&cs!==void 0?cs:[],Ia=!!this.bindings[REALTIME_LISTEN_TYPES.PRESENCE]&&this.bindings[REALTIME_LISTEN_TYPES.PRESENCE].length>0||((Qr=this.params.config.presence)===null||Qr===void 0?void 0:Qr.enabled)===!0,La={},Ba={broadcast:ja,presence:Object.assign(Object.assign({},Na),{enabled:Ia}),postgres_changes:Oa,private:Aa};this.socket.accessTokenValue&&(La.access_token=this.socket.accessTokenValue),this._onError(Ma=>$==null?void 0:$(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR,Ma)),this._onClose(()=>$==null?void 0:$(REALTIME_SUBSCRIBE_STATES.CLOSED)),this.updateJoinPayload(Object.assign({config:Ba},La)),this.joinedOnce=!0,this._rejoin(ts),this.joinPush.receive("ok",async({postgres_changes:Ma})=>{var qa;if(this.socket._isManualToken()||this.socket.setAuth(),Ma===void 0){$==null||$(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED);return}else{const Fa=this.bindings.postgres_changes,Ha=(qa=Fa==null?void 0:Fa.length)!==null&&qa!==void 0?qa:0,Ka=[];for(let Ga=0;Ga<Ha;Ga++){const Va=Fa[Ga],{filter:{event:Ja,schema:Ya,table:el,filter:tl}}=Va,rl=Ma&&Ma[Ga];if(rl&&rl.event===Ja&&RealtimeChannel.isFilterValueEqual(rl.schema,Ya)&&RealtimeChannel.isFilterValueEqual(rl.table,el)&&RealtimeChannel.isFilterValueEqual(rl.filter,tl))Ka.push(Object.assign(Object.assign({},Va),{id:rl.id}));else{this.unsubscribe(),this.state=CHANNEL_STATES.errored,$==null||$(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=Ka,$&&$(REALTIME_SUBSCRIBE_STATES.SUBSCRIBED);return}}).receive("error",Ma=>{this.state=CHANNEL_STATES.errored,$==null||$(REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(Ma).join(", ")||"error")))}).receive("timeout",()=>{$==null||$(REALTIME_SUBSCRIBE_STATES.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track($,ts={}){return await this.send({type:"presence",event:"track",payload:$},ts.timeout||this.timeout)}async untrack($={}){return await this.send({type:"presence",event:"untrack"},$)}on($,ts,is){return this.state===CHANNEL_STATES.joined&&$===REALTIME_LISTEN_TYPES.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on($,ts,is)}async httpSend($,ts,is={}){var cs;if(ts==null)return Promise.reject("Payload is required for httpSend()");const Qr={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(Qr.Authorization=`Bearer ${this.socket.accessTokenValue}`);const ja={method:"POST",headers:Qr,body:JSON.stringify({messages:[{topic:this.subTopic,event:$,payload:ts,private:this.private}]})},Na=await this._fetchWithTimeout(this.broadcastEndpointURL,ja,(cs=is.timeout)!==null&&cs!==void 0?cs:this.timeout);if(Na.status===202)return{success:!0};let Aa=Na.statusText;try{const Oa=await Na.json();Aa=Oa.error||Oa.message||Aa}catch{}return Promise.reject(new Error(Aa))}async send($,ts={}){var is,cs;if(!this._canPush()&&$.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:Qr,payload:ja}=$,Na={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(Na.Authorization=`Bearer ${this.socket.accessTokenValue}`);const Aa={method:"POST",headers:Na,body:JSON.stringify({messages:[{topic:this.subTopic,event:Qr,payload:ja,private:this.private}]})};try{const Oa=await this._fetchWithTimeout(this.broadcastEndpointURL,Aa,(is=ts.timeout)!==null&&is!==void 0?is:this.timeout);return await((cs=Oa.body)===null||cs===void 0?void 0:cs.cancel()),Oa.ok?"ok":"error"}catch(Oa){return Oa.name==="AbortError"?"timed out":"error"}}else return new Promise(Qr=>{var ja,Na,Aa;const Oa=this._push($.type,$,ts.timeout||this.timeout);$.type==="broadcast"&&!(!((Aa=(Na=(ja=this.params)===null||ja===void 0?void 0:ja.config)===null||Na===void 0?void 0:Na.broadcast)===null||Aa===void 0)&&Aa.ack)&&Qr("ok"),Oa.receive("ok",()=>Qr("ok")),Oa.receive("error",()=>Qr("error")),Oa.receive("timeout",()=>Qr("timed out"))})}updateJoinPayload($){this.joinPush.updatePayload($)}unsubscribe($=this.timeout){this.state=CHANNEL_STATES.leaving;const ts=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(CHANNEL_EVENTS.close,"leave",this._joinRef())};this.joinPush.destroy();let is=null;return new Promise(cs=>{is=new Push(this,CHANNEL_EVENTS.leave,{},$),is.receive("ok",()=>{ts(),cs("ok")}).receive("timeout",()=>{ts(),cs("timed out")}).receive("error",()=>{cs("error")}),is.send(),this._canPush()||is.trigger("ok",{})}).finally(()=>{is==null||is.destroy()})}teardown(){this.pushBuffer.forEach($=>$.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=CHANNEL_STATES.closed,this.bindings={}}async _fetchWithTimeout($,ts,is){const cs=new AbortController,Qr=setTimeout(()=>cs.abort(),is),ja=await this.socket.fetch($,Object.assign(Object.assign({},ts),{signal:cs.signal}));return clearTimeout(Qr),ja}_push($,ts,is=this.timeout){if(!this.joinedOnce)throw`tried to push '${$}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let cs=new Push(this,$,ts,is);return this._canPush()?cs.send():this._addToPushBuffer(cs),cs}_addToPushBuffer($){if($.startTimeout(),this.pushBuffer.push($),this.pushBuffer.length>MAX_PUSH_BUFFER_SIZE){const ts=this.pushBuffer.shift();ts&&(ts.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${ts.event}`,ts.payload))}}_onMessage($,ts,is){return ts}_isMember($){return this.topic===$}_joinRef(){return this.joinPush.ref}_trigger($,ts,is){var cs,Qr;const ja=$.toLocaleLowerCase(),{close:Na,error:Aa,leave:Oa,join:Ia}=CHANNEL_EVENTS;if(is&&[Na,Aa,Oa,Ia].indexOf(ja)>=0&&is!==this._joinRef())return;let Ba=this._onMessage(ja,ts,is);if(ts&&!Ba)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(ja)?(cs=this.bindings.postgres_changes)===null||cs===void 0||cs.filter(Ma=>{var qa,Fa,Ha;return((qa=Ma.filter)===null||qa===void 0?void 0:qa.event)==="*"||((Ha=(Fa=Ma.filter)===null||Fa===void 0?void 0:Fa.event)===null||Ha===void 0?void 0:Ha.toLocaleLowerCase())===ja}).map(Ma=>Ma.callback(Ba,is)):(Qr=this.bindings[ja])===null||Qr===void 0||Qr.filter(Ma=>{var qa,Fa,Ha,Ka,Ga,Va;if(["broadcast","presence","postgres_changes"].includes(ja))if("id"in Ma){const Ja=Ma.id,Ya=(qa=Ma.filter)===null||qa===void 0?void 0:qa.event;return Ja&&((Fa=ts.ids)===null||Fa===void 0?void 0:Fa.includes(Ja))&&(Ya==="*"||(Ya==null?void 0:Ya.toLocaleLowerCase())===((Ha=ts.data)===null||Ha===void 0?void 0:Ha.type.toLocaleLowerCase()))}else{const Ja=(Ga=(Ka=Ma==null?void 0:Ma.filter)===null||Ka===void 0?void 0:Ka.event)===null||Ga===void 0?void 0:Ga.toLocaleLowerCase();return Ja==="*"||Ja===((Va=ts==null?void 0:ts.event)===null||Va===void 0?void 0:Va.toLocaleLowerCase())}else return Ma.type.toLocaleLowerCase()===ja}).map(Ma=>{if(typeof Ba=="object"&&"ids"in Ba){const qa=Ba.data,{schema:Fa,table:Ha,commit_timestamp:Ka,type:Ga,errors:Va}=qa;Ba=Object.assign(Object.assign({},{schema:Fa,table:Ha,commit_timestamp:Ka,eventType:Ga,new:{},old:{},errors:Va}),this._getPayloadRecords(qa))}Ma.callback(Ba,is)})}_isClosed(){return this.state===CHANNEL_STATES.closed}_isJoined(){return this.state===CHANNEL_STATES.joined}_isJoining(){return this.state===CHANNEL_STATES.joining}_isLeaving(){return this.state===CHANNEL_STATES.leaving}_replyEventName($){return`chan_reply_${$}`}_on($,ts,is){const cs=$.toLocaleLowerCase(),Qr={type:cs,filter:ts,callback:is};return this.bindings[cs]?this.bindings[cs].push(Qr):this.bindings[cs]=[Qr],this}_off($,ts){const is=$.toLocaleLowerCase();return this.bindings[is]&&(this.bindings[is]=this.bindings[is].filter(cs=>{var Qr;return!(((Qr=cs.type)===null||Qr===void 0?void 0:Qr.toLocaleLowerCase())===is&&RealtimeChannel.isEqual(cs.filter,ts))})),this}static isEqual($,ts){if(Object.keys($).length!==Object.keys(ts).length)return!1;for(const is in $)if($[is]!==ts[is])return!1;return!0}static isFilterValueEqual($,ts){return($??void 0)===(ts??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose($){this._on(CHANNEL_EVENTS.close,{},$)}_onError($){this._on(CHANNEL_EVENTS.error,{},ts=>$(ts))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin($=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=CHANNEL_STATES.joining,this.joinPush.resend($))}_getPayloadRecords($){const ts={new:{},old:{}};return($.type==="INSERT"||$.type==="UPDATE")&&(ts.new=convertChangeData($.columns,$.record)),($.type==="UPDATE"||$.type==="DELETE")&&(ts.old=convertChangeData($.columns,$.old_record)),ts}}const noop=()=>{},CONNECTION_TIMEOUTS={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},RECONNECT_INTERVALS=[1e3,2e3,5e3,1e4],DEFAULT_RECONNECT_FALLBACK=1e4,WORKER_SCRIPT=`
|
|
34
|
+
addEventListener("message", (e) => {
|
|
35
|
+
if (e.data.event === "start") {
|
|
36
|
+
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
37
|
+
}
|
|
38
|
+
});`;class RealtimeClient{constructor($,ts){var is;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=DEFAULT_TIMEOUT,this.transport=null,this.heartbeatIntervalMs=CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=noop,this.ref=0,this.reconnectTimer=null,this.vsn=DEFAULT_VSN,this.logger=noop,this.conn=null,this.sendBuffer=[],this.serializer=new Serializer,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=cs=>cs?(...Qr)=>cs(...Qr):(...Qr)=>fetch(...Qr),!(!((is=ts==null?void 0:ts.params)===null||is===void 0)&&is.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=ts.params.apikey,this.endPoint=`${$}/${TRANSPORTS.websocket}`,this.httpEndpoint=httpEndpointURL($),this._initializeOptions(ts),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(ts==null?void 0:ts.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=WebSocketFactory.createWebSocket(this.endpointURL())}catch($){this._setConnectionState("disconnected");const ts=$.message;throw ts.includes("Node.js")?new Error(`${ts}
|
|
39
|
+
|
|
40
|
+
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
41
|
+
|
|
42
|
+
Option 1: Use Node.js 22+ which has native WebSocket support
|
|
43
|
+
Option 2: Install and provide the "ws" package:
|
|
44
|
+
|
|
45
|
+
npm install ws
|
|
46
|
+
|
|
47
|
+
import ws from "ws"
|
|
48
|
+
const client = new RealtimeClient(url, {
|
|
49
|
+
...options,
|
|
50
|
+
transport: ws
|
|
51
|
+
})`):new Error(`WebSocket not available: ${ts}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect($,ts){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const is=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(is),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&($?this.conn.close($,ts??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel($){const ts=await $.unsubscribe();return ts==="ok"&&this._remove($),this.channels.length===0&&this.disconnect(),ts}async removeAllChannels(){const $=await Promise.all(this.channels.map(ts=>ts.unsubscribe()));return this.channels=[],this.disconnect(),$}log($,ts,is){this.logger($,ts,is)}connectionState(){switch(this.conn&&this.conn.readyState){case SOCKET_STATES.connecting:return CONNECTION_STATE.Connecting;case SOCKET_STATES.open:return CONNECTION_STATE.Open;case SOCKET_STATES.closing:return CONNECTION_STATE.Closing;default:return CONNECTION_STATE.Closed}}isConnected(){return this.connectionState()===CONNECTION_STATE.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel($,ts={config:{}}){const is=`realtime:${$}`,cs=this.getChannels().find(Qr=>Qr.topic===is);if(cs)return cs;{const Qr=new RealtimeChannel(`realtime:${$}`,ts,this);return this.channels.push(Qr),Qr}}push($){const{topic:ts,event:is,payload:cs,ref:Qr}=$,ja=()=>{this.encode($,Na=>{var Aa;(Aa=this.conn)===null||Aa===void 0||Aa.send(Na)})};this.log("push",`${ts} ${is} (${Qr})`,cs),this.isConnected()?ja():this.sendBuffer.push(ja)}async setAuth($=null){this._authPromise=this._performAuth($);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var $;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(ts){this.log("error","error in heartbeat callback",ts)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(ts){this.log("error","error in heartbeat callback",ts)}this._wasManualDisconnect=!1,($=this.conn)===null||$===void 0||$.close(WS_CLOSE_NORMAL,"heartbeat timeout"),setTimeout(()=>{var ts;this.isConnected()||(ts=this.reconnectTimer)===null||ts===void 0||ts.scheduleTimeout()},CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(ts){this.log("error","error in heartbeat callback",ts)}this._setAuthSafely("heartbeat")}onHeartbeat($){this.heartbeatCallback=$}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach($=>$()),this.sendBuffer=[])}_makeRef(){let $=this.ref+1;return $===this.ref?this.ref=0:this.ref=$,this.ref.toString()}_leaveOpenTopic($){let ts=this.channels.find(is=>is.topic===$&&(is._isJoined()||is._isJoining()));ts&&(this.log("transport",`leaving duplicate topic "${$}"`),ts.unsubscribe())}_remove($){this.channels=this.channels.filter(ts=>ts.topic!==$.topic)}_onConnMessage($){this.decode($.data,ts=>{if(ts.topic==="phoenix"&&ts.event==="phx_reply"&&ts.ref&&ts.ref===this.pendingHeartbeatRef){const Oa=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(ts.payload.status==="ok"?"ok":"error",Oa)}catch(Ia){this.log("error","error in heartbeat callback",Ia)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:is,event:cs,payload:Qr,ref:ja}=ts,Na=ja?`(${ja})`:"",Aa=Qr.status||"";this.log("receive",`${Aa} ${is} ${cs} ${Na}`.trim(),Qr),this.channels.filter(Oa=>Oa._isMember(is)).forEach(Oa=>Oa._trigger(cs,Qr,ja)),this._triggerStateCallbacks("message",ts)})}_clearTimer($){var ts;$==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):$==="reconnect"&&((ts=this.reconnectTimer)===null||ts===void 0||ts.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=$=>this._onConnError($),this.conn.onmessage=$=>this._onConnMessage($),this.conn.onclose=$=>this._onConnClose($),this.conn.readyState===SOCKET_STATES.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===SOCKET_STATES.open||this.conn.readyState===SOCKET_STATES.connecting)try{this.conn.close()}catch($){this.log("error","Error closing connection",$)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach($=>$.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(ts=>{this.log("error","error waiting for auth on connect",ts),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const $=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker($),this.workerRef.onerror=ts=>{this.log("worker","worker error",ts.message),this._terminateWorker()},this.workerRef.onmessage=ts=>{ts.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose($){var ts;this._setConnectionState("disconnected"),this.log("transport","close",$),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(ts=this.reconnectTimer)===null||ts===void 0||ts.scheduleTimeout(),this._triggerStateCallbacks("close",$)}_onConnError($){this._setConnectionState("disconnected"),this.log("transport",`${$}`),this._triggerChanError(),this._triggerStateCallbacks("error",$);try{this.heartbeatCallback("error")}catch(ts){this.log("error","error in heartbeat callback",ts)}}_triggerChanError(){this.channels.forEach($=>$._trigger(CHANNEL_EVENTS.error))}_appendParams($,ts){if(Object.keys(ts).length===0)return $;const is=$.match(/\?/)?"&":"?",cs=new URLSearchParams(ts);return`${$}${is}${cs}`}_workerObjectUrl($){let ts;if($)ts=$;else{const is=new Blob([WORKER_SCRIPT],{type:"application/javascript"});ts=URL.createObjectURL(is)}return ts}_setConnectionState($,ts=!1){this._connectionState=$,$==="connecting"?this._wasManualDisconnect=!1:$==="disconnecting"&&(this._wasManualDisconnect=ts)}async _performAuth($=null){let ts,is=!1;if($)ts=$,is=!0;else if(this.accessToken)try{ts=await this.accessToken()}catch(cs){this.log("error","Error fetching access token from callback",cs),ts=this.accessTokenValue}else ts=this.accessTokenValue;is?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=ts&&(this.accessTokenValue=ts,this.channels.forEach(cs=>{const Qr={access_token:ts,version:DEFAULT_VERSION};ts&&cs.updateJoinPayload(Qr),cs.joinedOnce&&cs._isJoined()&&cs._push(CHANNEL_EVENTS.access_token,{access_token:ts})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely($="general"){this._isManualToken()||this.setAuth().catch(ts=>{this.log("error",`Error setting auth in ${$}`,ts)})}_triggerStateCallbacks($,ts){try{this.stateChangeCallbacks[$].forEach(is=>{try{is(ts)}catch(cs){this.log("error",`error in ${$} callback`,cs)}})}catch(is){this.log("error",`error triggering ${$} callbacks`,is)}}_setupReconnectionTimer(){this.reconnectTimer=new Timer(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},CONNECTION_TIMEOUTS.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions($){var ts,is,cs,Qr,ja,Na,Aa,Oa,Ia,La,Ba,Ma;switch(this.transport=(ts=$==null?void 0:$.transport)!==null&&ts!==void 0?ts:null,this.timeout=(is=$==null?void 0:$.timeout)!==null&&is!==void 0?is:DEFAULT_TIMEOUT,this.heartbeatIntervalMs=(cs=$==null?void 0:$.heartbeatIntervalMs)!==null&&cs!==void 0?cs:CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL,this.worker=(Qr=$==null?void 0:$.worker)!==null&&Qr!==void 0?Qr:!1,this.accessToken=(ja=$==null?void 0:$.accessToken)!==null&&ja!==void 0?ja:null,this.heartbeatCallback=(Na=$==null?void 0:$.heartbeatCallback)!==null&&Na!==void 0?Na:noop,this.vsn=(Aa=$==null?void 0:$.vsn)!==null&&Aa!==void 0?Aa:DEFAULT_VSN,$!=null&&$.params&&(this.params=$.params),$!=null&&$.logger&&(this.logger=$.logger),($!=null&&$.logLevel||$!=null&&$.log_level)&&(this.logLevel=$.logLevel||$.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(Oa=$==null?void 0:$.reconnectAfterMs)!==null&&Oa!==void 0?Oa:(qa=>RECONNECT_INTERVALS[qa-1]||DEFAULT_RECONNECT_FALLBACK),this.vsn){case VSN_1_0_0:this.encode=(Ia=$==null?void 0:$.encode)!==null&&Ia!==void 0?Ia:((qa,Fa)=>Fa(JSON.stringify(qa))),this.decode=(La=$==null?void 0:$.decode)!==null&&La!==void 0?La:((qa,Fa)=>Fa(JSON.parse(qa)));break;case VSN_2_0_0:this.encode=(Ba=$==null?void 0:$.encode)!==null&&Ba!==void 0?Ba:this.serializer.encode.bind(this.serializer),this.decode=(Ma=$==null?void 0:$.decode)!==null&&Ma!==void 0?Ma:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=$==null?void 0:$.workerUrl}}}var IcebergError=class extends Error{constructor(es,$){var ts;super(es),this.name="IcebergError",this.status=$.status,this.icebergType=$.icebergType,this.icebergCode=$.icebergCode,this.details=$.details,this.isCommitStateUnknown=$.icebergType==="CommitStateUnknownException"||[500,502,504].includes($.status)&&((ts=$.icebergType)==null?void 0:ts.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function buildUrl(es,$,ts){const is=new URL($,es);if(ts)for(const[cs,Qr]of Object.entries(ts))Qr!==void 0&&is.searchParams.set(cs,Qr);return is.toString()}async function buildAuthHeaders(es){return!es||es.type==="none"?{}:es.type==="bearer"?{Authorization:`Bearer ${es.token}`}:es.type==="header"?{[es.name]:es.value}:es.type==="custom"?await es.getHeaders():{}}function createFetchClient(es){const $=es.fetchImpl??globalThis.fetch;return{async request({method:ts,path:is,query:cs,body:Qr,headers:ja}){const Na=buildUrl(es.baseUrl,is,cs),Aa=await buildAuthHeaders(es.auth),Oa=await $(Na,{method:ts,headers:{...Qr?{"Content-Type":"application/json"}:{},...Aa,...ja},body:Qr?JSON.stringify(Qr):void 0}),Ia=await Oa.text(),La=(Oa.headers.get("content-type")||"").includes("application/json"),Ba=La&&Ia?JSON.parse(Ia):Ia;if(!Oa.ok){const Ma=La?Ba:void 0,qa=Ma==null?void 0:Ma.error;throw new IcebergError((qa==null?void 0:qa.message)??`Request failed with status ${Oa.status}`,{status:Oa.status,icebergType:qa==null?void 0:qa.type,icebergCode:qa==null?void 0:qa.code,details:Ma})}return{status:Oa.status,headers:Oa.headers,data:Ba}}}}function namespaceToPath(es){return es.join("")}var NamespaceOperations=class{constructor(es,$=""){this.client=es,this.prefix=$}async listNamespaces(es){const $=es?{parent:namespaceToPath(es.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:$})).data.namespaces.map(is=>({namespace:is}))}async createNamespace(es,$){const ts={namespace:es.namespace,properties:$==null?void 0:$.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:ts})).data}async dropNamespace(es){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${namespaceToPath(es.namespace)}`})}async loadNamespaceMetadata(es){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${namespaceToPath(es.namespace)}`})).data.properties}}async namespaceExists(es){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${namespaceToPath(es.namespace)}`}),!0}catch($){if($ instanceof IcebergError&&$.status===404)return!1;throw $}}async createNamespaceIfNotExists(es,$){try{return await this.createNamespace(es,$)}catch(ts){if(ts instanceof IcebergError&&ts.status===409)return;throw ts}}};function namespaceToPath2(es){return es.join("")}var TableOperations=class{constructor(es,$="",ts){this.client=es,this.prefix=$,this.accessDelegation=ts}async listTables(es){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${namespaceToPath2(es.namespace)}/tables`})).data.identifiers}async createTable(es,$){const ts={};return this.accessDelegation&&(ts["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${namespaceToPath2(es.namespace)}/tables`,body:$,headers:ts})).data.metadata}async updateTable(es,$){const ts=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${namespaceToPath2(es.namespace)}/tables/${es.name}`,body:$});return{"metadata-location":ts.data["metadata-location"],metadata:ts.data.metadata}}async dropTable(es,$){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${namespaceToPath2(es.namespace)}/tables/${es.name}`,query:{purgeRequested:String(($==null?void 0:$.purge)??!1)}})}async loadTable(es){const $={};return this.accessDelegation&&($["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${namespaceToPath2(es.namespace)}/tables/${es.name}`,headers:$})).data.metadata}async tableExists(es){const $={};this.accessDelegation&&($["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${namespaceToPath2(es.namespace)}/tables/${es.name}`,headers:$}),!0}catch(ts){if(ts instanceof IcebergError&&ts.status===404)return!1;throw ts}}async createTableIfNotExists(es,$){try{return await this.createTable(es,$)}catch(ts){if(ts instanceof IcebergError&&ts.status===409)return await this.loadTable({namespace:es.namespace,name:$.name});throw ts}}},IcebergRestCatalog=class{constructor(es){var is;let $="v1";es.catalogName&&($+=`/${es.catalogName}`);const ts=es.baseUrl.endsWith("/")?es.baseUrl:`${es.baseUrl}/`;this.client=createFetchClient({baseUrl:ts,auth:es.auth,fetchImpl:es.fetch}),this.accessDelegation=(is=es.accessDelegation)==null?void 0:is.join(","),this.namespaceOps=new NamespaceOperations(this.client,$),this.tableOps=new TableOperations(this.client,$,this.accessDelegation)}async listNamespaces(es){return this.namespaceOps.listNamespaces(es)}async createNamespace(es,$){return this.namespaceOps.createNamespace(es,$)}async dropNamespace(es){await this.namespaceOps.dropNamespace(es)}async loadNamespaceMetadata(es){return this.namespaceOps.loadNamespaceMetadata(es)}async listTables(es){return this.tableOps.listTables(es)}async createTable(es,$){return this.tableOps.createTable(es,$)}async updateTable(es,$){return this.tableOps.updateTable(es,$)}async dropTable(es,$){await this.tableOps.dropTable(es,$)}async loadTable(es){return this.tableOps.loadTable(es)}async namespaceExists(es){return this.namespaceOps.namespaceExists(es)}async tableExists(es){return this.tableOps.tableExists(es)}async createNamespaceIfNotExists(es,$){return this.namespaceOps.createNamespaceIfNotExists(es,$)}async createTableIfNotExists(es,$){return this.tableOps.createTableIfNotExists(es,$)}},StorageError=class extends Error{constructor(es,$="storage",ts,is){super(es),this.__isStorageError=!0,this.namespace=$,this.name=$==="vectors"?"StorageVectorsError":"StorageError",this.status=ts,this.statusCode=is}};function isStorageError(es){return typeof es=="object"&&es!==null&&"__isStorageError"in es}var StorageApiError=class extends StorageError{constructor(es,$,ts,is="storage"){super(es,is,$,ts),this.name=is==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=$,this.statusCode=ts}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},StorageUnknownError=class extends StorageError{constructor(es,$,ts="storage"){super(es,ts),this.name=ts==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=$}};const resolveFetch$2=es=>es?(...$)=>es(...$):(...$)=>fetch(...$),isPlainObject=es=>{if(typeof es!="object"||es===null)return!1;const $=Object.getPrototypeOf(es);return($===null||$===Object.prototype||Object.getPrototypeOf($)===null)&&!(Symbol.toStringTag in es)&&!(Symbol.iterator in es)},recursiveToCamel=es=>{if(Array.isArray(es))return es.map(ts=>recursiveToCamel(ts));if(typeof es=="function"||es!==Object(es))return es;const $={};return Object.entries(es).forEach(([ts,is])=>{const cs=ts.replace(/([-_][a-z])/gi,Qr=>Qr.toUpperCase().replace(/[-_]/g,""));$[cs]=recursiveToCamel(is)}),$},isValidBucketName=es=>!es||typeof es!="string"||es.length===0||es.length>100||es.trim()!==es||es.includes("/")||es.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(es);function _typeof$1(es){"@babel/helpers - typeof";return _typeof$1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},_typeof$1(es)}function toPrimitive$1(es,$){if(_typeof$1(es)!="object"||!es)return es;var ts=es[Symbol.toPrimitive];if(ts!==void 0){var is=ts.call(es,$);if(_typeof$1(is)!="object")return is;throw new TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(es)}function toPropertyKey$1(es){var $=toPrimitive$1(es,"string");return _typeof$1($)=="symbol"?$:$+""}function _defineProperty$1(es,$,ts){return($=toPropertyKey$1($))in es?Object.defineProperty(es,$,{value:ts,enumerable:!0,configurable:!0,writable:!0}):es[$]=ts,es}function ownKeys$1(es,$){var ts=Object.keys(es);if(Object.getOwnPropertySymbols){var is=Object.getOwnPropertySymbols(es);$&&(is=is.filter(function(cs){return Object.getOwnPropertyDescriptor(es,cs).enumerable})),ts.push.apply(ts,is)}return ts}function _objectSpread2$1(es){for(var $=1;$<arguments.length;$++){var ts=arguments[$]!=null?arguments[$]:{};$%2?ownKeys$1(Object(ts),!0).forEach(function(is){_defineProperty$1(es,is,ts[is])}):Object.getOwnPropertyDescriptors?Object.defineProperties(es,Object.getOwnPropertyDescriptors(ts)):ownKeys$1(Object(ts)).forEach(function(is){Object.defineProperty(es,is,Object.getOwnPropertyDescriptor(ts,is))})}return es}const _getErrorMessage$1=es=>{var $;return es.msg||es.message||es.error_description||(typeof es.error=="string"?es.error:($=es.error)===null||$===void 0?void 0:$.message)||JSON.stringify(es)},handleError$1=async(es,$,ts,is)=>{if(es&&typeof es=="object"&&"status"in es&&"ok"in es&&typeof es.status=="number"&&!(ts!=null&&ts.noResolveJson)){const cs=es,Qr=cs.status||500;if(typeof cs.json=="function")cs.json().then(ja=>{const Na=(ja==null?void 0:ja.statusCode)||(ja==null?void 0:ja.code)||Qr+"";$(new StorageApiError(_getErrorMessage$1(ja),Qr,Na,is))}).catch(()=>{if(is==="vectors"){const ja=Qr+"";$(new StorageApiError(cs.statusText||`HTTP ${Qr} error`,Qr,ja,is))}else{const ja=Qr+"";$(new StorageApiError(cs.statusText||`HTTP ${Qr} error`,Qr,ja,is))}});else{const ja=Qr+"";$(new StorageApiError(cs.statusText||`HTTP ${Qr} error`,Qr,ja,is))}}else $(new StorageUnknownError(_getErrorMessage$1(es),es,is))},_getRequestParams$1=(es,$,ts,is)=>{const cs={method:es,headers:($==null?void 0:$.headers)||{}};return es==="GET"||es==="HEAD"||!is?_objectSpread2$1(_objectSpread2$1({},cs),ts):(isPlainObject(is)?(cs.headers=_objectSpread2$1({"Content-Type":"application/json"},$==null?void 0:$.headers),cs.body=JSON.stringify(is)):cs.body=is,$!=null&&$.duplex&&(cs.duplex=$.duplex),_objectSpread2$1(_objectSpread2$1({},cs),ts))};async function _handleRequest$1(es,$,ts,is,cs,Qr,ja){return new Promise((Na,Aa)=>{es(ts,_getRequestParams$1($,is,cs,Qr)).then(Oa=>{if(!Oa.ok)throw Oa;if(is!=null&&is.noResolveJson)return Oa;if(ja==="vectors"){const Ia=Oa.headers.get("content-type");if(Oa.headers.get("content-length")==="0"||Oa.status===204)return{};if(!Ia||!Ia.includes("application/json"))return{}}return Oa.json()}).then(Oa=>Na(Oa)).catch(Oa=>handleError$1(Oa,Aa,is,ja))})}function createFetchApi(es="storage"){return{get:async($,ts,is,cs)=>_handleRequest$1($,"GET",ts,is,cs,void 0,es),post:async($,ts,is,cs,Qr)=>_handleRequest$1($,"POST",ts,cs,Qr,is,es),put:async($,ts,is,cs,Qr)=>_handleRequest$1($,"PUT",ts,cs,Qr,is,es),head:async($,ts,is,cs)=>_handleRequest$1($,"HEAD",ts,_objectSpread2$1(_objectSpread2$1({},is),{},{noResolveJson:!0}),cs,void 0,es),remove:async($,ts,is,cs,Qr)=>_handleRequest$1($,"DELETE",ts,cs,Qr,is,es)}}const defaultApi=createFetchApi("storage"),{get,post,put,head,remove}=defaultApi,vectorsApi=createFetchApi("vectors");var BaseApiClient=class{constructor(es,$={},ts,is="storage"){this.shouldThrowOnError=!1,this.url=es,this.headers=$,this.fetch=resolveFetch$2(ts),this.namespace=is}throwOnError(){return this.shouldThrowOnError=!0,this}async handleOperation(es){var $=this;try{return{data:await es(),error:null}}catch(ts){if($.shouldThrowOnError)throw ts;if(isStorageError(ts))return{data:null,error:ts};throw ts}}},StreamDownloadBuilder=class{constructor(es,$){this.downloadFn=es,this.shouldThrowOnError=$}then(es,$){return this.execute().then(es,$)}async execute(){var es=this;try{return{data:(await es.downloadFn()).body,error:null}}catch($){if(es.shouldThrowOnError)throw $;if(isStorageError($))return{data:null,error:$};throw $}}};let _Symbol$toStringTag;_Symbol$toStringTag=Symbol.toStringTag;var BlobDownloadBuilder=class{constructor(es,$){this.downloadFn=es,this.shouldThrowOnError=$,this[_Symbol$toStringTag]="BlobDownloadBuilder",this.promise=null}asStream(){return new StreamDownloadBuilder(this.downloadFn,this.shouldThrowOnError)}then(es,$){return this.getPromise().then(es,$)}catch(es){return this.getPromise().catch(es)}finally(es){return this.getPromise().finally(es)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var es=this;try{return{data:await(await es.downloadFn()).blob(),error:null}}catch($){if(es.shouldThrowOnError)throw $;if(isStorageError($))return{data:null,error:$};throw $}}};const DEFAULT_SEARCH_OPTIONS={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},DEFAULT_FILE_OPTIONS={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var StorageFileApi=class extends BaseApiClient{constructor(es,$={},ts,is){super(es,$,is,"storage"),this.bucketId=ts}async uploadOrUpdate(es,$,ts,is){var cs=this;return cs.handleOperation(async()=>{let Qr;const ja=_objectSpread2$1(_objectSpread2$1({},DEFAULT_FILE_OPTIONS),is);let Na=_objectSpread2$1(_objectSpread2$1({},cs.headers),es==="POST"&&{"x-upsert":String(ja.upsert)});const Aa=ja.metadata;typeof Blob<"u"&&ts instanceof Blob?(Qr=new FormData,Qr.append("cacheControl",ja.cacheControl),Aa&&Qr.append("metadata",cs.encodeMetadata(Aa)),Qr.append("",ts)):typeof FormData<"u"&&ts instanceof FormData?(Qr=ts,Qr.has("cacheControl")||Qr.append("cacheControl",ja.cacheControl),Aa&&!Qr.has("metadata")&&Qr.append("metadata",cs.encodeMetadata(Aa))):(Qr=ts,Na["cache-control"]=`max-age=${ja.cacheControl}`,Na["content-type"]=ja.contentType,Aa&&(Na["x-metadata"]=cs.toBase64(cs.encodeMetadata(Aa))),(typeof ReadableStream<"u"&&Qr instanceof ReadableStream||Qr&&typeof Qr=="object"&&"pipe"in Qr&&typeof Qr.pipe=="function")&&!ja.duplex&&(ja.duplex="half")),is!=null&&is.headers&&(Na=_objectSpread2$1(_objectSpread2$1({},Na),is.headers));const Oa=cs._removeEmptyFolders($),Ia=cs._getFinalPath(Oa),La=await(es=="PUT"?put:post)(cs.fetch,`${cs.url}/object/${Ia}`,Qr,_objectSpread2$1({headers:Na},ja!=null&&ja.duplex?{duplex:ja.duplex}:{}));return{path:Oa,id:La.Id,fullPath:La.Key}})}async upload(es,$,ts){return this.uploadOrUpdate("POST",es,$,ts)}async uploadToSignedUrl(es,$,ts,is){var cs=this;const Qr=cs._removeEmptyFolders(es),ja=cs._getFinalPath(Qr),Na=new URL(cs.url+`/object/upload/sign/${ja}`);return Na.searchParams.set("token",$),cs.handleOperation(async()=>{let Aa;const Oa=_objectSpread2$1({upsert:DEFAULT_FILE_OPTIONS.upsert},is),Ia=_objectSpread2$1(_objectSpread2$1({},cs.headers),{"x-upsert":String(Oa.upsert)});return typeof Blob<"u"&&ts instanceof Blob?(Aa=new FormData,Aa.append("cacheControl",Oa.cacheControl),Aa.append("",ts)):typeof FormData<"u"&&ts instanceof FormData?(Aa=ts,Aa.append("cacheControl",Oa.cacheControl)):(Aa=ts,Ia["cache-control"]=`max-age=${Oa.cacheControl}`,Ia["content-type"]=Oa.contentType),{path:Qr,fullPath:(await put(cs.fetch,Na.toString(),Aa,{headers:Ia})).Key}})}async createSignedUploadUrl(es,$){var ts=this;return ts.handleOperation(async()=>{let is=ts._getFinalPath(es);const cs=_objectSpread2$1({},ts.headers);$!=null&&$.upsert&&(cs["x-upsert"]="true");const Qr=await post(ts.fetch,`${ts.url}/object/upload/sign/${is}`,{},{headers:cs}),ja=new URL(ts.url+Qr.url),Na=ja.searchParams.get("token");if(!Na)throw new StorageError("No token returned by API");return{signedUrl:ja.toString(),path:es,token:Na}})}async update(es,$,ts){return this.uploadOrUpdate("PUT",es,$,ts)}async move(es,$,ts){var is=this;return is.handleOperation(async()=>await post(is.fetch,`${is.url}/object/move`,{bucketId:is.bucketId,sourceKey:es,destinationKey:$,destinationBucket:ts==null?void 0:ts.destinationBucket},{headers:is.headers}))}async copy(es,$,ts){var is=this;return is.handleOperation(async()=>({path:(await post(is.fetch,`${is.url}/object/copy`,{bucketId:is.bucketId,sourceKey:es,destinationKey:$,destinationBucket:ts==null?void 0:ts.destinationBucket},{headers:is.headers})).Key}))}async createSignedUrl(es,$,ts){var is=this;return is.handleOperation(async()=>{let cs=is._getFinalPath(es),Qr=await post(is.fetch,`${is.url}/object/sign/${cs}`,_objectSpread2$1({expiresIn:$},ts!=null&&ts.transform?{transform:ts.transform}:{}),{headers:is.headers});const ja=ts!=null&&ts.download?`&download=${ts.download===!0?"":ts.download}`:"";return{signedUrl:encodeURI(`${is.url}${Qr.signedURL}${ja}`)}})}async createSignedUrls(es,$,ts){var is=this;return is.handleOperation(async()=>{const cs=await post(is.fetch,`${is.url}/object/sign/${is.bucketId}`,{expiresIn:$,paths:es},{headers:is.headers}),Qr=ts!=null&&ts.download?`&download=${ts.download===!0?"":ts.download}`:"";return cs.map(ja=>_objectSpread2$1(_objectSpread2$1({},ja),{},{signedUrl:ja.signedURL?encodeURI(`${is.url}${ja.signedURL}${Qr}`):null}))})}download(es,$,ts){const is=typeof($==null?void 0:$.transform)<"u"?"render/image/authenticated":"object",cs=this.transformOptsToQueryString(($==null?void 0:$.transform)||{}),Qr=cs?`?${cs}`:"",ja=this._getFinalPath(es),Na=()=>get(this.fetch,`${this.url}/${is}/${ja}${Qr}`,{headers:this.headers,noResolveJson:!0},ts);return new BlobDownloadBuilder(Na,this.shouldThrowOnError)}async info(es){var $=this;const ts=$._getFinalPath(es);return $.handleOperation(async()=>recursiveToCamel(await get($.fetch,`${$.url}/object/info/${ts}`,{headers:$.headers})))}async exists(es){var $=this;const ts=$._getFinalPath(es);try{return await head($.fetch,`${$.url}/object/${ts}`,{headers:$.headers}),{data:!0,error:null}}catch(is){if($.shouldThrowOnError)throw is;if(isStorageError(is)&&is instanceof StorageUnknownError){const cs=is.originalError;if([400,404].includes(cs==null?void 0:cs.status))return{data:!1,error:is}}throw is}}getPublicUrl(es,$){const ts=this._getFinalPath(es),is=[],cs=$!=null&&$.download?`download=${$.download===!0?"":$.download}`:"";cs!==""&&is.push(cs);const Qr=typeof($==null?void 0:$.transform)<"u"?"render/image":"object",ja=this.transformOptsToQueryString(($==null?void 0:$.transform)||{});ja!==""&&is.push(ja);let Na=is.join("&");return Na!==""&&(Na=`?${Na}`),{data:{publicUrl:encodeURI(`${this.url}/${Qr}/public/${ts}${Na}`)}}}async remove(es){var $=this;return $.handleOperation(async()=>await remove($.fetch,`${$.url}/object/${$.bucketId}`,{prefixes:es},{headers:$.headers}))}async list(es,$,ts){var is=this;return is.handleOperation(async()=>{const cs=_objectSpread2$1(_objectSpread2$1(_objectSpread2$1({},DEFAULT_SEARCH_OPTIONS),$),{},{prefix:es||""});return await post(is.fetch,`${is.url}/object/list/${is.bucketId}`,cs,{headers:is.headers},ts)})}async listV2(es,$){var ts=this;return ts.handleOperation(async()=>{const is=_objectSpread2$1({},es);return await post(ts.fetch,`${ts.url}/object/list-v2/${ts.bucketId}`,is,{headers:ts.headers},$)})}encodeMetadata(es){return JSON.stringify(es)}toBase64(es){return typeof Buffer<"u"?Buffer.from(es).toString("base64"):btoa(es)}_getFinalPath(es){return`${this.bucketId}/${es.replace(/^\/+/,"")}`}_removeEmptyFolders(es){return es.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(es){const $=[];return es.width&&$.push(`width=${es.width}`),es.height&&$.push(`height=${es.height}`),es.resize&&$.push(`resize=${es.resize}`),es.format&&$.push(`format=${es.format}`),es.quality&&$.push(`quality=${es.quality}`),$.join("&")}};const version$2="2.95.3",DEFAULT_HEADERS$2={"X-Client-Info":`storage-js/${version$2}`};var StorageBucketApi=class extends BaseApiClient{constructor(es,$={},ts,is){const cs=new URL(es);is!=null&&is.useNewHostname&&/supabase\.(co|in|red)$/.test(cs.hostname)&&!cs.hostname.includes("storage.supabase.")&&(cs.hostname=cs.hostname.replace("supabase.","storage.supabase."));const Qr=cs.href.replace(/\/$/,""),ja=_objectSpread2$1(_objectSpread2$1({},DEFAULT_HEADERS$2),$);super(Qr,ja,ts,"storage")}async listBuckets(es){var $=this;return $.handleOperation(async()=>{const ts=$.listBucketOptionsToQueryString(es);return await get($.fetch,`${$.url}/bucket${ts}`,{headers:$.headers})})}async getBucket(es){var $=this;return $.handleOperation(async()=>await get($.fetch,`${$.url}/bucket/${es}`,{headers:$.headers}))}async createBucket(es,$={public:!1}){var ts=this;return ts.handleOperation(async()=>await post(ts.fetch,`${ts.url}/bucket`,{id:es,name:es,type:$.type,public:$.public,file_size_limit:$.fileSizeLimit,allowed_mime_types:$.allowedMimeTypes},{headers:ts.headers}))}async updateBucket(es,$){var ts=this;return ts.handleOperation(async()=>await put(ts.fetch,`${ts.url}/bucket/${es}`,{id:es,name:es,public:$.public,file_size_limit:$.fileSizeLimit,allowed_mime_types:$.allowedMimeTypes},{headers:ts.headers}))}async emptyBucket(es){var $=this;return $.handleOperation(async()=>await post($.fetch,`${$.url}/bucket/${es}/empty`,{},{headers:$.headers}))}async deleteBucket(es){var $=this;return $.handleOperation(async()=>await remove($.fetch,`${$.url}/bucket/${es}`,{},{headers:$.headers}))}listBucketOptionsToQueryString(es){const $={};return es&&("limit"in es&&($.limit=String(es.limit)),"offset"in es&&($.offset=String(es.offset)),es.search&&($.search=es.search),es.sortColumn&&($.sortColumn=es.sortColumn),es.sortOrder&&($.sortOrder=es.sortOrder)),Object.keys($).length>0?"?"+new URLSearchParams($).toString():""}},StorageAnalyticsClient=class extends BaseApiClient{constructor(es,$={},ts){const is=es.replace(/\/$/,""),cs=_objectSpread2$1(_objectSpread2$1({},DEFAULT_HEADERS$2),$);super(is,cs,ts,"storage")}async createBucket(es){var $=this;return $.handleOperation(async()=>await post($.fetch,`${$.url}/bucket`,{name:es},{headers:$.headers}))}async listBuckets(es){var $=this;return $.handleOperation(async()=>{const ts=new URLSearchParams;(es==null?void 0:es.limit)!==void 0&&ts.set("limit",es.limit.toString()),(es==null?void 0:es.offset)!==void 0&&ts.set("offset",es.offset.toString()),es!=null&&es.sortColumn&&ts.set("sortColumn",es.sortColumn),es!=null&&es.sortOrder&&ts.set("sortOrder",es.sortOrder),es!=null&&es.search&&ts.set("search",es.search);const is=ts.toString(),cs=is?`${$.url}/bucket?${is}`:`${$.url}/bucket`;return await get($.fetch,cs,{headers:$.headers})})}async deleteBucket(es){var $=this;return $.handleOperation(async()=>await remove($.fetch,`${$.url}/bucket/${es}`,{},{headers:$.headers}))}from(es){var $=this;if(!isValidBucketName(es))throw new StorageError("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const ts=new IcebergRestCatalog({baseUrl:this.url,catalogName:es,auth:{type:"custom",getHeaders:async()=>$.headers},fetch:this.fetch}),is=this.shouldThrowOnError;return new Proxy(ts,{get(cs,Qr){const ja=cs[Qr];return typeof ja!="function"?ja:async(...Na)=>{try{return{data:await ja.apply(cs,Na),error:null}}catch(Aa){if(is)throw Aa;return{data:null,error:Aa}}}}})}},VectorIndexApi=class extends BaseApiClient{constructor(es,$={},ts){const is=es.replace(/\/$/,""),cs=_objectSpread2$1(_objectSpread2$1({},DEFAULT_HEADERS$2),{},{"Content-Type":"application/json"},$);super(is,cs,ts,"vectors")}async createIndex(es){var $=this;return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/CreateIndex`,es,{headers:$.headers})||{})}async getIndex(es,$){var ts=this;return ts.handleOperation(async()=>await vectorsApi.post(ts.fetch,`${ts.url}/GetIndex`,{vectorBucketName:es,indexName:$},{headers:ts.headers}))}async listIndexes(es){var $=this;return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/ListIndexes`,es,{headers:$.headers}))}async deleteIndex(es,$){var ts=this;return ts.handleOperation(async()=>await vectorsApi.post(ts.fetch,`${ts.url}/DeleteIndex`,{vectorBucketName:es,indexName:$},{headers:ts.headers})||{})}},VectorDataApi=class extends BaseApiClient{constructor(es,$={},ts){const is=es.replace(/\/$/,""),cs=_objectSpread2$1(_objectSpread2$1({},DEFAULT_HEADERS$2),{},{"Content-Type":"application/json"},$);super(is,cs,ts,"vectors")}async putVectors(es){var $=this;if(es.vectors.length<1||es.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/PutVectors`,es,{headers:$.headers})||{})}async getVectors(es){var $=this;return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/GetVectors`,es,{headers:$.headers}))}async listVectors(es){var $=this;if(es.segmentCount!==void 0){if(es.segmentCount<1||es.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(es.segmentIndex!==void 0&&(es.segmentIndex<0||es.segmentIndex>=es.segmentCount))throw new Error(`segmentIndex must be between 0 and ${es.segmentCount-1}`)}return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/ListVectors`,es,{headers:$.headers}))}async queryVectors(es){var $=this;return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/QueryVectors`,es,{headers:$.headers}))}async deleteVectors(es){var $=this;if(es.keys.length<1||es.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/DeleteVectors`,es,{headers:$.headers})||{})}},VectorBucketApi=class extends BaseApiClient{constructor(es,$={},ts){const is=es.replace(/\/$/,""),cs=_objectSpread2$1(_objectSpread2$1({},DEFAULT_HEADERS$2),{},{"Content-Type":"application/json"},$);super(is,cs,ts,"vectors")}async createBucket(es){var $=this;return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/CreateVectorBucket`,{vectorBucketName:es},{headers:$.headers})||{})}async getBucket(es){var $=this;return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/GetVectorBucket`,{vectorBucketName:es},{headers:$.headers}))}async listBuckets(es={}){var $=this;return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/ListVectorBuckets`,es,{headers:$.headers}))}async deleteBucket(es){var $=this;return $.handleOperation(async()=>await vectorsApi.post($.fetch,`${$.url}/DeleteVectorBucket`,{vectorBucketName:es},{headers:$.headers})||{})}},StorageVectorsClient=class extends VectorBucketApi{constructor(es,$={}){super(es,$.headers||{},$.fetch)}from(es){return new VectorBucketScope(this.url,this.headers,es,this.fetch)}async createBucket(es){var $=()=>super.createBucket,ts=this;return $().call(ts,es)}async getBucket(es){var $=()=>super.getBucket,ts=this;return $().call(ts,es)}async listBuckets(es={}){var $=()=>super.listBuckets,ts=this;return $().call(ts,es)}async deleteBucket(es){var $=()=>super.deleteBucket,ts=this;return $().call(ts,es)}},VectorBucketScope=class extends VectorIndexApi{constructor(es,$,ts,is){super(es,$,is),this.vectorBucketName=ts}async createIndex(es){var $=()=>super.createIndex,ts=this;return $().call(ts,_objectSpread2$1(_objectSpread2$1({},es),{},{vectorBucketName:ts.vectorBucketName}))}async listIndexes(es={}){var $=()=>super.listIndexes,ts=this;return $().call(ts,_objectSpread2$1(_objectSpread2$1({},es),{},{vectorBucketName:ts.vectorBucketName}))}async getIndex(es){var $=()=>super.getIndex,ts=this;return $().call(ts,ts.vectorBucketName,es)}async deleteIndex(es){var $=()=>super.deleteIndex,ts=this;return $().call(ts,ts.vectorBucketName,es)}index(es){return new VectorIndexScope(this.url,this.headers,this.vectorBucketName,es,this.fetch)}},VectorIndexScope=class extends VectorDataApi{constructor(es,$,ts,is,cs){super(es,$,cs),this.vectorBucketName=ts,this.indexName=is}async putVectors(es){var $=()=>super.putVectors,ts=this;return $().call(ts,_objectSpread2$1(_objectSpread2$1({},es),{},{vectorBucketName:ts.vectorBucketName,indexName:ts.indexName}))}async getVectors(es){var $=()=>super.getVectors,ts=this;return $().call(ts,_objectSpread2$1(_objectSpread2$1({},es),{},{vectorBucketName:ts.vectorBucketName,indexName:ts.indexName}))}async listVectors(es={}){var $=()=>super.listVectors,ts=this;return $().call(ts,_objectSpread2$1(_objectSpread2$1({},es),{},{vectorBucketName:ts.vectorBucketName,indexName:ts.indexName}))}async queryVectors(es){var $=()=>super.queryVectors,ts=this;return $().call(ts,_objectSpread2$1(_objectSpread2$1({},es),{},{vectorBucketName:ts.vectorBucketName,indexName:ts.indexName}))}async deleteVectors(es){var $=()=>super.deleteVectors,ts=this;return $().call(ts,_objectSpread2$1(_objectSpread2$1({},es),{},{vectorBucketName:ts.vectorBucketName,indexName:ts.indexName}))}},StorageClient=class extends StorageBucketApi{constructor(es,$={},ts,is){super(es,$,ts,is)}from(es){return new StorageFileApi(this.url,this.headers,es,this.fetch)}get vectors(){return new StorageVectorsClient(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new StorageAnalyticsClient(this.url+"/iceberg",this.headers,this.fetch)}};const version$1="2.95.3",AUTO_REFRESH_TICK_DURATION_MS=30*1e3,AUTO_REFRESH_TICK_THRESHOLD=3,EXPIRY_MARGIN_MS=AUTO_REFRESH_TICK_THRESHOLD*AUTO_REFRESH_TICK_DURATION_MS,GOTRUE_URL="http://localhost:9999",STORAGE_KEY$1="supabase.auth.token",DEFAULT_HEADERS$1={"X-Client-Info":`gotrue-js/${version$1}`},API_VERSION_HEADER_NAME="X-Supabase-Api-Version",API_VERSIONS={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},BASE64URL_REGEX=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,JWKS_TTL=600*1e3;class AuthError extends Error{constructor($,ts,is){super($),this.__isAuthError=!0,this.name="AuthError",this.status=ts,this.code=is}}function isAuthError(es){return typeof es=="object"&&es!==null&&"__isAuthError"in es}class AuthApiError extends AuthError{constructor($,ts,is){super($,ts,is),this.name="AuthApiError",this.status=ts,this.code=is}}function isAuthApiError(es){return isAuthError(es)&&es.name==="AuthApiError"}class AuthUnknownError extends AuthError{constructor($,ts){super($),this.name="AuthUnknownError",this.originalError=ts}}class CustomAuthError extends AuthError{constructor($,ts,is,cs){super($,is,cs),this.name=ts,this.status=is}}class AuthSessionMissingError extends CustomAuthError{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function isAuthSessionMissingError(es){return isAuthError(es)&&es.name==="AuthSessionMissingError"}class AuthInvalidTokenResponseError extends CustomAuthError{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class AuthInvalidCredentialsError extends CustomAuthError{constructor($){super($,"AuthInvalidCredentialsError",400,void 0)}}class AuthImplicitGrantRedirectError extends CustomAuthError{constructor($,ts=null){super($,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=ts}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function isAuthImplicitGrantRedirectError(es){return isAuthError(es)&&es.name==="AuthImplicitGrantRedirectError"}class AuthPKCEGrantCodeExchangeError extends CustomAuthError{constructor($,ts=null){super($,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=ts}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class AuthPKCECodeVerifierMissingError extends CustomAuthError{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class AuthRetryableFetchError extends CustomAuthError{constructor($,ts){super($,"AuthRetryableFetchError",ts,void 0)}}function isAuthRetryableFetchError(es){return isAuthError(es)&&es.name==="AuthRetryableFetchError"}class AuthWeakPasswordError extends CustomAuthError{constructor($,ts,is){super($,"AuthWeakPasswordError",ts,"weak_password"),this.reasons=is}}class AuthInvalidJwtError extends CustomAuthError{constructor($){super($,"AuthInvalidJwtError",400,"invalid_jwt")}}const TO_BASE64URL="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),IGNORE_BASE64URL=`
|
|
52
|
+
\r=`.split(""),FROM_BASE64URL=(()=>{const es=new Array(128);for(let $=0;$<es.length;$+=1)es[$]=-1;for(let $=0;$<IGNORE_BASE64URL.length;$+=1)es[IGNORE_BASE64URL[$].charCodeAt(0)]=-2;for(let $=0;$<TO_BASE64URL.length;$+=1)es[TO_BASE64URL[$].charCodeAt(0)]=$;return es})();function byteToBase64URL(es,$,ts){if(es!==null)for($.queue=$.queue<<8|es,$.queuedBits+=8;$.queuedBits>=6;){const is=$.queue>>$.queuedBits-6&63;ts(TO_BASE64URL[is]),$.queuedBits-=6}else if($.queuedBits>0)for($.queue=$.queue<<6-$.queuedBits,$.queuedBits=6;$.queuedBits>=6;){const is=$.queue>>$.queuedBits-6&63;ts(TO_BASE64URL[is]),$.queuedBits-=6}}function byteFromBase64URL(es,$,ts){const is=FROM_BASE64URL[es];if(is>-1)for($.queue=$.queue<<6|is,$.queuedBits+=6;$.queuedBits>=8;)ts($.queue>>$.queuedBits-8&255),$.queuedBits-=8;else{if(is===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(es)}"`)}}function stringFromBase64URL(es){const $=[],ts=ja=>{$.push(String.fromCodePoint(ja))},is={utf8seq:0,codepoint:0},cs={queue:0,queuedBits:0},Qr=ja=>{stringFromUTF8(ja,is,ts)};for(let ja=0;ja<es.length;ja+=1)byteFromBase64URL(es.charCodeAt(ja),cs,Qr);return $.join("")}function codepointToUTF8(es,$){if(es<=127){$(es);return}else if(es<=2047){$(192|es>>6),$(128|es&63);return}else if(es<=65535){$(224|es>>12),$(128|es>>6&63),$(128|es&63);return}else if(es<=1114111){$(240|es>>18),$(128|es>>12&63),$(128|es>>6&63),$(128|es&63);return}throw new Error(`Unrecognized Unicode codepoint: ${es.toString(16)}`)}function stringToUTF8(es,$){for(let ts=0;ts<es.length;ts+=1){let is=es.charCodeAt(ts);if(is>55295&&is<=56319){const cs=(is-55296)*1024&65535;is=(es.charCodeAt(ts+1)-56320&65535|cs)+65536,ts+=1}codepointToUTF8(is,$)}}function stringFromUTF8(es,$,ts){if($.utf8seq===0){if(es<=127){ts(es);return}for(let is=1;is<6;is+=1)if((es>>7-is&1)===0){$.utf8seq=is;break}if($.utf8seq===2)$.codepoint=es&31;else if($.utf8seq===3)$.codepoint=es&15;else if($.utf8seq===4)$.codepoint=es&7;else throw new Error("Invalid UTF-8 sequence");$.utf8seq-=1}else if($.utf8seq>0){if(es<=127)throw new Error("Invalid UTF-8 sequence");$.codepoint=$.codepoint<<6|es&63,$.utf8seq-=1,$.utf8seq===0&&ts($.codepoint)}}function base64UrlToUint8Array(es){const $=[],ts={queue:0,queuedBits:0},is=cs=>{$.push(cs)};for(let cs=0;cs<es.length;cs+=1)byteFromBase64URL(es.charCodeAt(cs),ts,is);return new Uint8Array($)}function stringToUint8Array(es){const $=[];return stringToUTF8(es,ts=>$.push(ts)),new Uint8Array($)}function bytesToBase64URL(es){const $=[],ts={queue:0,queuedBits:0},is=cs=>{$.push(cs)};return es.forEach(cs=>byteToBase64URL(cs,ts,is)),byteToBase64URL(null,ts,is),$.join("")}function expiresAt(es){return Math.round(Date.now()/1e3)+es}function generateCallbackId(){return Symbol("auth-callback")}const isBrowser=()=>typeof window<"u"&&typeof document<"u",localStorageWriteTests={tested:!1,writable:!1},supportsLocalStorage=()=>{if(!isBrowser())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(localStorageWriteTests.tested)return localStorageWriteTests.writable;const es=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(es,es),globalThis.localStorage.removeItem(es),localStorageWriteTests.tested=!0,localStorageWriteTests.writable=!0}catch{localStorageWriteTests.tested=!0,localStorageWriteTests.writable=!1}return localStorageWriteTests.writable};function parseParametersFromURL(es){const $={},ts=new URL(es);if(ts.hash&&ts.hash[0]==="#")try{new URLSearchParams(ts.hash.substring(1)).forEach((cs,Qr)=>{$[Qr]=cs})}catch{}return ts.searchParams.forEach((is,cs)=>{$[cs]=is}),$}const resolveFetch$1=es=>es?(...$)=>es(...$):(...$)=>fetch(...$),looksLikeFetchResponse=es=>typeof es=="object"&&es!==null&&"status"in es&&"ok"in es&&"json"in es&&typeof es.json=="function",setItemAsync=async(es,$,ts)=>{await es.setItem($,JSON.stringify(ts))},getItemAsync=async(es,$)=>{const ts=await es.getItem($);if(!ts)return null;try{return JSON.parse(ts)}catch{return ts}},removeItemAsync=async(es,$)=>{await es.removeItem($)};class Deferred{constructor(){this.promise=new Deferred.promiseConstructor(($,ts)=>{this.resolve=$,this.reject=ts})}}Deferred.promiseConstructor=Promise;function decodeJWT(es){const $=es.split(".");if($.length!==3)throw new AuthInvalidJwtError("Invalid JWT structure");for(let is=0;is<$.length;is++)if(!BASE64URL_REGEX.test($[is]))throw new AuthInvalidJwtError("JWT not in base64url format");return{header:JSON.parse(stringFromBase64URL($[0])),payload:JSON.parse(stringFromBase64URL($[1])),signature:base64UrlToUint8Array($[2]),raw:{header:$[0],payload:$[1]}}}async function sleep(es){return await new Promise($=>{setTimeout(()=>$(null),es)})}function retryable(es,$){return new Promise((is,cs)=>{(async()=>{for(let Qr=0;Qr<1/0;Qr++)try{const ja=await es(Qr);if(!$(Qr,null,ja)){is(ja);return}}catch(ja){if(!$(Qr,ja)){cs(ja);return}}})()})}function dec2hex(es){return("0"+es.toString(16)).substr(-2)}function generatePKCEVerifier(){const $=new Uint32Array(56);if(typeof crypto>"u"){const ts="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",is=ts.length;let cs="";for(let Qr=0;Qr<56;Qr++)cs+=ts.charAt(Math.floor(Math.random()*is));return cs}return crypto.getRandomValues($),Array.from($,dec2hex).join("")}async function sha256(es){const ts=new TextEncoder().encode(es),is=await crypto.subtle.digest("SHA-256",ts),cs=new Uint8Array(is);return Array.from(cs).map(Qr=>String.fromCharCode(Qr)).join("")}async function generatePKCEChallenge(es){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),es;const ts=await sha256(es);return btoa(ts).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function getCodeChallengeAndMethod(es,$,ts=!1){const is=generatePKCEVerifier();let cs=is;ts&&(cs+="/PASSWORD_RECOVERY"),await setItemAsync(es,`${$}-code-verifier`,cs);const Qr=await generatePKCEChallenge(is);return[Qr,is===Qr?"plain":"s256"]}const API_VERSION_REGEX=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function parseResponseAPIVersion(es){const $=es.headers.get(API_VERSION_HEADER_NAME);if(!$||!$.match(API_VERSION_REGEX))return null;try{return new Date(`${$}T00:00:00.0Z`)}catch{return null}}function validateExp(es){if(!es)throw new Error("Missing exp claim");const $=Math.floor(Date.now()/1e3);if(es<=$)throw new Error("JWT has expired")}function getAlgorithm(es){switch(es){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const UUID_REGEX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function validateUUID(es){if(!UUID_REGEX.test(es))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function userNotAvailableProxy(){const es={};return new Proxy(es,{get:($,ts)=>{if(ts==="__isUserNotAvailableProxy")return!0;if(typeof ts=="symbol"){const is=ts.toString();if(is==="Symbol(Symbol.toPrimitive)"||is==="Symbol(Symbol.toStringTag)"||is==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${ts}" property of the session object is not supported. Please use getUser() instead.`)},set:($,ts)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${ts}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:($,ts)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${ts}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function insecureUserWarningProxy(es,$){return new Proxy(es,{get:(ts,is,cs)=>{if(is==="__isInsecureUserWarningProxy")return!0;if(typeof is=="symbol"){const Qr=is.toString();if(Qr==="Symbol(Symbol.toPrimitive)"||Qr==="Symbol(Symbol.toStringTag)"||Qr==="Symbol(util.inspect.custom)"||Qr==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(ts,is,cs)}return!$.value&&typeof is=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),$.value=!0),Reflect.get(ts,is,cs)}})}function deepClone(es){return JSON.parse(JSON.stringify(es))}const _getErrorMessage=es=>es.msg||es.message||es.error_description||es.error||JSON.stringify(es),NETWORK_ERROR_CODES=[502,503,504];async function handleError(es){var $;if(!looksLikeFetchResponse(es))throw new AuthRetryableFetchError(_getErrorMessage(es),0);if(NETWORK_ERROR_CODES.includes(es.status))throw new AuthRetryableFetchError(_getErrorMessage(es),es.status);let ts;try{ts=await es.json()}catch(Qr){throw new AuthUnknownError(_getErrorMessage(Qr),Qr)}let is;const cs=parseResponseAPIVersion(es);if(cs&&cs.getTime()>=API_VERSIONS["2024-01-01"].timestamp&&typeof ts=="object"&&ts&&typeof ts.code=="string"?is=ts.code:typeof ts=="object"&&ts&&typeof ts.error_code=="string"&&(is=ts.error_code),is){if(is==="weak_password")throw new AuthWeakPasswordError(_getErrorMessage(ts),es.status,(($=ts.weak_password)===null||$===void 0?void 0:$.reasons)||[]);if(is==="session_not_found")throw new AuthSessionMissingError}else if(typeof ts=="object"&&ts&&typeof ts.weak_password=="object"&&ts.weak_password&&Array.isArray(ts.weak_password.reasons)&&ts.weak_password.reasons.length&&ts.weak_password.reasons.reduce((Qr,ja)=>Qr&&typeof ja=="string",!0))throw new AuthWeakPasswordError(_getErrorMessage(ts),es.status,ts.weak_password.reasons);throw new AuthApiError(_getErrorMessage(ts),es.status||500,is)}const _getRequestParams=(es,$,ts,is)=>{const cs={method:es,headers:($==null?void 0:$.headers)||{}};return es==="GET"?cs:(cs.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},$==null?void 0:$.headers),cs.body=JSON.stringify(is),Object.assign(Object.assign({},cs),ts))};async function _request(es,$,ts,is){var cs;const Qr=Object.assign({},is==null?void 0:is.headers);Qr[API_VERSION_HEADER_NAME]||(Qr[API_VERSION_HEADER_NAME]=API_VERSIONS["2024-01-01"].name),is!=null&&is.jwt&&(Qr.Authorization=`Bearer ${is.jwt}`);const ja=(cs=is==null?void 0:is.query)!==null&&cs!==void 0?cs:{};is!=null&&is.redirectTo&&(ja.redirect_to=is.redirectTo);const Na=Object.keys(ja).length?"?"+new URLSearchParams(ja).toString():"",Aa=await _handleRequest(es,$,ts+Na,{headers:Qr,noResolveJson:is==null?void 0:is.noResolveJson},{},is==null?void 0:is.body);return is!=null&&is.xform?is==null?void 0:is.xform(Aa):{data:Object.assign({},Aa),error:null}}async function _handleRequest(es,$,ts,is,cs,Qr){const ja=_getRequestParams($,is,cs,Qr);let Na;try{Na=await es(ts,Object.assign({},ja))}catch(Aa){throw console.error(Aa),new AuthRetryableFetchError(_getErrorMessage(Aa),0)}if(Na.ok||await handleError(Na),is!=null&&is.noResolveJson)return Na;try{return await Na.json()}catch(Aa){await handleError(Aa)}}function _sessionResponse(es){var $;let ts=null;hasSession(es)&&(ts=Object.assign({},es),es.expires_at||(ts.expires_at=expiresAt(es.expires_in)));const is=($=es.user)!==null&&$!==void 0?$:es;return{data:{session:ts,user:is},error:null}}function _sessionResponsePassword(es){const $=_sessionResponse(es);return!$.error&&es.weak_password&&typeof es.weak_password=="object"&&Array.isArray(es.weak_password.reasons)&&es.weak_password.reasons.length&&es.weak_password.message&&typeof es.weak_password.message=="string"&&es.weak_password.reasons.reduce((ts,is)=>ts&&typeof is=="string",!0)&&($.data.weak_password=es.weak_password),$}function _userResponse(es){var $;return{data:{user:($=es.user)!==null&&$!==void 0?$:es},error:null}}function _ssoResponse(es){return{data:es,error:null}}function _generateLinkResponse(es){const{action_link:$,email_otp:ts,hashed_token:is,redirect_to:cs,verification_type:Qr}=es,ja=__rest(es,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),Na={action_link:$,email_otp:ts,hashed_token:is,redirect_to:cs,verification_type:Qr},Aa=Object.assign({},ja);return{data:{properties:Na,user:Aa},error:null}}function _noResolveJsonResponse(es){return es}function hasSession(es){return es.access_token&&es.refresh_token&&es.expires_in}const SIGN_OUT_SCOPES=["global","local","others"];class GoTrueAdminApi{constructor({url:$="",headers:ts={},fetch:is}){this.url=$,this.headers=ts,this.fetch=resolveFetch$1(is),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut($,ts=SIGN_OUT_SCOPES[0]){if(SIGN_OUT_SCOPES.indexOf(ts)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${SIGN_OUT_SCOPES.join(", ")}`);try{return await _request(this.fetch,"POST",`${this.url}/logout?scope=${ts}`,{headers:this.headers,jwt:$,noResolveJson:!0}),{data:null,error:null}}catch(is){if(isAuthError(is))return{data:null,error:is};throw is}}async inviteUserByEmail($,ts={}){try{return await _request(this.fetch,"POST",`${this.url}/invite`,{body:{email:$,data:ts.data},headers:this.headers,redirectTo:ts.redirectTo,xform:_userResponse})}catch(is){if(isAuthError(is))return{data:{user:null},error:is};throw is}}async generateLink($){try{const{options:ts}=$,is=__rest($,["options"]),cs=Object.assign(Object.assign({},is),ts);return"newEmail"in is&&(cs.new_email=is==null?void 0:is.newEmail,delete cs.newEmail),await _request(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:cs,headers:this.headers,xform:_generateLinkResponse,redirectTo:ts==null?void 0:ts.redirectTo})}catch(ts){if(isAuthError(ts))return{data:{properties:null,user:null},error:ts};throw ts}}async createUser($){try{return await _request(this.fetch,"POST",`${this.url}/admin/users`,{body:$,headers:this.headers,xform:_userResponse})}catch(ts){if(isAuthError(ts))return{data:{user:null},error:ts};throw ts}}async listUsers($){var ts,is,cs,Qr,ja,Na,Aa;try{const Oa={nextPage:null,lastPage:0,total:0},Ia=await _request(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(is=(ts=$==null?void 0:$.page)===null||ts===void 0?void 0:ts.toString())!==null&&is!==void 0?is:"",per_page:(Qr=(cs=$==null?void 0:$.perPage)===null||cs===void 0?void 0:cs.toString())!==null&&Qr!==void 0?Qr:""},xform:_noResolveJsonResponse});if(Ia.error)throw Ia.error;const La=await Ia.json(),Ba=(ja=Ia.headers.get("x-total-count"))!==null&&ja!==void 0?ja:0,Ma=(Aa=(Na=Ia.headers.get("link"))===null||Na===void 0?void 0:Na.split(","))!==null&&Aa!==void 0?Aa:[];return Ma.length>0&&(Ma.forEach(qa=>{const Fa=parseInt(qa.split(";")[0].split("=")[1].substring(0,1)),Ha=JSON.parse(qa.split(";")[1].split("=")[1]);Oa[`${Ha}Page`]=Fa}),Oa.total=parseInt(Ba)),{data:Object.assign(Object.assign({},La),Oa),error:null}}catch(Oa){if(isAuthError(Oa))return{data:{users:[]},error:Oa};throw Oa}}async getUserById($){validateUUID($);try{return await _request(this.fetch,"GET",`${this.url}/admin/users/${$}`,{headers:this.headers,xform:_userResponse})}catch(ts){if(isAuthError(ts))return{data:{user:null},error:ts};throw ts}}async updateUserById($,ts){validateUUID($);try{return await _request(this.fetch,"PUT",`${this.url}/admin/users/${$}`,{body:ts,headers:this.headers,xform:_userResponse})}catch(is){if(isAuthError(is))return{data:{user:null},error:is};throw is}}async deleteUser($,ts=!1){validateUUID($);try{return await _request(this.fetch,"DELETE",`${this.url}/admin/users/${$}`,{headers:this.headers,body:{should_soft_delete:ts},xform:_userResponse})}catch(is){if(isAuthError(is))return{data:{user:null},error:is};throw is}}async _listFactors($){validateUUID($.userId);try{const{data:ts,error:is}=await _request(this.fetch,"GET",`${this.url}/admin/users/${$.userId}/factors`,{headers:this.headers,xform:cs=>({data:{factors:cs},error:null})});return{data:ts,error:is}}catch(ts){if(isAuthError(ts))return{data:null,error:ts};throw ts}}async _deleteFactor($){validateUUID($.userId),validateUUID($.id);try{return{data:await _request(this.fetch,"DELETE",`${this.url}/admin/users/${$.userId}/factors/${$.id}`,{headers:this.headers}),error:null}}catch(ts){if(isAuthError(ts))return{data:null,error:ts};throw ts}}async _listOAuthClients($){var ts,is,cs,Qr,ja,Na,Aa;try{const Oa={nextPage:null,lastPage:0,total:0},Ia=await _request(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(is=(ts=$==null?void 0:$.page)===null||ts===void 0?void 0:ts.toString())!==null&&is!==void 0?is:"",per_page:(Qr=(cs=$==null?void 0:$.perPage)===null||cs===void 0?void 0:cs.toString())!==null&&Qr!==void 0?Qr:""},xform:_noResolveJsonResponse});if(Ia.error)throw Ia.error;const La=await Ia.json(),Ba=(ja=Ia.headers.get("x-total-count"))!==null&&ja!==void 0?ja:0,Ma=(Aa=(Na=Ia.headers.get("link"))===null||Na===void 0?void 0:Na.split(","))!==null&&Aa!==void 0?Aa:[];return Ma.length>0&&(Ma.forEach(qa=>{const Fa=parseInt(qa.split(";")[0].split("=")[1].substring(0,1)),Ha=JSON.parse(qa.split(";")[1].split("=")[1]);Oa[`${Ha}Page`]=Fa}),Oa.total=parseInt(Ba)),{data:Object.assign(Object.assign({},La),Oa),error:null}}catch(Oa){if(isAuthError(Oa))return{data:{clients:[]},error:Oa};throw Oa}}async _createOAuthClient($){try{return await _request(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:$,headers:this.headers,xform:ts=>({data:ts,error:null})})}catch(ts){if(isAuthError(ts))return{data:null,error:ts};throw ts}}async _getOAuthClient($){try{return await _request(this.fetch,"GET",`${this.url}/admin/oauth/clients/${$}`,{headers:this.headers,xform:ts=>({data:ts,error:null})})}catch(ts){if(isAuthError(ts))return{data:null,error:ts};throw ts}}async _updateOAuthClient($,ts){try{return await _request(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${$}`,{body:ts,headers:this.headers,xform:is=>({data:is,error:null})})}catch(is){if(isAuthError(is))return{data:null,error:is};throw is}}async _deleteOAuthClient($){try{return await _request(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${$}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(ts){if(isAuthError(ts))return{data:null,error:ts};throw ts}}async _regenerateOAuthClientSecret($){try{return await _request(this.fetch,"POST",`${this.url}/admin/oauth/clients/${$}/regenerate_secret`,{headers:this.headers,xform:ts=>({data:ts,error:null})})}catch(ts){if(isAuthError(ts))return{data:null,error:ts};throw ts}}}function memoryLocalStorageAdapter(es={}){return{getItem:$=>es[$]||null,setItem:($,ts)=>{es[$]=ts},removeItem:$=>{delete es[$]}}}const internals={debug:!!(globalThis&&supportsLocalStorage()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class LockAcquireTimeoutError extends Error{constructor($){super($),this.isAcquireTimeout=!0}}class NavigatorLockAcquireTimeoutError extends LockAcquireTimeoutError{}async function navigatorLock(es,$,ts){internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",es,$);const is=new globalThis.AbortController;return $>0&&setTimeout(()=>{is.abort(),internals.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",es)},$),await Promise.resolve().then(()=>globalThis.navigator.locks.request(es,$===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:is.signal},async cs=>{if(cs){internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",es,cs.name);try{return await ts()}finally{internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",es,cs.name)}}else{if($===0)throw internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",es),new NavigatorLockAcquireTimeoutError(`Acquiring an exclusive Navigator LockManager lock "${es}" immediately failed`);if(internals.debug)try{const Qr=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(Qr,null," "))}catch(Qr){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",Qr)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await ts()}}))}function polyfillGlobalThis(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function getAddress(es){if(!/^0x[a-fA-F0-9]{40}$/.test(es))throw new Error(`@supabase/auth-js: Address "${es}" is invalid.`);return es.toLowerCase()}function fromHex(es){return parseInt(es,16)}function toHex(es){const $=new TextEncoder().encode(es);return"0x"+Array.from($,is=>is.toString(16).padStart(2,"0")).join("")}function createSiweMessage(es){var $;const{chainId:ts,domain:is,expirationTime:cs,issuedAt:Qr=new Date,nonce:ja,notBefore:Na,requestId:Aa,resources:Oa,scheme:Ia,uri:La,version:Ba}=es;{if(!Number.isInteger(ts))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${ts}`);if(!is)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(ja&&ja.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${ja}`);if(!La)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(Ba!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${Ba}`);if(!(($=es.statement)===null||$===void 0)&&$.includes(`
|
|
53
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${es.statement}`)}const Ma=getAddress(es.address),qa=Ia?`${Ia}://${is}`:is,Fa=es.statement?`${es.statement}
|
|
54
|
+
`:"",Ha=`${qa} wants you to sign in with your Ethereum account:
|
|
55
|
+
${Ma}
|
|
56
|
+
|
|
57
|
+
${Fa}`;let Ka=`URI: ${La}
|
|
58
|
+
Version: ${Ba}
|
|
59
|
+
Chain ID: ${ts}${ja?`
|
|
60
|
+
Nonce: ${ja}`:""}
|
|
61
|
+
Issued At: ${Qr.toISOString()}`;if(cs&&(Ka+=`
|
|
62
|
+
Expiration Time: ${cs.toISOString()}`),Na&&(Ka+=`
|
|
63
|
+
Not Before: ${Na.toISOString()}`),Aa&&(Ka+=`
|
|
64
|
+
Request ID: ${Aa}`),Oa){let Ga=`
|
|
65
|
+
Resources:`;for(const Va of Oa){if(!Va||typeof Va!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${Va}`);Ga+=`
|
|
66
|
+
- ${Va}`}Ka+=Ga}return`${Ha}
|
|
67
|
+
${Ka}`}class WebAuthnError extends Error{constructor({message:$,code:ts,cause:is,name:cs}){var Qr;super($,{cause:is}),this.__isWebAuthnError=!0,this.name=(Qr=cs??(is instanceof Error?is.name:void 0))!==null&&Qr!==void 0?Qr:"Unknown Error",this.code=ts}}class WebAuthnUnknownError extends WebAuthnError{constructor($,ts){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:ts,message:$}),this.name="WebAuthnUnknownError",this.originalError=ts}}function identifyRegistrationError({error:es,options:$}){var ts,is,cs;const{publicKey:Qr}=$;if(!Qr)throw Error("options was missing required publicKey property");if(es.name==="AbortError"){if($.signal instanceof AbortSignal)return new WebAuthnError({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:es})}else if(es.name==="ConstraintError"){if(((ts=Qr.authenticatorSelection)===null||ts===void 0?void 0:ts.requireResidentKey)===!0)return new WebAuthnError({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:es});if($.mediation==="conditional"&&((is=Qr.authenticatorSelection)===null||is===void 0?void 0:is.userVerification)==="required")return new WebAuthnError({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:es});if(((cs=Qr.authenticatorSelection)===null||cs===void 0?void 0:cs.userVerification)==="required")return new WebAuthnError({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:es})}else{if(es.name==="InvalidStateError")return new WebAuthnError({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:es});if(es.name==="NotAllowedError")return new WebAuthnError({message:es.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:es});if(es.name==="NotSupportedError")return Qr.pubKeyCredParams.filter(Na=>Na.type==="public-key").length===0?new WebAuthnError({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:es}):new WebAuthnError({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:es});if(es.name==="SecurityError"){const ja=window.location.hostname;if(isValidDomain(ja)){if(Qr.rp.id!==ja)return new WebAuthnError({message:`The RP ID "${Qr.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:es})}else return new WebAuthnError({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:es})}else if(es.name==="TypeError"){if(Qr.user.id.byteLength<1||Qr.user.id.byteLength>64)return new WebAuthnError({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:es})}else if(es.name==="UnknownError")return new WebAuthnError({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:es})}return new WebAuthnError({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:es})}function identifyAuthenticationError({error:es,options:$}){const{publicKey:ts}=$;if(!ts)throw Error("options was missing required publicKey property");if(es.name==="AbortError"){if($.signal instanceof AbortSignal)return new WebAuthnError({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:es})}else{if(es.name==="NotAllowedError")return new WebAuthnError({message:es.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:es});if(es.name==="SecurityError"){const is=window.location.hostname;if(isValidDomain(is)){if(ts.rpId!==is)return new WebAuthnError({message:`The RP ID "${ts.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:es})}else return new WebAuthnError({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:es})}else if(es.name==="UnknownError")return new WebAuthnError({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:es})}return new WebAuthnError({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:es})}class WebAuthnAbortService{createNewAbortSignal(){if(this.controller){const ts=new Error("Cancelling existing WebAuthn API call for new one");ts.name="AbortError",this.controller.abort(ts)}const $=new AbortController;return this.controller=$,$.signal}cancelCeremony(){if(this.controller){const $=new Error("Manually cancelling existing WebAuthn API call");$.name="AbortError",this.controller.abort($),this.controller=void 0}}}const webAuthnAbortService=new WebAuthnAbortService;function deserializeCredentialCreationOptions(es){if(!es)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(es);const{challenge:$,user:ts,excludeCredentials:is}=es,cs=__rest(es,["challenge","user","excludeCredentials"]),Qr=base64UrlToUint8Array($).buffer,ja=Object.assign(Object.assign({},ts),{id:base64UrlToUint8Array(ts.id).buffer}),Na=Object.assign(Object.assign({},cs),{challenge:Qr,user:ja});if(is&&is.length>0){Na.excludeCredentials=new Array(is.length);for(let Aa=0;Aa<is.length;Aa++){const Oa=is[Aa];Na.excludeCredentials[Aa]=Object.assign(Object.assign({},Oa),{id:base64UrlToUint8Array(Oa.id).buffer,type:Oa.type||"public-key",transports:Oa.transports})}}return Na}function deserializeCredentialRequestOptions(es){if(!es)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(es);const{challenge:$,allowCredentials:ts}=es,is=__rest(es,["challenge","allowCredentials"]),cs=base64UrlToUint8Array($).buffer,Qr=Object.assign(Object.assign({},is),{challenge:cs});if(ts&&ts.length>0){Qr.allowCredentials=new Array(ts.length);for(let ja=0;ja<ts.length;ja++){const Na=ts[ja];Qr.allowCredentials[ja]=Object.assign(Object.assign({},Na),{id:base64UrlToUint8Array(Na.id).buffer,type:Na.type||"public-key",transports:Na.transports})}}return Qr}function serializeCredentialCreationResponse(es){var $;if("toJSON"in es&&typeof es.toJSON=="function")return es.toJSON();const ts=es;return{id:es.id,rawId:es.id,response:{attestationObject:bytesToBase64URL(new Uint8Array(es.response.attestationObject)),clientDataJSON:bytesToBase64URL(new Uint8Array(es.response.clientDataJSON))},type:"public-key",clientExtensionResults:es.getClientExtensionResults(),authenticatorAttachment:($=ts.authenticatorAttachment)!==null&&$!==void 0?$:void 0}}function serializeCredentialRequestResponse(es){var $;if("toJSON"in es&&typeof es.toJSON=="function")return es.toJSON();const ts=es,is=es.getClientExtensionResults(),cs=es.response;return{id:es.id,rawId:es.id,response:{authenticatorData:bytesToBase64URL(new Uint8Array(cs.authenticatorData)),clientDataJSON:bytesToBase64URL(new Uint8Array(cs.clientDataJSON)),signature:bytesToBase64URL(new Uint8Array(cs.signature)),userHandle:cs.userHandle?bytesToBase64URL(new Uint8Array(cs.userHandle)):void 0},type:"public-key",clientExtensionResults:is,authenticatorAttachment:($=ts.authenticatorAttachment)!==null&&$!==void 0?$:void 0}}function isValidDomain(es){return es==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(es)}function browserSupportsWebAuthn(){var es,$;return!!(isBrowser()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((es=navigator==null?void 0:navigator.credentials)===null||es===void 0?void 0:es.create)=="function"&&typeof(($=navigator==null?void 0:navigator.credentials)===null||$===void 0?void 0:$.get)=="function")}async function createCredential(es){try{const $=await navigator.credentials.create(es);return $?$ instanceof PublicKeyCredential?{data:$,error:null}:{data:null,error:new WebAuthnUnknownError("Browser returned unexpected credential type",$)}:{data:null,error:new WebAuthnUnknownError("Empty credential response",$)}}catch($){return{data:null,error:identifyRegistrationError({error:$,options:es})}}}async function getCredential(es){try{const $=await navigator.credentials.get(es);return $?$ instanceof PublicKeyCredential?{data:$,error:null}:{data:null,error:new WebAuthnUnknownError("Browser returned unexpected credential type",$)}:{data:null,error:new WebAuthnUnknownError("Empty credential response",$)}}catch($){return{data:null,error:identifyAuthenticationError({error:$,options:es})}}}const DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function deepMerge(...es){const $=cs=>cs!==null&&typeof cs=="object"&&!Array.isArray(cs),ts=cs=>cs instanceof ArrayBuffer||ArrayBuffer.isView(cs),is={};for(const cs of es)if(cs)for(const Qr in cs){const ja=cs[Qr];if(ja!==void 0)if(Array.isArray(ja))is[Qr]=ja;else if(ts(ja))is[Qr]=ja;else if($(ja)){const Na=is[Qr];$(Na)?is[Qr]=deepMerge(Na,ja):is[Qr]=deepMerge(ja)}else is[Qr]=ja}return is}function mergeCredentialCreationOptions(es,$){return deepMerge(DEFAULT_CREATION_OPTIONS,es,$||{})}function mergeCredentialRequestOptions(es,$){return deepMerge(DEFAULT_REQUEST_OPTIONS,es,$||{})}class WebAuthnApi{constructor($){this.client=$,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll($){return this.client.mfa.enroll(Object.assign(Object.assign({},$),{factorType:"webauthn"}))}async _challenge({factorId:$,webauthn:ts,friendlyName:is,signal:cs},Qr){var ja;try{const{data:Na,error:Aa}=await this.client.mfa.challenge({factorId:$,webauthn:ts});if(!Na)return{data:null,error:Aa};const Oa=cs??webAuthnAbortService.createNewAbortSignal();if(Na.webauthn.type==="create"){const{user:Ia}=Na.webauthn.credential_options.publicKey;if(!Ia.name){const La=is;if(La)Ia.name=`${Ia.id}:${La}`;else{const Ma=(await this.client.getUser()).data.user,qa=((ja=Ma==null?void 0:Ma.user_metadata)===null||ja===void 0?void 0:ja.name)||(Ma==null?void 0:Ma.email)||(Ma==null?void 0:Ma.id)||"User";Ia.name=`${Ia.id}:${qa}`}}Ia.displayName||(Ia.displayName=Ia.name)}switch(Na.webauthn.type){case"create":{const Ia=mergeCredentialCreationOptions(Na.webauthn.credential_options.publicKey,Qr==null?void 0:Qr.create),{data:La,error:Ba}=await createCredential({publicKey:Ia,signal:Oa});return La?{data:{factorId:$,challengeId:Na.id,webauthn:{type:Na.webauthn.type,credential_response:La}},error:null}:{data:null,error:Ba}}case"request":{const Ia=mergeCredentialRequestOptions(Na.webauthn.credential_options.publicKey,Qr==null?void 0:Qr.request),{data:La,error:Ba}=await getCredential(Object.assign(Object.assign({},Na.webauthn.credential_options),{publicKey:Ia,signal:Oa}));return La?{data:{factorId:$,challengeId:Na.id,webauthn:{type:Na.webauthn.type,credential_response:La}},error:null}:{data:null,error:Ba}}}}catch(Na){return isAuthError(Na)?{data:null,error:Na}:{data:null,error:new AuthUnknownError("Unexpected error in challenge",Na)}}}async _verify({challengeId:$,factorId:ts,webauthn:is}){return this.client.mfa.verify({factorId:ts,challengeId:$,webauthn:is})}async _authenticate({factorId:$,webauthn:{rpId:ts=typeof window<"u"?window.location.hostname:void 0,rpOrigins:is=typeof window<"u"?[window.location.origin]:void 0,signal:cs}={}},Qr){if(!ts)return{data:null,error:new AuthError("rpId is required for WebAuthn authentication")};try{if(!browserSupportsWebAuthn())return{data:null,error:new AuthUnknownError("Browser does not support WebAuthn",null)};const{data:ja,error:Na}=await this.challenge({factorId:$,webauthn:{rpId:ts,rpOrigins:is},signal:cs},{request:Qr});if(!ja)return{data:null,error:Na};const{webauthn:Aa}=ja;return this._verify({factorId:$,challengeId:ja.challengeId,webauthn:{type:Aa.type,rpId:ts,rpOrigins:is,credential_response:Aa.credential_response}})}catch(ja){return isAuthError(ja)?{data:null,error:ja}:{data:null,error:new AuthUnknownError("Unexpected error in authenticate",ja)}}}async _register({friendlyName:$,webauthn:{rpId:ts=typeof window<"u"?window.location.hostname:void 0,rpOrigins:is=typeof window<"u"?[window.location.origin]:void 0,signal:cs}={}},Qr){if(!ts)return{data:null,error:new AuthError("rpId is required for WebAuthn registration")};try{if(!browserSupportsWebAuthn())return{data:null,error:new AuthUnknownError("Browser does not support WebAuthn",null)};const{data:ja,error:Na}=await this._enroll({friendlyName:$});if(!ja)return await this.client.mfa.listFactors().then(Ia=>{var La;return(La=Ia.data)===null||La===void 0?void 0:La.all.find(Ba=>Ba.factor_type==="webauthn"&&Ba.friendly_name===$&&Ba.status!=="unverified")}).then(Ia=>Ia?this.client.mfa.unenroll({factorId:Ia==null?void 0:Ia.id}):void 0),{data:null,error:Na};const{data:Aa,error:Oa}=await this._challenge({factorId:ja.id,friendlyName:ja.friendly_name,webauthn:{rpId:ts,rpOrigins:is},signal:cs},{create:Qr});return Aa?this._verify({factorId:ja.id,challengeId:Aa.challengeId,webauthn:{rpId:ts,rpOrigins:is,type:Aa.webauthn.type,credential_response:Aa.webauthn.credential_response}}):{data:null,error:Oa}}catch(ja){return isAuthError(ja)?{data:null,error:ja}:{data:null,error:new AuthUnknownError("Unexpected error in register",ja)}}}}polyfillGlobalThis();const DEFAULT_OPTIONS={url:GOTRUE_URL,storageKey:STORAGE_KEY$1,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:DEFAULT_HEADERS$1,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function lockNoOp(es,$,ts){return await ts()}const GLOBAL_JWKS={};class GoTrueClient{get jwks(){var $,ts;return(ts=($=GLOBAL_JWKS[this.storageKey])===null||$===void 0?void 0:$.jwks)!==null&&ts!==void 0?ts:{keys:[]}}set jwks($){GLOBAL_JWKS[this.storageKey]=Object.assign(Object.assign({},GLOBAL_JWKS[this.storageKey]),{jwks:$})}get jwks_cached_at(){var $,ts;return(ts=($=GLOBAL_JWKS[this.storageKey])===null||$===void 0?void 0:$.cachedAt)!==null&&ts!==void 0?ts:Number.MIN_SAFE_INTEGER}set jwks_cached_at($){GLOBAL_JWKS[this.storageKey]=Object.assign(Object.assign({},GLOBAL_JWKS[this.storageKey]),{cachedAt:$})}constructor($){var ts,is,cs;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const Qr=Object.assign(Object.assign({},DEFAULT_OPTIONS),$);if(this.storageKey=Qr.storageKey,this.instanceID=(ts=GoTrueClient.nextInstanceID[this.storageKey])!==null&&ts!==void 0?ts:0,GoTrueClient.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!Qr.debug,typeof Qr.debug=="function"&&(this.logger=Qr.debug),this.instanceID>0&&isBrowser()){const ja=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(ja),this.logDebugMessages&&console.trace(ja)}if(this.persistSession=Qr.persistSession,this.autoRefreshToken=Qr.autoRefreshToken,this.admin=new GoTrueAdminApi({url:Qr.url,headers:Qr.headers,fetch:Qr.fetch}),this.url=Qr.url,this.headers=Qr.headers,this.fetch=resolveFetch$1(Qr.fetch),this.lock=Qr.lock||lockNoOp,this.detectSessionInUrl=Qr.detectSessionInUrl,this.flowType=Qr.flowType,this.hasCustomAuthorizationHeader=Qr.hasCustomAuthorizationHeader,this.throwOnError=Qr.throwOnError,this.lockAcquireTimeout=Qr.lockAcquireTimeout,Qr.lock?this.lock=Qr.lock:this.persistSession&&isBrowser()&&(!((is=globalThis==null?void 0:globalThis.navigator)===null||is===void 0)&&is.locks)?this.lock=navigatorLock:this.lock=lockNoOp,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new WebAuthnApi(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(Qr.storage?this.storage=Qr.storage:supportsLocalStorage()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=memoryLocalStorageAdapter(this.memoryStorage)),Qr.userStorage&&(this.userStorage=Qr.userStorage)):(this.memoryStorage={},this.storage=memoryLocalStorageAdapter(this.memoryStorage)),isBrowser()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(ja){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",ja)}(cs=this.broadcastChannel)===null||cs===void 0||cs.addEventListener("message",async ja=>{this._debug("received broadcast notification from other tab or client",ja);try{await this._notifyAllSubscribers(ja.data.event,ja.data.session,!1)}catch(Na){this._debug("#broadcastChannel","error",Na)}})}this.initialize().catch(ja=>{this._debug("#initialize()","error",ja)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult($){if(this.throwOnError&&$&&$.error)throw $.error;return $}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${version$1}) ${new Date().toISOString()}`}_debug(...$){return this.logDebugMessages&&this.logger(this._logPrefix(),...$),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var $;try{let ts={},is="none";if(isBrowser()&&(ts=parseParametersFromURL(window.location.href),this._isImplicitGrantCallback(ts)?is="implicit":await this._isPKCECallback(ts)&&(is="pkce")),isBrowser()&&this.detectSessionInUrl&&is!=="none"){const{data:cs,error:Qr}=await this._getSessionFromURL(ts,is);if(Qr){if(this._debug("#_initialize()","error detecting session from URL",Qr),isAuthImplicitGrantRedirectError(Qr)){const Aa=($=Qr.details)===null||$===void 0?void 0:$.code;if(Aa==="identity_already_exists"||Aa==="identity_not_found"||Aa==="single_identity_not_deletable")return{error:Qr}}return{error:Qr}}const{session:ja,redirectType:Na}=cs;return this._debug("#_initialize()","detected session in URL",ja,"redirect type",Na),await this._saveSession(ja),setTimeout(async()=>{Na==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",ja):await this._notifyAllSubscribers("SIGNED_IN",ja)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(ts){return isAuthError(ts)?this._returnResult({error:ts}):this._returnResult({error:new AuthUnknownError("Unexpected error during initialization",ts)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously($){var ts,is,cs;try{const Qr=await _request(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(is=(ts=$==null?void 0:$.options)===null||ts===void 0?void 0:ts.data)!==null&&is!==void 0?is:{},gotrue_meta_security:{captcha_token:(cs=$==null?void 0:$.options)===null||cs===void 0?void 0:cs.captchaToken}},xform:_sessionResponse}),{data:ja,error:Na}=Qr;if(Na||!ja)return this._returnResult({data:{user:null,session:null},error:Na});const Aa=ja.session,Oa=ja.user;return ja.session&&(await this._saveSession(ja.session),await this._notifyAllSubscribers("SIGNED_IN",Aa)),this._returnResult({data:{user:Oa,session:Aa},error:null})}catch(Qr){if(isAuthError(Qr))return this._returnResult({data:{user:null,session:null},error:Qr});throw Qr}}async signUp($){var ts,is,cs;try{let Qr;if("email"in $){const{email:Ia,password:La,options:Ba}=$;let Ma=null,qa=null;this.flowType==="pkce"&&([Ma,qa]=await getCodeChallengeAndMethod(this.storage,this.storageKey)),Qr=await _request(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:Ba==null?void 0:Ba.emailRedirectTo,body:{email:Ia,password:La,data:(ts=Ba==null?void 0:Ba.data)!==null&&ts!==void 0?ts:{},gotrue_meta_security:{captcha_token:Ba==null?void 0:Ba.captchaToken},code_challenge:Ma,code_challenge_method:qa},xform:_sessionResponse})}else if("phone"in $){const{phone:Ia,password:La,options:Ba}=$;Qr=await _request(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:Ia,password:La,data:(is=Ba==null?void 0:Ba.data)!==null&&is!==void 0?is:{},channel:(cs=Ba==null?void 0:Ba.channel)!==null&&cs!==void 0?cs:"sms",gotrue_meta_security:{captcha_token:Ba==null?void 0:Ba.captchaToken}},xform:_sessionResponse})}else throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a password");const{data:ja,error:Na}=Qr;if(Na||!ja)return await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:Na});const Aa=ja.session,Oa=ja.user;return ja.session&&(await this._saveSession(ja.session),await this._notifyAllSubscribers("SIGNED_IN",Aa)),this._returnResult({data:{user:Oa,session:Aa},error:null})}catch(Qr){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Qr))return this._returnResult({data:{user:null,session:null},error:Qr});throw Qr}}async signInWithPassword($){try{let ts;if("email"in $){const{email:Qr,password:ja,options:Na}=$;ts=await _request(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:Qr,password:ja,gotrue_meta_security:{captcha_token:Na==null?void 0:Na.captchaToken}},xform:_sessionResponsePassword})}else if("phone"in $){const{phone:Qr,password:ja,options:Na}=$;ts=await _request(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:Qr,password:ja,gotrue_meta_security:{captcha_token:Na==null?void 0:Na.captchaToken}},xform:_sessionResponsePassword})}else throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a password");const{data:is,error:cs}=ts;if(cs)return this._returnResult({data:{user:null,session:null},error:cs});if(!is||!is.session||!is.user){const Qr=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:Qr})}return is.session&&(await this._saveSession(is.session),await this._notifyAllSubscribers("SIGNED_IN",is.session)),this._returnResult({data:Object.assign({user:is.user,session:is.session},is.weak_password?{weakPassword:is.weak_password}:null),error:cs})}catch(ts){if(isAuthError(ts))return this._returnResult({data:{user:null,session:null},error:ts});throw ts}}async signInWithOAuth($){var ts,is,cs,Qr;return await this._handleProviderSignIn($.provider,{redirectTo:(ts=$.options)===null||ts===void 0?void 0:ts.redirectTo,scopes:(is=$.options)===null||is===void 0?void 0:is.scopes,queryParams:(cs=$.options)===null||cs===void 0?void 0:cs.queryParams,skipBrowserRedirect:(Qr=$.options)===null||Qr===void 0?void 0:Qr.skipBrowserRedirect})}async exchangeCodeForSession($){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession($))}async signInWithWeb3($){const{chain:ts}=$;switch(ts){case"ethereum":return await this.signInWithEthereum($);case"solana":return await this.signInWithSolana($);default:throw new Error(`@supabase/auth-js: Unsupported chain "${ts}"`)}}async signInWithEthereum($){var ts,is,cs,Qr,ja,Na,Aa,Oa,Ia,La,Ba;let Ma,qa;if("message"in $)Ma=$.message,qa=$.signature;else{const{chain:Fa,wallet:Ha,statement:Ka,options:Ga}=$;let Va;if(isBrowser())if(typeof Ha=="object")Va=Ha;else{const cl=window;if("ethereum"in cl&&typeof cl.ethereum=="object"&&"request"in cl.ethereum&&typeof cl.ethereum.request=="function")Va=cl.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof Ha!="object"||!(Ga!=null&&Ga.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");Va=Ha}const Ja=new URL((ts=Ga==null?void 0:Ga.url)!==null&&ts!==void 0?ts:window.location.href),Ya=await Va.request({method:"eth_requestAccounts"}).then(cl=>cl).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Ya||Ya.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const el=getAddress(Ya[0]);let tl=(is=Ga==null?void 0:Ga.signInWithEthereum)===null||is===void 0?void 0:is.chainId;if(!tl){const cl=await Va.request({method:"eth_chainId"});tl=fromHex(cl)}const rl={domain:Ja.host,address:el,statement:Ka,uri:Ja.href,version:"1",chainId:tl,nonce:(cs=Ga==null?void 0:Ga.signInWithEthereum)===null||cs===void 0?void 0:cs.nonce,issuedAt:(ja=(Qr=Ga==null?void 0:Ga.signInWithEthereum)===null||Qr===void 0?void 0:Qr.issuedAt)!==null&&ja!==void 0?ja:new Date,expirationTime:(Na=Ga==null?void 0:Ga.signInWithEthereum)===null||Na===void 0?void 0:Na.expirationTime,notBefore:(Aa=Ga==null?void 0:Ga.signInWithEthereum)===null||Aa===void 0?void 0:Aa.notBefore,requestId:(Oa=Ga==null?void 0:Ga.signInWithEthereum)===null||Oa===void 0?void 0:Oa.requestId,resources:(Ia=Ga==null?void 0:Ga.signInWithEthereum)===null||Ia===void 0?void 0:Ia.resources};Ma=createSiweMessage(rl),qa=await Va.request({method:"personal_sign",params:[toHex(Ma),el]})}try{const{data:Fa,error:Ha}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:Ma,signature:qa},!((La=$.options)===null||La===void 0)&&La.captchaToken?{gotrue_meta_security:{captcha_token:(Ba=$.options)===null||Ba===void 0?void 0:Ba.captchaToken}}:null),xform:_sessionResponse});if(Ha)throw Ha;if(!Fa||!Fa.session||!Fa.user){const Ka=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:Ka})}return Fa.session&&(await this._saveSession(Fa.session),await this._notifyAllSubscribers("SIGNED_IN",Fa.session)),this._returnResult({data:Object.assign({},Fa),error:Ha})}catch(Fa){if(isAuthError(Fa))return this._returnResult({data:{user:null,session:null},error:Fa});throw Fa}}async signInWithSolana($){var ts,is,cs,Qr,ja,Na,Aa,Oa,Ia,La,Ba,Ma;let qa,Fa;if("message"in $)qa=$.message,Fa=$.signature;else{const{chain:Ha,wallet:Ka,statement:Ga,options:Va}=$;let Ja;if(isBrowser())if(typeof Ka=="object")Ja=Ka;else{const el=window;if("solana"in el&&typeof el.solana=="object"&&("signIn"in el.solana&&typeof el.solana.signIn=="function"||"signMessage"in el.solana&&typeof el.solana.signMessage=="function"))Ja=el.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof Ka!="object"||!(Va!=null&&Va.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");Ja=Ka}const Ya=new URL((ts=Va==null?void 0:Va.url)!==null&&ts!==void 0?ts:window.location.href);if("signIn"in Ja&&Ja.signIn){const el=await Ja.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},Va==null?void 0:Va.signInWithSolana),{version:"1",domain:Ya.host,uri:Ya.href}),Ga?{statement:Ga}:null));let tl;if(Array.isArray(el)&&el[0]&&typeof el[0]=="object")tl=el[0];else if(el&&typeof el=="object"&&"signedMessage"in el&&"signature"in el)tl=el;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in tl&&"signature"in tl&&(typeof tl.signedMessage=="string"||tl.signedMessage instanceof Uint8Array)&&tl.signature instanceof Uint8Array)qa=typeof tl.signedMessage=="string"?tl.signedMessage:new TextDecoder().decode(tl.signedMessage),Fa=tl.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in Ja)||typeof Ja.signMessage!="function"||!("publicKey"in Ja)||typeof Ja!="object"||!Ja.publicKey||!("toBase58"in Ja.publicKey)||typeof Ja.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");qa=[`${Ya.host} wants you to sign in with your Solana account:`,Ja.publicKey.toBase58(),...Ga?["",Ga,""]:[""],"Version: 1",`URI: ${Ya.href}`,`Issued At: ${(cs=(is=Va==null?void 0:Va.signInWithSolana)===null||is===void 0?void 0:is.issuedAt)!==null&&cs!==void 0?cs:new Date().toISOString()}`,...!((Qr=Va==null?void 0:Va.signInWithSolana)===null||Qr===void 0)&&Qr.notBefore?[`Not Before: ${Va.signInWithSolana.notBefore}`]:[],...!((ja=Va==null?void 0:Va.signInWithSolana)===null||ja===void 0)&&ja.expirationTime?[`Expiration Time: ${Va.signInWithSolana.expirationTime}`]:[],...!((Na=Va==null?void 0:Va.signInWithSolana)===null||Na===void 0)&&Na.chainId?[`Chain ID: ${Va.signInWithSolana.chainId}`]:[],...!((Aa=Va==null?void 0:Va.signInWithSolana)===null||Aa===void 0)&&Aa.nonce?[`Nonce: ${Va.signInWithSolana.nonce}`]:[],...!((Oa=Va==null?void 0:Va.signInWithSolana)===null||Oa===void 0)&&Oa.requestId?[`Request ID: ${Va.signInWithSolana.requestId}`]:[],...!((La=(Ia=Va==null?void 0:Va.signInWithSolana)===null||Ia===void 0?void 0:Ia.resources)===null||La===void 0)&&La.length?["Resources",...Va.signInWithSolana.resources.map(tl=>`- ${tl}`)]:[]].join(`
|
|
68
|
+
`);const el=await Ja.signMessage(new TextEncoder().encode(qa),"utf8");if(!el||!(el instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");Fa=el}}try{const{data:Ha,error:Ka}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:qa,signature:bytesToBase64URL(Fa)},!((Ba=$.options)===null||Ba===void 0)&&Ba.captchaToken?{gotrue_meta_security:{captcha_token:(Ma=$.options)===null||Ma===void 0?void 0:Ma.captchaToken}}:null),xform:_sessionResponse});if(Ka)throw Ka;if(!Ha||!Ha.session||!Ha.user){const Ga=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:Ga})}return Ha.session&&(await this._saveSession(Ha.session),await this._notifyAllSubscribers("SIGNED_IN",Ha.session)),this._returnResult({data:Object.assign({},Ha),error:Ka})}catch(Ha){if(isAuthError(Ha))return this._returnResult({data:{user:null,session:null},error:Ha});throw Ha}}async _exchangeCodeForSession($){const ts=await getItemAsync(this.storage,`${this.storageKey}-code-verifier`),[is,cs]=(ts??"").split("/");try{if(!is&&this.flowType==="pkce")throw new AuthPKCECodeVerifierMissingError;const{data:Qr,error:ja}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:$,code_verifier:is},xform:_sessionResponse});if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),ja)throw ja;if(!Qr||!Qr.session||!Qr.user){const Na=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:Na})}return Qr.session&&(await this._saveSession(Qr.session),await this._notifyAllSubscribers("SIGNED_IN",Qr.session)),this._returnResult({data:Object.assign(Object.assign({},Qr),{redirectType:cs??null}),error:ja})}catch(Qr){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Qr))return this._returnResult({data:{user:null,session:null,redirectType:null},error:Qr});throw Qr}}async signInWithIdToken($){try{const{options:ts,provider:is,token:cs,access_token:Qr,nonce:ja}=$,Na=await _request(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:is,id_token:cs,access_token:Qr,nonce:ja,gotrue_meta_security:{captcha_token:ts==null?void 0:ts.captchaToken}},xform:_sessionResponse}),{data:Aa,error:Oa}=Na;if(Oa)return this._returnResult({data:{user:null,session:null},error:Oa});if(!Aa||!Aa.session||!Aa.user){const Ia=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:Ia})}return Aa.session&&(await this._saveSession(Aa.session),await this._notifyAllSubscribers("SIGNED_IN",Aa.session)),this._returnResult({data:Aa,error:Oa})}catch(ts){if(isAuthError(ts))return this._returnResult({data:{user:null,session:null},error:ts});throw ts}}async signInWithOtp($){var ts,is,cs,Qr,ja;try{if("email"in $){const{email:Na,options:Aa}=$;let Oa=null,Ia=null;this.flowType==="pkce"&&([Oa,Ia]=await getCodeChallengeAndMethod(this.storage,this.storageKey));const{error:La}=await _request(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:Na,data:(ts=Aa==null?void 0:Aa.data)!==null&&ts!==void 0?ts:{},create_user:(is=Aa==null?void 0:Aa.shouldCreateUser)!==null&&is!==void 0?is:!0,gotrue_meta_security:{captcha_token:Aa==null?void 0:Aa.captchaToken},code_challenge:Oa,code_challenge_method:Ia},redirectTo:Aa==null?void 0:Aa.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:La})}if("phone"in $){const{phone:Na,options:Aa}=$,{data:Oa,error:Ia}=await _request(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:Na,data:(cs=Aa==null?void 0:Aa.data)!==null&&cs!==void 0?cs:{},create_user:(Qr=Aa==null?void 0:Aa.shouldCreateUser)!==null&&Qr!==void 0?Qr:!0,gotrue_meta_security:{captcha_token:Aa==null?void 0:Aa.captchaToken},channel:(ja=Aa==null?void 0:Aa.channel)!==null&&ja!==void 0?ja:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:Oa==null?void 0:Oa.message_id},error:Ia})}throw new AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(Na){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Na))return this._returnResult({data:{user:null,session:null},error:Na});throw Na}}async verifyOtp($){var ts,is;try{let cs,Qr;"options"in $&&(cs=(ts=$.options)===null||ts===void 0?void 0:ts.redirectTo,Qr=(is=$.options)===null||is===void 0?void 0:is.captchaToken);const{data:ja,error:Na}=await _request(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},$),{gotrue_meta_security:{captcha_token:Qr}}),redirectTo:cs,xform:_sessionResponse});if(Na)throw Na;if(!ja)throw new Error("An error occurred on token verification.");const Aa=ja.session,Oa=ja.user;return Aa!=null&&Aa.access_token&&(await this._saveSession(Aa),await this._notifyAllSubscribers($.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",Aa)),this._returnResult({data:{user:Oa,session:Aa},error:null})}catch(cs){if(isAuthError(cs))return this._returnResult({data:{user:null,session:null},error:cs});throw cs}}async signInWithSSO($){var ts,is,cs,Qr,ja;try{let Na=null,Aa=null;this.flowType==="pkce"&&([Na,Aa]=await getCodeChallengeAndMethod(this.storage,this.storageKey));const Oa=await _request(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in $?{provider_id:$.providerId}:null),"domain"in $?{domain:$.domain}:null),{redirect_to:(is=(ts=$.options)===null||ts===void 0?void 0:ts.redirectTo)!==null&&is!==void 0?is:void 0}),!((cs=$==null?void 0:$.options)===null||cs===void 0)&&cs.captchaToken?{gotrue_meta_security:{captcha_token:$.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:Na,code_challenge_method:Aa}),headers:this.headers,xform:_ssoResponse});return!((Qr=Oa.data)===null||Qr===void 0)&&Qr.url&&isBrowser()&&!(!((ja=$.options)===null||ja===void 0)&&ja.skipBrowserRedirect)&&window.location.assign(Oa.data.url),this._returnResult(Oa)}catch(Na){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Na))return this._returnResult({data:null,error:Na});throw Na}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async $=>{const{data:{session:ts},error:is}=$;if(is)throw is;if(!ts)throw new AuthSessionMissingError;const{error:cs}=await _request(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:ts.access_token});return this._returnResult({data:{user:null,session:null},error:cs})})}catch($){if(isAuthError($))return this._returnResult({data:{user:null,session:null},error:$});throw $}}async resend($){try{const ts=`${this.url}/resend`;if("email"in $){const{email:is,type:cs,options:Qr}=$,{error:ja}=await _request(this.fetch,"POST",ts,{headers:this.headers,body:{email:is,type:cs,gotrue_meta_security:{captcha_token:Qr==null?void 0:Qr.captchaToken}},redirectTo:Qr==null?void 0:Qr.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:ja})}else if("phone"in $){const{phone:is,type:cs,options:Qr}=$,{data:ja,error:Na}=await _request(this.fetch,"POST",ts,{headers:this.headers,body:{phone:is,type:cs,gotrue_meta_security:{captcha_token:Qr==null?void 0:Qr.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:ja==null?void 0:ja.message_id},error:Na})}throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(ts){if(isAuthError(ts))return this._returnResult({data:{user:null,session:null},error:ts});throw ts}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async ts=>ts))}async _acquireLock($,ts){this._debug("#_acquireLock","begin",$);try{if(this.lockAcquired){const is=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),cs=(async()=>(await is,await ts()))();return this.pendingInLock.push((async()=>{try{await cs}catch{}})()),cs}return await this.lock(`lock:${this.storageKey}`,$,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const is=ts();for(this.pendingInLock.push((async()=>{try{await is}catch{}})()),await is;this.pendingInLock.length;){const cs=[...this.pendingInLock];await Promise.all(cs),this.pendingInLock.splice(0,cs.length)}return await is}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession($){this._debug("#_useSession","begin");try{const ts=await this.__loadSession();return await $(ts)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let $=null;const ts=await getItemAsync(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",ts),ts!==null&&(this._isValidSession(ts)?$=ts:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!$)return{data:{session:null},error:null};const is=$.expires_at?$.expires_at*1e3-Date.now()<EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${is?"":" not"} expired`,"expires_at",$.expires_at),!is){if(this.userStorage){const ja=await getItemAsync(this.userStorage,this.storageKey+"-user");ja!=null&&ja.user?$.user=ja.user:$.user=userNotAvailableProxy()}if(this.storage.isServer&&$.user&&!$.user.__isUserNotAvailableProxy){const ja={value:this.suppressGetSessionWarning};$.user=insecureUserWarningProxy($.user,ja),ja.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:$},error:null}}const{data:cs,error:Qr}=await this._callRefreshToken($.refresh_token);return Qr?this._returnResult({data:{session:null},error:Qr}):this._returnResult({data:{session:cs},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser($){if($)return await this._getUser($);await this.initializePromise;const ts=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return ts.data.user&&(this.suppressGetSessionWarning=!0),ts}async _getUser($){try{return $?await _request(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:$,xform:_userResponse}):await this._useSession(async ts=>{var is,cs,Qr;const{data:ja,error:Na}=ts;if(Na)throw Na;return!(!((is=ja.session)===null||is===void 0)&&is.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new AuthSessionMissingError}:await _request(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(Qr=(cs=ja.session)===null||cs===void 0?void 0:cs.access_token)!==null&&Qr!==void 0?Qr:void 0,xform:_userResponse})})}catch(ts){if(isAuthError(ts))return isAuthSessionMissingError(ts)&&(await this._removeSession(),await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:ts});throw ts}}async updateUser($,ts={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser($,ts))}async _updateUser($,ts={}){try{return await this._useSession(async is=>{const{data:cs,error:Qr}=is;if(Qr)throw Qr;if(!cs.session)throw new AuthSessionMissingError;const ja=cs.session;let Na=null,Aa=null;this.flowType==="pkce"&&$.email!=null&&([Na,Aa]=await getCodeChallengeAndMethod(this.storage,this.storageKey));const{data:Oa,error:Ia}=await _request(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:ts==null?void 0:ts.emailRedirectTo,body:Object.assign(Object.assign({},$),{code_challenge:Na,code_challenge_method:Aa}),jwt:ja.access_token,xform:_userResponse});if(Ia)throw Ia;return ja.user=Oa.user,await this._saveSession(ja),await this._notifyAllSubscribers("USER_UPDATED",ja),this._returnResult({data:{user:ja.user},error:null})})}catch(is){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(is))return this._returnResult({data:{user:null},error:is});throw is}}async setSession($){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession($))}async _setSession($){try{if(!$.access_token||!$.refresh_token)throw new AuthSessionMissingError;const ts=Date.now()/1e3;let is=ts,cs=!0,Qr=null;const{payload:ja}=decodeJWT($.access_token);if(ja.exp&&(is=ja.exp,cs=is<=ts),cs){const{data:Na,error:Aa}=await this._callRefreshToken($.refresh_token);if(Aa)return this._returnResult({data:{user:null,session:null},error:Aa});if(!Na)return{data:{user:null,session:null},error:null};Qr=Na}else{const{data:Na,error:Aa}=await this._getUser($.access_token);if(Aa)return this._returnResult({data:{user:null,session:null},error:Aa});Qr={access_token:$.access_token,refresh_token:$.refresh_token,user:Na.user,token_type:"bearer",expires_in:is-ts,expires_at:is},await this._saveSession(Qr),await this._notifyAllSubscribers("SIGNED_IN",Qr)}return this._returnResult({data:{user:Qr.user,session:Qr},error:null})}catch(ts){if(isAuthError(ts))return this._returnResult({data:{session:null,user:null},error:ts});throw ts}}async refreshSession($){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession($))}async _refreshSession($){try{return await this._useSession(async ts=>{var is;if(!$){const{data:ja,error:Na}=ts;if(Na)throw Na;$=(is=ja.session)!==null&&is!==void 0?is:void 0}if(!($!=null&&$.refresh_token))throw new AuthSessionMissingError;const{data:cs,error:Qr}=await this._callRefreshToken($.refresh_token);return Qr?this._returnResult({data:{user:null,session:null},error:Qr}):cs?this._returnResult({data:{user:cs.user,session:cs},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:{user:null,session:null},error:ts});throw ts}}async _getSessionFromURL($,ts){try{if(!isBrowser())throw new AuthImplicitGrantRedirectError("No browser detected.");if($.error||$.error_description||$.error_code)throw new AuthImplicitGrantRedirectError($.error_description||"Error in URL with unspecified error_description",{error:$.error||"unspecified_error",code:$.error_code||"unspecified_code"});switch(ts){case"implicit":if(this.flowType==="pkce")throw new AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");break;default:}if(ts==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!$.code)throw new AuthPKCEGrantCodeExchangeError("No code detected.");const{data:Ga,error:Va}=await this._exchangeCodeForSession($.code);if(Va)throw Va;const Ja=new URL(window.location.href);return Ja.searchParams.delete("code"),window.history.replaceState(window.history.state,"",Ja.toString()),{data:{session:Ga.session,redirectType:null},error:null}}const{provider_token:is,provider_refresh_token:cs,access_token:Qr,refresh_token:ja,expires_in:Na,expires_at:Aa,token_type:Oa}=$;if(!Qr||!Na||!ja||!Oa)throw new AuthImplicitGrantRedirectError("No session defined in URL");const Ia=Math.round(Date.now()/1e3),La=parseInt(Na);let Ba=Ia+La;Aa&&(Ba=parseInt(Aa));const Ma=Ba-Ia;Ma*1e3<=AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${Ma}s, should have been closer to ${La}s`);const qa=Ba-La;Ia-qa>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",qa,Ba,Ia):Ia-qa<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",qa,Ba,Ia);const{data:Fa,error:Ha}=await this._getUser(Qr);if(Ha)throw Ha;const Ka={provider_token:is,provider_refresh_token:cs,access_token:Qr,expires_in:La,expires_at:Ba,refresh_token:ja,token_type:Oa,user:Fa.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:Ka,redirectType:$.type},error:null})}catch(is){if(isAuthError(is))return this._returnResult({data:{session:null,redirectType:null},error:is});throw is}}_isImplicitGrantCallback($){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),$):!!($.access_token||$.error_description)}async _isPKCECallback($){const ts=await getItemAsync(this.storage,`${this.storageKey}-code-verifier`);return!!($.code&&ts)}async signOut($={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut($))}async _signOut({scope:$}={scope:"global"}){return await this._useSession(async ts=>{var is;const{data:cs,error:Qr}=ts;if(Qr&&!isAuthSessionMissingError(Qr))return this._returnResult({error:Qr});const ja=(is=cs.session)===null||is===void 0?void 0:is.access_token;if(ja){const{error:Na}=await this.admin.signOut(ja,$);if(Na&&!(isAuthApiError(Na)&&(Na.status===404||Na.status===401||Na.status===403)||isAuthSessionMissingError(Na)))return this._returnResult({error:Na})}return $!=="others"&&(await this._removeSession(),await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange($){const ts=generateCallbackId(),is={id:ts,callback:$,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",ts),this.stateChangeEmitters.delete(ts)}};return this._debug("#onAuthStateChange()","registered callback with id",ts),this.stateChangeEmitters.set(ts,is),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(ts)})))(),{data:{subscription:is}}}async _emitInitialSession($){return await this._useSession(async ts=>{var is,cs;try{const{data:{session:Qr},error:ja}=ts;if(ja)throw ja;await((is=this.stateChangeEmitters.get($))===null||is===void 0?void 0:is.callback("INITIAL_SESSION",Qr)),this._debug("INITIAL_SESSION","callback id",$,"session",Qr)}catch(Qr){await((cs=this.stateChangeEmitters.get($))===null||cs===void 0?void 0:cs.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",$,"error",Qr),console.error(Qr)}})}async resetPasswordForEmail($,ts={}){let is=null,cs=null;this.flowType==="pkce"&&([is,cs]=await getCodeChallengeAndMethod(this.storage,this.storageKey,!0));try{return await _request(this.fetch,"POST",`${this.url}/recover`,{body:{email:$,code_challenge:is,code_challenge_method:cs,gotrue_meta_security:{captcha_token:ts.captchaToken}},headers:this.headers,redirectTo:ts.redirectTo})}catch(Qr){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Qr))return this._returnResult({data:null,error:Qr});throw Qr}}async getUserIdentities(){var $;try{const{data:ts,error:is}=await this.getUser();if(is)throw is;return this._returnResult({data:{identities:($=ts.user.identities)!==null&&$!==void 0?$:[]},error:null})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async linkIdentity($){return"token"in $?this.linkIdentityIdToken($):this.linkIdentityOAuth($)}async linkIdentityOAuth($){var ts;try{const{data:is,error:cs}=await this._useSession(async Qr=>{var ja,Na,Aa,Oa,Ia;const{data:La,error:Ba}=Qr;if(Ba)throw Ba;const Ma=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,$.provider,{redirectTo:(ja=$.options)===null||ja===void 0?void 0:ja.redirectTo,scopes:(Na=$.options)===null||Na===void 0?void 0:Na.scopes,queryParams:(Aa=$.options)===null||Aa===void 0?void 0:Aa.queryParams,skipBrowserRedirect:!0});return await _request(this.fetch,"GET",Ma,{headers:this.headers,jwt:(Ia=(Oa=La.session)===null||Oa===void 0?void 0:Oa.access_token)!==null&&Ia!==void 0?Ia:void 0})});if(cs)throw cs;return isBrowser()&&!(!((ts=$.options)===null||ts===void 0)&&ts.skipBrowserRedirect)&&window.location.assign(is==null?void 0:is.url),this._returnResult({data:{provider:$.provider,url:is==null?void 0:is.url},error:null})}catch(is){if(isAuthError(is))return this._returnResult({data:{provider:$.provider,url:null},error:is});throw is}}async linkIdentityIdToken($){return await this._useSession(async ts=>{var is;try{const{error:cs,data:{session:Qr}}=ts;if(cs)throw cs;const{options:ja,provider:Na,token:Aa,access_token:Oa,nonce:Ia}=$,La=await _request(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(is=Qr==null?void 0:Qr.access_token)!==null&&is!==void 0?is:void 0,body:{provider:Na,id_token:Aa,access_token:Oa,nonce:Ia,link_identity:!0,gotrue_meta_security:{captcha_token:ja==null?void 0:ja.captchaToken}},xform:_sessionResponse}),{data:Ba,error:Ma}=La;return Ma?this._returnResult({data:{user:null,session:null},error:Ma}):!Ba||!Ba.session||!Ba.user?this._returnResult({data:{user:null,session:null},error:new AuthInvalidTokenResponseError}):(Ba.session&&(await this._saveSession(Ba.session),await this._notifyAllSubscribers("USER_UPDATED",Ba.session)),this._returnResult({data:Ba,error:Ma}))}catch(cs){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(cs))return this._returnResult({data:{user:null,session:null},error:cs});throw cs}})}async unlinkIdentity($){try{return await this._useSession(async ts=>{var is,cs;const{data:Qr,error:ja}=ts;if(ja)throw ja;return await _request(this.fetch,"DELETE",`${this.url}/user/identities/${$.identity_id}`,{headers:this.headers,jwt:(cs=(is=Qr.session)===null||is===void 0?void 0:is.access_token)!==null&&cs!==void 0?cs:void 0})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async _refreshAccessToken($){const ts=`#_refreshAccessToken(${$.substring(0,5)}...)`;this._debug(ts,"begin");try{const is=Date.now();return await retryable(async cs=>(cs>0&&await sleep(200*Math.pow(2,cs-1)),this._debug(ts,"refreshing attempt",cs),await _request(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:$},headers:this.headers,xform:_sessionResponse})),(cs,Qr)=>{const ja=200*Math.pow(2,cs);return Qr&&isAuthRetryableFetchError(Qr)&&Date.now()+ja-is<AUTO_REFRESH_TICK_DURATION_MS})}catch(is){if(this._debug(ts,"error",is),isAuthError(is))return this._returnResult({data:{session:null,user:null},error:is});throw is}finally{this._debug(ts,"end")}}_isValidSession($){return typeof $=="object"&&$!==null&&"access_token"in $&&"refresh_token"in $&&"expires_at"in $}async _handleProviderSignIn($,ts){const is=await this._getUrlForProvider(`${this.url}/authorize`,$,{redirectTo:ts.redirectTo,scopes:ts.scopes,queryParams:ts.queryParams});return this._debug("#_handleProviderSignIn()","provider",$,"options",ts,"url",is),isBrowser()&&!ts.skipBrowserRedirect&&window.location.assign(is),{data:{provider:$,url:is},error:null}}async _recoverAndRefresh(){var $,ts;const is="#_recoverAndRefresh()";this._debug(is,"begin");try{const cs=await getItemAsync(this.storage,this.storageKey);if(cs&&this.userStorage){let ja=await getItemAsync(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!ja&&(ja={user:cs.user},await setItemAsync(this.userStorage,this.storageKey+"-user",ja)),cs.user=($=ja==null?void 0:ja.user)!==null&&$!==void 0?$:userNotAvailableProxy()}else if(cs&&!cs.user&&!cs.user){const ja=await getItemAsync(this.storage,this.storageKey+"-user");ja&&(ja!=null&&ja.user)?(cs.user=ja.user,await removeItemAsync(this.storage,this.storageKey+"-user"),await setItemAsync(this.storage,this.storageKey,cs)):cs.user=userNotAvailableProxy()}if(this._debug(is,"session from storage",cs),!this._isValidSession(cs)){this._debug(is,"session is not valid"),cs!==null&&await this._removeSession();return}const Qr=((ts=cs.expires_at)!==null&&ts!==void 0?ts:1/0)*1e3-Date.now()<EXPIRY_MARGIN_MS;if(this._debug(is,`session has${Qr?"":" not"} expired with margin of ${EXPIRY_MARGIN_MS}s`),Qr){if(this.autoRefreshToken&&cs.refresh_token){const{error:ja}=await this._callRefreshToken(cs.refresh_token);ja&&(console.error(ja),isAuthRetryableFetchError(ja)||(this._debug(is,"refresh failed with a non-retryable error, removing the session",ja),await this._removeSession()))}}else if(cs.user&&cs.user.__isUserNotAvailableProxy===!0)try{const{data:ja,error:Na}=await this._getUser(cs.access_token);!Na&&(ja!=null&&ja.user)?(cs.user=ja.user,await this._saveSession(cs),await this._notifyAllSubscribers("SIGNED_IN",cs)):this._debug(is,"could not get user data, skipping SIGNED_IN notification")}catch(ja){console.error("Error getting user data:",ja),this._debug(is,"error getting user data, skipping SIGNED_IN notification",ja)}else await this._notifyAllSubscribers("SIGNED_IN",cs)}catch(cs){this._debug(is,"error",cs),console.error(cs);return}finally{this._debug(is,"end")}}async _callRefreshToken($){var ts,is;if(!$)throw new AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const cs=`#_callRefreshToken(${$.substring(0,5)}...)`;this._debug(cs,"begin");try{this.refreshingDeferred=new Deferred;const{data:Qr,error:ja}=await this._refreshAccessToken($);if(ja)throw ja;if(!Qr.session)throw new AuthSessionMissingError;await this._saveSession(Qr.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",Qr.session);const Na={data:Qr.session,error:null};return this.refreshingDeferred.resolve(Na),Na}catch(Qr){if(this._debug(cs,"error",Qr),isAuthError(Qr)){const ja={data:null,error:Qr};return isAuthRetryableFetchError(Qr)||await this._removeSession(),(ts=this.refreshingDeferred)===null||ts===void 0||ts.resolve(ja),ja}throw(is=this.refreshingDeferred)===null||is===void 0||is.reject(Qr),Qr}finally{this.refreshingDeferred=null,this._debug(cs,"end")}}async _notifyAllSubscribers($,ts,is=!0){const cs=`#_notifyAllSubscribers(${$})`;this._debug(cs,"begin",ts,`broadcast = ${is}`);try{this.broadcastChannel&&is&&this.broadcastChannel.postMessage({event:$,session:ts});const Qr=[],ja=Array.from(this.stateChangeEmitters.values()).map(async Na=>{try{await Na.callback($,ts)}catch(Aa){Qr.push(Aa)}});if(await Promise.all(ja),Qr.length>0){for(let Na=0;Na<Qr.length;Na+=1)console.error(Qr[Na]);throw Qr[0]}}finally{this._debug(cs,"end")}}async _saveSession($){this._debug("#_saveSession()",$),this.suppressGetSessionWarning=!0,await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`);const ts=Object.assign({},$),is=ts.user&&ts.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!is&&ts.user&&await setItemAsync(this.userStorage,this.storageKey+"-user",{user:ts.user});const cs=Object.assign({},ts);delete cs.user;const Qr=deepClone(cs);await setItemAsync(this.storage,this.storageKey,Qr)}else{const cs=deepClone(ts);await setItemAsync(this.storage,this.storageKey,cs)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await removeItemAsync(this.storage,this.storageKey),await removeItemAsync(this.storage,this.storageKey+"-code-verifier"),await removeItemAsync(this.storage,this.storageKey+"-user"),this.userStorage&&await removeItemAsync(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const $=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{$&&isBrowser()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",$)}catch(ts){console.error("removing visibilitychange callback failed",ts)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const $=setInterval(()=>this._autoRefreshTokenTick(),AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=$,$&&typeof $=="object"&&typeof $.unref=="function"?$.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer($);const ts=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=ts,ts&&typeof ts=="object"&&typeof ts.unref=="function"?ts.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(ts)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const $=this.autoRefreshTicker;this.autoRefreshTicker=null,$&&clearInterval($);const ts=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,ts&&clearTimeout(ts)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const $=Date.now();try{return await this._useSession(async ts=>{const{data:{session:is}}=ts;if(!is||!is.refresh_token||!is.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const cs=Math.floor((is.expires_at*1e3-$)/AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${cs} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`),cs<=AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(is.refresh_token)})}catch(ts){console.error("Auto refresh tick failed with error. This is likely a transient error.",ts)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch($){if($.isAcquireTimeout||$ instanceof LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw $}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!isBrowser()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch($){this._debug("#visibilityChangedCallback","error",$)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch($){console.error("_handleVisibilityChange",$)}}async _onVisibilityChanged($){const ts=`#_onVisibilityChanged(${$})`;this._debug(ts,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),$||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(ts,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider($,ts,is){const cs=[`provider=${encodeURIComponent(ts)}`];if(is!=null&&is.redirectTo&&cs.push(`redirect_to=${encodeURIComponent(is.redirectTo)}`),is!=null&&is.scopes&&cs.push(`scopes=${encodeURIComponent(is.scopes)}`),this.flowType==="pkce"){const[Qr,ja]=await getCodeChallengeAndMethod(this.storage,this.storageKey),Na=new URLSearchParams({code_challenge:`${encodeURIComponent(Qr)}`,code_challenge_method:`${encodeURIComponent(ja)}`});cs.push(Na.toString())}if(is!=null&&is.queryParams){const Qr=new URLSearchParams(is.queryParams);cs.push(Qr.toString())}return is!=null&&is.skipBrowserRedirect&&cs.push(`skip_http_redirect=${is.skipBrowserRedirect}`),`${$}?${cs.join("&")}`}async _unenroll($){try{return await this._useSession(async ts=>{var is;const{data:cs,error:Qr}=ts;return Qr?this._returnResult({data:null,error:Qr}):await _request(this.fetch,"DELETE",`${this.url}/factors/${$.factorId}`,{headers:this.headers,jwt:(is=cs==null?void 0:cs.session)===null||is===void 0?void 0:is.access_token})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async _enroll($){try{return await this._useSession(async ts=>{var is,cs;const{data:Qr,error:ja}=ts;if(ja)return this._returnResult({data:null,error:ja});const Na=Object.assign({friendly_name:$.friendlyName,factor_type:$.factorType},$.factorType==="phone"?{phone:$.phone}:$.factorType==="totp"?{issuer:$.issuer}:{}),{data:Aa,error:Oa}=await _request(this.fetch,"POST",`${this.url}/factors`,{body:Na,headers:this.headers,jwt:(is=Qr==null?void 0:Qr.session)===null||is===void 0?void 0:is.access_token});return Oa?this._returnResult({data:null,error:Oa}):($.factorType==="totp"&&Aa.type==="totp"&&(!((cs=Aa==null?void 0:Aa.totp)===null||cs===void 0)&&cs.qr_code)&&(Aa.totp.qr_code=`data:image/svg+xml;utf-8,${Aa.totp.qr_code}`),this._returnResult({data:Aa,error:null}))})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async _verify($){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async ts=>{var is;const{data:cs,error:Qr}=ts;if(Qr)return this._returnResult({data:null,error:Qr});const ja=Object.assign({challenge_id:$.challengeId},"webauthn"in $?{webauthn:Object.assign(Object.assign({},$.webauthn),{credential_response:$.webauthn.type==="create"?serializeCredentialCreationResponse($.webauthn.credential_response):serializeCredentialRequestResponse($.webauthn.credential_response)})}:{code:$.code}),{data:Na,error:Aa}=await _request(this.fetch,"POST",`${this.url}/factors/${$.factorId}/verify`,{body:ja,headers:this.headers,jwt:(is=cs==null?void 0:cs.session)===null||is===void 0?void 0:is.access_token});return Aa?this._returnResult({data:null,error:Aa}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+Na.expires_in},Na)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",Na),this._returnResult({data:Na,error:Aa}))})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}})}async _challenge($){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async ts=>{var is;const{data:cs,error:Qr}=ts;if(Qr)return this._returnResult({data:null,error:Qr});const ja=await _request(this.fetch,"POST",`${this.url}/factors/${$.factorId}/challenge`,{body:$,headers:this.headers,jwt:(is=cs==null?void 0:cs.session)===null||is===void 0?void 0:is.access_token});if(ja.error)return ja;const{data:Na}=ja;if(Na.type!=="webauthn")return{data:Na,error:null};switch(Na.webauthn.type){case"create":return{data:Object.assign(Object.assign({},Na),{webauthn:Object.assign(Object.assign({},Na.webauthn),{credential_options:Object.assign(Object.assign({},Na.webauthn.credential_options),{publicKey:deserializeCredentialCreationOptions(Na.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},Na),{webauthn:Object.assign(Object.assign({},Na.webauthn),{credential_options:Object.assign(Object.assign({},Na.webauthn.credential_options),{publicKey:deserializeCredentialRequestOptions(Na.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}})}async _challengeAndVerify($){const{data:ts,error:is}=await this._challenge({factorId:$.factorId});return is?this._returnResult({data:null,error:is}):await this._verify({factorId:$.factorId,challengeId:ts.id,code:$.code})}async _listFactors(){var $;const{data:{user:ts},error:is}=await this.getUser();if(is)return{data:null,error:is};const cs={all:[],phone:[],totp:[],webauthn:[]};for(const Qr of($=ts==null?void 0:ts.factors)!==null&&$!==void 0?$:[])cs.all.push(Qr),Qr.status==="verified"&&cs[Qr.factor_type].push(Qr);return{data:cs,error:null}}async _getAuthenticatorAssuranceLevel($){var ts,is,cs,Qr;if($)try{const{payload:Ma}=decodeJWT($);let qa=null;Ma.aal&&(qa=Ma.aal);let Fa=qa;const{data:{user:Ha},error:Ka}=await this.getUser($);if(Ka)return this._returnResult({data:null,error:Ka});((is=(ts=Ha==null?void 0:Ha.factors)===null||ts===void 0?void 0:ts.filter(Ja=>Ja.status==="verified"))!==null&&is!==void 0?is:[]).length>0&&(Fa="aal2");const Va=Ma.amr||[];return{data:{currentLevel:qa,nextLevel:Fa,currentAuthenticationMethods:Va},error:null}}catch(Ma){if(isAuthError(Ma))return this._returnResult({data:null,error:Ma});throw Ma}const{data:{session:ja},error:Na}=await this.getSession();if(Na)return this._returnResult({data:null,error:Na});if(!ja)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:Aa}=decodeJWT(ja.access_token);let Oa=null;Aa.aal&&(Oa=Aa.aal);let Ia=Oa;((Qr=(cs=ja.user.factors)===null||cs===void 0?void 0:cs.filter(Ma=>Ma.status==="verified"))!==null&&Qr!==void 0?Qr:[]).length>0&&(Ia="aal2");const Ba=Aa.amr||[];return{data:{currentLevel:Oa,nextLevel:Ia,currentAuthenticationMethods:Ba},error:null}}async _getAuthorizationDetails($){try{return await this._useSession(async ts=>{const{data:{session:is},error:cs}=ts;return cs?this._returnResult({data:null,error:cs}):is?await _request(this.fetch,"GET",`${this.url}/oauth/authorizations/${$}`,{headers:this.headers,jwt:is.access_token,xform:Qr=>({data:Qr,error:null})}):this._returnResult({data:null,error:new AuthSessionMissingError})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async _approveAuthorization($,ts){try{return await this._useSession(async is=>{const{data:{session:cs},error:Qr}=is;if(Qr)return this._returnResult({data:null,error:Qr});if(!cs)return this._returnResult({data:null,error:new AuthSessionMissingError});const ja=await _request(this.fetch,"POST",`${this.url}/oauth/authorizations/${$}/consent`,{headers:this.headers,jwt:cs.access_token,body:{action:"approve"},xform:Na=>({data:Na,error:null})});return ja.data&&ja.data.redirect_url&&isBrowser()&&!(ts!=null&&ts.skipBrowserRedirect)&&window.location.assign(ja.data.redirect_url),ja})}catch(is){if(isAuthError(is))return this._returnResult({data:null,error:is});throw is}}async _denyAuthorization($,ts){try{return await this._useSession(async is=>{const{data:{session:cs},error:Qr}=is;if(Qr)return this._returnResult({data:null,error:Qr});if(!cs)return this._returnResult({data:null,error:new AuthSessionMissingError});const ja=await _request(this.fetch,"POST",`${this.url}/oauth/authorizations/${$}/consent`,{headers:this.headers,jwt:cs.access_token,body:{action:"deny"},xform:Na=>({data:Na,error:null})});return ja.data&&ja.data.redirect_url&&isBrowser()&&!(ts!=null&&ts.skipBrowserRedirect)&&window.location.assign(ja.data.redirect_url),ja})}catch(is){if(isAuthError(is))return this._returnResult({data:null,error:is});throw is}}async _listOAuthGrants(){try{return await this._useSession(async $=>{const{data:{session:ts},error:is}=$;return is?this._returnResult({data:null,error:is}):ts?await _request(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:ts.access_token,xform:cs=>({data:cs,error:null})}):this._returnResult({data:null,error:new AuthSessionMissingError})})}catch($){if(isAuthError($))return this._returnResult({data:null,error:$});throw $}}async _revokeOAuthGrant($){try{return await this._useSession(async ts=>{const{data:{session:is},error:cs}=ts;return cs?this._returnResult({data:null,error:cs}):is?(await _request(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:is.access_token,query:{client_id:$.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new AuthSessionMissingError})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async fetchJwk($,ts={keys:[]}){let is=ts.keys.find(Na=>Na.kid===$);if(is)return is;const cs=Date.now();if(is=this.jwks.keys.find(Na=>Na.kid===$),is&&this.jwks_cached_at+JWKS_TTL>cs)return is;const{data:Qr,error:ja}=await _request(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(ja)throw ja;return!Qr.keys||Qr.keys.length===0||(this.jwks=Qr,this.jwks_cached_at=cs,is=Qr.keys.find(Na=>Na.kid===$),!is)?null:is}async getClaims($,ts={}){try{let is=$;if(!is){const{data:Ma,error:qa}=await this.getSession();if(qa||!Ma.session)return this._returnResult({data:null,error:qa});is=Ma.session.access_token}const{header:cs,payload:Qr,signature:ja,raw:{header:Na,payload:Aa}}=decodeJWT(is);ts!=null&&ts.allowExpired||validateExp(Qr.exp);const Oa=!cs.alg||cs.alg.startsWith("HS")||!cs.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(cs.kid,ts!=null&&ts.keys?{keys:ts.keys}:ts==null?void 0:ts.jwks);if(!Oa){const{error:Ma}=await this.getUser(is);if(Ma)throw Ma;return{data:{claims:Qr,header:cs,signature:ja},error:null}}const Ia=getAlgorithm(cs.alg),La=await crypto.subtle.importKey("jwk",Oa,Ia,!0,["verify"]);if(!await crypto.subtle.verify(Ia,La,ja,stringToUint8Array(`${Na}.${Aa}`)))throw new AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:Qr,header:cs,signature:ja},error:null}}catch(is){if(isAuthError(is))return this._returnResult({data:null,error:is});throw is}}}GoTrueClient.nextInstanceID={};const AuthClient=GoTrueClient,version="2.95.3";let JS_ENV="";typeof Deno<"u"?JS_ENV="deno":typeof document<"u"?JS_ENV="web":typeof navigator<"u"&&navigator.product==="ReactNative"?JS_ENV="react-native":JS_ENV="node";const DEFAULT_HEADERS={"X-Client-Info":`supabase-js-${JS_ENV}/${version}`},DEFAULT_GLOBAL_OPTIONS={headers:DEFAULT_HEADERS},DEFAULT_DB_OPTIONS={schema:"public"},DEFAULT_AUTH_OPTIONS={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},DEFAULT_REALTIME_OPTIONS={};function _typeof(es){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},_typeof(es)}function toPrimitive(es,$){if(_typeof(es)!="object"||!es)return es;var ts=es[Symbol.toPrimitive];if(ts!==void 0){var is=ts.call(es,$);if(_typeof(is)!="object")return is;throw new TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(es)}function toPropertyKey(es){var $=toPrimitive(es,"string");return _typeof($)=="symbol"?$:$+""}function _defineProperty(es,$,ts){return($=toPropertyKey($))in es?Object.defineProperty(es,$,{value:ts,enumerable:!0,configurable:!0,writable:!0}):es[$]=ts,es}function ownKeys(es,$){var ts=Object.keys(es);if(Object.getOwnPropertySymbols){var is=Object.getOwnPropertySymbols(es);$&&(is=is.filter(function(cs){return Object.getOwnPropertyDescriptor(es,cs).enumerable})),ts.push.apply(ts,is)}return ts}function _objectSpread2(es){for(var $=1;$<arguments.length;$++){var ts=arguments[$]!=null?arguments[$]:{};$%2?ownKeys(Object(ts),!0).forEach(function(is){_defineProperty(es,is,ts[is])}):Object.getOwnPropertyDescriptors?Object.defineProperties(es,Object.getOwnPropertyDescriptors(ts)):ownKeys(Object(ts)).forEach(function(is){Object.defineProperty(es,is,Object.getOwnPropertyDescriptor(ts,is))})}return es}const resolveFetch=es=>es?(...$)=>es(...$):(...$)=>fetch(...$),resolveHeadersConstructor=()=>Headers,fetchWithAuth=(es,$,ts)=>{const is=resolveFetch(ts),cs=resolveHeadersConstructor();return async(Qr,ja)=>{var Na;const Aa=(Na=await $())!==null&&Na!==void 0?Na:es;let Oa=new cs(ja==null?void 0:ja.headers);return Oa.has("apikey")||Oa.set("apikey",es),Oa.has("Authorization")||Oa.set("Authorization",`Bearer ${Aa}`),is(Qr,_objectSpread2(_objectSpread2({},ja),{},{headers:Oa}))}};function ensureTrailingSlash(es){return es.endsWith("/")?es:es+"/"}function applySettingDefaults(es,$){var ts,is;const{db:cs,auth:Qr,realtime:ja,global:Na}=es,{db:Aa,auth:Oa,realtime:Ia,global:La}=$,Ba={db:_objectSpread2(_objectSpread2({},Aa),cs),auth:_objectSpread2(_objectSpread2({},Oa),Qr),realtime:_objectSpread2(_objectSpread2({},Ia),ja),storage:{},global:_objectSpread2(_objectSpread2(_objectSpread2({},La),Na),{},{headers:_objectSpread2(_objectSpread2({},(ts=La==null?void 0:La.headers)!==null&&ts!==void 0?ts:{}),(is=Na==null?void 0:Na.headers)!==null&&is!==void 0?is:{})}),accessToken:async()=>""};return es.accessToken?Ba.accessToken=es.accessToken:delete Ba.accessToken,Ba}function validateSupabaseUrl(es){const $=es==null?void 0:es.trim();if(!$)throw new Error("supabaseUrl is required.");if(!$.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(ensureTrailingSlash($))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var SupabaseAuthClient=class extends AuthClient{constructor(es){super(es)}},SupabaseClient=class{constructor(es,$,ts){var is,cs;this.supabaseUrl=es,this.supabaseKey=$;const Qr=validateSupabaseUrl(es);if(!$)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",Qr),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",Qr),this.storageUrl=new URL("storage/v1",Qr),this.functionsUrl=new URL("functions/v1",Qr);const ja=`sb-${Qr.hostname.split(".")[0]}-auth-token`,Na={db:DEFAULT_DB_OPTIONS,realtime:DEFAULT_REALTIME_OPTIONS,auth:_objectSpread2(_objectSpread2({},DEFAULT_AUTH_OPTIONS),{},{storageKey:ja}),global:DEFAULT_GLOBAL_OPTIONS},Aa=applySettingDefaults(ts??{},Na);if(this.storageKey=(is=Aa.auth.storageKey)!==null&&is!==void 0?is:"",this.headers=(cs=Aa.global.headers)!==null&&cs!==void 0?cs:{},Aa.accessToken)this.accessToken=Aa.accessToken,this.auth=new Proxy({},{get:(Ia,La)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(La)} is not possible`)}});else{var Oa;this.auth=this._initSupabaseAuthClient((Oa=Aa.auth)!==null&&Oa!==void 0?Oa:{},this.headers,Aa.global.fetch)}this.fetch=fetchWithAuth($,this._getAccessToken.bind(this),Aa.global.fetch),this.realtime=this._initRealtimeClient(_objectSpread2({headers:this.headers,accessToken:this._getAccessToken.bind(this)},Aa.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(Ia=>this.realtime.setAuth(Ia)).catch(Ia=>console.warn("Failed to set initial Realtime auth token:",Ia)),this.rest=new PostgrestClient(new URL("rest/v1",Qr).href,{headers:this.headers,schema:Aa.db.schema,fetch:this.fetch,timeout:Aa.db.timeout,urlLengthLimit:Aa.db.urlLengthLimit}),this.storage=new StorageClient(this.storageUrl.href,this.headers,this.fetch,ts==null?void 0:ts.storage),Aa.accessToken||this._listenForAuthEvents()}get functions(){return new FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(es){return this.rest.from(es)}schema(es){return this.rest.schema(es)}rpc(es,$={},ts={head:!1,get:!1,count:void 0}){return this.rest.rpc(es,$,ts)}channel(es,$={config:{}}){return this.realtime.channel(es,$)}getChannels(){return this.realtime.getChannels()}removeChannel(es){return this.realtime.removeChannel(es)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var es=this,$,ts;if(es.accessToken)return await es.accessToken();const{data:is}=await es.auth.getSession();return($=(ts=is.session)===null||ts===void 0?void 0:ts.access_token)!==null&&$!==void 0?$:es.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:es,persistSession:$,detectSessionInUrl:ts,storage:is,userStorage:cs,storageKey:Qr,flowType:ja,lock:Na,debug:Aa,throwOnError:Oa},Ia,La){const Ba={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new SupabaseAuthClient({url:this.authUrl.href,headers:_objectSpread2(_objectSpread2({},Ba),Ia),storageKey:Qr,autoRefreshToken:es,persistSession:$,detectSessionInUrl:ts,storage:is,userStorage:cs,flowType:ja,lock:Na,debug:Aa,throwOnError:Oa,fetch:La,hasCustomAuthorizationHeader:Object.keys(this.headers).some(Ma=>Ma.toLowerCase()==="authorization")})}_initRealtimeClient(es){return new RealtimeClient(this.realtimeUrl.href,_objectSpread2(_objectSpread2({},es),{},{params:_objectSpread2(_objectSpread2({},{apikey:this.supabaseKey}),es==null?void 0:es.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((es,$)=>{this._handleTokenChanged(es,"CLIENT",$==null?void 0:$.access_token)})}_handleTokenChanged(es,$,ts){(es==="TOKEN_REFRESHED"||es==="SIGNED_IN")&&this.changedAccessToken!==ts?(this.changedAccessToken=ts,this.realtime.setAuth(ts)):es==="SIGNED_OUT"&&(this.realtime.setAuth(),$=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const createClient=(es,$,ts)=>new SupabaseClient(es,$,ts);function shouldShowDeprecationWarning(){if(typeof window<"u")return!1;const es=globalThis.process;if(!es)return!1;const $=es.version;if($==null)return!1;const ts=$.match(/^v(\d+)\./);return ts?parseInt(ts[1],10)<=18:!1}shouldShowDeprecationWarning()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const RING_LIMIT=200,ring=[],counts={};function callerFromStack(){var $;const es=(($=new Error().stack)==null?void 0:$.split(`
|
|
69
|
+
`))??[];for(let ts=2;ts<es.length;ts++){const is=es[ts];if(is&&!is.includes("auth-log.ts")&&!is.includes("supabase.ts"))return is.trim()}}function authLog(es,$,ts){const is={ts:Date.now(),method:es,caller:callerFromStack(),detail:$};ring.push(is),ring.length>RING_LIMIT&&ring.shift(),counts[es]=(counts[es]??0)+1,console.log(`[auth] ${es}${$?` ${$}`:""}${is.caller?` ← ${is.caller}`:""}`)}const ROLLUP_MS=6e4;let lastRollup=Date.now();setInterval(()=>{const es=Date.now(),$=ring.filter(is=>es-is.ts<ROLLUP_MS);if($.length===0)return;const ts={};for(const is of $)ts[is.method]=(ts[is.method]??0)+1;console.log(`[auth] rollup last 60s: ${$.length} calls`,ts,`(total since load: ${Object.values(counts).reduce((is,cs)=>is+cs,0)})`),lastRollup=es},3e4);typeof window<"u"&&(window.__authLog={ring:()=>ring.slice(),counts:()=>({...counts}),sinceRollup:()=>Date.now()-lastRollup});function readRuntimeConfig(es=globalThis){const $=es.__RM_CONFIG;if(!$||typeof $!="object")return;const{supabaseUrl:ts,supabaseAnonKey:is}=$;return{supabaseUrl:typeof ts=="string"&&ts?ts:void 0,supabaseAnonKey:typeof is=="string"&&is?is:void 0}}function resolveSupabaseConfig(es,$){return{url:(es==null?void 0:es.supabaseUrl)??$.url,anonKey:(es==null?void 0:es.supabaseAnonKey)??$.anonKey}}const runtimeConfig=Object.freeze(Object.defineProperty({__proto__:null,readRuntimeConfig,resolveSupabaseConfig},Symbol.toStringTag,{value:"Module"})),resolved=resolveSupabaseConfig(readRuntimeConfig(),{url:void 0,anonKey:void 0});if(!resolved.url||!resolved.anonKey)throw new Error("Missing Supabase config: no window.__RM_CONFIG stamped by the server and no VITE_SUPABASE_URL / VITE_SUPABASE_ANON_KEY baked at build time.");const supabaseUrl=resolved.url,supabaseAnonKey=resolved.anonKey,g$1=globalThis;function maskJwt(es){return es?`${es.slice(0,6)}…${es.slice(-4)} (len=${es.length})`:"<none>"}let cachedToken=null;const EXPIRY_MARGIN_S=60;function getCachedAccessToken(){if(!cachedToken)return null;const es=Math.floor(Date.now()/1e3);return cachedToken.expiresAt-es<=EXPIRY_MARGIN_S?null:cachedToken.accessToken}function buildClient(){const es=createClient(supabaseUrl,supabaseAnonKey,{auth:{flowType:"implicit"}});return g$1.__rmSupabaseAuthSubscribed||(g$1.__rmSupabaseAuthSubscribed=!0,es.auth.onAuthStateChange(($,ts)=>{ts!=null&&ts.access_token&&ts.expires_at?cachedToken={accessToken:ts.access_token,expiresAt:ts.expires_at}:cachedToken=null,authLog("onAuthStateChange:event",`${$} access=${maskJwt(ts==null?void 0:ts.access_token)} expires_at=${(ts==null?void 0:ts.expires_at)??"n/a"}`)})),es}const realClient=g$1.__rmSupabaseClient??(g$1.__rmSupabaseClient=buildClient()),realAuth=realClient.auth,watched=new Set(["getSession","refreshSession","signInWithPassword","signInWithOAuth","signUp","signOut","resetPasswordForEmail","updateUser","getUser"]);let currentDetail;function withAuthContext(es,$){const ts=currentDetail;currentDetail=es;try{return $()}finally{currentDetail=ts}}const wrappedAuth=new Proxy(realAuth,{get(es,$,ts){const is=Reflect.get(es,$,ts);return typeof is!="function"||!watched.has(String($))?is:(...cs)=>(authLog(String($),currentDetail),is.apply(es,cs))}}),supabase=new Proxy(realClient,{get(es,$,ts){return $==="auth"?wrappedAuth:Reflect.get(es,$,ts)}}),scriptRel="modulepreload",assetsURL=function(es){return"/"+es},seen={},__vitePreload=function($,ts,is){let cs=Promise.resolve();if(ts&&ts.length>0){let ja=function(Oa){return Promise.all(Oa.map(Ia=>Promise.resolve(Ia).then(La=>({status:"fulfilled",value:La}),La=>({status:"rejected",reason:La}))))};document.getElementsByTagName("link");const Na=document.querySelector("meta[property=csp-nonce]"),Aa=(Na==null?void 0:Na.nonce)||(Na==null?void 0:Na.getAttribute("nonce"));cs=ja(ts.map(Oa=>{if(Oa=assetsURL(Oa),Oa in seen)return;seen[Oa]=!0;const Ia=Oa.endsWith(".css"),La=Ia?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${Oa}"]${La}`))return;const Ba=document.createElement("link");if(Ba.rel=Ia?"stylesheet":scriptRel,Ia||(Ba.as="script"),Ba.crossOrigin="",Ba.href=Oa,Aa&&Ba.setAttribute("nonce",Aa),document.head.appendChild(Ba),Ia)return new Promise((Ma,qa)=>{Ba.addEventListener("load",Ma),Ba.addEventListener("error",()=>qa(new Error(`Unable to preload CSS for ${Oa}`)))})}))}function Qr(ja){const Na=new Event("vite:preloadError",{cancelable:!0});if(Na.payload=ja,window.dispatchEvent(Na),!Na.defaultPrevented)throw ja}return cs.then(ja=>{for(const Na of ja||[])Na.status==="rejected"&&Qr(Na.reason);return $().catch(Qr)})},SOCIAL_AUTH_PROVIDERS=[{id:"google",label:"Google"},{id:"github",label:"GitHub"}];function safeNext(es){return!es||!es.startsWith("/")||es.startsWith("//")?null:es}function buildAuthConfirmUrl(es,$){const ts=new URL("/auth/confirm",es),is=safeNext($);return is&&ts.searchParams.set("next",is),ts.toString()}function parseEnabledSocialAuthProviders(es){if(!es||typeof es!="object")return[];const $=es.external;if(!$||typeof $!="object")return[];const ts=$;return SOCIAL_AUTH_PROVIDERS.filter(({id:is})=>ts[is]===!0).map(({id:is})=>is)}async function fetchEnabledSocialAuthProviders(es){const{readRuntimeConfig:$,resolveSupabaseConfig:ts}=await __vitePreload(async()=>{const{readRuntimeConfig:Qr,resolveSupabaseConfig:ja}=await Promise.resolve().then(()=>runtimeConfig);return{readRuntimeConfig:Qr,resolveSupabaseConfig:ja}},void 0),{url:is,anonKey:cs}=ts($(),{url:void 0,anonKey:void 0});if(!is||!cs)return[];try{const Qr=await fetch(`${is.replace(/\/$/,"")}/auth/v1/settings`,{headers:{apikey:cs},signal:es});return Qr.ok?parseEnabledSocialAuthProviders(await Qr.json()):[]}catch{return[]}}function oauthCallbackError(es){if(!es)return null;const $=new URLSearchParams(es.startsWith("#")?es.slice(1):es),ts=$.get("error_code")??$.get("error");return ts?ts==="access_denied"?"Sign-in was cancelled.":ts.includes("email")?"The provider did not return a verified email address. Verify an email with the provider and try again.":"Social sign-in could not be completed. Please try again.":null}async function signInWithSocialProvider(es,$,ts,is){const{error:cs}=await es.signInWithOAuth({provider:$,options:{redirectTo:buildAuthConfirmUrl(ts,is)}});if(cs)throw cs}const AuthContext=reactExports.createContext(null);function AuthProvider({children:es}){const[$,ts]=reactExports.useState(null),[is,cs]=reactExports.useState(null),[Qr,ja]=reactExports.useState(!0);reactExports.useEffect(()=>{supabase.auth.getSession().then(({data:{session:qa}})=>{cs(qa),ts((qa==null?void 0:qa.user)??null),qa!=null&&qa.access_token&&supabase.realtime.setAuth(qa.access_token),ja(!1)});const{data:{subscription:Ma}}=supabase.auth.onAuthStateChange((qa,Fa)=>{cs(Fa),ts((Fa==null?void 0:Fa.user)??null),Fa!=null&&Fa.access_token&&supabase.realtime.setAuth(Fa.access_token)});return()=>Ma.unsubscribe()},[]);const Na=reactExports.useCallback(async(Ma,qa)=>{const{error:Fa}=await supabase.auth.signInWithPassword({email:Ma,password:qa});if(Fa)throw Fa},[]),Aa=reactExports.useCallback(async(Ma,qa)=>{await signInWithSocialProvider(supabase.auth,Ma,window.location.origin,qa)},[]),Oa=reactExports.useCallback(async(Ma,qa,Fa)=>{const Ha=buildAuthConfirmUrl(window.location.origin,Fa),{data:Ka,error:Ga}=await supabase.auth.signUp({email:Ma,password:qa,options:{emailRedirectTo:Ha}});if(Ga)throw Ga;const Va=!Ka.session&&!!Ka.user&&Array.isArray(Ka.user.identities)&&Ka.user.identities.length===0;return{needsConfirmation:!Ka.session&&!Va,alreadyRegistered:Va}},[]),Ia=reactExports.useCallback(async()=>{const{error:Ma}=await supabase.auth.signOut();if(Ma)throw Ma},[]),La=reactExports.useCallback(async Ma=>{const{error:qa}=await supabase.auth.resetPasswordForEmail(Ma,{redirectTo:`${window.location.origin}/auth/confirm`});if(qa)throw qa},[]),Ba=reactExports.useCallback(async Ma=>{const{error:qa}=await supabase.auth.updateUser({password:Ma});if(qa)throw qa},[]);return reactExports.createElement(AuthContext.Provider,{value:{user:$,session:is,loading:Qr,signIn:Na,signInWithProvider:Aa,signUp:Oa,signOut:Ia,resetPassword:La,updatePassword:Ba}},es)}function useAuth(){const es=reactExports.useContext(AuthContext);if(!es)throw new Error("useAuth must be used within AuthProvider");return es}function Skeleton({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"skeleton",className:cn$1("bg-accent animate-pulse rounded-md",es),...$})}function AuthGuard(){const{session:es,loading:$}=useAuth();return $?jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 w-64",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-1/2"})]})}):es?jsxRuntimeExports.jsx(Outlet,{}):jsxRuntimeExports.jsx(Navigate,{to:"/login",replace:!0})}var util;(function(es){es.assertEqual=cs=>{};function $(cs){}es.assertIs=$;function ts(cs){throw new Error}es.assertNever=ts,es.arrayToEnum=cs=>{const Qr={};for(const ja of cs)Qr[ja]=ja;return Qr},es.getValidEnumValues=cs=>{const Qr=es.objectKeys(cs).filter(Na=>typeof cs[cs[Na]]!="number"),ja={};for(const Na of Qr)ja[Na]=cs[Na];return es.objectValues(ja)},es.objectValues=cs=>es.objectKeys(cs).map(function(Qr){return cs[Qr]}),es.objectKeys=typeof Object.keys=="function"?cs=>Object.keys(cs):cs=>{const Qr=[];for(const ja in cs)Object.prototype.hasOwnProperty.call(cs,ja)&&Qr.push(ja);return Qr},es.find=(cs,Qr)=>{for(const ja of cs)if(Qr(ja))return ja},es.isInteger=typeof Number.isInteger=="function"?cs=>Number.isInteger(cs):cs=>typeof cs=="number"&&Number.isFinite(cs)&&Math.floor(cs)===cs;function is(cs,Qr=" | "){return cs.map(ja=>typeof ja=="string"?`'${ja}'`:ja).join(Qr)}es.joinValues=is,es.jsonStringifyReplacer=(cs,Qr)=>typeof Qr=="bigint"?Qr.toString():Qr})(util||(util={}));var objectUtil;(function(es){es.mergeShapes=($,ts)=>({...$,...ts})})(objectUtil||(objectUtil={}));const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=es=>{switch(typeof es){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(es)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(es)?ZodParsedType.array:es===null?ZodParsedType.null:es.then&&typeof es.then=="function"&&es.catch&&typeof es.catch=="function"?ZodParsedType.promise:typeof Map<"u"&&es instanceof Map?ZodParsedType.map:typeof Set<"u"&&es instanceof Set?ZodParsedType.set:typeof Date<"u"&&es instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.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 ZodError extends Error{get errors(){return this.issues}constructor($){super(),this.issues=[],this.addIssue=is=>{this.issues=[...this.issues,is]},this.addIssues=(is=[])=>{this.issues=[...this.issues,...is]};const ts=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,ts):this.__proto__=ts,this.name="ZodError",this.issues=$}format($){const ts=$||function(Qr){return Qr.message},is={_errors:[]},cs=Qr=>{for(const ja of Qr.issues)if(ja.code==="invalid_union")ja.unionErrors.map(cs);else if(ja.code==="invalid_return_type")cs(ja.returnTypeError);else if(ja.code==="invalid_arguments")cs(ja.argumentsError);else if(ja.path.length===0)is._errors.push(ts(ja));else{let Na=is,Aa=0;for(;Aa<ja.path.length;){const Oa=ja.path[Aa];Aa===ja.path.length-1?(Na[Oa]=Na[Oa]||{_errors:[]},Na[Oa]._errors.push(ts(ja))):Na[Oa]=Na[Oa]||{_errors:[]},Na=Na[Oa],Aa++}}};return cs(this),is}static assert($){if(!($ instanceof ZodError))throw new Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=ts=>ts.message){const ts={},is=[];for(const cs of this.issues)if(cs.path.length>0){const Qr=cs.path[0];ts[Qr]=ts[Qr]||[],ts[Qr].push($(cs))}else is.push($(cs));return{formErrors:is,fieldErrors:ts}}get formErrors(){return this.flatten()}}ZodError.create=es=>new ZodError(es);const errorMap=(es,$)=>{let ts;switch(es.code){case ZodIssueCode.invalid_type:es.received===ZodParsedType.undefined?ts="Required":ts=`Expected ${es.expected}, received ${es.received}`;break;case ZodIssueCode.invalid_literal:ts=`Invalid literal value, expected ${JSON.stringify(es.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:ts=`Unrecognized key(s) in object: ${util.joinValues(es.keys,", ")}`;break;case ZodIssueCode.invalid_union:ts="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:ts=`Invalid discriminator value. Expected ${util.joinValues(es.options)}`;break;case ZodIssueCode.invalid_enum_value:ts=`Invalid enum value. Expected ${util.joinValues(es.options)}, received '${es.received}'`;break;case ZodIssueCode.invalid_arguments:ts="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:ts="Invalid function return type";break;case ZodIssueCode.invalid_date:ts="Invalid date";break;case ZodIssueCode.invalid_string:typeof es.validation=="object"?"includes"in es.validation?(ts=`Invalid input: must include "${es.validation.includes}"`,typeof es.validation.position=="number"&&(ts=`${ts} at one or more positions greater than or equal to ${es.validation.position}`)):"startsWith"in es.validation?ts=`Invalid input: must start with "${es.validation.startsWith}"`:"endsWith"in es.validation?ts=`Invalid input: must end with "${es.validation.endsWith}"`:util.assertNever(es.validation):es.validation!=="regex"?ts=`Invalid ${es.validation}`:ts="Invalid";break;case ZodIssueCode.too_small:es.type==="array"?ts=`Array must contain ${es.exact?"exactly":es.inclusive?"at least":"more than"} ${es.minimum} element(s)`:es.type==="string"?ts=`String must contain ${es.exact?"exactly":es.inclusive?"at least":"over"} ${es.minimum} character(s)`:es.type==="number"?ts=`Number must be ${es.exact?"exactly equal to ":es.inclusive?"greater than or equal to ":"greater than "}${es.minimum}`:es.type==="bigint"?ts=`Number must be ${es.exact?"exactly equal to ":es.inclusive?"greater than or equal to ":"greater than "}${es.minimum}`:es.type==="date"?ts=`Date must be ${es.exact?"exactly equal to ":es.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(es.minimum))}`:ts="Invalid input";break;case ZodIssueCode.too_big:es.type==="array"?ts=`Array must contain ${es.exact?"exactly":es.inclusive?"at most":"less than"} ${es.maximum} element(s)`:es.type==="string"?ts=`String must contain ${es.exact?"exactly":es.inclusive?"at most":"under"} ${es.maximum} character(s)`:es.type==="number"?ts=`Number must be ${es.exact?"exactly":es.inclusive?"less than or equal to":"less than"} ${es.maximum}`:es.type==="bigint"?ts=`BigInt must be ${es.exact?"exactly":es.inclusive?"less than or equal to":"less than"} ${es.maximum}`:es.type==="date"?ts=`Date must be ${es.exact?"exactly":es.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(es.maximum))}`:ts="Invalid input";break;case ZodIssueCode.custom:ts="Invalid input";break;case ZodIssueCode.invalid_intersection_types:ts="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:ts=`Number must be a multiple of ${es.multipleOf}`;break;case ZodIssueCode.not_finite:ts="Number must be finite";break;default:ts=$.defaultError,util.assertNever(es)}return{message:ts}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=es=>{const{data:$,path:ts,errorMaps:is,issueData:cs}=es,Qr=[...ts,...cs.path||[]],ja={...cs,path:Qr};if(cs.message!==void 0)return{...cs,path:Qr,message:cs.message};let Na="";const Aa=is.filter(Oa=>!!Oa).slice().reverse();for(const Oa of Aa)Na=Oa(ja,{data:$,defaultError:Na}).message;return{...cs,path:Qr,message:Na}};function addIssueToContext(es,$){const ts=getErrorMap(),is=makeIssue({issueData:$,data:es.data,path:es.path,errorMaps:[es.common.contextualErrorMap,es.schemaErrorMap,ts,ts===errorMap?void 0:errorMap].filter(cs=>!!cs)});es.common.issues.push(is)}class ParseStatus{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray($,ts){const is=[];for(const cs of ts){if(cs.status==="aborted")return INVALID;cs.status==="dirty"&&$.dirty(),is.push(cs.value)}return{status:$.value,value:is}}static async mergeObjectAsync($,ts){const is=[];for(const cs of ts){const Qr=await cs.key,ja=await cs.value;is.push({key:Qr,value:ja})}return ParseStatus.mergeObjectSync($,is)}static mergeObjectSync($,ts){const is={};for(const cs of ts){const{key:Qr,value:ja}=cs;if(Qr.status==="aborted"||ja.status==="aborted")return INVALID;Qr.status==="dirty"&&$.dirty(),ja.status==="dirty"&&$.dirty(),Qr.value!=="__proto__"&&(typeof ja.value<"u"||cs.alwaysSet)&&(is[Qr.value]=ja.value)}return{status:$.value,value:is}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=es=>({status:"dirty",value:es}),OK=es=>({status:"valid",value:es}),isAborted=es=>es.status==="aborted",isDirty=es=>es.status==="dirty",isValid=es=>es.status==="valid",isAsync=es=>typeof Promise<"u"&&es instanceof Promise;var errorUtil;(function(es){es.errToObj=$=>typeof $=="string"?{message:$}:$||{},es.toString=$=>typeof $=="string"?$:$==null?void 0:$.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor($,ts,is,cs){this._cachedPath=[],this.parent=$,this.data=ts,this._path=is,this._key=cs}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 handleResult=(es,$)=>{if(isValid($))return{success:!0,data:$.value};if(!es.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const ts=new ZodError(es.common.issues);return this._error=ts,this._error}}};function processCreateParams(es){if(!es)return{};const{errorMap:$,invalid_type_error:ts,required_error:is,description:cs}=es;if($&&(ts||is))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return $?{errorMap:$,description:cs}:{errorMap:(ja,Na)=>{const{message:Aa}=es;return ja.code==="invalid_enum_value"?{message:Aa??Na.defaultError}:typeof Na.data>"u"?{message:Aa??is??Na.defaultError}:ja.code!=="invalid_type"?{message:Na.defaultError}:{message:Aa??ts??Na.defaultError}},description:cs}}class ZodType{get description(){return this._def.description}_getType($){return getParsedType($.data)}_getOrReturnCtx($,ts){return ts||{common:$.parent.common,data:$.data,parsedType:getParsedType($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new ParseStatus,ctx:{common:$.parent.common,data:$.data,parsedType:getParsedType($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){const ts=this._parse($);if(isAsync(ts))throw new Error("Synchronous parse encountered promise.");return ts}_parseAsync($){const ts=this._parse($);return Promise.resolve(ts)}parse($,ts){const is=this.safeParse($,ts);if(is.success)return is.data;throw is.error}safeParse($,ts){const is={common:{issues:[],async:(ts==null?void 0:ts.async)??!1,contextualErrorMap:ts==null?void 0:ts.errorMap},path:(ts==null?void 0:ts.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:getParsedType($)},cs=this._parseSync({data:$,path:is.path,parent:is});return handleResult(is,cs)}"~validate"($){var is,cs;const ts={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:getParsedType($)};if(!this["~standard"].async)try{const Qr=this._parseSync({data:$,path:[],parent:ts});return isValid(Qr)?{value:Qr.value}:{issues:ts.common.issues}}catch(Qr){(cs=(is=Qr==null?void 0:Qr.message)==null?void 0:is.toLowerCase())!=null&&cs.includes("encountered")&&(this["~standard"].async=!0),ts.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:ts}).then(Qr=>isValid(Qr)?{value:Qr.value}:{issues:ts.common.issues})}async parseAsync($,ts){const is=await this.safeParseAsync($,ts);if(is.success)return is.data;throw is.error}async safeParseAsync($,ts){const is={common:{issues:[],contextualErrorMap:ts==null?void 0:ts.errorMap,async:!0},path:(ts==null?void 0:ts.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:getParsedType($)},cs=this._parse({data:$,path:is.path,parent:is}),Qr=await(isAsync(cs)?cs:Promise.resolve(cs));return handleResult(is,Qr)}refine($,ts){const is=cs=>typeof ts=="string"||typeof ts>"u"?{message:ts}:typeof ts=="function"?ts(cs):ts;return this._refinement((cs,Qr)=>{const ja=$(cs),Na=()=>Qr.addIssue({code:ZodIssueCode.custom,...is(cs)});return typeof Promise<"u"&&ja instanceof Promise?ja.then(Aa=>Aa?!0:(Na(),!1)):ja?!0:(Na(),!1)})}refinement($,ts){return this._refinement((is,cs)=>$(is)?!0:(cs.addIssue(typeof ts=="function"?ts(is,cs):ts),!1))}_refinement($){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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:ts=>this["~validate"](ts)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or($){return ZodUnion.create([this,$],this._def)}and($){return ZodIntersection.create(this,$,this._def)}transform($){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:$}})}default($){const ts=typeof $=="function"?$:()=>$;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:ts,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch($){const ts=typeof $=="function"?$:()=>$;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:ts,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe($){const ts=this.constructor;return new ts({...this._def,description:$})}pipe($){return ZodPipeline.create(this,$)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[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,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?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)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?: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])$/,ipv4CidrRegex=/^(?:(?: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])$/,ipv6Regex=/^(([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]))$/,ipv6CidrRegex=/^(([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])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\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])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(es){let $="[0-5]\\d";es.precision?$=`${$}\\.\\d{${es.precision}}`:es.precision==null&&($=`${$}(\\.\\d+)?`);const ts=es.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${ts}`}function timeRegex(es){return new RegExp(`^${timeRegexSource(es)}$`)}function datetimeRegex(es){let $=`${dateRegexSource}T${timeRegexSource(es)}`;const ts=[];return ts.push(es.local?"Z?":"Z"),es.offset&&ts.push("([+-]\\d{2}:?\\d{2})"),$=`${$}(${ts.join("|")})`,new RegExp(`^${$}$`)}function isValidIP(es,$){return!!(($==="v4"||!$)&&ipv4Regex.test(es)||($==="v6"||!$)&&ipv6Regex.test(es))}function isValidJWT(es,$){if(!jwtRegex.test(es))return!1;try{const[ts]=es.split(".");if(!ts)return!1;const is=ts.replace(/-/g,"+").replace(/_/g,"/").padEnd(ts.length+(4-ts.length%4)%4,"="),cs=JSON.parse(atob(is));return!(typeof cs!="object"||cs===null||"typ"in cs&&(cs==null?void 0:cs.typ)!=="JWT"||!cs.alg||$&&cs.alg!==$)}catch{return!1}}function isValidCidr(es,$){return!!(($==="v4"||!$)&&ipv4CidrRegex.test(es)||($==="v6"||!$)&&ipv6CidrRegex.test(es))}class ZodString extends ZodType{_parse($){if(this._def.coerce&&($.data=String($.data)),this._getType($)!==ZodParsedType.string){const Qr=this._getOrReturnCtx($);return addIssueToContext(Qr,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:Qr.parsedType}),INVALID}const is=new ParseStatus;let cs;for(const Qr of this._def.checks)if(Qr.kind==="min")$.data.length<Qr.value&&(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.too_small,minimum:Qr.value,type:"string",inclusive:!0,exact:!1,message:Qr.message}),is.dirty());else if(Qr.kind==="max")$.data.length>Qr.value&&(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.too_big,maximum:Qr.value,type:"string",inclusive:!0,exact:!1,message:Qr.message}),is.dirty());else if(Qr.kind==="length"){const ja=$.data.length>Qr.value,Na=$.data.length<Qr.value;(ja||Na)&&(cs=this._getOrReturnCtx($,cs),ja?addIssueToContext(cs,{code:ZodIssueCode.too_big,maximum:Qr.value,type:"string",inclusive:!0,exact:!0,message:Qr.message}):Na&&addIssueToContext(cs,{code:ZodIssueCode.too_small,minimum:Qr.value,type:"string",inclusive:!0,exact:!0,message:Qr.message}),is.dirty())}else if(Qr.kind==="email")emailRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"email",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty());else if(Qr.kind==="emoji")emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"emoji",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty());else if(Qr.kind==="uuid")uuidRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"uuid",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty());else if(Qr.kind==="nanoid")nanoidRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty());else if(Qr.kind==="cuid")cuidRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"cuid",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty());else if(Qr.kind==="cuid2")cuid2Regex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty());else if(Qr.kind==="ulid")ulidRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"ulid",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty());else if(Qr.kind==="url")try{new URL($.data)}catch{cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"url",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty()}else Qr.kind==="regex"?(Qr.regex.lastIndex=0,Qr.regex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"regex",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty())):Qr.kind==="trim"?$.data=$.data.trim():Qr.kind==="includes"?$.data.includes(Qr.value,Qr.position)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.invalid_string,validation:{includes:Qr.value,position:Qr.position},message:Qr.message}),is.dirty()):Qr.kind==="toLowerCase"?$.data=$.data.toLowerCase():Qr.kind==="toUpperCase"?$.data=$.data.toUpperCase():Qr.kind==="startsWith"?$.data.startsWith(Qr.value)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.invalid_string,validation:{startsWith:Qr.value},message:Qr.message}),is.dirty()):Qr.kind==="endsWith"?$.data.endsWith(Qr.value)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.invalid_string,validation:{endsWith:Qr.value},message:Qr.message}),is.dirty()):Qr.kind==="datetime"?datetimeRegex(Qr).test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.invalid_string,validation:"datetime",message:Qr.message}),is.dirty()):Qr.kind==="date"?dateRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.invalid_string,validation:"date",message:Qr.message}),is.dirty()):Qr.kind==="time"?timeRegex(Qr).test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.invalid_string,validation:"time",message:Qr.message}),is.dirty()):Qr.kind==="duration"?durationRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"duration",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty()):Qr.kind==="ip"?isValidIP($.data,Qr.version)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"ip",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty()):Qr.kind==="jwt"?isValidJWT($.data,Qr.alg)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"jwt",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty()):Qr.kind==="cidr"?isValidCidr($.data,Qr.version)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"cidr",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty()):Qr.kind==="base64"?base64Regex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"base64",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty()):Qr.kind==="base64url"?base64urlRegex.test($.data)||(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{validation:"base64url",code:ZodIssueCode.invalid_string,message:Qr.message}),is.dirty()):util.assertNever(Qr);return{status:is.value,value:$.data}}_regex($,ts,is){return this.refinement(cs=>$.test(cs),{validation:ts,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(is)})}_addCheck($){return new ZodString({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...errorUtil.errToObj($)})}url($){return this._addCheck({kind:"url",...errorUtil.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...errorUtil.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...errorUtil.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...errorUtil.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...errorUtil.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...errorUtil.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...errorUtil.errToObj($)})}base64($){return this._addCheck({kind:"base64",...errorUtil.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...errorUtil.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...errorUtil.errToObj($)})}ip($){return this._addCheck({kind:"ip",...errorUtil.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...errorUtil.errToObj($)})}datetime($){return typeof $=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$}):this._addCheck({kind:"datetime",precision:typeof($==null?void 0:$.precision)>"u"?null:$==null?void 0:$.precision,offset:($==null?void 0:$.offset)??!1,local:($==null?void 0:$.local)??!1,...errorUtil.errToObj($==null?void 0:$.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){return typeof $=="string"?this._addCheck({kind:"time",precision:null,message:$}):this._addCheck({kind:"time",precision:typeof($==null?void 0:$.precision)>"u"?null:$==null?void 0:$.precision,...errorUtil.errToObj($==null?void 0:$.message)})}duration($){return this._addCheck({kind:"duration",...errorUtil.errToObj($)})}regex($,ts){return this._addCheck({kind:"regex",regex:$,...errorUtil.errToObj(ts)})}includes($,ts){return this._addCheck({kind:"includes",value:$,position:ts==null?void 0:ts.position,...errorUtil.errToObj(ts==null?void 0:ts.message)})}startsWith($,ts){return this._addCheck({kind:"startsWith",value:$,...errorUtil.errToObj(ts)})}endsWith($,ts){return this._addCheck({kind:"endsWith",value:$,...errorUtil.errToObj(ts)})}min($,ts){return this._addCheck({kind:"min",value:$,...errorUtil.errToObj(ts)})}max($,ts){return this._addCheck({kind:"max",value:$,...errorUtil.errToObj(ts)})}length($,ts){return this._addCheck({kind:"length",value:$,...errorUtil.errToObj(ts)})}nonempty($){return this.min(1,errorUtil.errToObj($))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find($=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find($=>$.kind==="date")}get isTime(){return!!this._def.checks.find($=>$.kind==="time")}get isDuration(){return!!this._def.checks.find($=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find($=>$.kind==="email")}get isURL(){return!!this._def.checks.find($=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find($=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find($=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find($=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find($=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find($=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find($=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find($=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find($=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find($=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find($=>$.kind==="base64url")}get minLength(){let $=null;for(const ts of this._def.checks)ts.kind==="min"&&($===null||ts.value>$)&&($=ts.value);return $}get maxLength(){let $=null;for(const ts of this._def.checks)ts.kind==="max"&&($===null||ts.value<$)&&($=ts.value);return $}}ZodString.create=es=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:(es==null?void 0:es.coerce)??!1,...processCreateParams(es)});function floatSafeRemainder(es,$){const ts=(es.toString().split(".")[1]||"").length,is=($.toString().split(".")[1]||"").length,cs=ts>is?ts:is,Qr=Number.parseInt(es.toFixed(cs).replace(".","")),ja=Number.parseInt($.toFixed(cs).replace(".",""));return Qr%ja/10**cs}class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce&&($.data=Number($.data)),this._getType($)!==ZodParsedType.number){const Qr=this._getOrReturnCtx($);return addIssueToContext(Qr,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:Qr.parsedType}),INVALID}let is;const cs=new ParseStatus;for(const Qr of this._def.checks)Qr.kind==="int"?util.isInteger($.data)||(is=this._getOrReturnCtx($,is),addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:Qr.message}),cs.dirty()):Qr.kind==="min"?(Qr.inclusive?$.data<Qr.value:$.data<=Qr.value)&&(is=this._getOrReturnCtx($,is),addIssueToContext(is,{code:ZodIssueCode.too_small,minimum:Qr.value,type:"number",inclusive:Qr.inclusive,exact:!1,message:Qr.message}),cs.dirty()):Qr.kind==="max"?(Qr.inclusive?$.data>Qr.value:$.data>=Qr.value)&&(is=this._getOrReturnCtx($,is),addIssueToContext(is,{code:ZodIssueCode.too_big,maximum:Qr.value,type:"number",inclusive:Qr.inclusive,exact:!1,message:Qr.message}),cs.dirty()):Qr.kind==="multipleOf"?floatSafeRemainder($.data,Qr.value)!==0&&(is=this._getOrReturnCtx($,is),addIssueToContext(is,{code:ZodIssueCode.not_multiple_of,multipleOf:Qr.value,message:Qr.message}),cs.dirty()):Qr.kind==="finite"?Number.isFinite($.data)||(is=this._getOrReturnCtx($,is),addIssueToContext(is,{code:ZodIssueCode.not_finite,message:Qr.message}),cs.dirty()):util.assertNever(Qr);return{status:cs.value,value:$.data}}gte($,ts){return this.setLimit("min",$,!0,errorUtil.toString(ts))}gt($,ts){return this.setLimit("min",$,!1,errorUtil.toString(ts))}lte($,ts){return this.setLimit("max",$,!0,errorUtil.toString(ts))}lt($,ts){return this.setLimit("max",$,!1,errorUtil.toString(ts))}setLimit($,ts,is,cs){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:$,value:ts,inclusive:is,message:errorUtil.toString(cs)}]})}_addCheck($){return new ZodNumber({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:errorUtil.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString($)})}multipleOf($,ts){return this._addCheck({kind:"multipleOf",value:$,message:errorUtil.toString(ts)})}finite($){return this._addCheck({kind:"finite",message:errorUtil.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString($)})}get minValue(){let $=null;for(const ts of this._def.checks)ts.kind==="min"&&($===null||ts.value>$)&&($=ts.value);return $}get maxValue(){let $=null;for(const ts of this._def.checks)ts.kind==="max"&&($===null||ts.value<$)&&($=ts.value);return $}get isInt(){return!!this._def.checks.find($=>$.kind==="int"||$.kind==="multipleOf"&&util.isInteger($.value))}get isFinite(){let $=null,ts=null;for(const is of this._def.checks){if(is.kind==="finite"||is.kind==="int"||is.kind==="multipleOf")return!0;is.kind==="min"?(ts===null||is.value>ts)&&(ts=is.value):is.kind==="max"&&($===null||is.value<$)&&($=is.value)}return Number.isFinite(ts)&&Number.isFinite($)}}ZodNumber.create=es=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:(es==null?void 0:es.coerce)||!1,...processCreateParams(es)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==ZodParsedType.bigint)return this._getInvalidInput($);let is;const cs=new ParseStatus;for(const Qr of this._def.checks)Qr.kind==="min"?(Qr.inclusive?$.data<Qr.value:$.data<=Qr.value)&&(is=this._getOrReturnCtx($,is),addIssueToContext(is,{code:ZodIssueCode.too_small,type:"bigint",minimum:Qr.value,inclusive:Qr.inclusive,message:Qr.message}),cs.dirty()):Qr.kind==="max"?(Qr.inclusive?$.data>Qr.value:$.data>=Qr.value)&&(is=this._getOrReturnCtx($,is),addIssueToContext(is,{code:ZodIssueCode.too_big,type:"bigint",maximum:Qr.value,inclusive:Qr.inclusive,message:Qr.message}),cs.dirty()):Qr.kind==="multipleOf"?$.data%Qr.value!==BigInt(0)&&(is=this._getOrReturnCtx($,is),addIssueToContext(is,{code:ZodIssueCode.not_multiple_of,multipleOf:Qr.value,message:Qr.message}),cs.dirty()):util.assertNever(Qr);return{status:cs.value,value:$.data}}_getInvalidInput($){const ts=this._getOrReturnCtx($);return addIssueToContext(ts,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ts.parsedType}),INVALID}gte($,ts){return this.setLimit("min",$,!0,errorUtil.toString(ts))}gt($,ts){return this.setLimit("min",$,!1,errorUtil.toString(ts))}lte($,ts){return this.setLimit("max",$,!0,errorUtil.toString(ts))}lt($,ts){return this.setLimit("max",$,!1,errorUtil.toString(ts))}setLimit($,ts,is,cs){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:$,value:ts,inclusive:is,message:errorUtil.toString(cs)}]})}_addCheck($){return new ZodBigInt({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString($)})}multipleOf($,ts){return this._addCheck({kind:"multipleOf",value:$,message:errorUtil.toString(ts)})}get minValue(){let $=null;for(const ts of this._def.checks)ts.kind==="min"&&($===null||ts.value>$)&&($=ts.value);return $}get maxValue(){let $=null;for(const ts of this._def.checks)ts.kind==="max"&&($===null||ts.value<$)&&($=ts.value);return $}}ZodBigInt.create=es=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:(es==null?void 0:es.coerce)??!1,...processCreateParams(es)});class ZodBoolean extends ZodType{_parse($){if(this._def.coerce&&($.data=!!$.data),this._getType($)!==ZodParsedType.boolean){const is=this._getOrReturnCtx($);return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:is.parsedType}),INVALID}return OK($.data)}}ZodBoolean.create=es=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:(es==null?void 0:es.coerce)||!1,...processCreateParams(es)});class ZodDate extends ZodType{_parse($){if(this._def.coerce&&($.data=new Date($.data)),this._getType($)!==ZodParsedType.date){const Qr=this._getOrReturnCtx($);return addIssueToContext(Qr,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:Qr.parsedType}),INVALID}if(Number.isNaN($.data.getTime())){const Qr=this._getOrReturnCtx($);return addIssueToContext(Qr,{code:ZodIssueCode.invalid_date}),INVALID}const is=new ParseStatus;let cs;for(const Qr of this._def.checks)Qr.kind==="min"?$.data.getTime()<Qr.value&&(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.too_small,message:Qr.message,inclusive:!0,exact:!1,minimum:Qr.value,type:"date"}),is.dirty()):Qr.kind==="max"?$.data.getTime()>Qr.value&&(cs=this._getOrReturnCtx($,cs),addIssueToContext(cs,{code:ZodIssueCode.too_big,message:Qr.message,inclusive:!0,exact:!1,maximum:Qr.value,type:"date"}),is.dirty()):util.assertNever(Qr);return{status:is.value,value:new Date($.data.getTime())}}_addCheck($){return new ZodDate({...this._def,checks:[...this._def.checks,$]})}min($,ts){return this._addCheck({kind:"min",value:$.getTime(),message:errorUtil.toString(ts)})}max($,ts){return this._addCheck({kind:"max",value:$.getTime(),message:errorUtil.toString(ts)})}get minDate(){let $=null;for(const ts of this._def.checks)ts.kind==="min"&&($===null||ts.value>$)&&($=ts.value);return $!=null?new Date($):null}get maxDate(){let $=null;for(const ts of this._def.checks)ts.kind==="max"&&($===null||ts.value<$)&&($=ts.value);return $!=null?new Date($):null}}ZodDate.create=es=>new ZodDate({checks:[],coerce:(es==null?void 0:es.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(es)});class ZodSymbol extends ZodType{_parse($){if(this._getType($)!==ZodParsedType.symbol){const is=this._getOrReturnCtx($);return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:is.parsedType}),INVALID}return OK($.data)}}ZodSymbol.create=es=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(es)});class ZodUndefined extends ZodType{_parse($){if(this._getType($)!==ZodParsedType.undefined){const is=this._getOrReturnCtx($);return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:is.parsedType}),INVALID}return OK($.data)}}ZodUndefined.create=es=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(es)});class ZodNull extends ZodType{_parse($){if(this._getType($)!==ZodParsedType.null){const is=this._getOrReturnCtx($);return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:is.parsedType}),INVALID}return OK($.data)}}ZodNull.create=es=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(es)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse($){return OK($.data)}}ZodAny.create=es=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(es)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse($){return OK($.data)}}ZodUnknown.create=es=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(es)});class ZodNever extends ZodType{_parse($){const ts=this._getOrReturnCtx($);return addIssueToContext(ts,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ts.parsedType}),INVALID}}ZodNever.create=es=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(es)});class ZodVoid extends ZodType{_parse($){if(this._getType($)!==ZodParsedType.undefined){const is=this._getOrReturnCtx($);return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:is.parsedType}),INVALID}return OK($.data)}}ZodVoid.create=es=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(es)});class ZodArray extends ZodType{_parse($){const{ctx:ts,status:is}=this._processInputParams($),cs=this._def;if(ts.parsedType!==ZodParsedType.array)return addIssueToContext(ts,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ts.parsedType}),INVALID;if(cs.exactLength!==null){const ja=ts.data.length>cs.exactLength.value,Na=ts.data.length<cs.exactLength.value;(ja||Na)&&(addIssueToContext(ts,{code:ja?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:Na?cs.exactLength.value:void 0,maximum:ja?cs.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:cs.exactLength.message}),is.dirty())}if(cs.minLength!==null&&ts.data.length<cs.minLength.value&&(addIssueToContext(ts,{code:ZodIssueCode.too_small,minimum:cs.minLength.value,type:"array",inclusive:!0,exact:!1,message:cs.minLength.message}),is.dirty()),cs.maxLength!==null&&ts.data.length>cs.maxLength.value&&(addIssueToContext(ts,{code:ZodIssueCode.too_big,maximum:cs.maxLength.value,type:"array",inclusive:!0,exact:!1,message:cs.maxLength.message}),is.dirty()),ts.common.async)return Promise.all([...ts.data].map((ja,Na)=>cs.type._parseAsync(new ParseInputLazyPath(ts,ja,ts.path,Na)))).then(ja=>ParseStatus.mergeArray(is,ja));const Qr=[...ts.data].map((ja,Na)=>cs.type._parseSync(new ParseInputLazyPath(ts,ja,ts.path,Na)));return ParseStatus.mergeArray(is,Qr)}get element(){return this._def.type}min($,ts){return new ZodArray({...this._def,minLength:{value:$,message:errorUtil.toString(ts)}})}max($,ts){return new ZodArray({...this._def,maxLength:{value:$,message:errorUtil.toString(ts)}})}length($,ts){return new ZodArray({...this._def,exactLength:{value:$,message:errorUtil.toString(ts)}})}nonempty($){return this.min(1,$)}}ZodArray.create=(es,$)=>new ZodArray({type:es,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams($)});function deepPartialify(es){if(es instanceof ZodObject){const $={};for(const ts in es.shape){const is=es.shape[ts];$[ts]=ZodOptional.create(deepPartialify(is))}return new ZodObject({...es._def,shape:()=>$})}else return es instanceof ZodArray?new ZodArray({...es._def,type:deepPartialify(es.element)}):es instanceof ZodOptional?ZodOptional.create(deepPartialify(es.unwrap())):es instanceof ZodNullable?ZodNullable.create(deepPartialify(es.unwrap())):es instanceof ZodTuple?ZodTuple.create(es.items.map($=>deepPartialify($))):es}class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const $=this._def.shape(),ts=util.objectKeys($);return this._cached={shape:$,keys:ts},this._cached}_parse($){if(this._getType($)!==ZodParsedType.object){const Oa=this._getOrReturnCtx($);return addIssueToContext(Oa,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:Oa.parsedType}),INVALID}const{status:is,ctx:cs}=this._processInputParams($),{shape:Qr,keys:ja}=this._getCached(),Na=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip"))for(const Oa in cs.data)ja.includes(Oa)||Na.push(Oa);const Aa=[];for(const Oa of ja){const Ia=Qr[Oa],La=cs.data[Oa];Aa.push({key:{status:"valid",value:Oa},value:Ia._parse(new ParseInputLazyPath(cs,La,cs.path,Oa)),alwaysSet:Oa in cs.data})}if(this._def.catchall instanceof ZodNever){const Oa=this._def.unknownKeys;if(Oa==="passthrough")for(const Ia of Na)Aa.push({key:{status:"valid",value:Ia},value:{status:"valid",value:cs.data[Ia]}});else if(Oa==="strict")Na.length>0&&(addIssueToContext(cs,{code:ZodIssueCode.unrecognized_keys,keys:Na}),is.dirty());else if(Oa!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const Oa=this._def.catchall;for(const Ia of Na){const La=cs.data[Ia];Aa.push({key:{status:"valid",value:Ia},value:Oa._parse(new ParseInputLazyPath(cs,La,cs.path,Ia)),alwaysSet:Ia in cs.data})}}return cs.common.async?Promise.resolve().then(async()=>{const Oa=[];for(const Ia of Aa){const La=await Ia.key,Ba=await Ia.value;Oa.push({key:La,value:Ba,alwaysSet:Ia.alwaysSet})}return Oa}).then(Oa=>ParseStatus.mergeObjectSync(is,Oa)):ParseStatus.mergeObjectSync(is,Aa)}get shape(){return this._def.shape()}strict($){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(ts,is)=>{var Qr,ja;const cs=((ja=(Qr=this._def).errorMap)==null?void 0:ja.call(Qr,ts,is).message)??is.defaultError;return ts.code==="unrecognized_keys"?{message:errorUtil.errToObj($).message??cs}:{message:cs}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend($){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new ZodObject({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey($,ts){return this.augment({[$]:ts})}catchall($){return new ZodObject({...this._def,catchall:$})}pick($){const ts={};for(const is of util.objectKeys($))$[is]&&this.shape[is]&&(ts[is]=this.shape[is]);return new ZodObject({...this._def,shape:()=>ts})}omit($){const ts={};for(const is of util.objectKeys(this.shape))$[is]||(ts[is]=this.shape[is]);return new ZodObject({...this._def,shape:()=>ts})}deepPartial(){return deepPartialify(this)}partial($){const ts={};for(const is of util.objectKeys(this.shape)){const cs=this.shape[is];$&&!$[is]?ts[is]=cs:ts[is]=cs.optional()}return new ZodObject({...this._def,shape:()=>ts})}required($){const ts={};for(const is of util.objectKeys(this.shape))if($&&!$[is])ts[is]=this.shape[is];else{let Qr=this.shape[is];for(;Qr instanceof ZodOptional;)Qr=Qr._def.innerType;ts[is]=Qr}return new ZodObject({...this._def,shape:()=>ts})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(es,$)=>new ZodObject({shape:()=>es,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams($)});ZodObject.strictCreate=(es,$)=>new ZodObject({shape:()=>es,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams($)});ZodObject.lazycreate=(es,$)=>new ZodObject({shape:es,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams($)});class ZodUnion extends ZodType{_parse($){const{ctx:ts}=this._processInputParams($),is=this._def.options;function cs(Qr){for(const Na of Qr)if(Na.result.status==="valid")return Na.result;for(const Na of Qr)if(Na.result.status==="dirty")return ts.common.issues.push(...Na.ctx.common.issues),Na.result;const ja=Qr.map(Na=>new ZodError(Na.ctx.common.issues));return addIssueToContext(ts,{code:ZodIssueCode.invalid_union,unionErrors:ja}),INVALID}if(ts.common.async)return Promise.all(is.map(async Qr=>{const ja={...ts,common:{...ts.common,issues:[]},parent:null};return{result:await Qr._parseAsync({data:ts.data,path:ts.path,parent:ja}),ctx:ja}})).then(cs);{let Qr;const ja=[];for(const Aa of is){const Oa={...ts,common:{...ts.common,issues:[]},parent:null},Ia=Aa._parseSync({data:ts.data,path:ts.path,parent:Oa});if(Ia.status==="valid")return Ia;Ia.status==="dirty"&&!Qr&&(Qr={result:Ia,ctx:Oa}),Oa.common.issues.length&&ja.push(Oa.common.issues)}if(Qr)return ts.common.issues.push(...Qr.ctx.common.issues),Qr.result;const Na=ja.map(Aa=>new ZodError(Aa));return addIssueToContext(ts,{code:ZodIssueCode.invalid_union,unionErrors:Na}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(es,$)=>new ZodUnion({options:es,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams($)});function mergeValues(es,$){const ts=getParsedType(es),is=getParsedType($);if(es===$)return{valid:!0,data:es};if(ts===ZodParsedType.object&&is===ZodParsedType.object){const cs=util.objectKeys($),Qr=util.objectKeys(es).filter(Na=>cs.indexOf(Na)!==-1),ja={...es,...$};for(const Na of Qr){const Aa=mergeValues(es[Na],$[Na]);if(!Aa.valid)return{valid:!1};ja[Na]=Aa.data}return{valid:!0,data:ja}}else if(ts===ZodParsedType.array&&is===ZodParsedType.array){if(es.length!==$.length)return{valid:!1};const cs=[];for(let Qr=0;Qr<es.length;Qr++){const ja=es[Qr],Na=$[Qr],Aa=mergeValues(ja,Na);if(!Aa.valid)return{valid:!1};cs.push(Aa.data)}return{valid:!0,data:cs}}else return ts===ZodParsedType.date&&is===ZodParsedType.date&&+es==+$?{valid:!0,data:es}:{valid:!1}}class ZodIntersection extends ZodType{_parse($){const{status:ts,ctx:is}=this._processInputParams($),cs=(Qr,ja)=>{if(isAborted(Qr)||isAborted(ja))return INVALID;const Na=mergeValues(Qr.value,ja.value);return Na.valid?((isDirty(Qr)||isDirty(ja))&&ts.dirty(),{status:ts.value,value:Na.data}):(addIssueToContext(is,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return is.common.async?Promise.all([this._def.left._parseAsync({data:is.data,path:is.path,parent:is}),this._def.right._parseAsync({data:is.data,path:is.path,parent:is})]).then(([Qr,ja])=>cs(Qr,ja)):cs(this._def.left._parseSync({data:is.data,path:is.path,parent:is}),this._def.right._parseSync({data:is.data,path:is.path,parent:is}))}}ZodIntersection.create=(es,$,ts)=>new ZodIntersection({left:es,right:$,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(ts)});class ZodTuple extends ZodType{_parse($){const{status:ts,ctx:is}=this._processInputParams($);if(is.parsedType!==ZodParsedType.array)return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:is.parsedType}),INVALID;if(is.data.length<this._def.items.length)return addIssueToContext(is,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&is.data.length>this._def.items.length&&(addIssueToContext(is,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ts.dirty());const Qr=[...is.data].map((ja,Na)=>{const Aa=this._def.items[Na]||this._def.rest;return Aa?Aa._parse(new ParseInputLazyPath(is,ja,is.path,Na)):null}).filter(ja=>!!ja);return is.common.async?Promise.all(Qr).then(ja=>ParseStatus.mergeArray(ts,ja)):ParseStatus.mergeArray(ts,Qr)}get items(){return this._def.items}rest($){return new ZodTuple({...this._def,rest:$})}}ZodTuple.create=(es,$)=>{if(!Array.isArray(es))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:es,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams($)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){const{status:ts,ctx:is}=this._processInputParams($);if(is.parsedType!==ZodParsedType.object)return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:is.parsedType}),INVALID;const cs=[],Qr=this._def.keyType,ja=this._def.valueType;for(const Na in is.data)cs.push({key:Qr._parse(new ParseInputLazyPath(is,Na,is.path,Na)),value:ja._parse(new ParseInputLazyPath(is,is.data[Na],is.path,Na)),alwaysSet:Na in is.data});return is.common.async?ParseStatus.mergeObjectAsync(ts,cs):ParseStatus.mergeObjectSync(ts,cs)}get element(){return this._def.valueType}static create($,ts,is){return ts instanceof ZodType?new ZodRecord({keyType:$,valueType:ts,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(is)}):new ZodRecord({keyType:ZodString.create(),valueType:$,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(ts)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){const{status:ts,ctx:is}=this._processInputParams($);if(is.parsedType!==ZodParsedType.map)return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:is.parsedType}),INVALID;const cs=this._def.keyType,Qr=this._def.valueType,ja=[...is.data.entries()].map(([Na,Aa],Oa)=>({key:cs._parse(new ParseInputLazyPath(is,Na,is.path,[Oa,"key"])),value:Qr._parse(new ParseInputLazyPath(is,Aa,is.path,[Oa,"value"]))}));if(is.common.async){const Na=new Map;return Promise.resolve().then(async()=>{for(const Aa of ja){const Oa=await Aa.key,Ia=await Aa.value;if(Oa.status==="aborted"||Ia.status==="aborted")return INVALID;(Oa.status==="dirty"||Ia.status==="dirty")&&ts.dirty(),Na.set(Oa.value,Ia.value)}return{status:ts.value,value:Na}})}else{const Na=new Map;for(const Aa of ja){const Oa=Aa.key,Ia=Aa.value;if(Oa.status==="aborted"||Ia.status==="aborted")return INVALID;(Oa.status==="dirty"||Ia.status==="dirty")&&ts.dirty(),Na.set(Oa.value,Ia.value)}return{status:ts.value,value:Na}}}}ZodMap.create=(es,$,ts)=>new ZodMap({valueType:$,keyType:es,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(ts)});class ZodSet extends ZodType{_parse($){const{status:ts,ctx:is}=this._processInputParams($);if(is.parsedType!==ZodParsedType.set)return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:is.parsedType}),INVALID;const cs=this._def;cs.minSize!==null&&is.data.size<cs.minSize.value&&(addIssueToContext(is,{code:ZodIssueCode.too_small,minimum:cs.minSize.value,type:"set",inclusive:!0,exact:!1,message:cs.minSize.message}),ts.dirty()),cs.maxSize!==null&&is.data.size>cs.maxSize.value&&(addIssueToContext(is,{code:ZodIssueCode.too_big,maximum:cs.maxSize.value,type:"set",inclusive:!0,exact:!1,message:cs.maxSize.message}),ts.dirty());const Qr=this._def.valueType;function ja(Aa){const Oa=new Set;for(const Ia of Aa){if(Ia.status==="aborted")return INVALID;Ia.status==="dirty"&&ts.dirty(),Oa.add(Ia.value)}return{status:ts.value,value:Oa}}const Na=[...is.data.values()].map((Aa,Oa)=>Qr._parse(new ParseInputLazyPath(is,Aa,is.path,Oa)));return is.common.async?Promise.all(Na).then(Aa=>ja(Aa)):ja(Na)}min($,ts){return new ZodSet({...this._def,minSize:{value:$,message:errorUtil.toString(ts)}})}max($,ts){return new ZodSet({...this._def,maxSize:{value:$,message:errorUtil.toString(ts)}})}size($,ts){return this.min($,ts).max($,ts)}nonempty($){return this.min(1,$)}}ZodSet.create=(es,$)=>new ZodSet({valueType:es,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams($)});class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse($){const{ctx:ts}=this._processInputParams($);return this._def.getter()._parse({data:ts.data,path:ts.path,parent:ts})}}ZodLazy.create=(es,$)=>new ZodLazy({getter:es,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams($)});class ZodLiteral extends ZodType{_parse($){if($.data!==this._def.value){const ts=this._getOrReturnCtx($);return addIssueToContext(ts,{received:ts.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:$.data}}get value(){return this._def.value}}ZodLiteral.create=(es,$)=>new ZodLiteral({value:es,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams($)});function createZodEnum(es,$){return new ZodEnum({values:es,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams($)})}class ZodEnum extends ZodType{_parse($){if(typeof $.data!="string"){const ts=this._getOrReturnCtx($),is=this._def.values;return addIssueToContext(ts,{expected:util.joinValues(is),received:ts.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has($.data)){const ts=this._getOrReturnCtx($),is=this._def.values;return addIssueToContext(ts,{received:ts.data,code:ZodIssueCode.invalid_enum_value,options:is}),INVALID}return OK($.data)}get options(){return this._def.values}get enum(){const $={};for(const ts of this._def.values)$[ts]=ts;return $}get Values(){const $={};for(const ts of this._def.values)$[ts]=ts;return $}get Enum(){const $={};for(const ts of this._def.values)$[ts]=ts;return $}extract($,ts=this._def){return ZodEnum.create($,{...this._def,...ts})}exclude($,ts=this._def){return ZodEnum.create(this.options.filter(is=>!$.includes(is)),{...this._def,...ts})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse($){const ts=util.getValidEnumValues(this._def.values),is=this._getOrReturnCtx($);if(is.parsedType!==ZodParsedType.string&&is.parsedType!==ZodParsedType.number){const cs=util.objectValues(ts);return addIssueToContext(is,{expected:util.joinValues(cs),received:is.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util.getValidEnumValues(this._def.values))),!this._cache.has($.data)){const cs=util.objectValues(ts);return addIssueToContext(is,{received:is.data,code:ZodIssueCode.invalid_enum_value,options:cs}),INVALID}return OK($.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(es,$)=>new ZodNativeEnum({values:es,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams($)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse($){const{ctx:ts}=this._processInputParams($);if(ts.parsedType!==ZodParsedType.promise&&ts.common.async===!1)return addIssueToContext(ts,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ts.parsedType}),INVALID;const is=ts.parsedType===ZodParsedType.promise?ts.data:Promise.resolve(ts.data);return OK(is.then(cs=>this._def.type.parseAsync(cs,{path:ts.path,errorMap:ts.common.contextualErrorMap})))}}ZodPromise.create=(es,$)=>new ZodPromise({type:es,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams($)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){const{status:ts,ctx:is}=this._processInputParams($),cs=this._def.effect||null,Qr={addIssue:ja=>{addIssueToContext(is,ja),ja.fatal?ts.abort():ts.dirty()},get path(){return is.path}};if(Qr.addIssue=Qr.addIssue.bind(Qr),cs.type==="preprocess"){const ja=cs.transform(is.data,Qr);if(is.common.async)return Promise.resolve(ja).then(async Na=>{if(ts.value==="aborted")return INVALID;const Aa=await this._def.schema._parseAsync({data:Na,path:is.path,parent:is});return Aa.status==="aborted"?INVALID:Aa.status==="dirty"||ts.value==="dirty"?DIRTY(Aa.value):Aa});{if(ts.value==="aborted")return INVALID;const Na=this._def.schema._parseSync({data:ja,path:is.path,parent:is});return Na.status==="aborted"?INVALID:Na.status==="dirty"||ts.value==="dirty"?DIRTY(Na.value):Na}}if(cs.type==="refinement"){const ja=Na=>{const Aa=cs.refinement(Na,Qr);if(is.common.async)return Promise.resolve(Aa);if(Aa instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Na};if(is.common.async===!1){const Na=this._def.schema._parseSync({data:is.data,path:is.path,parent:is});return Na.status==="aborted"?INVALID:(Na.status==="dirty"&&ts.dirty(),ja(Na.value),{status:ts.value,value:Na.value})}else return this._def.schema._parseAsync({data:is.data,path:is.path,parent:is}).then(Na=>Na.status==="aborted"?INVALID:(Na.status==="dirty"&&ts.dirty(),ja(Na.value).then(()=>({status:ts.value,value:Na.value}))))}if(cs.type==="transform")if(is.common.async===!1){const ja=this._def.schema._parseSync({data:is.data,path:is.path,parent:is});if(!isValid(ja))return INVALID;const Na=cs.transform(ja.value,Qr);if(Na instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:ts.value,value:Na}}else return this._def.schema._parseAsync({data:is.data,path:is.path,parent:is}).then(ja=>isValid(ja)?Promise.resolve(cs.transform(ja.value,Qr)).then(Na=>({status:ts.value,value:Na})):INVALID);util.assertNever(cs)}}ZodEffects.create=(es,$,ts)=>new ZodEffects({schema:es,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:$,...processCreateParams(ts)});ZodEffects.createWithPreprocess=(es,$,ts)=>new ZodEffects({schema:$,effect:{type:"preprocess",transform:es},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(ts)});class ZodOptional extends ZodType{_parse($){return this._getType($)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse($)}unwrap(){return this._def.innerType}}ZodOptional.create=(es,$)=>new ZodOptional({innerType:es,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams($)});class ZodNullable extends ZodType{_parse($){return this._getType($)===ZodParsedType.null?OK(null):this._def.innerType._parse($)}unwrap(){return this._def.innerType}}ZodNullable.create=(es,$)=>new ZodNullable({innerType:es,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams($)});class ZodDefault extends ZodType{_parse($){const{ctx:ts}=this._processInputParams($);let is=ts.data;return ts.parsedType===ZodParsedType.undefined&&(is=this._def.defaultValue()),this._def.innerType._parse({data:is,path:ts.path,parent:ts})}removeDefault(){return this._def.innerType}}ZodDefault.create=(es,$)=>new ZodDefault({innerType:es,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof $.default=="function"?$.default:()=>$.default,...processCreateParams($)});class ZodCatch extends ZodType{_parse($){const{ctx:ts}=this._processInputParams($),is={...ts,common:{...ts.common,issues:[]}},cs=this._def.innerType._parse({data:is.data,path:is.path,parent:{...is}});return isAsync(cs)?cs.then(Qr=>({status:"valid",value:Qr.status==="valid"?Qr.value:this._def.catchValue({get error(){return new ZodError(is.common.issues)},input:is.data})})):{status:"valid",value:cs.status==="valid"?cs.value:this._def.catchValue({get error(){return new ZodError(is.common.issues)},input:is.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(es,$)=>new ZodCatch({innerType:es,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof $.catch=="function"?$.catch:()=>$.catch,...processCreateParams($)});class ZodNaN extends ZodType{_parse($){if(this._getType($)!==ZodParsedType.nan){const is=this._getOrReturnCtx($);return addIssueToContext(is,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:is.parsedType}),INVALID}return{status:"valid",value:$.data}}}ZodNaN.create=es=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(es)});class ZodBranded extends ZodType{_parse($){const{ctx:ts}=this._processInputParams($),is=ts.data;return this._def.type._parse({data:is,path:ts.path,parent:ts})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse($){const{status:ts,ctx:is}=this._processInputParams($);if(is.common.async)return(async()=>{const Qr=await this._def.in._parseAsync({data:is.data,path:is.path,parent:is});return Qr.status==="aborted"?INVALID:Qr.status==="dirty"?(ts.dirty(),DIRTY(Qr.value)):this._def.out._parseAsync({data:Qr.value,path:is.path,parent:is})})();{const cs=this._def.in._parseSync({data:is.data,path:is.path,parent:is});return cs.status==="aborted"?INVALID:cs.status==="dirty"?(ts.dirty(),{status:"dirty",value:cs.value}):this._def.out._parseSync({data:cs.value,path:is.path,parent:is})}}static create($,ts){return new ZodPipeline({in:$,out:ts,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse($){const ts=this._def.innerType._parse($),is=cs=>(isValid(cs)&&(cs.value=Object.freeze(cs.value)),cs);return isAsync(ts)?ts.then(cs=>is(cs)):is(ts)}unwrap(){return this._def.innerType}}ZodReadonly.create=(es,$)=>new ZodReadonly({innerType:es,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams($)});var ZodFirstPartyTypeKind;(function(es){es.ZodString="ZodString",es.ZodNumber="ZodNumber",es.ZodNaN="ZodNaN",es.ZodBigInt="ZodBigInt",es.ZodBoolean="ZodBoolean",es.ZodDate="ZodDate",es.ZodSymbol="ZodSymbol",es.ZodUndefined="ZodUndefined",es.ZodNull="ZodNull",es.ZodAny="ZodAny",es.ZodUnknown="ZodUnknown",es.ZodNever="ZodNever",es.ZodVoid="ZodVoid",es.ZodArray="ZodArray",es.ZodObject="ZodObject",es.ZodUnion="ZodUnion",es.ZodDiscriminatedUnion="ZodDiscriminatedUnion",es.ZodIntersection="ZodIntersection",es.ZodTuple="ZodTuple",es.ZodRecord="ZodRecord",es.ZodMap="ZodMap",es.ZodSet="ZodSet",es.ZodFunction="ZodFunction",es.ZodLazy="ZodLazy",es.ZodLiteral="ZodLiteral",es.ZodEnum="ZodEnum",es.ZodEffects="ZodEffects",es.ZodNativeEnum="ZodNativeEnum",es.ZodOptional="ZodOptional",es.ZodNullable="ZodNullable",es.ZodDefault="ZodDefault",es.ZodCatch="ZodCatch",es.ZodPromise="ZodPromise",es.ZodBranded="ZodBranded",es.ZodPipeline="ZodPipeline",es.ZodReadonly="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,numberType=ZodNumber.create,booleanType=ZodBoolean.create,unknownType=ZodUnknown.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create;ZodUnion.create;ZodIntersection.create;ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create;ZodPromise.create;ZodOptional.create;ZodNullable.create;const INSTRUCTION_SCOPES=["org","team","project","personal"];objectType({name:stringType().min(1),description:stringType().min(1),type:literalType("instruction").default("instruction"),scope:enumType(INSTRUCTION_SCOPES),version:stringType().min(1),tags:arrayType(stringType()).optional(),compatibility:arrayType(stringType()).optional(),slots:recordType(stringType(),stringType()).optional(),metadata:recordType(stringType(),unknownType()).optional()});objectType({name:stringType().min(1),description:stringType().min(1),type:literalType("prompt"),version:stringType().min(1),tags:arrayType(stringType()).optional(),variables:arrayType(stringType()).optional(),metadata:recordType(stringType(),unknownType()).optional()});const __viteBrowserExternal={},__viteBrowserExternal$1=Object.freeze(Object.defineProperty({__proto__:null,default:__viteBrowserExternal},Symbol.toStringTag,{value:"Module"})),require$$0=getAugmentedNamespace(__viteBrowserExternal$1);var kindOf,hasRequiredKindOf;function requireKindOf(){if(hasRequiredKindOf)return kindOf;hasRequiredKindOf=1;var es=Object.prototype.toString;kindOf=function(La){if(La===void 0)return"undefined";if(La===null)return"null";var Ba=typeof La;if(Ba==="boolean")return"boolean";if(Ba==="string")return"string";if(Ba==="number")return"number";if(Ba==="symbol")return"symbol";if(Ba==="function")return ja(La)?"generatorfunction":"function";if(ts(La))return"array";if(Oa(La))return"buffer";if(Aa(La))return"arguments";if(cs(La))return"date";if(is(La))return"error";if(Qr(La))return"regexp";switch($(La)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(Na(La))return"generator";switch(Ba=es.call(La),Ba){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return Ba.slice(8,-1).toLowerCase().replace(/\s/g,"")};function $(Ia){return typeof Ia.constructor=="function"?Ia.constructor.name:null}function ts(Ia){return Array.isArray?Array.isArray(Ia):Ia instanceof Array}function is(Ia){return Ia instanceof Error||typeof Ia.message=="string"&&Ia.constructor&&typeof Ia.constructor.stackTraceLimit=="number"}function cs(Ia){return Ia instanceof Date?!0:typeof Ia.toDateString=="function"&&typeof Ia.getDate=="function"&&typeof Ia.setDate=="function"}function Qr(Ia){return Ia instanceof RegExp?!0:typeof Ia.flags=="string"&&typeof Ia.ignoreCase=="boolean"&&typeof Ia.multiline=="boolean"&&typeof Ia.global=="boolean"}function ja(Ia,La){return $(Ia)==="GeneratorFunction"}function Na(Ia){return typeof Ia.throw=="function"&&typeof Ia.return=="function"&&typeof Ia.next=="function"}function Aa(Ia){try{if(typeof Ia.length=="number"&&typeof Ia.callee=="function")return!0}catch(La){if(La.message.indexOf("callee")!==-1)return!0}return!1}function Oa(Ia){return Ia.constructor&&typeof Ia.constructor.isBuffer=="function"?Ia.constructor.isBuffer(Ia):!1}return kindOf}/*!
|
|
70
|
+
* is-extendable <https://github.com/jonschlinkert/is-extendable>
|
|
71
|
+
*
|
|
72
|
+
* Copyright (c) 2015, Jon Schlinkert.
|
|
73
|
+
* Licensed under the MIT License.
|
|
74
|
+
*/var isExtendable,hasRequiredIsExtendable;function requireIsExtendable(){return hasRequiredIsExtendable||(hasRequiredIsExtendable=1,isExtendable=function($){return typeof $<"u"&&$!==null&&(typeof $=="object"||typeof $=="function")}),isExtendable}var extendShallow,hasRequiredExtendShallow;function requireExtendShallow(){if(hasRequiredExtendShallow)return extendShallow;hasRequiredExtendShallow=1;var es=requireIsExtendable();extendShallow=function(cs){es(cs)||(cs={});for(var Qr=arguments.length,ja=1;ja<Qr;ja++){var Na=arguments[ja];es(Na)&&$(cs,Na)}return cs};function $(is,cs){for(var Qr in cs)ts(cs,Qr)&&(is[Qr]=cs[Qr])}function ts(is,cs){return Object.prototype.hasOwnProperty.call(is,cs)}return extendShallow}var sectionMatter,hasRequiredSectionMatter;function requireSectionMatter(){if(hasRequiredSectionMatter)return sectionMatter;hasRequiredSectionMatter=1;var es=requireKindOf(),$=requireExtendShallow();sectionMatter=function(Aa,Oa){typeof Oa=="function"&&(Oa={parse:Oa});var Ia=is(Aa),La={section_delimiter:"---",parse:ja},Ba=$({},La,Oa),Ma=Ba.section_delimiter,qa=Ia.content.split(/\r?\n/),Fa=null,Ha=Qr(),Ka=[],Ga=[];function Va(cl){Ia.content=cl,Fa=[],Ka=[]}function Ja(cl){Ga.length&&(Ha.key=cs(Ga[0],Ma),Ha.content=cl,Ba.parse(Ha,Fa),Fa.push(Ha),Ha=Qr(),Ka=[],Ga=[])}for(var Ya=0;Ya<qa.length;Ya++){var el=qa[Ya],tl=Ga.length,rl=el.trim();if(ts(rl,Ma)){if(rl.length===3&&Ya!==0){if(tl===0||tl===2){Ka.push(el);continue}Ga.push(rl),Ha.data=Ka.join(`
|
|
75
|
+
`),Ka=[];continue}Fa===null&&Va(Ka.join(`
|
|
76
|
+
`)),tl===2&&Ja(Ka.join(`
|
|
77
|
+
`)),Ga.push(rl);continue}Ka.push(el)}return Fa===null?Va(Ka.join(`
|
|
78
|
+
`)):Ja(Ka.join(`
|
|
79
|
+
`)),Ia.sections=Fa,Ia};function ts(Aa,Oa){return!(Aa.slice(0,Oa.length)!==Oa||Aa.charAt(Oa.length+1)===Oa.slice(-1))}function is(Aa){if(es(Aa)!=="object"&&(Aa={content:Aa}),typeof Aa.content!="string"&&!Na(Aa.content))throw new TypeError("expected a buffer or string");return Aa.content=Aa.content.toString(),Aa.sections=[],Aa}function cs(Aa,Oa){return Aa?Aa.slice(Oa.length).trim():""}function Qr(){return{key:"",data:"",content:""}}function ja(Aa){return Aa}function Na(Aa){return Aa&&Aa.constructor&&typeof Aa.constructor.isBuffer=="function"?Aa.constructor.isBuffer(Aa):!1}return sectionMatter}var engines={exports:{}},jsYaml$1={},loader={},common={},hasRequiredCommon;function requireCommon(){if(hasRequiredCommon)return common;hasRequiredCommon=1;function es(ja){return typeof ja>"u"||ja===null}function $(ja){return typeof ja=="object"&&ja!==null}function ts(ja){return Array.isArray(ja)?ja:es(ja)?[]:[ja]}function is(ja,Na){var Aa,Oa,Ia,La;if(Na)for(La=Object.keys(Na),Aa=0,Oa=La.length;Aa<Oa;Aa+=1)Ia=La[Aa],ja[Ia]=Na[Ia];return ja}function cs(ja,Na){var Aa="",Oa;for(Oa=0;Oa<Na;Oa+=1)Aa+=ja;return Aa}function Qr(ja){return ja===0&&Number.NEGATIVE_INFINITY===1/ja}return common.isNothing=es,common.isObject=$,common.toArray=ts,common.repeat=cs,common.isNegativeZero=Qr,common.extend=is,common}var exception,hasRequiredException;function requireException(){if(hasRequiredException)return exception;hasRequiredException=1;function es($,ts){Error.call(this),this.name="YAMLException",this.reason=$,this.mark=ts,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return es.prototype=Object.create(Error.prototype),es.prototype.constructor=es,es.prototype.toString=function(ts){var is=this.name+": ";return is+=this.reason||"(unknown reason)",!ts&&this.mark&&(is+=" "+this.mark.toString()),is},exception=es,exception}var mark,hasRequiredMark;function requireMark(){if(hasRequiredMark)return mark;hasRequiredMark=1;var es=requireCommon();function $(ts,is,cs,Qr,ja){this.name=ts,this.buffer=is,this.position=cs,this.line=Qr,this.column=ja}return $.prototype.getSnippet=function(is,cs){var Qr,ja,Na,Aa,Oa;if(!this.buffer)return null;for(is=is||4,cs=cs||75,Qr="",ja=this.position;ja>0&&`\0\r
|
|
80
|
+
\u2028\u2029`.indexOf(this.buffer.charAt(ja-1))===-1;)if(ja-=1,this.position-ja>cs/2-1){Qr=" ... ",ja+=5;break}for(Na="",Aa=this.position;Aa<this.buffer.length&&`\0\r
|
|
81
|
+
\u2028\u2029`.indexOf(this.buffer.charAt(Aa))===-1;)if(Aa+=1,Aa-this.position>cs/2-1){Na=" ... ",Aa-=5;break}return Oa=this.buffer.slice(ja,Aa),es.repeat(" ",is)+Qr+Oa+Na+`
|
|
82
|
+
`+es.repeat(" ",is+this.position-ja+Qr.length)+"^"},$.prototype.toString=function(is){var cs,Qr="";return this.name&&(Qr+='in "'+this.name+'" '),Qr+="at line "+(this.line+1)+", column "+(this.column+1),is||(cs=this.getSnippet(),cs&&(Qr+=`:
|
|
83
|
+
`+cs)),Qr},mark=$,mark}var type,hasRequiredType;function requireType(){if(hasRequiredType)return type;hasRequiredType=1;var es=requireException(),$=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],ts=["scalar","sequence","mapping"];function is(Qr){var ja={};return Qr!==null&&Object.keys(Qr).forEach(function(Na){Qr[Na].forEach(function(Aa){ja[String(Aa)]=Na})}),ja}function cs(Qr,ja){if(ja=ja||{},Object.keys(ja).forEach(function(Na){if($.indexOf(Na)===-1)throw new es('Unknown option "'+Na+'" is met in definition of "'+Qr+'" YAML type.')}),this.tag=Qr,this.kind=ja.kind||null,this.resolve=ja.resolve||function(){return!0},this.construct=ja.construct||function(Na){return Na},this.instanceOf=ja.instanceOf||null,this.predicate=ja.predicate||null,this.represent=ja.represent||null,this.defaultStyle=ja.defaultStyle||null,this.styleAliases=is(ja.styleAliases||null),ts.indexOf(this.kind)===-1)throw new es('Unknown kind "'+this.kind+'" is specified for "'+Qr+'" YAML type.')}return type=cs,type}var schema,hasRequiredSchema;function requireSchema(){if(hasRequiredSchema)return schema;hasRequiredSchema=1;var es=requireCommon(),$=requireException(),ts=requireType();function is(ja,Na,Aa){var Oa=[];return ja.include.forEach(function(Ia){Aa=is(Ia,Na,Aa)}),ja[Na].forEach(function(Ia){Aa.forEach(function(La,Ba){La.tag===Ia.tag&&La.kind===Ia.kind&&Oa.push(Ba)}),Aa.push(Ia)}),Aa.filter(function(Ia,La){return Oa.indexOf(La)===-1})}function cs(){var ja={scalar:{},sequence:{},mapping:{},fallback:{}},Na,Aa;function Oa(Ia){ja[Ia.kind][Ia.tag]=ja.fallback[Ia.tag]=Ia}for(Na=0,Aa=arguments.length;Na<Aa;Na+=1)arguments[Na].forEach(Oa);return ja}function Qr(ja){this.include=ja.include||[],this.implicit=ja.implicit||[],this.explicit=ja.explicit||[],this.implicit.forEach(function(Na){if(Na.loadKind&&Na.loadKind!=="scalar")throw new $("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=is(this,"implicit",[]),this.compiledExplicit=is(this,"explicit",[]),this.compiledTypeMap=cs(this.compiledImplicit,this.compiledExplicit)}return Qr.DEFAULT=null,Qr.create=function(){var Na,Aa;switch(arguments.length){case 1:Na=Qr.DEFAULT,Aa=arguments[0];break;case 2:Na=arguments[0],Aa=arguments[1];break;default:throw new $("Wrong number of arguments for Schema.create function")}if(Na=es.toArray(Na),Aa=es.toArray(Aa),!Na.every(function(Oa){return Oa instanceof Qr}))throw new $("Specified list of super schemas (or a single Schema object) contains a non-Schema object.");if(!Aa.every(function(Oa){return Oa instanceof ts}))throw new $("Specified list of YAML types (or a single Type object) contains a non-Type object.");return new Qr({include:Na,explicit:Aa})},schema=Qr,schema}var str,hasRequiredStr;function requireStr(){if(hasRequiredStr)return str;hasRequiredStr=1;var es=requireType();return str=new es("tag:yaml.org,2002:str",{kind:"scalar",construct:function($){return $!==null?$:""}}),str}var seq,hasRequiredSeq;function requireSeq(){if(hasRequiredSeq)return seq;hasRequiredSeq=1;var es=requireType();return seq=new es("tag:yaml.org,2002:seq",{kind:"sequence",construct:function($){return $!==null?$:[]}}),seq}var map,hasRequiredMap;function requireMap(){if(hasRequiredMap)return map;hasRequiredMap=1;var es=requireType();return map=new es("tag:yaml.org,2002:map",{kind:"mapping",construct:function($){return $!==null?$:{}}}),map}var failsafe,hasRequiredFailsafe;function requireFailsafe(){if(hasRequiredFailsafe)return failsafe;hasRequiredFailsafe=1;var es=requireSchema();return failsafe=new es({explicit:[requireStr(),requireSeq(),requireMap()]}),failsafe}var _null,hasRequired_null;function require_null(){if(hasRequired_null)return _null;hasRequired_null=1;var es=requireType();function $(cs){if(cs===null)return!0;var Qr=cs.length;return Qr===1&&cs==="~"||Qr===4&&(cs==="null"||cs==="Null"||cs==="NULL")}function ts(){return null}function is(cs){return cs===null}return _null=new es("tag:yaml.org,2002:null",{kind:"scalar",resolve:$,construct:ts,predicate:is,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"}),_null}var bool,hasRequiredBool;function requireBool(){if(hasRequiredBool)return bool;hasRequiredBool=1;var es=requireType();function $(cs){if(cs===null)return!1;var Qr=cs.length;return Qr===4&&(cs==="true"||cs==="True"||cs==="TRUE")||Qr===5&&(cs==="false"||cs==="False"||cs==="FALSE")}function ts(cs){return cs==="true"||cs==="True"||cs==="TRUE"}function is(cs){return Object.prototype.toString.call(cs)==="[object Boolean]"}return bool=new es("tag:yaml.org,2002:bool",{kind:"scalar",resolve:$,construct:ts,predicate:is,represent:{lowercase:function(cs){return cs?"true":"false"},uppercase:function(cs){return cs?"TRUE":"FALSE"},camelcase:function(cs){return cs?"True":"False"}},defaultStyle:"lowercase"}),bool}var int,hasRequiredInt;function requireInt(){if(hasRequiredInt)return int;hasRequiredInt=1;var es=requireCommon(),$=requireType();function ts(Aa){return 48<=Aa&&Aa<=57||65<=Aa&&Aa<=70||97<=Aa&&Aa<=102}function is(Aa){return 48<=Aa&&Aa<=55}function cs(Aa){return 48<=Aa&&Aa<=57}function Qr(Aa){if(Aa===null)return!1;var Oa=Aa.length,Ia=0,La=!1,Ba;if(!Oa)return!1;if(Ba=Aa[Ia],(Ba==="-"||Ba==="+")&&(Ba=Aa[++Ia]),Ba==="0"){if(Ia+1===Oa)return!0;if(Ba=Aa[++Ia],Ba==="b"){for(Ia++;Ia<Oa;Ia++)if(Ba=Aa[Ia],Ba!=="_"){if(Ba!=="0"&&Ba!=="1")return!1;La=!0}return La&&Ba!=="_"}if(Ba==="x"){for(Ia++;Ia<Oa;Ia++)if(Ba=Aa[Ia],Ba!=="_"){if(!ts(Aa.charCodeAt(Ia)))return!1;La=!0}return La&&Ba!=="_"}for(;Ia<Oa;Ia++)if(Ba=Aa[Ia],Ba!=="_"){if(!is(Aa.charCodeAt(Ia)))return!1;La=!0}return La&&Ba!=="_"}if(Ba==="_")return!1;for(;Ia<Oa;Ia++)if(Ba=Aa[Ia],Ba!=="_"){if(Ba===":")break;if(!cs(Aa.charCodeAt(Ia)))return!1;La=!0}return!La||Ba==="_"?!1:Ba!==":"?!0:/^(:[0-5]?[0-9])+$/.test(Aa.slice(Ia))}function ja(Aa){var Oa=Aa,Ia=1,La,Ba,Ma=[];return Oa.indexOf("_")!==-1&&(Oa=Oa.replace(/_/g,"")),La=Oa[0],(La==="-"||La==="+")&&(La==="-"&&(Ia=-1),Oa=Oa.slice(1),La=Oa[0]),Oa==="0"?0:La==="0"?Oa[1]==="b"?Ia*parseInt(Oa.slice(2),2):Oa[1]==="x"?Ia*parseInt(Oa,16):Ia*parseInt(Oa,8):Oa.indexOf(":")!==-1?(Oa.split(":").forEach(function(qa){Ma.unshift(parseInt(qa,10))}),Oa=0,Ba=1,Ma.forEach(function(qa){Oa+=qa*Ba,Ba*=60}),Ia*Oa):Ia*parseInt(Oa,10)}function Na(Aa){return Object.prototype.toString.call(Aa)==="[object Number]"&&Aa%1===0&&!es.isNegativeZero(Aa)}return int=new $("tag:yaml.org,2002:int",{kind:"scalar",resolve:Qr,construct:ja,predicate:Na,represent:{binary:function(Aa){return Aa>=0?"0b"+Aa.toString(2):"-0b"+Aa.toString(2).slice(1)},octal:function(Aa){return Aa>=0?"0"+Aa.toString(8):"-0"+Aa.toString(8).slice(1)},decimal:function(Aa){return Aa.toString(10)},hexadecimal:function(Aa){return Aa>=0?"0x"+Aa.toString(16).toUpperCase():"-0x"+Aa.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),int}var float,hasRequiredFloat;function requireFloat(){if(hasRequiredFloat)return float;hasRequiredFloat=1;var es=requireCommon(),$=requireType(),ts=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function is(Aa){return!(Aa===null||!ts.test(Aa)||Aa[Aa.length-1]==="_")}function cs(Aa){var Oa,Ia,La,Ba;return Oa=Aa.replace(/_/g,"").toLowerCase(),Ia=Oa[0]==="-"?-1:1,Ba=[],"+-".indexOf(Oa[0])>=0&&(Oa=Oa.slice(1)),Oa===".inf"?Ia===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:Oa===".nan"?NaN:Oa.indexOf(":")>=0?(Oa.split(":").forEach(function(Ma){Ba.unshift(parseFloat(Ma,10))}),Oa=0,La=1,Ba.forEach(function(Ma){Oa+=Ma*La,La*=60}),Ia*Oa):Ia*parseFloat(Oa,10)}var Qr=/^[-+]?[0-9]+e/;function ja(Aa,Oa){var Ia;if(isNaN(Aa))switch(Oa){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===Aa)switch(Oa){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===Aa)switch(Oa){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(es.isNegativeZero(Aa))return"-0.0";return Ia=Aa.toString(10),Qr.test(Ia)?Ia.replace("e",".e"):Ia}function Na(Aa){return Object.prototype.toString.call(Aa)==="[object Number]"&&(Aa%1!==0||es.isNegativeZero(Aa))}return float=new $("tag:yaml.org,2002:float",{kind:"scalar",resolve:is,construct:cs,predicate:Na,represent:ja,defaultStyle:"lowercase"}),float}var json,hasRequiredJson;function requireJson(){if(hasRequiredJson)return json;hasRequiredJson=1;var es=requireSchema();return json=new es({include:[requireFailsafe()],implicit:[require_null(),requireBool(),requireInt(),requireFloat()]}),json}var core,hasRequiredCore;function requireCore(){if(hasRequiredCore)return core;hasRequiredCore=1;var es=requireSchema();return core=new es({include:[requireJson()]}),core}var timestamp,hasRequiredTimestamp;function requireTimestamp(){if(hasRequiredTimestamp)return timestamp;hasRequiredTimestamp=1;var es=requireType(),$=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),ts=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function is(ja){return ja===null?!1:$.exec(ja)!==null||ts.exec(ja)!==null}function cs(ja){var Na,Aa,Oa,Ia,La,Ba,Ma,qa=0,Fa=null,Ha,Ka,Ga;if(Na=$.exec(ja),Na===null&&(Na=ts.exec(ja)),Na===null)throw new Error("Date resolve error");if(Aa=+Na[1],Oa=+Na[2]-1,Ia=+Na[3],!Na[4])return new Date(Date.UTC(Aa,Oa,Ia));if(La=+Na[4],Ba=+Na[5],Ma=+Na[6],Na[7]){for(qa=Na[7].slice(0,3);qa.length<3;)qa+="0";qa=+qa}return Na[9]&&(Ha=+Na[10],Ka=+(Na[11]||0),Fa=(Ha*60+Ka)*6e4,Na[9]==="-"&&(Fa=-Fa)),Ga=new Date(Date.UTC(Aa,Oa,Ia,La,Ba,Ma,qa)),Fa&&Ga.setTime(Ga.getTime()-Fa),Ga}function Qr(ja){return ja.toISOString()}return timestamp=new es("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:is,construct:cs,instanceOf:Date,represent:Qr}),timestamp}var merge,hasRequiredMerge;function requireMerge(){if(hasRequiredMerge)return merge;hasRequiredMerge=1;var es=requireType();function $(ts){return ts==="<<"||ts===null}return merge=new es("tag:yaml.org,2002:merge",{kind:"scalar",resolve:$}),merge}function commonjsRequire(es){throw new Error('Could not dynamically require "'+es+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var binary,hasRequiredBinary;function requireBinary(){if(hasRequiredBinary)return binary;hasRequiredBinary=1;var es;try{var $=commonjsRequire;es=$("buffer").Buffer}catch{}var ts=requireType(),is=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
84
|
+
\r`;function cs(Aa){if(Aa===null)return!1;var Oa,Ia,La=0,Ba=Aa.length,Ma=is;for(Ia=0;Ia<Ba;Ia++)if(Oa=Ma.indexOf(Aa.charAt(Ia)),!(Oa>64)){if(Oa<0)return!1;La+=6}return La%8===0}function Qr(Aa){var Oa,Ia,La=Aa.replace(/[\r\n=]/g,""),Ba=La.length,Ma=is,qa=0,Fa=[];for(Oa=0;Oa<Ba;Oa++)Oa%4===0&&Oa&&(Fa.push(qa>>16&255),Fa.push(qa>>8&255),Fa.push(qa&255)),qa=qa<<6|Ma.indexOf(La.charAt(Oa));return Ia=Ba%4*6,Ia===0?(Fa.push(qa>>16&255),Fa.push(qa>>8&255),Fa.push(qa&255)):Ia===18?(Fa.push(qa>>10&255),Fa.push(qa>>2&255)):Ia===12&&Fa.push(qa>>4&255),es?es.from?es.from(Fa):new es(Fa):Fa}function ja(Aa){var Oa="",Ia=0,La,Ba,Ma=Aa.length,qa=is;for(La=0;La<Ma;La++)La%3===0&&La&&(Oa+=qa[Ia>>18&63],Oa+=qa[Ia>>12&63],Oa+=qa[Ia>>6&63],Oa+=qa[Ia&63]),Ia=(Ia<<8)+Aa[La];return Ba=Ma%3,Ba===0?(Oa+=qa[Ia>>18&63],Oa+=qa[Ia>>12&63],Oa+=qa[Ia>>6&63],Oa+=qa[Ia&63]):Ba===2?(Oa+=qa[Ia>>10&63],Oa+=qa[Ia>>4&63],Oa+=qa[Ia<<2&63],Oa+=qa[64]):Ba===1&&(Oa+=qa[Ia>>2&63],Oa+=qa[Ia<<4&63],Oa+=qa[64],Oa+=qa[64]),Oa}function Na(Aa){return es&&es.isBuffer(Aa)}return binary=new ts("tag:yaml.org,2002:binary",{kind:"scalar",resolve:cs,construct:Qr,predicate:Na,represent:ja}),binary}var omap,hasRequiredOmap;function requireOmap(){if(hasRequiredOmap)return omap;hasRequiredOmap=1;var es=requireType(),$=Object.prototype.hasOwnProperty,ts=Object.prototype.toString;function is(Qr){if(Qr===null)return!0;var ja=[],Na,Aa,Oa,Ia,La,Ba=Qr;for(Na=0,Aa=Ba.length;Na<Aa;Na+=1){if(Oa=Ba[Na],La=!1,ts.call(Oa)!=="[object Object]")return!1;for(Ia in Oa)if($.call(Oa,Ia))if(!La)La=!0;else return!1;if(!La)return!1;if(ja.indexOf(Ia)===-1)ja.push(Ia);else return!1}return!0}function cs(Qr){return Qr!==null?Qr:[]}return omap=new es("tag:yaml.org,2002:omap",{kind:"sequence",resolve:is,construct:cs}),omap}var pairs,hasRequiredPairs;function requirePairs(){if(hasRequiredPairs)return pairs;hasRequiredPairs=1;var es=requireType(),$=Object.prototype.toString;function ts(cs){if(cs===null)return!0;var Qr,ja,Na,Aa,Oa,Ia=cs;for(Oa=new Array(Ia.length),Qr=0,ja=Ia.length;Qr<ja;Qr+=1){if(Na=Ia[Qr],$.call(Na)!=="[object Object]"||(Aa=Object.keys(Na),Aa.length!==1))return!1;Oa[Qr]=[Aa[0],Na[Aa[0]]]}return!0}function is(cs){if(cs===null)return[];var Qr,ja,Na,Aa,Oa,Ia=cs;for(Oa=new Array(Ia.length),Qr=0,ja=Ia.length;Qr<ja;Qr+=1)Na=Ia[Qr],Aa=Object.keys(Na),Oa[Qr]=[Aa[0],Na[Aa[0]]];return Oa}return pairs=new es("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:ts,construct:is}),pairs}var set,hasRequiredSet;function requireSet(){if(hasRequiredSet)return set;hasRequiredSet=1;var es=requireType(),$=Object.prototype.hasOwnProperty;function ts(cs){if(cs===null)return!0;var Qr,ja=cs;for(Qr in ja)if($.call(ja,Qr)&&ja[Qr]!==null)return!1;return!0}function is(cs){return cs!==null?cs:{}}return set=new es("tag:yaml.org,2002:set",{kind:"mapping",resolve:ts,construct:is}),set}var default_safe,hasRequiredDefault_safe;function requireDefault_safe(){if(hasRequiredDefault_safe)return default_safe;hasRequiredDefault_safe=1;var es=requireSchema();return default_safe=new es({include:[requireCore()],implicit:[requireTimestamp(),requireMerge()],explicit:[requireBinary(),requireOmap(),requirePairs(),requireSet()]}),default_safe}var _undefined,hasRequired_undefined;function require_undefined(){if(hasRequired_undefined)return _undefined;hasRequired_undefined=1;var es=requireType();function $(){return!0}function ts(){}function is(){return""}function cs(Qr){return typeof Qr>"u"}return _undefined=new es("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve:$,construct:ts,predicate:cs,represent:is}),_undefined}var regexp,hasRequiredRegexp;function requireRegexp(){if(hasRequiredRegexp)return regexp;hasRequiredRegexp=1;var es=requireType();function $(Qr){if(Qr===null||Qr.length===0)return!1;var ja=Qr,Na=/\/([gim]*)$/.exec(Qr),Aa="";return!(ja[0]==="/"&&(Na&&(Aa=Na[1]),Aa.length>3||ja[ja.length-Aa.length-1]!=="/"))}function ts(Qr){var ja=Qr,Na=/\/([gim]*)$/.exec(Qr),Aa="";return ja[0]==="/"&&(Na&&(Aa=Na[1]),ja=ja.slice(1,ja.length-Aa.length-1)),new RegExp(ja,Aa)}function is(Qr){var ja="/"+Qr.source+"/";return Qr.global&&(ja+="g"),Qr.multiline&&(ja+="m"),Qr.ignoreCase&&(ja+="i"),ja}function cs(Qr){return Object.prototype.toString.call(Qr)==="[object RegExp]"}return regexp=new es("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:$,construct:ts,predicate:cs,represent:is}),regexp}var _function,hasRequired_function;function require_function(){if(hasRequired_function)return _function;hasRequired_function=1;var es;try{var $=commonjsRequire;es=$("esprima")}catch{typeof window<"u"&&(es=window.esprima)}var ts=requireType();function is(Na){if(Na===null)return!1;try{var Aa="("+Na+")",Oa=es.parse(Aa,{range:!0});return!(Oa.type!=="Program"||Oa.body.length!==1||Oa.body[0].type!=="ExpressionStatement"||Oa.body[0].expression.type!=="ArrowFunctionExpression"&&Oa.body[0].expression.type!=="FunctionExpression")}catch{return!1}}function cs(Na){var Aa="("+Na+")",Oa=es.parse(Aa,{range:!0}),Ia=[],La;if(Oa.type!=="Program"||Oa.body.length!==1||Oa.body[0].type!=="ExpressionStatement"||Oa.body[0].expression.type!=="ArrowFunctionExpression"&&Oa.body[0].expression.type!=="FunctionExpression")throw new Error("Failed to resolve function");return Oa.body[0].expression.params.forEach(function(Ba){Ia.push(Ba.name)}),La=Oa.body[0].expression.body.range,Oa.body[0].expression.body.type==="BlockStatement"?new Function(Ia,Aa.slice(La[0]+1,La[1]-1)):new Function(Ia,"return "+Aa.slice(La[0],La[1]))}function Qr(Na){return Na.toString()}function ja(Na){return Object.prototype.toString.call(Na)==="[object Function]"}return _function=new ts("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:is,construct:cs,predicate:ja,represent:Qr}),_function}var default_full,hasRequiredDefault_full;function requireDefault_full(){if(hasRequiredDefault_full)return default_full;hasRequiredDefault_full=1;var es=requireSchema();return default_full=es.DEFAULT=new es({include:[requireDefault_safe()],explicit:[require_undefined(),requireRegexp(),require_function()]}),default_full}var hasRequiredLoader;function requireLoader(){if(hasRequiredLoader)return loader;hasRequiredLoader=1;var es=requireCommon(),$=requireException(),ts=requireMark(),is=requireDefault_safe(),cs=requireDefault_full(),Qr=Object.prototype.hasOwnProperty,ja=1,Na=2,Aa=3,Oa=4,Ia=1,La=2,Ba=3,Ma=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,qa=/[\x85\u2028\u2029]/,Fa=/[,\[\]\{\}]/,Ha=/^(?:!|!!|![a-z\-]+!)$/i,Ka=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function Ga(Ua){return Object.prototype.toString.call(Ua)}function Va(Ua){return Ua===10||Ua===13}function Ja(Ua){return Ua===9||Ua===32}function Ya(Ua){return Ua===9||Ua===32||Ua===10||Ua===13}function el(Ua){return Ua===44||Ua===91||Ua===93||Ua===123||Ua===125}function tl(Ua){var ll;return 48<=Ua&&Ua<=57?Ua-48:(ll=Ua|32,97<=ll&&ll<=102?ll-97+10:-1)}function rl(Ua){return Ua===120?2:Ua===117?4:Ua===85?8:0}function cl(Ua){return 48<=Ua&&Ua<=57?Ua-48:-1}function dl(Ua){return Ua===48?"\0":Ua===97?"\x07":Ua===98?"\b":Ua===116||Ua===9?" ":Ua===110?`
|
|
85
|
+
`:Ua===118?"\v":Ua===102?"\f":Ua===114?"\r":Ua===101?"\x1B":Ua===32?" ":Ua===34?'"':Ua===47?"/":Ua===92?"\\":Ua===78?"
":Ua===95?" ":Ua===76?"\u2028":Ua===80?"\u2029":""}function fl(Ua){return Ua<=65535?String.fromCharCode(Ua):String.fromCharCode((Ua-65536>>10)+55296,(Ua-65536&1023)+56320)}function nl(Ua,ll,yl){ll==="__proto__"?Object.defineProperty(Ua,ll,{configurable:!0,enumerable:!0,writable:!0,value:yl}):Ua[ll]=yl}for(var ol=new Array(256),pl=new Array(256),Tl=0;Tl<256;Tl++)ol[Tl]=dl(Tl)?1:0,pl[Tl]=dl(Tl);function ul(Ua,ll){this.input=Ua,this.filename=ll.filename||null,this.schema=ll.schema||cs,this.onWarning=ll.onWarning||null,this.legacy=ll.legacy||!1,this.json=ll.json||!1,this.listener=ll.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=Ua.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function hl(Ua,ll){return new $(ll,new ts(Ua.filename,Ua.input,Ua.position,Ua.line,Ua.position-Ua.lineStart))}function jl(Ua,ll){throw hl(Ua,ll)}function Nl(Ua,ll){Ua.onWarning&&Ua.onWarning.call(null,hl(Ua,ll))}var zl={YAML:function(ll,yl,$l){var kl,Za,al;ll.version!==null&&jl(ll,"duplication of %YAML directive"),$l.length!==1&&jl(ll,"YAML directive accepts exactly one argument"),kl=/^([0-9]+)\.([0-9]+)$/.exec($l[0]),kl===null&&jl(ll,"ill-formed argument of the YAML directive"),Za=parseInt(kl[1],10),al=parseInt(kl[2],10),Za!==1&&jl(ll,"unacceptable YAML version of the document"),ll.version=$l[0],ll.checkLineBreaks=al<2,al!==1&&al!==2&&Nl(ll,"unsupported YAML version of the document")},TAG:function(ll,yl,$l){var kl,Za;$l.length!==2&&jl(ll,"TAG directive accepts exactly two arguments"),kl=$l[0],Za=$l[1],Ha.test(kl)||jl(ll,"ill-formed tag handle (first argument) of the TAG directive"),Qr.call(ll.tagMap,kl)&&jl(ll,'there is a previously declared suffix for "'+kl+'" tag handle'),Ka.test(Za)||jl(ll,"ill-formed tag prefix (second argument) of the TAG directive"),ll.tagMap[kl]=Za}};function Zl(Ua,ll,yl,$l){var kl,Za,al,El;if(ll<yl){if(El=Ua.input.slice(ll,yl),$l)for(kl=0,Za=El.length;kl<Za;kl+=1)al=El.charCodeAt(kl),al===9||32<=al&&al<=1114111||jl(Ua,"expected valid JSON character");else Ma.test(El)&&jl(Ua,"the stream contains non-printable characters");Ua.result+=El}}function Dl(Ua,ll,yl,$l){var kl,Za,al,El;for(es.isObject(yl)||jl(Ua,"cannot merge mappings; the provided source object is unacceptable"),kl=Object.keys(yl),al=0,El=kl.length;al<El;al+=1)Za=kl[al],Qr.call(ll,Za)||(nl(ll,Za,yl[Za]),$l[Za]=!0)}function Il(Ua,ll,yl,$l,kl,Za,al,El){var bl,_l;if(Array.isArray(kl))for(kl=Array.prototype.slice.call(kl),bl=0,_l=kl.length;bl<_l;bl+=1)Array.isArray(kl[bl])&&jl(Ua,"nested arrays are not supported inside keys"),typeof kl=="object"&&Ga(kl[bl])==="[object Object]"&&(kl[bl]="[object Object]");if(typeof kl=="object"&&Ga(kl)==="[object Object]"&&(kl="[object Object]"),kl=String(kl),ll===null&&(ll={}),$l==="tag:yaml.org,2002:merge")if(Array.isArray(Za))for(bl=0,_l=Za.length;bl<_l;bl+=1)Dl(Ua,ll,Za[bl],yl);else Dl(Ua,ll,Za,yl);else!Ua.json&&!Qr.call(yl,kl)&&Qr.call(ll,kl)&&(Ua.line=al||Ua.line,Ua.position=El||Ua.position,jl(Ua,"duplicated mapping key")),nl(ll,kl,Za),delete yl[kl];return ll}function Fl(Ua){var ll;ll=Ua.input.charCodeAt(Ua.position),ll===10?Ua.position++:ll===13?(Ua.position++,Ua.input.charCodeAt(Ua.position)===10&&Ua.position++):jl(Ua,"a line break is expected"),Ua.line+=1,Ua.lineStart=Ua.position}function ql(Ua,ll,yl){for(var $l=0,kl=Ua.input.charCodeAt(Ua.position);kl!==0;){for(;Ja(kl);)kl=Ua.input.charCodeAt(++Ua.position);if(ll&&kl===35)do kl=Ua.input.charCodeAt(++Ua.position);while(kl!==10&&kl!==13&&kl!==0);if(Va(kl))for(Fl(Ua),kl=Ua.input.charCodeAt(Ua.position),$l++,Ua.lineIndent=0;kl===32;)Ua.lineIndent++,kl=Ua.input.charCodeAt(++Ua.position);else break}return yl!==-1&&$l!==0&&Ua.lineIndent<yl&&Nl(Ua,"deficient indentation"),$l}function nu(Ua){var ll=Ua.position,yl;return yl=Ua.input.charCodeAt(ll),!!((yl===45||yl===46)&&yl===Ua.input.charCodeAt(ll+1)&&yl===Ua.input.charCodeAt(ll+2)&&(ll+=3,yl=Ua.input.charCodeAt(ll),yl===0||Ya(yl)))}function Gl(Ua,ll){ll===1?Ua.result+=" ":ll>1&&(Ua.result+=es.repeat(`
|
|
86
|
+
`,ll-1))}function cu(Ua,ll,yl){var $l,kl,Za,al,El,bl,_l,Ol,Rl=Ua.kind,Ul=Ua.result,Ll;if(Ll=Ua.input.charCodeAt(Ua.position),Ya(Ll)||el(Ll)||Ll===35||Ll===38||Ll===42||Ll===33||Ll===124||Ll===62||Ll===39||Ll===34||Ll===37||Ll===64||Ll===96||(Ll===63||Ll===45)&&(kl=Ua.input.charCodeAt(Ua.position+1),Ya(kl)||yl&&el(kl)))return!1;for(Ua.kind="scalar",Ua.result="",Za=al=Ua.position,El=!1;Ll!==0;){if(Ll===58){if(kl=Ua.input.charCodeAt(Ua.position+1),Ya(kl)||yl&&el(kl))break}else if(Ll===35){if($l=Ua.input.charCodeAt(Ua.position-1),Ya($l))break}else{if(Ua.position===Ua.lineStart&&nu(Ua)||yl&&el(Ll))break;if(Va(Ll))if(bl=Ua.line,_l=Ua.lineStart,Ol=Ua.lineIndent,ql(Ua,!1,-1),Ua.lineIndent>=ll){El=!0,Ll=Ua.input.charCodeAt(Ua.position);continue}else{Ua.position=al,Ua.line=bl,Ua.lineStart=_l,Ua.lineIndent=Ol;break}}El&&(Zl(Ua,Za,al,!1),Gl(Ua,Ua.line-bl),Za=al=Ua.position,El=!1),Ja(Ll)||(al=Ua.position+1),Ll=Ua.input.charCodeAt(++Ua.position)}return Zl(Ua,Za,al,!1),Ua.result?!0:(Ua.kind=Rl,Ua.result=Ul,!1)}function Al(Ua,ll){var yl,$l,kl;if(yl=Ua.input.charCodeAt(Ua.position),yl!==39)return!1;for(Ua.kind="scalar",Ua.result="",Ua.position++,$l=kl=Ua.position;(yl=Ua.input.charCodeAt(Ua.position))!==0;)if(yl===39)if(Zl(Ua,$l,Ua.position,!0),yl=Ua.input.charCodeAt(++Ua.position),yl===39)$l=Ua.position,Ua.position++,kl=Ua.position;else return!0;else Va(yl)?(Zl(Ua,$l,kl,!0),Gl(Ua,ql(Ua,!1,ll)),$l=kl=Ua.position):Ua.position===Ua.lineStart&&nu(Ua)?jl(Ua,"unexpected end of the document within a single quoted scalar"):(Ua.position++,kl=Ua.position);jl(Ua,"unexpected end of the stream within a single quoted scalar")}function Ml(Ua,ll){var yl,$l,kl,Za,al,El;if(El=Ua.input.charCodeAt(Ua.position),El!==34)return!1;for(Ua.kind="scalar",Ua.result="",Ua.position++,yl=$l=Ua.position;(El=Ua.input.charCodeAt(Ua.position))!==0;){if(El===34)return Zl(Ua,yl,Ua.position,!0),Ua.position++,!0;if(El===92){if(Zl(Ua,yl,Ua.position,!0),El=Ua.input.charCodeAt(++Ua.position),Va(El))ql(Ua,!1,ll);else if(El<256&&ol[El])Ua.result+=pl[El],Ua.position++;else if((al=rl(El))>0){for(kl=al,Za=0;kl>0;kl--)El=Ua.input.charCodeAt(++Ua.position),(al=tl(El))>=0?Za=(Za<<4)+al:jl(Ua,"expected hexadecimal character");Ua.result+=fl(Za),Ua.position++}else jl(Ua,"unknown escape sequence");yl=$l=Ua.position}else Va(El)?(Zl(Ua,yl,$l,!0),Gl(Ua,ql(Ua,!1,ll)),yl=$l=Ua.position):Ua.position===Ua.lineStart&&nu(Ua)?jl(Ua,"unexpected end of the document within a double quoted scalar"):(Ua.position++,$l=Ua.position)}jl(Ua,"unexpected end of the stream within a double quoted scalar")}function Ql(Ua,ll){var yl=!0,$l,kl=Ua.tag,Za,al=Ua.anchor,El,bl,_l,Ol,Rl,Ul={},Ll,Yl,au,su;if(su=Ua.input.charCodeAt(Ua.position),su===91)bl=93,Rl=!1,Za=[];else if(su===123)bl=125,Rl=!0,Za={};else return!1;for(Ua.anchor!==null&&(Ua.anchorMap[Ua.anchor]=Za),su=Ua.input.charCodeAt(++Ua.position);su!==0;){if(ql(Ua,!0,ll),su=Ua.input.charCodeAt(Ua.position),su===bl)return Ua.position++,Ua.tag=kl,Ua.anchor=al,Ua.kind=Rl?"mapping":"sequence",Ua.result=Za,!0;yl||jl(Ua,"missed comma between flow collection entries"),Yl=Ll=au=null,_l=Ol=!1,su===63&&(El=Ua.input.charCodeAt(Ua.position+1),Ya(El)&&(_l=Ol=!0,Ua.position++,ql(Ua,!0,ll))),$l=Ua.line,Iu(Ua,ll,ja,!1,!0),Yl=Ua.tag,Ll=Ua.result,ql(Ua,!0,ll),su=Ua.input.charCodeAt(Ua.position),(Ol||Ua.line===$l)&&su===58&&(_l=!0,su=Ua.input.charCodeAt(++Ua.position),ql(Ua,!0,ll),Iu(Ua,ll,ja,!1,!0),au=Ua.result),Rl?Il(Ua,Za,Ul,Yl,Ll,au):_l?Za.push(Il(Ua,null,Ul,Yl,Ll,au)):Za.push(Ll),ql(Ua,!0,ll),su=Ua.input.charCodeAt(Ua.position),su===44?(yl=!0,su=Ua.input.charCodeAt(++Ua.position)):yl=!1}jl(Ua,"unexpected end of the stream within a flow collection")}function eu(Ua,ll){var yl,$l,kl=Ia,Za=!1,al=!1,El=ll,bl=0,_l=!1,Ol,Rl;if(Rl=Ua.input.charCodeAt(Ua.position),Rl===124)$l=!1;else if(Rl===62)$l=!0;else return!1;for(Ua.kind="scalar",Ua.result="";Rl!==0;)if(Rl=Ua.input.charCodeAt(++Ua.position),Rl===43||Rl===45)Ia===kl?kl=Rl===43?Ba:La:jl(Ua,"repeat of a chomping mode identifier");else if((Ol=cl(Rl))>=0)Ol===0?jl(Ua,"bad explicit indentation width of a block scalar; it cannot be less than one"):al?jl(Ua,"repeat of an indentation width identifier"):(El=ll+Ol-1,al=!0);else break;if(Ja(Rl)){do Rl=Ua.input.charCodeAt(++Ua.position);while(Ja(Rl));if(Rl===35)do Rl=Ua.input.charCodeAt(++Ua.position);while(!Va(Rl)&&Rl!==0)}for(;Rl!==0;){for(Fl(Ua),Ua.lineIndent=0,Rl=Ua.input.charCodeAt(Ua.position);(!al||Ua.lineIndent<El)&&Rl===32;)Ua.lineIndent++,Rl=Ua.input.charCodeAt(++Ua.position);if(!al&&Ua.lineIndent>El&&(El=Ua.lineIndent),Va(Rl)){bl++;continue}if(Ua.lineIndent<El){kl===Ba?Ua.result+=es.repeat(`
|
|
87
|
+
`,Za?1+bl:bl):kl===Ia&&Za&&(Ua.result+=`
|
|
88
|
+
`);break}for($l?Ja(Rl)?(_l=!0,Ua.result+=es.repeat(`
|
|
89
|
+
`,Za?1+bl:bl)):_l?(_l=!1,Ua.result+=es.repeat(`
|
|
90
|
+
`,bl+1)):bl===0?Za&&(Ua.result+=" "):Ua.result+=es.repeat(`
|
|
91
|
+
`,bl):Ua.result+=es.repeat(`
|
|
92
|
+
`,Za?1+bl:bl),Za=!0,al=!0,bl=0,yl=Ua.position;!Va(Rl)&&Rl!==0;)Rl=Ua.input.charCodeAt(++Ua.position);Zl(Ua,yl,Ua.position,!1)}return!0}function xu(Ua,ll){var yl,$l=Ua.tag,kl=Ua.anchor,Za=[],al,El=!1,bl;for(Ua.anchor!==null&&(Ua.anchorMap[Ua.anchor]=Za),bl=Ua.input.charCodeAt(Ua.position);bl!==0&&!(bl!==45||(al=Ua.input.charCodeAt(Ua.position+1),!Ya(al)));){if(El=!0,Ua.position++,ql(Ua,!0,-1)&&Ua.lineIndent<=ll){Za.push(null),bl=Ua.input.charCodeAt(Ua.position);continue}if(yl=Ua.line,Iu(Ua,ll,Aa,!1,!0),Za.push(Ua.result),ql(Ua,!0,-1),bl=Ua.input.charCodeAt(Ua.position),(Ua.line===yl||Ua.lineIndent>ll)&&bl!==0)jl(Ua,"bad indentation of a sequence entry");else if(Ua.lineIndent<ll)break}return El?(Ua.tag=$l,Ua.anchor=kl,Ua.kind="sequence",Ua.result=Za,!0):!1}function fu(Ua,ll,yl){var $l,kl,Za,al,El=Ua.tag,bl=Ua.anchor,_l={},Ol={},Rl=null,Ul=null,Ll=null,Yl=!1,au=!1,su;for(Ua.anchor!==null&&(Ua.anchorMap[Ua.anchor]=_l),su=Ua.input.charCodeAt(Ua.position);su!==0;){if($l=Ua.input.charCodeAt(Ua.position+1),Za=Ua.line,al=Ua.position,(su===63||su===58)&&Ya($l))su===63?(Yl&&(Il(Ua,_l,Ol,Rl,Ul,null),Rl=Ul=Ll=null),au=!0,Yl=!0,kl=!0):Yl?(Yl=!1,kl=!0):jl(Ua,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),Ua.position+=1,su=$l;else if(Iu(Ua,yl,Na,!1,!0))if(Ua.line===Za){for(su=Ua.input.charCodeAt(Ua.position);Ja(su);)su=Ua.input.charCodeAt(++Ua.position);if(su===58)su=Ua.input.charCodeAt(++Ua.position),Ya(su)||jl(Ua,"a whitespace character is expected after the key-value separator within a block mapping"),Yl&&(Il(Ua,_l,Ol,Rl,Ul,null),Rl=Ul=Ll=null),au=!0,Yl=!1,kl=!1,Rl=Ua.tag,Ul=Ua.result;else if(au)jl(Ua,"can not read an implicit mapping pair; a colon is missed");else return Ua.tag=El,Ua.anchor=bl,!0}else if(au)jl(Ua,"can not read a block mapping entry; a multiline key may not be an implicit key");else return Ua.tag=El,Ua.anchor=bl,!0;else break;if((Ua.line===Za||Ua.lineIndent>ll)&&(Iu(Ua,ll,Oa,!0,kl)&&(Yl?Ul=Ua.result:Ll=Ua.result),Yl||(Il(Ua,_l,Ol,Rl,Ul,Ll,Za,al),Rl=Ul=Ll=null),ql(Ua,!0,-1),su=Ua.input.charCodeAt(Ua.position)),Ua.lineIndent>ll&&su!==0)jl(Ua,"bad indentation of a mapping entry");else if(Ua.lineIndent<ll)break}return Yl&&Il(Ua,_l,Ol,Rl,Ul,null),au&&(Ua.tag=El,Ua.anchor=bl,Ua.kind="mapping",Ua.result=_l),au}function Ou(Ua){var ll,yl=!1,$l=!1,kl,Za,al;if(al=Ua.input.charCodeAt(Ua.position),al!==33)return!1;if(Ua.tag!==null&&jl(Ua,"duplication of a tag property"),al=Ua.input.charCodeAt(++Ua.position),al===60?(yl=!0,al=Ua.input.charCodeAt(++Ua.position)):al===33?($l=!0,kl="!!",al=Ua.input.charCodeAt(++Ua.position)):kl="!",ll=Ua.position,yl){do al=Ua.input.charCodeAt(++Ua.position);while(al!==0&&al!==62);Ua.position<Ua.length?(Za=Ua.input.slice(ll,Ua.position),al=Ua.input.charCodeAt(++Ua.position)):jl(Ua,"unexpected end of the stream within a verbatim tag")}else{for(;al!==0&&!Ya(al);)al===33&&($l?jl(Ua,"tag suffix cannot contain exclamation marks"):(kl=Ua.input.slice(ll-1,Ua.position+1),Ha.test(kl)||jl(Ua,"named tag handle cannot contain such characters"),$l=!0,ll=Ua.position+1)),al=Ua.input.charCodeAt(++Ua.position);Za=Ua.input.slice(ll,Ua.position),Fa.test(Za)&&jl(Ua,"tag suffix cannot contain flow indicator characters")}return Za&&!Ka.test(Za)&&jl(Ua,"tag name cannot contain such characters: "+Za),yl?Ua.tag=Za:Qr.call(Ua.tagMap,kl)?Ua.tag=Ua.tagMap[kl]+Za:kl==="!"?Ua.tag="!"+Za:kl==="!!"?Ua.tag="tag:yaml.org,2002:"+Za:jl(Ua,'undeclared tag handle "'+kl+'"'),!0}function yu(Ua){var ll,yl;if(yl=Ua.input.charCodeAt(Ua.position),yl!==38)return!1;for(Ua.anchor!==null&&jl(Ua,"duplication of an anchor property"),yl=Ua.input.charCodeAt(++Ua.position),ll=Ua.position;yl!==0&&!Ya(yl)&&!el(yl);)yl=Ua.input.charCodeAt(++Ua.position);return Ua.position===ll&&jl(Ua,"name of an anchor node must contain at least one character"),Ua.anchor=Ua.input.slice(ll,Ua.position),!0}function ic(Ua){var ll,yl,$l;if($l=Ua.input.charCodeAt(Ua.position),$l!==42)return!1;for($l=Ua.input.charCodeAt(++Ua.position),ll=Ua.position;$l!==0&&!Ya($l)&&!el($l);)$l=Ua.input.charCodeAt(++Ua.position);return Ua.position===ll&&jl(Ua,"name of an alias node must contain at least one character"),yl=Ua.input.slice(ll,Ua.position),Qr.call(Ua.anchorMap,yl)||jl(Ua,'unidentified alias "'+yl+'"'),Ua.result=Ua.anchorMap[yl],ql(Ua,!0,-1),!0}function Iu(Ua,ll,yl,$l,kl){var Za,al,El,bl=1,_l=!1,Ol=!1,Rl,Ul,Ll,Yl,au;if(Ua.listener!==null&&Ua.listener("open",Ua),Ua.tag=null,Ua.anchor=null,Ua.kind=null,Ua.result=null,Za=al=El=Oa===yl||Aa===yl,$l&&ql(Ua,!0,-1)&&(_l=!0,Ua.lineIndent>ll?bl=1:Ua.lineIndent===ll?bl=0:Ua.lineIndent<ll&&(bl=-1)),bl===1)for(;Ou(Ua)||yu(Ua);)ql(Ua,!0,-1)?(_l=!0,El=Za,Ua.lineIndent>ll?bl=1:Ua.lineIndent===ll?bl=0:Ua.lineIndent<ll&&(bl=-1)):El=!1;if(El&&(El=_l||kl),(bl===1||Oa===yl)&&(ja===yl||Na===yl?Yl=ll:Yl=ll+1,au=Ua.position-Ua.lineStart,bl===1?El&&(xu(Ua,au)||fu(Ua,au,Yl))||Ql(Ua,Yl)?Ol=!0:(al&&eu(Ua,Yl)||Al(Ua,Yl)||Ml(Ua,Yl)?Ol=!0:ic(Ua)?(Ol=!0,(Ua.tag!==null||Ua.anchor!==null)&&jl(Ua,"alias node should not have any properties")):cu(Ua,Yl,ja===yl)&&(Ol=!0,Ua.tag===null&&(Ua.tag="?")),Ua.anchor!==null&&(Ua.anchorMap[Ua.anchor]=Ua.result)):bl===0&&(Ol=El&&xu(Ua,au))),Ua.tag!==null&&Ua.tag!=="!")if(Ua.tag==="?"){for(Ua.result!==null&&Ua.kind!=="scalar"&&jl(Ua,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+Ua.kind+'"'),Rl=0,Ul=Ua.implicitTypes.length;Rl<Ul;Rl+=1)if(Ll=Ua.implicitTypes[Rl],Ll.resolve(Ua.result)){Ua.result=Ll.construct(Ua.result),Ua.tag=Ll.tag,Ua.anchor!==null&&(Ua.anchorMap[Ua.anchor]=Ua.result);break}}else Qr.call(Ua.typeMap[Ua.kind||"fallback"],Ua.tag)?(Ll=Ua.typeMap[Ua.kind||"fallback"][Ua.tag],Ua.result!==null&&Ll.kind!==Ua.kind&&jl(Ua,"unacceptable node kind for !<"+Ua.tag+'> tag; it should be "'+Ll.kind+'", not "'+Ua.kind+'"'),Ll.resolve(Ua.result)?(Ua.result=Ll.construct(Ua.result),Ua.anchor!==null&&(Ua.anchorMap[Ua.anchor]=Ua.result)):jl(Ua,"cannot resolve a node with !<"+Ua.tag+"> explicit tag")):jl(Ua,"unknown tag !<"+Ua.tag+">");return Ua.listener!==null&&Ua.listener("close",Ua),Ua.tag!==null||Ua.anchor!==null||Ol}function Bl(Ua){var ll=Ua.position,yl,$l,kl,Za=!1,al;for(Ua.version=null,Ua.checkLineBreaks=Ua.legacy,Ua.tagMap={},Ua.anchorMap={};(al=Ua.input.charCodeAt(Ua.position))!==0&&(ql(Ua,!0,-1),al=Ua.input.charCodeAt(Ua.position),!(Ua.lineIndent>0||al!==37));){for(Za=!0,al=Ua.input.charCodeAt(++Ua.position),yl=Ua.position;al!==0&&!Ya(al);)al=Ua.input.charCodeAt(++Ua.position);for($l=Ua.input.slice(yl,Ua.position),kl=[],$l.length<1&&jl(Ua,"directive name must not be less than one character in length");al!==0;){for(;Ja(al);)al=Ua.input.charCodeAt(++Ua.position);if(al===35){do al=Ua.input.charCodeAt(++Ua.position);while(al!==0&&!Va(al));break}if(Va(al))break;for(yl=Ua.position;al!==0&&!Ya(al);)al=Ua.input.charCodeAt(++Ua.position);kl.push(Ua.input.slice(yl,Ua.position))}al!==0&&Fl(Ua),Qr.call(zl,$l)?zl[$l](Ua,$l,kl):Nl(Ua,'unknown document directive "'+$l+'"')}if(ql(Ua,!0,-1),Ua.lineIndent===0&&Ua.input.charCodeAt(Ua.position)===45&&Ua.input.charCodeAt(Ua.position+1)===45&&Ua.input.charCodeAt(Ua.position+2)===45?(Ua.position+=3,ql(Ua,!0,-1)):Za&&jl(Ua,"directives end mark is expected"),Iu(Ua,Ua.lineIndent-1,Oa,!1,!0),ql(Ua,!0,-1),Ua.checkLineBreaks&&qa.test(Ua.input.slice(ll,Ua.position))&&Nl(Ua,"non-ASCII line breaks are interpreted as content"),Ua.documents.push(Ua.result),Ua.position===Ua.lineStart&&nu(Ua)){Ua.input.charCodeAt(Ua.position)===46&&(Ua.position+=3,ql(Ua,!0,-1));return}if(Ua.position<Ua.length-1)jl(Ua,"end of the stream or a document separator is expected");else return}function ru(Ua,ll){Ua=String(Ua),ll=ll||{},Ua.length!==0&&(Ua.charCodeAt(Ua.length-1)!==10&&Ua.charCodeAt(Ua.length-1)!==13&&(Ua+=`
|
|
93
|
+
`),Ua.charCodeAt(0)===65279&&(Ua=Ua.slice(1)));var yl=new ul(Ua,ll),$l=Ua.indexOf("\0");for($l!==-1&&(yl.position=$l,jl(yl,"null byte is not allowed in input")),yl.input+="\0";yl.input.charCodeAt(yl.position)===32;)yl.lineIndent+=1,yl.position+=1;for(;yl.position<yl.length-1;)Bl(yl);return yl.documents}function Mu(Ua,ll,yl){ll!==null&&typeof ll=="object"&&typeof yl>"u"&&(yl=ll,ll=null);var $l=ru(Ua,yl);if(typeof ll!="function")return $l;for(var kl=0,Za=$l.length;kl<Za;kl+=1)ll($l[kl])}function lc(Ua,ll){var yl=ru(Ua,ll);if(yl.length!==0){if(yl.length===1)return yl[0];throw new $("expected a single document in the stream, but found more")}}function Tu(Ua,ll,yl){return typeof ll=="object"&&ll!==null&&typeof yl>"u"&&(yl=ll,ll=null),Mu(Ua,ll,es.extend({schema:is},yl))}function Eu(Ua,ll){return lc(Ua,es.extend({schema:is},ll))}return loader.loadAll=Mu,loader.load=lc,loader.safeLoadAll=Tu,loader.safeLoad=Eu,loader}var dumper={},hasRequiredDumper;function requireDumper(){if(hasRequiredDumper)return dumper;hasRequiredDumper=1;var es=requireCommon(),$=requireException(),ts=requireDefault_full(),is=requireDefault_safe(),cs=Object.prototype.toString,Qr=Object.prototype.hasOwnProperty,ja=9,Na=10,Aa=13,Oa=32,Ia=33,La=34,Ba=35,Ma=37,qa=38,Fa=39,Ha=42,Ka=44,Ga=45,Va=58,Ja=61,Ya=62,el=63,tl=64,rl=91,cl=93,dl=96,fl=123,nl=124,ol=125,pl={};pl[0]="\\0",pl[7]="\\a",pl[8]="\\b",pl[9]="\\t",pl[10]="\\n",pl[11]="\\v",pl[12]="\\f",pl[13]="\\r",pl[27]="\\e",pl[34]='\\"',pl[92]="\\\\",pl[133]="\\N",pl[160]="\\_",pl[8232]="\\L",pl[8233]="\\P";var Tl=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"];function ul(Za,al){var El,bl,_l,Ol,Rl,Ul,Ll;if(al===null)return{};for(El={},bl=Object.keys(al),_l=0,Ol=bl.length;_l<Ol;_l+=1)Rl=bl[_l],Ul=String(al[Rl]),Rl.slice(0,2)==="!!"&&(Rl="tag:yaml.org,2002:"+Rl.slice(2)),Ll=Za.compiledTypeMap.fallback[Rl],Ll&&Qr.call(Ll.styleAliases,Ul)&&(Ul=Ll.styleAliases[Ul]),El[Rl]=Ul;return El}function hl(Za){var al,El,bl;if(al=Za.toString(16).toUpperCase(),Za<=255)El="x",bl=2;else if(Za<=65535)El="u",bl=4;else if(Za<=4294967295)El="U",bl=8;else throw new $("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+El+es.repeat("0",bl-al.length)+al}function jl(Za){this.schema=Za.schema||ts,this.indent=Math.max(1,Za.indent||2),this.noArrayIndent=Za.noArrayIndent||!1,this.skipInvalid=Za.skipInvalid||!1,this.flowLevel=es.isNothing(Za.flowLevel)?-1:Za.flowLevel,this.styleMap=ul(this.schema,Za.styles||null),this.sortKeys=Za.sortKeys||!1,this.lineWidth=Za.lineWidth||80,this.noRefs=Za.noRefs||!1,this.noCompatMode=Za.noCompatMode||!1,this.condenseFlow=Za.condenseFlow||!1,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function Nl(Za,al){for(var El=es.repeat(" ",al),bl=0,_l=-1,Ol="",Rl,Ul=Za.length;bl<Ul;)_l=Za.indexOf(`
|
|
94
|
+
`,bl),_l===-1?(Rl=Za.slice(bl),bl=Ul):(Rl=Za.slice(bl,_l+1),bl=_l+1),Rl.length&&Rl!==`
|
|
95
|
+
`&&(Ol+=El),Ol+=Rl;return Ol}function zl(Za,al){return`
|
|
96
|
+
`+es.repeat(" ",Za.indent*al)}function Zl(Za,al){var El,bl,_l;for(El=0,bl=Za.implicitTypes.length;El<bl;El+=1)if(_l=Za.implicitTypes[El],_l.resolve(al))return!0;return!1}function Dl(Za){return Za===Oa||Za===ja}function Il(Za){return 32<=Za&&Za<=126||161<=Za&&Za<=55295&&Za!==8232&&Za!==8233||57344<=Za&&Za<=65533&&Za!==65279||65536<=Za&&Za<=1114111}function Fl(Za){return Il(Za)&&!Dl(Za)&&Za!==65279&&Za!==Aa&&Za!==Na}function ql(Za,al){return Il(Za)&&Za!==65279&&Za!==Ka&&Za!==rl&&Za!==cl&&Za!==fl&&Za!==ol&&Za!==Va&&(Za!==Ba||al&&Fl(al))}function nu(Za){return Il(Za)&&Za!==65279&&!Dl(Za)&&Za!==Ga&&Za!==el&&Za!==Va&&Za!==Ka&&Za!==rl&&Za!==cl&&Za!==fl&&Za!==ol&&Za!==Ba&&Za!==qa&&Za!==Ha&&Za!==Ia&&Za!==nl&&Za!==Ja&&Za!==Ya&&Za!==Fa&&Za!==La&&Za!==Ma&&Za!==tl&&Za!==dl}function Gl(Za){var al=/^\n* /;return al.test(Za)}var cu=1,Al=2,Ml=3,Ql=4,eu=5;function xu(Za,al,El,bl,_l){var Ol,Rl,Ul,Ll=!1,Yl=!1,au=bl!==-1,su=-1,Lu=nu(Za.charCodeAt(0))&&!Dl(Za.charCodeAt(Za.length-1));if(al)for(Ol=0;Ol<Za.length;Ol++){if(Rl=Za.charCodeAt(Ol),!Il(Rl))return eu;Ul=Ol>0?Za.charCodeAt(Ol-1):null,Lu=Lu&&ql(Rl,Ul)}else{for(Ol=0;Ol<Za.length;Ol++){if(Rl=Za.charCodeAt(Ol),Rl===Na)Ll=!0,au&&(Yl=Yl||Ol-su-1>bl&&Za[su+1]!==" ",su=Ol);else if(!Il(Rl))return eu;Ul=Ol>0?Za.charCodeAt(Ol-1):null,Lu=Lu&&ql(Rl,Ul)}Yl=Yl||au&&Ol-su-1>bl&&Za[su+1]!==" "}return!Ll&&!Yl?Lu&&!_l(Za)?cu:Al:El>9&&Gl(Za)?eu:Yl?Ql:Ml}function fu(Za,al,El,bl){Za.dump=(function(){if(al.length===0)return"''";if(!Za.noCompatMode&&Tl.indexOf(al)!==-1)return"'"+al+"'";var _l=Za.indent*Math.max(1,El),Ol=Za.lineWidth===-1?-1:Math.max(Math.min(Za.lineWidth,40),Za.lineWidth-_l),Rl=bl||Za.flowLevel>-1&&El>=Za.flowLevel;function Ul(Ll){return Zl(Za,Ll)}switch(xu(al,Rl,Za.indent,Ol,Ul)){case cu:return al;case Al:return"'"+al.replace(/'/g,"''")+"'";case Ml:return"|"+Ou(al,Za.indent)+yu(Nl(al,_l));case Ql:return">"+Ou(al,Za.indent)+yu(Nl(ic(al,Ol),_l));case eu:return'"'+Bl(al)+'"';default:throw new $("impossible error: invalid scalar style")}})()}function Ou(Za,al){var El=Gl(Za)?String(al):"",bl=Za[Za.length-1]===`
|
|
97
|
+
`,_l=bl&&(Za[Za.length-2]===`
|
|
98
|
+
`||Za===`
|
|
99
|
+
`),Ol=_l?"+":bl?"":"-";return El+Ol+`
|
|
100
|
+
`}function yu(Za){return Za[Za.length-1]===`
|
|
101
|
+
`?Za.slice(0,-1):Za}function ic(Za,al){for(var El=/(\n+)([^\n]*)/g,bl=(function(){var Yl=Za.indexOf(`
|
|
102
|
+
`);return Yl=Yl!==-1?Yl:Za.length,El.lastIndex=Yl,Iu(Za.slice(0,Yl),al)})(),_l=Za[0]===`
|
|
103
|
+
`||Za[0]===" ",Ol,Rl;Rl=El.exec(Za);){var Ul=Rl[1],Ll=Rl[2];Ol=Ll[0]===" ",bl+=Ul+(!_l&&!Ol&&Ll!==""?`
|
|
104
|
+
`:"")+Iu(Ll,al),_l=Ol}return bl}function Iu(Za,al){if(Za===""||Za[0]===" ")return Za;for(var El=/ [^ ]/g,bl,_l=0,Ol,Rl=0,Ul=0,Ll="";bl=El.exec(Za);)Ul=bl.index,Ul-_l>al&&(Ol=Rl>_l?Rl:Ul,Ll+=`
|
|
105
|
+
`+Za.slice(_l,Ol),_l=Ol+1),Rl=Ul;return Ll+=`
|
|
106
|
+
`,Za.length-_l>al&&Rl>_l?Ll+=Za.slice(_l,Rl)+`
|
|
107
|
+
`+Za.slice(Rl+1):Ll+=Za.slice(_l),Ll.slice(1)}function Bl(Za){for(var al="",El,bl,_l,Ol=0;Ol<Za.length;Ol++){if(El=Za.charCodeAt(Ol),El>=55296&&El<=56319&&(bl=Za.charCodeAt(Ol+1),bl>=56320&&bl<=57343)){al+=hl((El-55296)*1024+bl-56320+65536),Ol++;continue}_l=pl[El],al+=!_l&&Il(El)?Za[Ol]:_l||hl(El)}return al}function ru(Za,al,El){var bl="",_l=Za.tag,Ol,Rl;for(Ol=0,Rl=El.length;Ol<Rl;Ol+=1)Ua(Za,al,El[Ol],!1,!1)&&(Ol!==0&&(bl+=","+(Za.condenseFlow?"":" ")),bl+=Za.dump);Za.tag=_l,Za.dump="["+bl+"]"}function Mu(Za,al,El,bl){var _l="",Ol=Za.tag,Rl,Ul;for(Rl=0,Ul=El.length;Rl<Ul;Rl+=1)Ua(Za,al+1,El[Rl],!0,!0)&&((!bl||Rl!==0)&&(_l+=zl(Za,al)),Za.dump&&Na===Za.dump.charCodeAt(0)?_l+="-":_l+="- ",_l+=Za.dump);Za.tag=Ol,Za.dump=_l||"[]"}function lc(Za,al,El){var bl="",_l=Za.tag,Ol=Object.keys(El),Rl,Ul,Ll,Yl,au;for(Rl=0,Ul=Ol.length;Rl<Ul;Rl+=1)au="",Rl!==0&&(au+=", "),Za.condenseFlow&&(au+='"'),Ll=Ol[Rl],Yl=El[Ll],Ua(Za,al,Ll,!1,!1)&&(Za.dump.length>1024&&(au+="? "),au+=Za.dump+(Za.condenseFlow?'"':"")+":"+(Za.condenseFlow?"":" "),Ua(Za,al,Yl,!1,!1)&&(au+=Za.dump,bl+=au));Za.tag=_l,Za.dump="{"+bl+"}"}function Tu(Za,al,El,bl){var _l="",Ol=Za.tag,Rl=Object.keys(El),Ul,Ll,Yl,au,su,Lu;if(Za.sortKeys===!0)Rl.sort();else if(typeof Za.sortKeys=="function")Rl.sort(Za.sortKeys);else if(Za.sortKeys)throw new $("sortKeys must be a boolean or a function");for(Ul=0,Ll=Rl.length;Ul<Ll;Ul+=1)Lu="",(!bl||Ul!==0)&&(Lu+=zl(Za,al)),Yl=Rl[Ul],au=El[Yl],Ua(Za,al+1,Yl,!0,!0,!0)&&(su=Za.tag!==null&&Za.tag!=="?"||Za.dump&&Za.dump.length>1024,su&&(Za.dump&&Na===Za.dump.charCodeAt(0)?Lu+="?":Lu+="? "),Lu+=Za.dump,su&&(Lu+=zl(Za,al)),Ua(Za,al+1,au,!0,su)&&(Za.dump&&Na===Za.dump.charCodeAt(0)?Lu+=":":Lu+=": ",Lu+=Za.dump,_l+=Lu));Za.tag=Ol,Za.dump=_l||"{}"}function Eu(Za,al,El){var bl,_l,Ol,Rl,Ul,Ll;for(_l=El?Za.explicitTypes:Za.implicitTypes,Ol=0,Rl=_l.length;Ol<Rl;Ol+=1)if(Ul=_l[Ol],(Ul.instanceOf||Ul.predicate)&&(!Ul.instanceOf||typeof al=="object"&&al instanceof Ul.instanceOf)&&(!Ul.predicate||Ul.predicate(al))){if(Za.tag=El?Ul.tag:"?",Ul.represent){if(Ll=Za.styleMap[Ul.tag]||Ul.defaultStyle,cs.call(Ul.represent)==="[object Function]")bl=Ul.represent(al,Ll);else if(Qr.call(Ul.represent,Ll))bl=Ul.represent[Ll](al,Ll);else throw new $("!<"+Ul.tag+'> tag resolver accepts not "'+Ll+'" style');Za.dump=bl}return!0}return!1}function Ua(Za,al,El,bl,_l,Ol){Za.tag=null,Za.dump=El,Eu(Za,El,!1)||Eu(Za,El,!0);var Rl=cs.call(Za.dump);bl&&(bl=Za.flowLevel<0||Za.flowLevel>al);var Ul=Rl==="[object Object]"||Rl==="[object Array]",Ll,Yl;if(Ul&&(Ll=Za.duplicates.indexOf(El),Yl=Ll!==-1),(Za.tag!==null&&Za.tag!=="?"||Yl||Za.indent!==2&&al>0)&&(_l=!1),Yl&&Za.usedDuplicates[Ll])Za.dump="*ref_"+Ll;else{if(Ul&&Yl&&!Za.usedDuplicates[Ll]&&(Za.usedDuplicates[Ll]=!0),Rl==="[object Object]")bl&&Object.keys(Za.dump).length!==0?(Tu(Za,al,Za.dump,_l),Yl&&(Za.dump="&ref_"+Ll+Za.dump)):(lc(Za,al,Za.dump),Yl&&(Za.dump="&ref_"+Ll+" "+Za.dump));else if(Rl==="[object Array]"){var au=Za.noArrayIndent&&al>0?al-1:al;bl&&Za.dump.length!==0?(Mu(Za,au,Za.dump,_l),Yl&&(Za.dump="&ref_"+Ll+Za.dump)):(ru(Za,au,Za.dump),Yl&&(Za.dump="&ref_"+Ll+" "+Za.dump))}else if(Rl==="[object String]")Za.tag!=="?"&&fu(Za,Za.dump,al,Ol);else{if(Za.skipInvalid)return!1;throw new $("unacceptable kind of an object to dump "+Rl)}Za.tag!==null&&Za.tag!=="?"&&(Za.dump="!<"+Za.tag+"> "+Za.dump)}return!0}function ll(Za,al){var El=[],bl=[],_l,Ol;for(yl(Za,El,bl),_l=0,Ol=bl.length;_l<Ol;_l+=1)al.duplicates.push(El[bl[_l]]);al.usedDuplicates=new Array(Ol)}function yl(Za,al,El){var bl,_l,Ol;if(Za!==null&&typeof Za=="object")if(_l=al.indexOf(Za),_l!==-1)El.indexOf(_l)===-1&&El.push(_l);else if(al.push(Za),Array.isArray(Za))for(_l=0,Ol=Za.length;_l<Ol;_l+=1)yl(Za[_l],al,El);else for(bl=Object.keys(Za),_l=0,Ol=bl.length;_l<Ol;_l+=1)yl(Za[bl[_l]],al,El)}function $l(Za,al){al=al||{};var El=new jl(al);return El.noRefs||ll(Za,El),Ua(El,0,Za,!0,!0)?El.dump+`
|
|
108
|
+
`:""}function kl(Za,al){return $l(Za,es.extend({schema:is},al))}return dumper.dump=$l,dumper.safeDump=kl,dumper}var hasRequiredJsYaml$1;function requireJsYaml$1(){if(hasRequiredJsYaml$1)return jsYaml$1;hasRequiredJsYaml$1=1;var es=requireLoader(),$=requireDumper();function ts(is){return function(){throw new Error("Function "+is+" is deprecated and cannot be used.")}}return jsYaml$1.Type=requireType(),jsYaml$1.Schema=requireSchema(),jsYaml$1.FAILSAFE_SCHEMA=requireFailsafe(),jsYaml$1.JSON_SCHEMA=requireJson(),jsYaml$1.CORE_SCHEMA=requireCore(),jsYaml$1.DEFAULT_SAFE_SCHEMA=requireDefault_safe(),jsYaml$1.DEFAULT_FULL_SCHEMA=requireDefault_full(),jsYaml$1.load=es.load,jsYaml$1.loadAll=es.loadAll,jsYaml$1.safeLoad=es.safeLoad,jsYaml$1.safeLoadAll=es.safeLoadAll,jsYaml$1.dump=$.dump,jsYaml$1.safeDump=$.safeDump,jsYaml$1.YAMLException=requireException(),jsYaml$1.MINIMAL_SCHEMA=requireFailsafe(),jsYaml$1.SAFE_SCHEMA=requireDefault_safe(),jsYaml$1.DEFAULT_SCHEMA=requireDefault_full(),jsYaml$1.scan=ts("scan"),jsYaml$1.parse=ts("parse"),jsYaml$1.compose=ts("compose"),jsYaml$1.addConstructor=ts("addConstructor"),jsYaml$1}var jsYaml,hasRequiredJsYaml;function requireJsYaml(){if(hasRequiredJsYaml)return jsYaml;hasRequiredJsYaml=1;var es=requireJsYaml$1();return jsYaml=es,jsYaml}var hasRequiredEngines;function requireEngines(){return hasRequiredEngines||(hasRequiredEngines=1,(function(module,exports$1){const yaml=requireJsYaml(),engines=module.exports;engines.yaml={parse:yaml.safeLoad.bind(yaml),stringify:yaml.safeDump.bind(yaml)},engines.json={parse:JSON.parse.bind(JSON),stringify:function(es,$){const ts=Object.assign({replacer:null,space:2},$);return JSON.stringify(es,ts.replacer,ts.space)}},engines.javascript={parse:function parse(str,options,wrap){try{return wrap!==!1&&(str=`(function() {
|
|
109
|
+
return `+str.trim()+`;
|
|
110
|
+
}());`),eval(str)||{}}catch(es){if(wrap!==!1&&/(unexpected|identifier)/i.test(es.message))return parse(str,options,!1);throw new SyntaxError(es)}},stringify:function(){throw new Error("stringifying JavaScript is not supported")}}})(engines)),engines.exports}var utils={};/*!
|
|
111
|
+
* strip-bom-string <https://github.com/jonschlinkert/strip-bom-string>
|
|
112
|
+
*
|
|
113
|
+
* Copyright (c) 2015, 2017, Jon Schlinkert.
|
|
114
|
+
* Released under the MIT License.
|
|
115
|
+
*/var stripBomString,hasRequiredStripBomString;function requireStripBomString(){return hasRequiredStripBomString||(hasRequiredStripBomString=1,stripBomString=function(es){return typeof es=="string"&&es.charAt(0)==="\uFEFF"?es.slice(1):es}),stripBomString}var hasRequiredUtils;function requireUtils(){return hasRequiredUtils||(hasRequiredUtils=1,(function(es){const $=requireStripBomString(),ts=requireKindOf();es.define=function(is,cs,Qr){Reflect.defineProperty(is,cs,{enumerable:!1,configurable:!0,writable:!0,value:Qr})},es.isBuffer=function(is){return ts(is)==="buffer"},es.isObject=function(is){return ts(is)==="object"},es.toBuffer=function(is){return typeof is=="string"?Buffer.from(is):is},es.toString=function(is){if(es.isBuffer(is))return $(String(is));if(typeof is!="string")throw new TypeError("expected input to be a string or buffer");return $(is)},es.arrayify=function(is){return is?Array.isArray(is)?is:[is]:[]},es.startsWith=function(is,cs,Qr){return typeof Qr!="number"&&(Qr=cs.length),is.slice(0,Qr)===cs}})(utils)),utils}var defaults,hasRequiredDefaults;function requireDefaults(){if(hasRequiredDefaults)return defaults;hasRequiredDefaults=1;const es=requireEngines(),$=requireUtils();return defaults=function(ts){const is=Object.assign({},ts);return is.delimiters=$.arrayify(is.delims||is.delimiters||"---"),is.delimiters.length===1&&is.delimiters.push(is.delimiters[0]),is.language=(is.language||is.lang||"yaml").toLowerCase(),is.engines=Object.assign({},es,is.parsers,is.engines),is},defaults}var engine,hasRequiredEngine;function requireEngine(){if(hasRequiredEngine)return engine;hasRequiredEngine=1,engine=function($,ts){let is=ts.engines[$]||ts.engines[es($)];if(typeof is>"u")throw new Error('gray-matter engine "'+$+'" is not registered');return typeof is=="function"&&(is={parse:is}),is};function es($){switch($.toLowerCase()){case"js":case"javascript":return"javascript";case"coffee":case"coffeescript":case"cson":return"coffee";case"yaml":case"yml":return"yaml";default:return $}}return engine}var stringify,hasRequiredStringify;function requireStringify(){if(hasRequiredStringify)return stringify;hasRequiredStringify=1;const es=requireKindOf(),$=requireEngine(),ts=requireDefaults();stringify=function(cs,Qr,ja){if(Qr==null&&ja==null)switch(es(cs)){case"object":Qr=cs.data,ja={};break;case"string":return cs;default:throw new TypeError("expected file to be a string or object")}const Na=cs.content,Aa=ts(ja);if(Qr==null){if(!Aa.data)return cs;Qr=Aa.data}const Oa=cs.language||Aa.language,Ia=$(Oa,Aa);if(typeof Ia.stringify!="function")throw new TypeError('expected "'+Oa+'.stringify" to be a function');Qr=Object.assign({},cs.data,Qr);const La=Aa.delimiters[0],Ba=Aa.delimiters[1],Ma=Ia.stringify(Qr,ja).trim();let qa="";return Ma!=="{}"&&(qa=is(La)+is(Ma)+is(Ba)),typeof cs.excerpt=="string"&&cs.excerpt!==""&&Na.indexOf(cs.excerpt.trim())===-1&&(qa+=is(cs.excerpt)+is(Ba)),qa+is(Na)};function is(cs){return cs.slice(-1)!==`
|
|
116
|
+
`?cs+`
|
|
117
|
+
`:cs}return stringify}var excerpt,hasRequiredExcerpt;function requireExcerpt(){if(hasRequiredExcerpt)return excerpt;hasRequiredExcerpt=1;const es=requireDefaults();return excerpt=function($,ts){const is=es(ts);if($.data==null&&($.data={}),typeof is.excerpt=="function")return is.excerpt($,is);const cs=$.data.excerpt_separator||is.excerpt_separator;if(cs==null&&(is.excerpt===!1||is.excerpt==null))return $;const Qr=typeof is.excerpt=="string"?is.excerpt:cs||is.delimiters[0],ja=$.content.indexOf(Qr);return ja!==-1&&($.excerpt=$.content.slice(0,ja)),$},excerpt}var toFile,hasRequiredToFile;function requireToFile(){if(hasRequiredToFile)return toFile;hasRequiredToFile=1;const es=requireKindOf(),$=requireStringify(),ts=requireUtils();return toFile=function(is){return es(is)!=="object"&&(is={content:is}),es(is.data)!=="object"&&(is.data={}),is.contents&&is.content==null&&(is.content=is.contents),ts.define(is,"orig",ts.toBuffer(is.content)),ts.define(is,"language",is.language||""),ts.define(is,"matter",is.matter||""),ts.define(is,"stringify",function(cs,Qr){return Qr&&Qr.language&&(is.language=Qr.language),$(is,cs,Qr)}),is.content=ts.toString(is.content),is.isEmpty=!1,is.excerpt="",is},toFile}var parse,hasRequiredParse;function requireParse(){if(hasRequiredParse)return parse;hasRequiredParse=1;const es=requireEngine(),$=requireDefaults();return parse=function(ts,is,cs){const Qr=$(cs),ja=es(ts,Qr);if(typeof ja.parse!="function")throw new TypeError('expected "'+ts+'.parse" to be a function');return ja.parse(is,Qr)},parse}var grayMatter,hasRequiredGrayMatter;function requireGrayMatter(){if(hasRequiredGrayMatter)return grayMatter;hasRequiredGrayMatter=1;const es=require$$0,$=requireSectionMatter(),ts=requireDefaults(),is=requireStringify(),cs=requireExcerpt(),Qr=requireEngines(),ja=requireToFile(),Na=requireParse(),Aa=requireUtils();function Oa(La,Ba){if(La==="")return{data:{},content:La,excerpt:"",orig:La};let Ma=ja(La);const qa=Oa.cache[Ma.content];if(!Ba){if(qa)return Ma=Object.assign({},qa),Ma.orig=qa.orig,Ma;Oa.cache[Ma.content]=Ma}return Ia(Ma,Ba)}function Ia(La,Ba){const Ma=ts(Ba),qa=Ma.delimiters[0],Fa=`
|
|
118
|
+
`+Ma.delimiters[1];let Ha=La.content;Ma.language&&(La.language=Ma.language);const Ka=qa.length;if(!Aa.startsWith(Ha,qa,Ka))return cs(La,Ma),La;if(Ha.charAt(Ka)===qa.slice(-1))return La;Ha=Ha.slice(Ka);const Ga=Ha.length,Va=Oa.language(Ha,Ma);Va.name&&(La.language=Va.name,Ha=Ha.slice(Va.raw.length));let Ja=Ha.indexOf(Fa);return Ja===-1&&(Ja=Ga),La.matter=Ha.slice(0,Ja),La.matter.replace(/^\s*#[^\n]+/gm,"").trim()===""?(La.isEmpty=!0,La.empty=La.content,La.data={}):La.data=Na(La.language,La.matter,Ma),Ja===Ga?La.content="":(La.content=Ha.slice(Ja+Fa.length),La.content[0]==="\r"&&(La.content=La.content.slice(1)),La.content[0]===`
|
|
119
|
+
`&&(La.content=La.content.slice(1))),cs(La,Ma),(Ma.sections===!0||typeof Ma.section=="function")&&$(La,Ma.section),La}return Oa.engines=Qr,Oa.stringify=function(La,Ba,Ma){return typeof La=="string"&&(La=Oa(La,Ma)),is(La,Ba,Ma)},Oa.read=function(La,Ba){const Ma=es.readFileSync(La,"utf8"),qa=Oa(Ma,Ba);return qa.path=La,qa},Oa.test=function(La,Ba){return Aa.startsWith(La,ts(Ba).delimiters[0])},Oa.language=function(La,Ba){const qa=ts(Ba).delimiters[0];Oa.test(La)&&(La=La.slice(qa.length));const Fa=La.slice(0,La.search(/\r?\n/));return{raw:Fa,name:Fa?Fa.trim():""}},Oa.cache={},Oa.clearCache=function(){Oa.cache={}},grayMatter=Oa,grayMatter}requireGrayMatter();objectType({type:enumType(["instruction","prompt"])});function readStampedSource(es){if(!es||typeof es!="object")return null;const $=es.source;return $==="insights"||$==="evolution"?$:null}function classifyProvenance(es,$){const ts=es.source==="insights"||es.source==="evolution"?es.source:readStampedSource(es.frontmatter);return ts||(es.createdBy&&es.createdBy===$?"user":"catalog")}function isGenerated(es){return es==="insights"||es==="evolution"}function provenanceLabel(es){return es==="insights"?"from insights":es==="evolution"?"from evolution":null}const PROVENANCE_TOOLTIP="Proposed by a background generator, not written by you. It is not injected into sessions until you accept it.";function parseApiError(es,$){const ts=`HTTP ${es}`;if(!$||typeof $!="object")return{message:ts};const is=$,cs=typeof is.error=="string"&&is.error?is.error:is.error?JSON.stringify(is.error):ts,Qr=typeof is.code=="string"&&is.code?is.code:void 0;return Qr?{message:cs,code:Qr}:{message:cs}}const MeasurementEngineSchema=enumType(["claude","codex","pi"]),model=stringType().trim().min(1).max(200).nullable(),requirePin=(es,$)=>{es.engine==="codex"&&!es.model&&$.addIssue({code:"custom",path:["model"],message:"Codex requires a model pin"}),es.engine==="pi"&&!/^[^\s/:]+\/[^\s/]+$/.test(es.model??"")&&$.addIssue({code:"custom",path:["model"],message:"Pi requires a provider/model pin (for example openai-codex/gpt-5.4-mini)"}),es.engine===null&&es.model!==null&&$.addIssue({code:"custom",path:["model"],message:"Choose an engine before a model"})},MeasurementPreferenceSchema=objectType({engine:MeasurementEngineSchema.nullable(),model}).strict().superRefine(requirePin);objectType({preference:MeasurementPreferenceSchema,workers:arrayType(objectType({lastSeen:stringType(),protocol:numberType().nullable(),engines:arrayType(stringType())})).optional(),graderBlockers:arrayType(objectType({targetId:stringType(),name:stringType(),engine:stringType(),model:stringType()})).optional()});objectType({cadence:stringType(),summary:stringType(),readiness:objectType({ready:booleanType(),reported:booleanType(),missing:arrayType(stringType())}),sweeps:arrayType(objectType({task:stringType(),last:objectType({status:stringType(),decision:stringType().nullable(),reason:stringType().nullable()}).nullable()}))});objectType({version:literalType(1),engine:MeasurementEngineSchema,model,source:enumType(["account","explicit"])}).strict().superRefine(requirePin);class ApiError extends Error{constructor($,ts,is){super(ts),this.statusCode=$,this.code=is,this.name="ApiError"}}const DEFAULT_TIMEOUT_MS=2e4;function getBaseUrl(){return""}async function api(es,$={}){const is=`${getBaseUrl()}${es}`,cs={"Content-Type":"application/json",...$.headers};let Qr=getCachedAccessToken();if(!Qr){const{data:{session:Ba}}=await withAuthContext(`for ${$.method??"GET"} ${es}`,()=>supabase.auth.getSession());Qr=(Ba==null?void 0:Ba.access_token)??null}Qr&&(cs.Authorization=`Bearer ${Qr}`);const ja=$.timeoutMs??DEFAULT_TIMEOUT_MS,Na=ja>0?new AbortController:null,Aa=Na!=null?setTimeout(()=>Na.abort(),ja):null;let Oa;try{Oa=await fetch(is,{method:$.method??"GET",headers:cs,body:$.body?JSON.stringify($.body):void 0,signal:Na==null?void 0:Na.signal})}catch(Ba){throw Na!=null&&Na.signal.aborted?new ApiError(0,`Request timed out after ${ja}ms: ${$.method??"GET"} ${es}`,"TIMEOUT"):Ba}finally{Aa!=null&&clearTimeout(Aa)}if(Oa.status===401)throw await supabase.auth.signOut(),new ApiError(401,"Session expired");let Ia;const La=Oa.headers.get("content-type");if(La!=null&&La.includes("application/json")?Ia=await Oa.json():Ia=await Oa.text(),!Oa.ok){const{message:Ba,code:Ma}=parseApiError(Oa.status,Ia);throw new ApiError(Oa.status,Ba,Ma)}return Ia}const apiGet=es=>api(es),apiPost=(es,$)=>api(es,{method:"POST",body:$}),apiPut=(es,$)=>api(es,{method:"PUT",body:$}),apiPatch=(es,$)=>api(es,{method:"PATCH",body:$}),apiDelete=es=>api(es,{method:"DELETE"});function getOrgs(){return apiGet("/api/orgs")}function getOrg(es){return apiGet(`/api/orgs/${encodeURIComponent(es)}`)}function getProfile(){return apiGet("/api/profile")}async function setActiveOrg(es){return await apiPatch("/api/profile",{activeOrgId:es}),getProfile()}function createOrg(es){return apiPost("/api/orgs",es)}function updateOrg(es,$){return apiPatch(`/api/orgs/${encodeURIComponent(es)}`,$)}function listMembers(es){return apiGet(`/api/orgs/${encodeURIComponent(es)}/members`)}function updateMemberRole(es,$,ts){return apiPatch(`/api/orgs/${encodeURIComponent(es)}/members/${encodeURIComponent($)}`,{role:ts})}function removeMember(es,$){return apiDelete(`/api/orgs/${encodeURIComponent(es)}/members/${encodeURIComponent($)}`)}function transferOwnership(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/transfer`,{newOwnerId:$})}function listTeams(es){return apiGet(`/api/orgs/${encodeURIComponent(es)}/teams`)}function createTeam(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/teams`,$)}function updateTeam(es,$,ts){return apiPatch(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}`,ts)}function deleteTeam(es,$){return apiDelete(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}`)}function addTeamMember(es,$,ts){return apiPost(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}/members`,{userId:ts})}function removeTeamMember(es,$,ts){return apiDelete(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}/members/${encodeURIComponent(ts)}`)}function listInvitations(es){return apiGet(`/api/orgs/${encodeURIComponent(es)}/invitations`)}function createInvitation(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/invitations`,$)}function revokeInvitation(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/invitations/${encodeURIComponent($)}/revoke`,{})}function resendInvitation(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/invitations/${encodeURIComponent($)}/resend`,{})}function previewInvitation(es){return apiGet(`/api/invitations/${encodeURIComponent(es)}`)}function acceptInvitation(es){return apiPost("/api/invitations/accept",es)}function getOrgActivity(es,$="7d"){return apiGet(`/api/orgs/${encodeURIComponent(es)}/activity?range=${encodeURIComponent($)}`)}function getTeamActivity(es,$,ts="7d"){return apiGet(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}/activity?range=${encodeURIComponent(ts)}`)}function deleteOrg(es){return apiDelete(`/api/orgs/${encodeURIComponent(es)}`)}function useActiveOrg(){const{session:es}=useAuth(),$=!!es,ts=useQuery({queryKey:["profile"],queryFn:getProfile,enabled:$}),is=useQuery({queryKey:["orgs"],queryFn:getOrgs,enabled:$});return{activeOrg:reactExports.useMemo(()=>{var Na;const Qr=(Na=ts.data)==null?void 0:Na.activeOrgId;return Qr?(is.data??[]).find(Aa=>Aa.id===Qr)??null:null},[ts.data,is.data]),orgs:is.data??[],profile:ts.data??null,isLoading:ts.isLoading||is.isLoading,error:ts.error??is.error??null}}function useSetActiveOrg(){const es=useQueryClient();return useMutation({mutationFn:$=>setActiveOrg($),onSuccess:()=>{es.invalidateQueries({queryKey:["profile"]}),es.invalidateQueries({queryKey:["orgs"]}),es.invalidateQueries({queryKey:["sessions"]}),es.invalidateQueries({queryKey:["insights"]}),es.invalidateQueries({queryKey:["projects"]}),es.invalidateQueries({queryKey:["activity"]}),es.invalidateQueries({queryKey:["analytics"]})}})}function OrgAdminGuard({children:es}){return useActiveOrg(),jsxRuntimeExports.jsx(Navigate,{to:"/dashboard",replace:!0})}var t=typeof window<"u"?window:void 0,e=typeof globalThis<"u"?globalThis:t;typeof self>"u"&&(e.self=e),typeof File>"u"&&(e.File=function(){});var i=e==null?void 0:e.navigator,r=e==null?void 0:e.document,s=e==null?void 0:e.location,n=e==null?void 0:e.fetch,o=e!=null&&e.XMLHttpRequest&&"withCredentials"in new e.XMLHttpRequest?e.XMLHttpRequest:void 0,a=e==null?void 0:e.AbortController,l=e==null?void 0:e.CompressionStream,u=i==null?void 0:i.userAgent,h=t??{},d="1.372.5",v={DEBUG:!1,LIB_VERSION:d,LIB_NAME:"web",JS_SDK_VERSION:d};function c(es,$,ts,is,cs,Qr,ja){try{var Na=es[Qr](ja),Aa=Na.value}catch(Oa){return void ts(Oa)}Na.done?$(Aa):Promise.resolve(Aa).then(is,cs)}function p(es){return function(){var $=this,ts=arguments;return new Promise((function(is,cs){var Qr=es.apply($,ts);function ja(Aa){c(Qr,is,cs,ja,Na,"next",Aa)}function Na(Aa){c(Qr,is,cs,ja,Na,"throw",Aa)}ja(void 0)}))}}function f(){return f=Object.assign?Object.assign.bind():function(es){for(var $=1;arguments.length>$;$++){var ts=arguments[$];for(var is in ts)({}).hasOwnProperty.call(ts,is)&&(es[is]=ts[is])}return es},f.apply(null,arguments)}function _(es,$){if(es==null)return{};var ts={};for(var is in es)if({}.hasOwnProperty.call(es,is)){if($.indexOf(is)!==-1)continue;ts[is]=es[is]}return ts}function g(){return g=p((function*(es,$,ts){$===void 0&&($=!0);try{var is=new CompressionStream("gzip"),cs=is.writable.getWriter(),Qr=cs.write(new TextEncoder().encode(es)).then((()=>cs.close())).catch((function(){var Aa=p((function*(Oa){try{yield cs.abort(Oa)}catch{}throw Oa}));return function(Oa){return Aa.apply(this,arguments)}})()),ja=new Response(is.readable).blob(),[Na]=yield Promise.all([ja,Qr]);return Na}catch(Aa){if(ts!=null&&ts.rethrow)throw Aa;return $&&console.error("Failed to gzip compress data",Aa),null}})),g.apply(this,arguments)}var m=["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"],b=function(es,$){if($===void 0&&($=[]),!es)return!1;var ts=es.toLowerCase();return m.concat($).some((is=>{var cs=is.toLowerCase();return ts.indexOf(cs)!==-1}))},y=["$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 w(es,$){return es.indexOf($)!==-1}var x=function(es){return es.trim()},E=function(es){return es.replace(/^\$/,"")},S=Object.prototype,T=S.hasOwnProperty,k=S.toString,R=Array.isArray||function(es){return k.call(es)==="[object Array]"},P=es=>typeof es=="function",O=es=>es===Object(es)&&!R(es),I=es=>{if(O(es)){for(var $ in es)if(T.call(es,$))return!1;return!0}return!1},C=es=>es===void 0,F=es=>k.call(es)=="[object String]",A=es=>F(es)&&es.trim().length===0,M=es=>es===null,D=es=>C(es)||M(es),L=es=>k.call(es)=="[object Number]"&&es==es,U=es=>L(es)&&es>0,N=es=>k.call(es)==="[object Boolean]",j=es=>es instanceof FormData,z=es=>w(y,es);function B(es){return es===null||typeof es!="object"}function H(es,$){return{}.toString.call(es)==="[object "+$+"]"}function q(es){return typeof Event<"u"&&(function($,ts){try{return $ instanceof ts}catch{return!1}})(es,Event)}var V=[!0,"true",1,"1","yes"],W=es=>w(V,es),G=[!1,"false",0,"0","no"];function Y(es,$,ts,is,cs){return $>ts&&(is.warn("min cannot be greater than max."),$=ts),L(es)?es>ts?(is.warn(" cannot be greater than max: "+ts+". Using max value instead."),ts):$>es?(is.warn(" cannot be less than min: "+$+". Using min value instead."),$):es:(is.warn(" must be a number. using max or fallback. max: "+ts+", fallback: "+cs),Y(cs||ts,$,ts,is))}class J{constructor($){this.$t={},this.zt=$.zt,this.Ut=Y($.bucketSize,0,100,$.Gt),this.Wt=Y($.refillRate,0,this.Ut,$.Gt),this.Xt=Y($.refillInterval,0,864e5,$.Gt)}Jt($,ts){var is=Math.floor((ts-$.lastAccess)/this.Xt);is>0&&($.tokens=Math.min($.tokens+is*this.Wt,this.Ut),$.lastAccess=$.lastAccess+is*this.Xt)}consumeRateLimit($){var ts,is=Date.now(),cs=String($),Qr=this.$t[cs];return Qr?this.Jt(Qr,is):this.$t[cs]=Qr={tokens:this.Ut,lastAccess:is},Qr.tokens===0||(Qr.tokens--,Qr.tokens===0&&((ts=this.zt)==null||ts.call(this,$)),Qr.tokens===0)}stop(){this.$t={}}}var K,X,Q,Z="Mobile",tt="iOS",et="Android",it="Tablet",rt=et+" "+it,st="iPad",nt="Apple",ot=nt+" Watch",at="Safari",lt="BlackBerry",ut="Samsung",ht=ut+"Browser",dt=ut+" Internet",vt="Chrome",ct=vt+" OS",pt=vt+" "+tt,ft="Internet Explorer",_t=ft+" "+Z,gt="Opera",mt=gt+" Mini",bt="Edge",yt="Microsoft "+bt,wt="Firefox",xt=wt+" "+tt,Et="Nintendo",St="PlayStation",$t="Xbox",Tt=et+" "+Z,kt=Z+" "+at,Rt="Windows",Pt=Rt+" Phone",Ot="Nokia",It="Ouya",Ct="Generic",Ft=Ct+" "+Z.toLowerCase(),At=Ct+" "+it.toLowerCase(),Mt="Konqueror",Dt="(\\d+(\\.\\d+)?)",Lt=new RegExp("Version/"+Dt),Ut=new RegExp($t,"i"),Nt=new RegExp(St+" \\w+","i"),jt=new RegExp(Et+" \\w+","i"),zt=new RegExp(lt+"|PlayBook|BB10","i"),Bt={"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"},Ht=function(es,$){return $=$||"",w(es," OPR/")&&w(es,"Mini")?mt:w(es," OPR/")?gt:zt.test(es)?lt:w(es,"IE"+Z)||w(es,"WPDesktop")?_t:w(es,ht)?dt:w(es,bt)||w(es,"Edg/")?yt:w(es,"FBIOS")?"Facebook "+Z:w(es,"UCWEB")||w(es,"UCBrowser")?"UC Browser":w(es,"CriOS")?pt:w(es,"CrMo")||w(es,vt)?vt:w(es,et)&&w(es,at)?Tt:w(es,"FxiOS")?xt:w(es.toLowerCase(),Mt.toLowerCase())?Mt:((ts,is)=>is&&w(is,nt)||(function(cs){return w(cs,at)&&!w(cs,vt)&&!w(cs,et)})(ts))(es,$)?w(es,Z)?kt:at:w(es,wt)?wt:w(es,"MSIE")||w(es,"Trident/")?ft:w(es,"Gecko")?wt:""},qt={[_t]:[new RegExp("rv:"+Dt)],[yt]:[new RegExp(bt+"?\\/"+Dt)],[vt]:[new RegExp("("+vt+"|CrMo)\\/"+Dt)],[pt]:[new RegExp("CriOS\\/"+Dt)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Dt)],[at]:[Lt],[kt]:[Lt],[gt]:[new RegExp("(Opera|OPR)\\/"+Dt)],[wt]:[new RegExp(wt+"\\/"+Dt)],[xt]:[new RegExp("FxiOS\\/"+Dt)],[Mt]:[new RegExp("Konqueror[:/]?"+Dt,"i")],[lt]:[new RegExp(lt+" "+Dt),Lt],[Tt]:[new RegExp("android\\s"+Dt,"i")],[dt]:[new RegExp(ht+"\\/"+Dt)],[ft]:[new RegExp("(rv:|MSIE )"+Dt)],Mozilla:[new RegExp("rv:"+Dt)]},Vt=function(es,$){var ts=Ht(es,$),is=qt[ts];if(C(is))return null;for(var cs=0;is.length>cs;cs++){var Qr=es.match(is[cs]);if(Qr)return parseFloat(Qr[Qr.length-2])}return null},Wt=[[new RegExp($t+"; "+$t+" (.*?)[);]","i"),es=>[$t,es&&es[1]||""]],[new RegExp(Et,"i"),[Et,""]],[new RegExp(St,"i"),[St,""]],[zt,[lt,""]],[new RegExp(Rt,"i"),(es,$)=>{if(/Phone/.test($)||/WPDesktop/.test($))return[Pt,""];if(new RegExp(Z).test($)&&!/IEMobile\b/.test($))return[Rt+" "+Z,""];var ts=/Windows NT ([0-9.]+)/i.exec($);if(ts&&ts[1]){var is=Bt[ts[1]]||"";return/arm/i.test($)&&(is="RT"),[Rt,is]}return[Rt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,es=>es&&es[3]?[tt,[es[3],es[4],es[5]||"0"].join(".")]:[tt,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,es=>{var $="";return es&&es.length>=3&&($=C(es[2])?es[3]:es[2]),["watchOS",$]}],[new RegExp("("+et+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+et+")","i"),es=>es&&es[2]?[et,[es[2],es[3],es[4]||"0"].join(".")]:[et,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,es=>{var $=["Mac OS X",""];return es&&es[1]&&($[1]=[es[1],es[2],es[3]||"0"].join(".")),$}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ct,""]],[/Linux|debian/i,["Linux",""]]],Gt=function(es){return jt.test(es)?Et:Nt.test(es)?St:Ut.test(es)?$t:new RegExp(It,"i").test(es)?It:new RegExp("("+Pt+"|WPDesktop)","i").test(es)?Pt:/iPad/.test(es)?st:/iPod/.test(es)?"iPod Touch":/iPhone/.test(es)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(es)?ot:zt.test(es)?lt:/(kobo)\s(ereader|touch)/i.test(es)?"Kobo":new RegExp(Ot,"i").test(es)?Ot:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(es)||/(kf[a-z]+)( bui|\)).+silk\//i.test(es)?"Kindle Fire":/(Android|ZTE)/i.test(es)?new RegExp(Z).test(es)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(es)||/pixel[\daxl ]{1,6}/i.test(es)&&!/pixel c/i.test(es)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(es)||/lmy47v/i.test(es)&&!/QTAQZ3/i.test(es)?et:rt:new RegExp("(pda|"+Z+")","i").test(es)?Ft:new RegExp(it,"i").test(es)&&!new RegExp(it+" pc","i").test(es)?At:""},Yt=es=>es instanceof Error,Jt={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Kt=Jt.info;function Xt(es){if(N(es))return{boolValue:es};if(typeof es=="number")return Number.isFinite(es)?Number.isInteger(es)?{intValue:es}:{doubleValue:es}:{stringValue:String(es)};if(typeof es=="string")return{stringValue:es};if(R(es))return{arrayValue:{values:es.map(($=>Xt($)))}};try{return{stringValue:JSON.stringify(es)}}catch{return{stringValue:String(es)}}}function Qt(es){var $=[];for(var ts in es){var is=es[ts];M(is)||C(is)||$.push({key:ts,value:Xt(is)})}return $}function Zt(es){var $=globalThis._posthogChunkIds;if($){var ts=Object.keys($);return Q&&ts.length===X||(X=ts.length,Q=ts.reduce(((is,cs)=>{K||(K={});var Qr=K[cs];if(Qr)is[Qr[0]]=Qr[1];else for(var ja=es(cs),Na=ja.length-1;Na>=0;Na--){var Aa=ja[Na],Oa=Aa==null?void 0:Aa.filename,Ia=$[cs];if(Oa&&Ia){is[Oa]=Ia,K[cs]=[Oa,Ia];break}}return is}),{})),Q}}class te{constructor($,ts,is){is===void 0&&(is=[]),this.coercers=$,this.stackParser=ts,this.modifiers=is}buildFromUnknown($,ts){ts===void 0&&(ts={});var is=ts&&ts.mechanism||{handled:!0,type:"generic"},cs=this.buildCoercingContext(is,ts,0).apply($),Qr=this.buildParsingContext(ts),ja=this.parseStacktrace(cs,Qr);return{$exception_list:this.convertToExceptionList(ja,is),$exception_level:"error"}}modifyFrames($){var ts=this;return p((function*(){for(var is of $)is.stacktrace&&is.stacktrace.frames&&R(is.stacktrace.frames)&&(is.stacktrace.frames=yield ts.applyModifiers(is.stacktrace.frames));return $}))()}coerceFallback($){var ts;return{type:"Error",value:"Unknown error",stack:(ts=$.syntheticException)==null?void 0:ts.stack,synthetic:!0}}parseStacktrace($,ts){var is,cs;return $.cause!=null&&(is=this.parseStacktrace($.cause,ts)),$.stack!=""&&$.stack!=null&&(cs=this.applyChunkIds(this.stackParser($.stack,$.synthetic?ts.skipFirstLines:0),ts.chunkIdMap)),f({},$,{cause:is,stack:cs})}applyChunkIds($,ts){return $.map((is=>(is.filename&&ts&&(is.chunk_id=ts[is.filename]),is)))}applyCoercers($,ts){for(var is of this.coercers)if(is.match($))return is.coerce($,ts);return this.coerceFallback(ts)}applyModifiers($){var ts=this;return p((function*(){var is=$;for(var cs of ts.modifiers)is=yield cs(is);return is}))()}convertToExceptionList($,ts){var is,cs,Qr,ja={type:$.type,value:$.value,mechanism:{type:(is=ts.type)!==null&&is!==void 0?is:"generic",handled:(cs=ts.handled)===null||cs===void 0||cs,synthetic:(Qr=$.synthetic)!==null&&Qr!==void 0&&Qr}};$.stack&&(ja.stacktrace={type:"raw",frames:$.stack});var Na=[ja];return $.cause!=null&&Na.push(...this.convertToExceptionList($.cause,f({},ts,{handled:!0}))),Na}buildParsingContext($){var ts;return{chunkIdMap:Zt(this.stackParser),skipFirstLines:(ts=$.skipFirstLines)!==null&&ts!==void 0?ts:1}}buildCoercingContext($,ts,is){is===void 0&&(is=0);var cs=(Qr,ja)=>{if(4>=ja){var Na=this.buildCoercingContext($,ts,ja);return this.applyCoercers(Qr,Na)}};return f({},ts,{syntheticException:is==0?ts.syntheticException:void 0,mechanism:$,apply:Qr=>cs(Qr,is),next:Qr=>cs(Qr,is+1)})}}var ee="?";function ie(es,$,ts,is,cs){var Qr={platform:es,filename:$,function:ts==="<anonymous>"?ee:ts,in_app:!0};return C(is)||(Qr.lineno=is),C(cs)||(Qr.colno=cs),Qr}var re=(es,$)=>{var ts=es.indexOf("safari-extension")!==-1,is=es.indexOf("safari-web-extension")!==-1;return ts||is?[es.indexOf("@")!==-1?es.split("@")[0]:ee,ts?"safari-extension:"+$:"safari-web-extension:"+$]:[es,$]},se=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ne=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,oe=/\((\S*)(?::(\d+))(?::(\d+))\)/,ae=(es,$)=>{var ts=se.exec(es);if(ts){var[,is,cs,Qr]=ts;return ie($,is,ee,+cs,+Qr)}var ja=ne.exec(es);if(ja){if(ja[2]&&ja[2].indexOf("eval")===0){var Na=oe.exec(ja[2]);Na&&(ja[2]=Na[1],ja[3]=Na[2],ja[4]=Na[3])}var[Aa,Oa]=re(ja[1]||ee,ja[2]);return ie($,Oa,Aa,ja[3]?+ja[3]:void 0,ja[4]?+ja[4]:void 0)}},le=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ue=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,he=(es,$)=>{var ts=le.exec(es);if(ts){if(ts[3]&&ts[3].indexOf(" > eval")>-1){var is=ue.exec(ts[3]);is&&(ts[1]=ts[1]||"eval",ts[3]=is[1],ts[4]=is[2],ts[5]="")}var cs=ts[3],Qr=ts[1]||ee;return[Qr,cs]=re(Qr,cs),ie($,cs,Qr,ts[4]?+ts[4]:void 0,ts[5]?+ts[5]:void 0)}},de=/\(error: (.*)\)/;class ve{match($){return this.isDOMException($)||this.isDOMError($)}coerce($,ts){var is=F($.stack);return{type:this.getType($),value:this.getValue($),stack:is?$.stack:void 0,cause:$.cause?ts.next($.cause):void 0,synthetic:!1}}getType($){return this.isDOMError($)?"DOMError":"DOMException"}getValue($){var ts=$.name||(this.isDOMError($)?"DOMError":"DOMException");return $.message?ts+": "+$.message:ts}isDOMException($){return H($,"DOMException")}isDOMError($){return H($,"DOMError")}}class ce{match($){return(ts=>ts instanceof Error)($)}coerce($,ts){return{type:this.getType($),value:this.getMessage($,ts),stack:this.getStack($),cause:$.cause?ts.next($.cause):void 0,synthetic:!1}}getType($){return $.name||$.constructor.name}getMessage($,ts){var is=$.message;return String(is.error&&typeof is.error.message=="string"?is.error.message:is)}getStack($){return $.stacktrace||$.stack||void 0}}class pe{constructor(){}match($){return H($,"ErrorEvent")&&$.error!=null}coerce($,ts){var is;return ts.apply($.error)||{type:"ErrorEvent",value:$.message,stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}}}var fe=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class _e{match($){return typeof $=="string"}coerce($,ts){var is,[cs,Qr]=this.getInfos($);return{type:cs??"Error",value:Qr??$,stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}}getInfos($){var ts="Error",is=$,cs=$.match(fe);return cs&&(ts=cs[1],is=cs[2]),[ts,is]}}var ge=["fatal","error","warning","log","info","debug"];function me(es,$){$===void 0&&($=40);var ts=Object.keys(es);if(ts.sort(),!ts.length)return"[object has no keys]";for(var is=ts.length;is>0;is--){var cs=ts.slice(0,is).join(", ");if($>=cs.length)return is===ts.length?cs:cs.length>$?cs.slice(0,$)+"...":cs}return""}class be{match($){return typeof $=="object"&&$!==null}coerce($,ts){var is,cs=this.getErrorPropertyFromObject($);return cs?ts.apply(cs):{type:this.getType($),value:this.getValue($),stack:(is=ts.syntheticException)==null?void 0:is.stack,level:this.isSeverityLevel($.level)?$.level:"error",synthetic:!0}}getType($){return q($)?$.constructor.name:"Error"}getValue($){if("name"in $&&typeof $.name=="string"){var ts="'"+$.name+"' captured as exception";return"message"in $&&typeof $.message=="string"&&(ts+=" with message: '"+$.message+"'"),ts}if("message"in $&&typeof $.message=="string")return $.message;var is=this.getObjectClassName($);return(is&&is!=="Object"?"'"+is+"'":"Object")+" captured as exception with keys: "+me($)}isSeverityLevel($){return F($)&&!A($)&&ge.indexOf($)>=0}getErrorPropertyFromObject($){for(var ts in $)if({}.hasOwnProperty.call($,ts)){var is=$[ts];if(Yt(is))return is}}getObjectClassName($){try{var ts=Object.getPrototypeOf($);return ts?ts.constructor.name:void 0}catch{return}}}class ye{match($){return q($)}coerce($,ts){var is,cs=$.constructor.name;return{type:cs,value:cs+" captured as exception with keys: "+me($),stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}}}class we{match($){return B($)}coerce($,ts){var is;return{type:"Error",value:"Primitive value captured as exception: "+String($),stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}}}class xe{match($){return H($,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection($)}isCustomEventWrappingRejection($){if(!q($))return!1;try{var ts=$.detail;return ts!=null&&typeof ts=="object"&&"reason"in ts}catch{return!1}}coerce($,ts){var is,cs=this.getUnhandledRejectionReason($);return B(cs)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(cs),stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}:ts.apply(cs)}getUnhandledRejectionReason($){try{if("reason"in $)return $.reason;if("detail"in $&&$.detail!=null&&typeof $.detail=="object"&&"reason"in $.detail)return $.detail.reason}catch{}return $}}var Ee="$message",Se="$timestamp",$e=new Set([Ee,Se]),Te={enabled:!0,max_bytes:32768};function ke(es){var $;return es?{enabled:($=es.enabled)!==null&&$!==void 0?$:Te.enabled,max_bytes:Pe(es.max_bytes,Te.max_bytes)}:f({},Te)}class Re{constructor($){this.Kt=[],this.Qt=0,this.Bt=ke($)}setConfig($){this.Bt=ke($),this.er()}add($){var ts=(function(cs){var Qr=(function(Ia){var La=new WeakSet;try{return JSON.stringify(Ia,((Ba,Ma)=>{if(typeof Ma=="bigint")return Ma.toString();if(typeof Ma!="function"&&typeof Ma!="symbol"){if(Ma instanceof Date)return Ma.toISOString();if(Ma instanceof Error)return{name:Ma.name,message:Ma.message,stack:Ma.stack};if(Ma&&typeof Ma=="object"){if(La.has(Ma))return"[Circular]";La.add(Ma)}return Ma}}))}catch{return}})(cs);if(Qr)try{var ja=JSON.parse(Qr);if(!O(ja))return;var Na=ja,Aa=Na[Ee],Oa=Na[Se];return!F(Aa)||Aa.trim().length===0||!F(Oa)&&!L(Oa)?void 0:{step:Na,json:Qr}}catch{return}})($);if(ts){var is=(function(cs){if(typeof TextEncoder<"u")return new TextEncoder().encode(cs).length;for(var Qr=encodeURIComponent(cs),ja=0,Na=0;Qr.length>Na;Na++)Qr[Na]==="%"?(ja+=1,Na+=2):ja+=1;return ja})(ts.json);is>this.Bt.max_bytes||(this.Kt.push({step:ts.step,bytes:is}),this.Qt+=is,this.er())}}getAttachable(){return this.Kt.map(($=>$.step))}clear(){this.Kt=[],this.Qt=0}size(){return this.Kt.length}er(){for(;this.Qt>this.Bt.max_bytes&&this.Kt.length>0;){var $=this.Kt.shift();$&&(this.Qt-=$.bytes)}}}function Pe(es,$){if(!L(es)||es===1/0||es===-1/0)return $;var ts=Math.floor(es);return 0>ts?$:ts}var Oe=function(es,$){var{debugEnabled:ts}=$===void 0?{}:$,is={C(cs){if(t&&(v.DEBUG||h.POSTHOG_DEBUG||ts)&&!C(t.console)&&t.console){for(var Qr=("__rrweb_original__"in t.console[cs])?t.console[cs].__rrweb_original__:t.console[cs],ja=arguments.length,Na=new Array(ja>1?ja-1:0),Aa=1;ja>Aa;Aa++)Na[Aa-1]=arguments[Aa];Qr(es,...Na)}},info(){for(var cs=arguments.length,Qr=new Array(cs),ja=0;cs>ja;ja++)Qr[ja]=arguments[ja];is.C("log",...Qr)},warn(){for(var cs=arguments.length,Qr=new Array(cs),ja=0;cs>ja;ja++)Qr[ja]=arguments[ja];is.C("warn",...Qr)},error(){for(var cs=arguments.length,Qr=new Array(cs),ja=0;cs>ja;ja++)Qr[ja]=arguments[ja];is.C("error",...Qr)},critical(){for(var cs=arguments.length,Qr=new Array(cs),ja=0;cs>ja;ja++)Qr[ja]=arguments[ja];console.error(es,...Qr)},uninitializedWarning(cs){is.error("You must initialize PostHog before calling "+cs)},createLogger:(cs,Qr)=>Oe(es+" "+cs,Qr)};return is},Ie=Oe("[PostHog.js]"),Ce=Ie.createLogger,Fe=Ce("[ExternalScriptsLoader]"),Ae=(es,$,ts)=>{if(es.config.disable_external_dependency_loading)return Fe.warn($+" was requested but loading of external scripts is disabled."),ts("Loading of external scripts is disabled");var is=r==null?void 0:r.querySelectorAll("script");if(is){for(var cs,Qr=function(){if(is[ja].src===$){var Aa=is[ja];return Aa.__posthog_loading_callback_fired?{v:ts()}:(Aa.addEventListener("load",(Oa=>{Aa.__posthog_loading_callback_fired=!0,ts(void 0,Oa)})),Aa.onerror=Oa=>ts(Oa),{v:void 0})}},ja=0;is.length>ja;ja++)if(cs=Qr())return cs.v}var Na=()=>{if(!r)return ts("document not found");var Aa=r.createElement("script");if(Aa.type="text/javascript",Aa.crossOrigin="anonymous",Aa.src=$,Aa.onload=La=>{Aa.__posthog_loading_callback_fired=!0,ts(void 0,La)},Aa.onerror=La=>ts(La),es.config.prepare_external_dependency_script&&(Aa=es.config.prepare_external_dependency_script(Aa)),!Aa)return ts("prepare_external_dependency_script returned null");if(es.config.external_scripts_inject_target==="head")r.head.appendChild(Aa);else{var Oa,Ia=r.querySelectorAll("body > script");Ia.length>0?(Oa=Ia[0].parentNode)==null||Oa.insertBefore(Aa,Ia[0]):r.body.appendChild(Aa)}};r!=null&&r.body?Na():r==null||r.addEventListener("DOMContentLoaded",Na)};h.__PosthogExtensions__=h.__PosthogExtensions__||{},h.__PosthogExtensions__.loadExternalDependency=(es,$,ts)=>{if($!=="remote-config"){var is;if(es.config.__preview_external_dependency_versioned_paths)is=es.requestRouter.endpointFor("assets","/static/"+es.version+"/"+$+".js");else{var cs="/static/"+$+".js?v="+es.version;if($==="toolbar"){var Qr=3e5;cs=cs+"&t="+Math.floor(Date.now()/Qr)*Qr}is=es.requestRouter.endpointFor("assets",cs)}Ae(es,is,ts)}else{var ja=es.requestRouter.endpointFor("assets","/array/"+es.config.token+"/config.js");Ae(es,ja,ts)}},h.__PosthogExtensions__.loadSiteApp=(es,$,ts)=>{var is=es.requestRouter.endpointFor("api",$);Ae(es,is,ts)};var Me="$people_distinct_id",De="$device_id",Le="__alias",Ue="__timers",Ne="$autocapture_disabled_server_side",je="$heatmaps_enabled_server_side",ze="$exception_capture_enabled_server_side",Be="$error_tracking_suppression_rules",He="$error_tracking_capture_extension_exceptions",qe="$web_vitals_enabled_server_side",Ve="$dead_clicks_enabled_server_side",We="$product_tours_enabled_server_side",Ge="$web_vitals_allowed_metrics",Ye="$session_recording_remote_config",Je="$replay_override_sampling",Ke="$replay_override_linked_flag",Xe="$replay_override_url_trigger",Qe="$replay_override_event_trigger",Ze="$sesid",ti="$session_is_sampled",ei="$enabled_feature_flags",ii="$active_feature_flags",ri="$early_access_features",si="$feature_flag_details",ni="$feature_flag_payloads",oi="$feature_flag_request_id",ai="$override_feature_flags",li="$override_feature_flag_payloads",ui="$stored_person_properties",hi="$stored_group_properties",di="$surveys",vi="$surveys_activated",ci="ph_product_tours",pi="$flag_call_reported",fi="$flag_call_reported_session_id",_i="$feature_flag_errors",gi="$feature_flag_evaluated_at",mi="$user_state",bi="$client_session_props",yi="$capture_rate_limit",wi="$initial_campaign_params",xi="$initial_referrer_info",Ei="$initial_person_info",Si="$epp",$i="__POSTHOG_TOOLBAR__",Ti="$posthog_cookieless",ki="$sdk_debug_extensions_init_method",Ri="$sdk_debug_extensions_init_time_ms",Pi="$sdk_debug_recording_script_not_loaded",Oi="PostHog loadExternalDependency extension not found.",Ii="on_reject",Ci="always",Fi="anonymous",Ai="identified",Mi="identified_only",Di="visibilitychange",Li="beforeunload",Ui="$pageview",Ni="$pageleave",ji="$identify",zi="$groupidentify";function Bi(es,$){R(es)&&es.forEach($)}function Hi(es,$){if(!D(es))if(R(es))es.forEach($);else if(j(es))es.forEach(((is,cs)=>$(is,cs)));else for(var ts in es)T.call(es,ts)&&$(es[ts],ts)}var qi=function(es){for(var $=arguments.length,ts=new Array($>1?$-1:0),is=1;$>is;is++)ts[is-1]=arguments[is];for(var cs of ts)for(var Qr in cs)cs[Qr]!==void 0&&(es[Qr]=cs[Qr]);return es};function Vi(es){for(var $=Object.keys(es),ts=$.length,is=new Array(ts);ts--;)is[ts]=[$[ts],es[$[ts]]];return is}var Wi=function(es){try{return es()}catch{return}},Gi=function(es){return function(){try{for(var $=arguments.length,ts=new Array($),is=0;$>is;is++)ts[is]=arguments[is];return es.apply(this,ts)}catch(cs){Ie.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ie.critical(cs)}}},Yi=function(es){var $={};return Hi(es,(function(ts,is){(F(ts)&&ts.length>0||L(ts))&&($[is]=ts)})),$},Ji=["herokuapp.com","vercel.app","netlify.app"];function Ki(es){var $=es==null?void 0:es.hostname;if(!F($))return!1;var ts=$.split(".").slice(-2).join(".");for(var is of Ji)if(ts===is)return!1;return!0}function Xi(es,$,ts,is){var{capture:cs=!1,passive:Qr=!0}=is??{};es==null||es.addEventListener($,ts,{capture:cs,passive:Qr})}function Qi(es){return es.name==="ph_toolbar_internal"}Math.trunc||(Math.trunc=function(es){return 0>es?Math.ceil(es):Math.floor(es)}),Number.isInteger||(Number.isInteger=function(es){return L(es)&&isFinite(es)&&Math.floor(es)===es});class Zi{constructor($){if(this.bytes=$,$.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7($,ts,is,cs){if(!Number.isInteger($)||!Number.isInteger(ts)||!Number.isInteger(is)||!Number.isInteger(cs)||0>$||0>ts||0>is||0>cs||$>0xffffffffffff||ts>4095||is>1073741823||cs>4294967295)throw new RangeError("invalid field value");var Qr=new Uint8Array(16);return Qr[0]=$/Math.pow(2,40),Qr[1]=$/Math.pow(2,32),Qr[2]=$/Math.pow(2,24),Qr[3]=$/Math.pow(2,16),Qr[4]=$/Math.pow(2,8),Qr[5]=$,Qr[6]=112|ts>>>8,Qr[7]=ts,Qr[8]=128|is>>>24,Qr[9]=is>>>16,Qr[10]=is>>>8,Qr[11]=is,Qr[12]=cs>>>24,Qr[13]=cs>>>16,Qr[14]=cs>>>8,Qr[15]=cs,new Zi(Qr)}toString(){for(var $="",ts=0;this.bytes.length>ts;ts++)$=$+(this.bytes[ts]>>>4).toString(16)+(15&this.bytes[ts]).toString(16),ts!==3&&ts!==5&&ts!==7&&ts!==9||($+="-");if($.length!==36)throw new Error("Invalid UUIDv7 was generated");return $}clone(){return new Zi(this.bytes.slice(0))}equals($){return this.compareTo($)===0}compareTo($){for(var ts=0;16>ts;ts++){var is=this.bytes[ts]-$.bytes[ts];if(is!==0)return Math.sign(is)}return 0}}class tr{constructor(){this.I=0,this.S=0,this.k=new rr}generate(){var $=this.generateOrAbort();if(C($)){this.I=0;var ts=this.generateOrAbort();if(C(ts))throw new Error("Could not generate UUID after timestamp reset");return ts}return $}generateOrAbort(){var $=Date.now();if($>this.I)this.I=$,this.A();else{if(this.I>=$+1e4)return;this.S++,this.S>4398046511103&&(this.I++,this.A())}return Zi.fromFieldsV7(this.I,Math.trunc(this.S/Math.pow(2,30)),this.S&Math.pow(2,30)-1,this.k.nextUint32())}A(){this.S=1024*this.k.nextUint32()+(1023&this.k.nextUint32())}}var er,ir=es=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var $=0;es.length>$;$++)es[$]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return es};t&&!C(t.crypto)&&crypto.getRandomValues&&(ir=es=>crypto.getRandomValues(es));class rr{constructor(){this.T=new Uint32Array(8),this.N=1/0}nextUint32(){return this.T.length>this.N||(ir(this.T),this.N=0),this.T[this.N++]}}var sr=()=>nr().toString(),nr=()=>(er||(er=new tr)).generate(),or="",ar=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,lr={R:()=>!!r,B(es){Ie.error("cookieStore error: "+es)},O(es){if(r){try{for(var $=es+"=",ts=r.cookie.split(";").filter((Qr=>Qr.length)),is=0;ts.length>is;is++){for(var cs=ts[is];cs.charAt(0)==" ";)cs=cs.substring(1,cs.length);if(cs.indexOf($)===0)return decodeURIComponent(cs.substring($.length,cs.length))}}catch{}return null}},Z(es){var $;try{$=JSON.parse(lr.O(es))||{}}catch{}return $},M(es,$,ts,is,cs){if(r)try{var Qr="",ja="",Na=(function(Ia,La){if(La){var Ba=(function(qa,Fa){if(Fa===void 0&&(Fa=r),or)return or;if(!Fa||["localhost","127.0.0.1"].includes(qa))return"";for(var Ha=qa.split("."),Ka=Math.min(Ha.length,8),Ga="dmn_chk_"+sr();!or&&Ka--;){var Va=Ha.slice(Ka).join("."),Ja=Ga+"=1;domain=."+Va+";path=/";Fa.cookie=Ja+";max-age=3",Fa.cookie.includes(Ga)&&(Fa.cookie=Ja+";max-age=0",or=Va)}return or})(Ia);if(!Ba){var Ma=(qa=>{var Fa=qa.match(ar);return Fa?Fa[0]:""})(Ia);Ma!==Ba&&Ie.info("Warning: cookie subdomain discovery mismatch",Ma,Ba),Ba=Ma}return Ba?"; domain=."+Ba:""}return""})(r.location.hostname,is);if(ts){var Aa=new Date;Aa.setTime(Aa.getTime()+864e5*ts),Qr="; expires="+Aa.toUTCString()}cs&&(ja="; secure");var Oa=es+"="+encodeURIComponent(JSON.stringify($))+Qr+"; SameSite=Lax; path=/"+Na+ja;return Oa.length>3686.4&&Ie.warn("cookieStore warning: large cookie, len="+Oa.length),r.cookie=Oa,Oa}catch{return}},F(es,$){if(r!=null&&r.cookie)try{lr.M(es,"",-1,$)}catch{return}}},ur=null,hr={R(){if(!M(ur))return ur;var es=!0;if(C(t))es=!1;else try{var $="__mplssupport__";hr.M($,"xyz"),hr.O($)!=='"xyz"'&&(es=!1),hr.F($)}catch{es=!1}return es||Ie.error("localStorage unsupported; falling back to cookie store"),ur=es,es},B(es){Ie.error("localStorage error: "+es)},O(es){try{return t==null?void 0:t.localStorage.getItem(es)}catch($){hr.B($)}return null},Z(es){try{return JSON.parse(hr.O(es))||{}}catch{}return null},M(es,$){try{t==null||t.localStorage.setItem(es,JSON.stringify($))}catch(ts){hr.B(ts)}},F(es){try{t==null||t.localStorage.removeItem(es)}catch($){hr.B($)}}},dr=[De,"distinct_id",Ze,ti,Si,Ei,mi],vr={},cr={R:()=>!0,B(es){Ie.error("memoryStorage error: "+es)},O:es=>vr[es]||null,Z:es=>vr[es]||null,M(es,$){vr[es]=$},F(es){delete vr[es]}},pr=null,fr={R(){if(!M(pr))return pr;if(pr=!0,C(t))pr=!1;else try{var es="__support__";fr.M(es,"xyz"),fr.O(es)!=='"xyz"'&&(pr=!1),fr.F(es)}catch{pr=!1}return pr},B(es){Ie.error("sessionStorage error: ",es)},O(es){try{return t==null?void 0:t.sessionStorage.getItem(es)}catch($){fr.B($)}return null},Z(es){try{return JSON.parse(fr.O(es))||null}catch{}return null},M(es,$){try{t==null||t.sessionStorage.setItem(es,JSON.stringify($))}catch(ts){fr.B(ts)}},F(es){try{t==null||t.sessionStorage.removeItem(es)}catch($){fr.B($)}}};class _r{constructor($){this._instance=$}get Bt(){return this._instance.config}get consent(){return this.rr()?0:this.ir}isOptedOut(){return this.Bt.cookieless_mode===Ci||this.isRejected()||this.consent===-1&&this.Bt.cookieless_mode===Ii}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Bt.opt_out_capturing_by_default}optInOut($){this.nr.M(this.sr,$?1:0,this.Bt.cookie_expiration,this.Bt.cross_subdomain_cookie,this.Bt.secure_cookie)}reset(){this.nr.F(this.sr,this.Bt.cross_subdomain_cookie)}get sr(){var{token:$,opt_out_capturing_cookie_prefix:ts,consent_persistence_name:is}=this._instance.config;return is||(ts?ts+$:"__ph_opt_in_out_"+$)}get ir(){var $=this.nr.O(this.sr);return W($)?1:w(G,$)?0:-1}get nr(){var $=this.Bt.opt_out_capturing_persistence_type,ts=$==="localStorage"?hr:lr;if(!this.ar||this.ar!==ts){this.ar=ts;var is=$==="localStorage"?lr:hr;is.O(this.sr)&&(this.ar.O(this.sr)||this.optInOut(W(is.O(this.sr))),is.F(this.sr,this.Bt.cross_subdomain_cookie))}return this.ar}rr(){return!!this.Bt.respect_dnt&&[i==null?void 0:i.doNotTrack,i==null?void 0:i.msDoNotTrack,h.doNotTrack].some(($=>W($)))}}var gr=Ce("[Dead Clicks]"),mr=()=>!0,br=es=>{var $,ts=!(($=es.instance.persistence)==null||!$.get_property(Ve)),is=es.instance.config.capture_dead_clicks;return N(is)?is:!!O(is)||ts};class yr{get lazyLoadedDeadClicksAutocapture(){return this.lr}constructor($,ts,is){this.instance=$,this.isEnabled=ts,this.onCapture=is,this.startIfEnabledOrStop()}onRemoteConfig($){"captureDeadClicks"in $&&(this.instance.persistence&&this.instance.persistence.register({[Ve]:$.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.ur((()=>{this.hr()})):this.stop()}ur($){var ts,is;(ts=h.__PosthogExtensions__)!=null&&ts.initDeadClicksAutocapture&&$(),(is=h.__PosthogExtensions__)==null||is.loadExternalDependency==null||is.loadExternalDependency(this.instance,"dead-clicks-autocapture",(cs=>{cs?gr.error("failed to load script",cs):$()}))}hr(){var $;if(r){if(!this.lr&&($=h.__PosthogExtensions__)!=null&&$.initDeadClicksAutocapture){var ts=O(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};ts.__onCapture=this.onCapture,this.lr=h.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,ts),this.lr.start(r),gr.info("starting...")}}else gr.error("`document` not found. Cannot start.")}stop(){this.lr&&(this.lr.stop(),this.lr=void 0,gr.info("stopping..."))}}var wr=Ce("[SegmentIntegration]"),xr="posthog-js";function Er(es,$){var{organization:ts,projectId:is,prefix:cs,severityAllowList:Qr=["error"],sendExceptionsToPostHog:ja=!0}=$===void 0?{}:$;return Na=>{var Aa,Oa,Ia,La,Ba;if(Qr!=="*"&&!Qr.includes(Na.level)||!es.__loaded)return Na;Na.tags||(Na.tags={});var Ma=es.requestRouter.endpointFor("ui","/project/"+es.config.token+"/person/"+es.get_distinct_id());Na.tags["PostHog Person URL"]=Ma,es.sessionRecordingStarted()&&(Na.tags["PostHog Recording URL"]=es.get_session_replay_url({withTimestamp:!0}));var qa,Fa=((Aa=Na.exception)==null?void 0:Aa.values)||[],Ha=Fa.map((Ga=>f({},Ga,{stacktrace:Ga.stacktrace?f({},Ga.stacktrace,{type:"raw",frames:(Ga.stacktrace.frames||[]).map((Va=>f({},Va,{platform:"web:javascript"})))}):void 0}))),Ka={$exception_message:((Oa=Fa[0])==null?void 0:Oa.value)||Na.message,$exception_type:(Ia=Fa[0])==null?void 0:Ia.type,$exception_level:Na.level,$exception_list:Ha,$sentry_event_id:Na.event_id,$sentry_exception:Na.exception,$sentry_exception_message:((La=Fa[0])==null?void 0:La.value)||Na.message,$sentry_exception_type:(Ba=Fa[0])==null?void 0:Ba.type,$sentry_tags:Na.tags};return ts&&is&&(Ka.$sentry_url=(cs||"https://sentry.io/organizations/")+ts+"/issues/?project="+is+"&query="+Na.event_id),ja&&((qa=es.exceptions)==null||qa.sendExceptionEvent(Ka)),Na}}class Sr{constructor($,ts,is,cs,Qr,ja){this.name=xr,this.setupOnce=function(Na){Na(Er($,{organization:ts,projectId:is,prefix:cs,severityAllowList:Qr,sendExceptionsToPostHog:ja==null||ja}))}}}class $r{constructor($){this.cr=(ts,is,cs)=>{cs&&(cs.noSessionId||cs.activityTimeout||cs.sessionPastMaximumLength)&&(Ie.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:ts,changeReason:cs}),this.dr=void 0,this._instance.scrollManager.resetContext())},this._instance=$,this.vr()}vr(){var $;this.pr=($=this._instance.sessionManager)==null?void 0:$.onSessionId(this.cr)}destroy(){var $;($=this.pr)==null||$.call(this),this.pr=void 0}doPageView($,ts){var is,cs=this.gr($,ts);return this.dr={pathname:(is=t==null?void 0:t.location.pathname)!==null&&is!==void 0?is:"",pageViewId:ts,timestamp:$},this._instance.scrollManager.resetContext(),cs}doPageLeave($){var ts;return this.gr($,(ts=this.dr)==null?void 0:ts.pageViewId)}doEvent(){var $;return{$pageview_id:($=this.dr)==null?void 0:$.pageViewId}}gr($,ts){var is=this.dr;if(!is)return{$pageview_id:ts};var cs={$pageview_id:ts,$prev_pageview_id:is.pageViewId},Qr=this._instance.scrollManager.getContext();if(Qr&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:ja,lastScrollY:Na,maxScrollY:Aa,maxContentHeight:Oa,lastContentY:Ia,maxContentY:La}=Qr;if(!(C(ja)||C(Na)||C(Aa)||C(Oa)||C(Ia)||C(La))){ja=Math.ceil(ja),Na=Math.ceil(Na),Aa=Math.ceil(Aa),Oa=Math.ceil(Oa),Ia=Math.ceil(Ia),La=Math.ceil(La);var Ba=ja>1?Y(Na/ja,0,1,Ie):1,Ma=ja>1?Y(Aa/ja,0,1,Ie):1,qa=Oa>1?Y(Ia/Oa,0,1,Ie):1,Fa=Oa>1?Y(La/Oa,0,1,Ie):1;cs=qi(cs,{$prev_pageview_last_scroll:Na,$prev_pageview_last_scroll_percentage:Ba,$prev_pageview_max_scroll:Aa,$prev_pageview_max_scroll_percentage:Ma,$prev_pageview_last_content:Ia,$prev_pageview_last_content_percentage:qa,$prev_pageview_max_content:La,$prev_pageview_max_content_percentage:Fa})}}return is.pathname&&(cs.$prev_pageview_pathname=is.pathname),is.timestamp&&(cs.$prev_pageview_duration=($.getTime()-is.timestamp.getTime())/1e3),cs}}var Tr={[Me]:{exposure:"hidden"},[Le]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ue]:{exposure:"hidden"},[Ne]:{exposure:"event"},[je]:{exposure:"hidden"},[ze]:{exposure:"event"},[Be]:{exposure:"hidden"},[He]:{exposure:"event"},[qe]:{exposure:"event"},[Ve]:{exposure:"event"},[We]:{exposure:"hidden"},[Ge]:{exposure:"event"},[Ye]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Ze]:{exposure:"hidden"},[ti]:{exposure:"event"},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},[ei]:{exposure:"derived",shouldSkipFromEventProperties:(es,$)=>$(),transformToEventProperties(es){if(!O(es))return{};for(var $={},ts=Object.keys(es),is=0;ts.length>is;is++)$["$feature/"+ts[is]]=es[ts[is]];return $}},[ii]:{exposure:"event"},[ri]:{exposure:"hidden"},[si]:{exposure:"hidden"},[ni]:{exposure:"event"},[oi]:{exposure:"event"},[ai]:{exposure:"event"},[li]:{exposure:"hidden"},[ui]:{exposure:"hidden"},[hi]:{exposure:"hidden"},[di]:{exposure:"hidden"},[vi]:{exposure:"event"},[ci]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[pi]:{exposure:"hidden"},[fi]:{exposure:"hidden"},[_i]:{exposure:"hidden"},[gi]:{exposure:"hidden"},[mi]:{exposure:"hidden"},[bi]:{exposure:"hidden"},[yi]:{exposure:"hidden"},[wi]:{exposure:"hidden"},[xi]:{exposure:"hidden"},[Ei]:{exposure:"hidden"},[Si]:{exposure:"hidden"},[Je]:{exposure:"event"},[Ke]:{exposure:"event"},[Xe]:{exposure:"event"},[Qe]:{exposure:"event"},[ki]:{exposure:"event"},[Ri]:{exposure:"event"},[Pi]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},kr=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Rr=es=>{var $=r==null?void 0:r.createElement("a");return C($)?null:($.href=es,$)},Pr=function(es,$){for(var ts,is=((es.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),cs=0;is.length>cs;cs++){var Qr=is[cs].split("=");if(Qr[0]===$){ts=Qr;break}}if(!R(ts)||2>ts.length)return"";var ja=ts[1];try{ja=decodeURIComponent(ja)}catch{Ie.error("Skipping decoding for malformed query param: "+ja)}return ja.replace(/\+/g," ")},Or=function(es,$,ts){if(!es||!$||!$.length)return es;for(var is=es.split("#"),cs=is[1],Qr=(is[0]||"").split("?"),ja=Qr[1],Na=Qr[0],Aa=(ja||"").split("&"),Oa=[],Ia=0;Aa.length>Ia;Ia++){var La=Aa[Ia].split("=");R(La)&&($.includes(La[0])?Oa.push(La[0]+"="+ts):Oa.push(Aa[Ia]))}var Ba=Na;return ja!=null&&(Ba+="?"+Oa.join("&")),cs!=null&&(Ba+="#"+cs),Ba},Ir=function(es,$){var ts=es.match(new RegExp($+"=([^&]*)"));return ts?ts[1]:null},Cr="https?://(.*)",Fr=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Ar=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Fr],Mr="<masked>",Dr=["li_fat_id"];function Lr(es,$,ts){if(!r)return{};var is,cs=$?[...Fr,...ts||[]]:[],Qr=Ur(Or(r.URL,cs,Mr),es),ja=(is={},Hi(Dr,(function(Na){var Aa=lr.O(Na);is[Na]=Aa||null})),is);return qi(ja,Qr)}function Ur(es,$){var ts=Ar.concat($||[]),is={};return Hi(ts,(function(cs){var Qr=Pr(es,cs);is[cs]=Qr||null})),is}function Nr(es){var $=(function(Qr){return Qr?Qr.search(Cr+"google.([^/?]*)")===0?"google":Qr.search(Cr+"bing.com")===0?"bing":Qr.search(Cr+"yahoo.com")===0?"yahoo":Qr.search(Cr+"duckduckgo.com")===0?"duckduckgo":null:null})(es),ts=$!="yahoo"?"q":"p",is={};if(!M($)){is.$search_engine=$;var cs=r?Pr(r.referrer,ts):"";cs.length&&(is.ph_keyword=cs)}return is}function jr(){return navigator.language||navigator.userLanguage}var zr="$direct";function Br(){return(r==null?void 0:r.referrer)||zr}function Hr(es,$){var ts=es?[...Fr,...$||[]]:[],is=s==null?void 0:s.href.substring(0,1e3);return{r:Br().substring(0,1e3),u:is?Or(is,ts,Mr):void 0}}function qr(es){var $,{r:ts,u:is}=es,cs={$referrer:ts,$referring_domain:ts==null?void 0:ts==zr?zr:($=Rr(ts))==null?void 0:$.host};if(is){cs.$current_url=is;var Qr=Rr(is);cs.$host=Qr==null?void 0:Qr.host,cs.$pathname=Qr==null?void 0:Qr.pathname;var ja=Ur(is);qi(cs,ja)}if(ts){var Na=Nr(ts);qi(cs,Na)}return cs}function Vr(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Wr(){try{return new Date().getTimezoneOffset()}catch{return}}var Gr=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class Yr{constructor($,ts){this.Bt=$,this.props={},this.mr=!1,this.yr=(is=>{var cs="";return is.token&&(cs=is.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),is.persistence_name?"ph_"+is.persistence_name:"ph_"+cs+"_posthog"})($),this.nr=this.br($),this.load(),$.debug&&Ie.info("Persistence loaded",$.persistence,f({},this.props)),this.update_config($,$,ts),this.save()}isDisabled(){return!!this._r}br($){Gr.indexOf($.persistence.toLowerCase())===-1&&(Ie.critical("Unknown persistence type "+$.persistence+"; falling back to localStorage+cookie"),$.persistence="localStorage+cookie");var ts=(function(cs){cs===void 0&&(cs=[]);var Qr=[...dr,...cs];return f({},hr,{Z(ja){try{var Na={};try{Na=lr.Z(ja)||{}}catch{}var Aa=qi(Na,JSON.parse(hr.O(ja)||"{}"));return hr.M(ja,Aa),Aa}catch{}return null},M(ja,Na,Aa,Oa,Ia,La){try{hr.M(ja,Na,void 0,void 0,La);var Ba={};Qr.forEach((Ma=>{Na[Ma]&&(Ba[Ma]=Na[Ma])})),Object.keys(Ba).length&&lr.M(ja,Ba,Aa,Oa,Ia,La)}catch(Ma){hr.B(Ma)}},F(ja,Na){try{t==null||t.localStorage.removeItem(ja),lr.F(ja,Na)}catch(Aa){hr.B(Aa)}}})})($.cookie_persisted_properties||[]),is=$.persistence.toLowerCase();return is==="localstorage"&&hr.R()?hr:is==="localstorage+cookie"&&ts.R()?ts:is==="sessionstorage"&&fr.R()?fr:is==="memory"?cr:is==="cookie"?lr:ts.R()?ts:lr}wr($){var ts=$??this.Bt.feature_flag_cache_ttl_ms;if(!ts||0>=ts)return!1;var is=this.props[gi];return!is||typeof is!="number"||Date.now()-is>ts}properties(){var $={};return Hi(this.props,((ts,is)=>{var cs=(Qr=>{var ja=Tr[Qr];if(ja)return ja;for(var[Na,Aa]of kr)if(Qr.indexOf(Na)===0)return Aa})(is);if((cs==null?void 0:cs.exposure)==="derived"){if(cs.shouldSkipFromEventProperties!=null&&cs.shouldSkipFromEventProperties(ts,is===ei?()=>this.wr():()=>!1))return;cs.transformToEventProperties&&qi($,cs.transformToEventProperties(ts))}else cs&&cs.exposure!=="event"||($[is]=ts)})),$}load(){if(!this._r){var $=this.nr.Z(this.yr);$&&(this.props=qi({},$))}}save(){this._r||this.nr.M(this.yr,this.props,this.Ir,this.Cr,this.Sr,this.Bt.debug)}remove(){this.nr.F(this.yr,!1),this.nr.F(this.yr,!0)}clear(){this.remove(),this.props={}}register_once($,ts,is){if(O($)){C(ts)&&(ts="None"),this.Ir=C(is)?this.kr:is;var cs=!1;if(Hi($,((Qr,ja)=>{this.props.hasOwnProperty(ja)&&this.props[ja]!==ts||(this.Tr(ja,Qr),cs=!0)})),cs)return this.save(),!0}return!1}register($,ts){if(O($)){this.Ir=C(ts)?this.kr:ts;var is=!1;if(Hi($,((cs,Qr)=>{$.hasOwnProperty(Qr)&&this.props[Qr]!==cs&&(this.Tr(Qr,cs),is=!0)})),is)return this.save(),!0}return!1}unregister($){$ in this.props&&(this.Ar($),this.save())}update_campaign_params(){if(!this.mr){var $=Lr(this.Bt.custom_campaign_params,this.Bt.mask_personal_data_properties,this.Bt.custom_personal_data_properties);I(Yi($))||this.register($),this.mr=!0}}update_search_keyword(){var $;this.register(($=r==null?void 0:r.referrer)?Nr($):{})}update_referrer_info(){var $;this.register_once({$referrer:Br(),$referring_domain:r!=null&&r.referrer&&(($=Rr(r.referrer))==null?void 0:$.host)||zr},void 0)}set_initial_person_info(){this.props[wi]||this.props[xi]||this.register_once({[Ei]:Hr(this.Bt.mask_personal_data_properties,this.Bt.custom_personal_data_properties)},void 0)}get_initial_props(){var $={};Hi([xi,wi],(ja=>{var Na=this.props[ja];Na&&Hi(Na,(function(Aa,Oa){$["$initial_"+E(Oa)]=Aa}))}));var ts,is,cs=this.props[Ei];if(cs){var Qr=(ts=qr(cs),is={},Hi(ts,(function(ja,Na){is["$initial_"+E(Na)]=ja})),is);qi($,Qr)}return $}safe_merge($){return Hi(this.props,(function(ts,is){is in $||($[is]=ts)})),$}update_config($,ts,is){if(this.kr=this.Ir=$.cookie_expiration,this.set_disabled($.disable_persistence||!!is),this.set_cross_subdomain($.cross_subdomain_cookie),this.set_secure($.secure_cookie),$.persistence!==ts.persistence||!((ja,Na)=>{if(ja.length!==Na.length)return!1;var Aa=[...ja].sort(),Oa=[...Na].sort();return Aa.every(((Ia,La)=>Ia===Oa[La]))})($.cookie_persisted_properties||[],ts.cookie_persisted_properties||[])){var cs=this.br($),Qr=this.props;this.clear(),this.nr=cs,this.props=Qr,this.save()}}set_disabled($){this._r=$,this._r?this.remove():this.save()}set_cross_subdomain($){$!==this.Cr&&(this.Cr=$,this.remove(),this.save())}set_secure($){$!==this.Sr&&(this.Sr=$,this.remove(),this.save())}set_event_timer($,ts){var is=this.props[Ue]||{};is[$]=ts,this.Tr(Ue,is),this.save()}remove_event_timer($){var ts=this.props[Ue]||{},is=ts[$];return C(is)||(delete ts[$],this.Tr(Ue,ts),this.save()),is}get_property($){return this.props[$]}set_property($,ts){this.Tr($,ts),this.save()}Tr($,ts){this.props[$]=ts}Ar($){delete this.props[$]}}var Jr={Activation:"events",Cancellation:"cancelEvents"},Zr={Popover:"popover",API:"api",Widget:"widget"},rs={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ss={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},ns={Popover:"popover",Inline:"inline"},as={SHOWN:"product tour shown"},ls={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},us=Ce("[RateLimiter]");class hs{constructor($){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=ts=>{var is=ts.text;if(is&&is.length)try{(JSON.parse(is).quota_limited||[]).forEach((cs=>{us.info((cs||"events")+" is quota limited."),this.serverLimits[cs]=new Date().getTime()+6e4}))}catch(cs){return void us.warn('could not rate limit - continuing. Error: "'+(cs==null?void 0:cs.message)+'"',{text:is})}},this.instance=$,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var $;return(($=this.instance.config.rate_limiting)==null?void 0:$.events_per_second)||10}get captureEventsBurstLimit(){var $;return Math.max((($=this.instance.config.rate_limiting)==null?void 0:$.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext($){var ts,is,cs;$===void 0&&($=!1);var{captureEventsBurstLimit:Qr,captureEventsPerSecond:ja}=this,Na=new Date().getTime(),Aa=(ts=(is=this.instance.persistence)==null?void 0:is.get_property(yi))!==null&&ts!==void 0?ts:{tokens:Qr,last:Na};Aa.tokens+=(Na-Aa.last)/1e3*ja,Aa.last=Na,Aa.tokens>Qr&&(Aa.tokens=Qr);var Oa=1>Aa.tokens;return Oa||$||(Aa.tokens=Math.max(0,Aa.tokens-1)),!Oa||this.lastEventRateLimited||$||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+ja+" events per second and "+Qr+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=Oa,(cs=this.instance.persistence)==null||cs.set_property(yi,Aa),{isRateLimited:Oa,remainingTokens:Aa.tokens}}isServerRateLimited($){var ts=this.serverLimits[$||"events"]||!1;return ts!==!1&&new Date().getTime()<ts}}var ds=Ce("[RemoteConfig]");class vs{constructor($){this._instance=$}get remoteConfig(){var $;return($=h._POSTHOG_REMOTE_CONFIG)==null||($=$[this._instance.config.token])==null?void 0:$.config}Er($){var ts,is;(ts=h.__PosthogExtensions__)!=null&&ts.loadExternalDependency?(is=h.__PosthogExtensions__)==null||is.loadExternalDependency==null||is.loadExternalDependency(this._instance,"remote-config",(()=>$(this.remoteConfig))):$()}Rr($){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback(ts){$(ts.json)}})}load(){try{if(this.remoteConfig)return ds.info("Using preloaded remote config",this.remoteConfig),this.Nr(this.remoteConfig),void this.Mr();if(this._instance.Fr())return void ds.warn("Remote config is disabled. Falling back to local config.");this.Er(($=>{if(!$)return ds.info("No config found after loading remote JS config. Falling back to JSON."),void this.Rr((ts=>{this.Nr(ts),this.Mr()}));this.Nr($),this.Mr()}))}catch($){ds.error("Error loading remote config",$)}}stop(){this.Or&&(clearInterval(this.Or),this.Or=void 0)}refresh(){this._instance.Fr()||(r==null?void 0:r.visibilityState)==="hidden"||this._instance.reloadFeatureFlags()}Mr(){var $;if(!this.Or){var ts=($=this._instance.config.remote_config_refresh_interval_ms)!==null&&$!==void 0?$:3e5;ts!==0&&(this.Or=setInterval((()=>{this.refresh()}),ts))}}Nr($){var ts;$||ds.error("Failed to fetch remote config from PostHog."),this._instance.Nr($??{}),($==null?void 0:$.hasFeatureFlags)!==!1&&(this._instance.config.advanced_disable_feature_flags_on_first_load||(ts=this._instance.featureFlags)==null||ts.ensureFlagsLoaded())}}var ps={GZipJS:"gzip-js",Base64:"base64"},fs=Uint8Array,_s=Uint16Array,gs=Uint32Array,ms=new fs([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]),bs=new fs([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]),ys=new fs([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ws=function(es,$){for(var ts=new _s(31),is=0;31>is;++is)ts[is]=$+=1<<es[is-1];var cs=new gs(ts[30]);for(is=1;30>is;++is)for(var Qr=ts[is];ts[is+1]>Qr;++Qr)cs[Qr]=Qr-ts[is]<<5|is;return[ts,cs]},xs=ws(ms,2),Es=xs[1];xs[0][28]=258,Es[258]=28;for(var Ss=ws(bs,0)[1],$s=new _s(32768),Ts=0;32768>Ts;++Ts){var ks=(43690&Ts)>>>1|(21845&Ts)<<1;$s[Ts]=((65280&(ks=(61680&(ks=(52428&ks)>>>2|(13107&ks)<<2))>>>4|(3855&ks)<<4))>>>8|(255&ks)<<8)>>>1}var Rs=function(es,$,ts){for(var is=es.length,cs=0,Qr=new _s($);is>cs;++cs)++Qr[es[cs]-1];var ja,Na=new _s($);for(cs=0;$>cs;++cs)Na[cs]=Na[cs-1]+Qr[cs-1]<<1;for(ja=new _s(is),cs=0;is>cs;++cs)ja[cs]=$s[Na[es[cs]-1]++]>>>15-es[cs];return ja},Ps=new fs(288);for(Ts=0;144>Ts;++Ts)Ps[Ts]=8;for(Ts=144;256>Ts;++Ts)Ps[Ts]=9;for(Ts=256;280>Ts;++Ts)Ps[Ts]=7;for(Ts=280;288>Ts;++Ts)Ps[Ts]=8;var Os=new fs(32);for(Ts=0;32>Ts;++Ts)Os[Ts]=5;var Is=Rs(Ps,9),Cs=Rs(Os,5),Fs=function(es){return(es/8>>0)+(7&es&&1)},As=function(es,$,ts){(ts==null||ts>es.length)&&(ts=es.length);var is=new(es instanceof _s?_s:es instanceof gs?gs:fs)(ts-$);return is.set(es.subarray($,ts)),is},Ms=function(es,$,ts){var is=$/8>>0;es[is]|=ts<<=7&$,es[is+1]|=ts>>>8},Ds=function(es,$,ts){var is=$/8>>0;es[is]|=ts<<=7&$,es[is+1]|=ts>>>8,es[is+2]|=ts>>>16},Ls=function(es,$){for(var ts=[],is=0;es.length>is;++is)es[is]&&ts.push({s:is,f:es[is]});var cs=ts.length,Qr=ts.slice();if(!cs)return[new fs(0),0];if(cs==1){var ja=new fs(ts[0].s+1);return ja[ts[0].s]=1,[ja,1]}ts.sort((function(Ya,el){return Ya.f-el.f})),ts.push({s:-1,f:25001});var Na=ts[0],Aa=ts[1],Oa=0,Ia=1,La=2;for(ts[0]={s:-1,f:Na.f+Aa.f,l:Na,r:Aa};Ia!=cs-1;)Na=ts[ts[La].f>ts[Oa].f?Oa++:La++],Aa=ts[Oa!=Ia&&ts[La].f>ts[Oa].f?Oa++:La++],ts[Ia++]={s:-1,f:Na.f+Aa.f,l:Na,r:Aa};var Ba=Qr[0].s;for(is=1;cs>is;++is)Qr[is].s>Ba&&(Ba=Qr[is].s);var Ma=new _s(Ba+1),qa=Us(ts[Ia-1],Ma,0);if(qa>$){is=0;var Fa=0,Ha=qa-$,Ka=1<<Ha;for(Qr.sort((function(Ya,el){return Ma[el.s]-Ma[Ya.s]||Ya.f-el.f}));cs>is;++is){var Ga=Qr[is].s;if($>=Ma[Ga])break;Fa+=Ka-(1<<qa-Ma[Ga]),Ma[Ga]=$}for(Fa>>>=Ha;Fa>0;){var Va=Qr[is].s;$>Ma[Va]?Fa-=1<<$-Ma[Va]++-1:++is}for(;is>=0&&Fa;--is){var Ja=Qr[is].s;Ma[Ja]==$&&(--Ma[Ja],++Fa)}qa=$}return[new fs(Ma),qa]},Us=function(es,$,ts){return es.s==-1?Math.max(Us(es.l,$,ts+1),Us(es.r,$,ts+1)):$[es.s]=ts},Ns=function(es){for(var $=es.length;$&&!es[--$];);for(var ts=new _s(++$),is=0,cs=es[0],Qr=1,ja=function(Aa){ts[is++]=Aa},Na=1;$>=Na;++Na)if(es[Na]==cs&&Na!=$)++Qr;else{if(!cs&&Qr>2){for(;Qr>138;Qr-=138)ja(32754);Qr>2&&(ja(Qr>10?Qr-11<<5|28690:Qr-3<<5|12305),Qr=0)}else if(Qr>3){for(ja(cs),--Qr;Qr>6;Qr-=6)ja(8304);Qr>2&&(ja(Qr-3<<5|8208),Qr=0)}for(;Qr--;)ja(cs);Qr=1,cs=es[Na]}return[ts.subarray(0,is),$]},js=function(es,$){for(var ts=0,is=0;$.length>is;++is)ts+=es[is]*$[is];return ts},zs=function(es,$,ts){var is=ts.length,cs=Fs($+2);es[cs]=255&is,es[cs+1]=is>>>8,es[cs+2]=255^es[cs],es[cs+3]=255^es[cs+1];for(var Qr=0;is>Qr;++Qr)es[cs+Qr+4]=ts[Qr];return 8*(cs+4+is)},Bs=function(es,$,ts,is,cs,Qr,ja,Na,Aa,Oa,Ia){Ms($,Ia++,ts),++cs[256];for(var La=Ls(cs,15),Ba=La[0],Ma=La[1],qa=Ls(Qr,15),Fa=qa[0],Ha=qa[1],Ka=Ns(Ba),Ga=Ka[0],Va=Ka[1],Ja=Ns(Fa),Ya=Ja[0],el=Ja[1],tl=new _s(19),rl=0;Ga.length>rl;++rl)tl[31&Ga[rl]]++;for(rl=0;Ya.length>rl;++rl)tl[31&Ya[rl]]++;for(var cl=Ls(tl,7),dl=cl[0],fl=cl[1],nl=19;nl>4&&!dl[ys[nl-1]];--nl);var ol,pl,Tl,ul,hl=Oa+5<<3,jl=js(cs,Ps)+js(Qr,Os)+ja,Nl=js(cs,Ba)+js(Qr,Fa)+ja+14+3*nl+js(tl,dl)+(2*tl[16]+3*tl[17]+7*tl[18]);if(jl>=hl&&Nl>=hl)return zs($,Ia,es.subarray(Aa,Aa+Oa));if(Ms($,Ia,1+(jl>Nl)),Ia+=2,jl>Nl){ol=Rs(Ba,Ma),pl=Ba,Tl=Rs(Fa,Ha),ul=Fa;var zl=Rs(dl,fl);for(Ms($,Ia,Va-257),Ms($,Ia+5,el-1),Ms($,Ia+10,nl-4),Ia+=14,rl=0;nl>rl;++rl)Ms($,Ia+3*rl,dl[ys[rl]]);Ia+=3*nl;for(var Zl=[Ga,Ya],Dl=0;2>Dl;++Dl){var Il=Zl[Dl];for(rl=0;Il.length>rl;++rl)Ms($,Ia,zl[Fl=31&Il[rl]]),Ia+=dl[Fl],Fl>15&&(Ms($,Ia,Il[rl]>>>5&127),Ia+=Il[rl]>>>12)}}else ol=Is,pl=Ps,Tl=Cs,ul=Os;for(rl=0;Na>rl;++rl)if(is[rl]>255){var Fl;Ds($,Ia,ol[257+(Fl=is[rl]>>>18&31)]),Ia+=pl[Fl+257],Fl>7&&(Ms($,Ia,is[rl]>>>23&31),Ia+=ms[Fl]);var ql=31&is[rl];Ds($,Ia,Tl[ql]),Ia+=ul[ql],ql>3&&(Ds($,Ia,is[rl]>>>5&8191),Ia+=bs[ql])}else Ds($,Ia,ol[is[rl]]),Ia+=pl[is[rl]];return Ds($,Ia,ol[256]),Ia+pl[256]},Hs=new gs([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),qs=(function(){for(var es=new gs(256),$=0;256>$;++$){for(var ts=$,is=9;--is;)ts=(1&ts&&3988292384)^ts>>>1;es[$]=ts}return es})(),Vs=function(es,$,ts){for(;ts;++$)es[$]=ts,ts>>>=8};function Ws(es,$){$===void 0&&($={});var ts=(function(){var La=4294967295;return{p(Ba){for(var Ma=La,qa=0;Ba.length>qa;++qa)Ma=qs[255&Ma^Ba[qa]]^Ma>>>8;La=Ma},d(){return 4294967295^La}}})(),is=es.length;ts.p(es);var cs,Qr,ja,Na,Aa,Oa=(Na=10+((cs=$).filename&&cs.filename.length+1||0),Aa=8,(function(La,Ba,Ma,qa,Fa,Ha){var Ka=La.length,Ga=new fs(qa+Ka+5*(1+Math.floor(Ka/7e3))+Fa),Va=Ga.subarray(qa,Ga.length-Fa),Ja=0;if(!Ba||8>Ka)for(var Ya=0;Ka>=Ya;Ya+=65535){var el=Ya+65535;Ka>el?Ja=zs(Va,Ja,La.subarray(Ya,el)):(Va[Ya]=!0,Ja=zs(Va,Ja,La.subarray(Ya,Ka)))}else{for(var tl=Hs[Ba-1],rl=tl>>>13,cl=8191&tl,dl=(1<<Ma)-1,fl=new _s(32768),nl=new _s(dl+1),ol=Math.ceil(Ma/3),pl=2*ol,Tl=function(Tu){return(La[Tu]^La[Tu+1]<<ol^La[Tu+2]<<pl)&dl},ul=new gs(25e3),hl=new _s(288),jl=new _s(32),Nl=0,zl=0,Zl=(Ya=0,0),Dl=0,Il=0;Ka>Ya;++Ya){var Fl=Tl(Ya),ql=32767&Ya,nu=nl[Fl];if(fl[ql]=nu,nl[Fl]=ql,Ya>=Dl){var Gl=Ka-Ya;if((Nl>7e3||Zl>24576)&&Gl>423){Ja=Bs(La,Va,0,ul,hl,jl,zl,Zl,Il,Ya-Il,Ja),Zl=Nl=zl=0,Il=Ya;for(var cu=0;286>cu;++cu)hl[cu]=0;for(cu=0;30>cu;++cu)jl[cu]=0}var Al=2,Ml=0,Ql=cl,eu=ql-nu&32767;if(Gl>2&&Fl==Tl(Ya-eu))for(var xu=Math.min(rl,Gl)-1,fu=Math.min(32767,Ya),Ou=Math.min(258,Gl);fu>=eu&&--Ql&&ql!=nu;){if(La[Ya+Al]==La[Ya+Al-eu]){for(var yu=0;Ou>yu&&La[Ya+yu]==La[Ya+yu-eu];++yu);if(yu>Al){if(Al=yu,Ml=eu,yu>xu)break;var ic=Math.min(eu,yu-2),Iu=0;for(cu=0;ic>cu;++cu){var Bl=Ya-eu+cu+32768&32767,ru=Bl-fl[Bl]+32768&32767;ru>Iu&&(Iu=ru,nu=Bl)}}}eu+=(ql=nu)-(nu=fl[ql])+32768&32767}if(Ml){ul[Zl++]=268435456|Es[Al]<<18|Ss[Ml];var Mu=31&Es[Al],lc=31&Ss[Ml];zl+=ms[Mu]+bs[lc],++hl[257+Mu],++jl[lc],Dl=Ya+Al,++Nl}else ul[Zl++]=La[Ya],++hl[La[Ya]]}}Ja=Bs(La,Va,!0,ul,hl,jl,zl,Zl,Il,Ya-Il,Ja)}return As(Ga,0,qa+Fs(Ja)+Fa)})(Qr=es,(ja=$).level==null?6:ja.level,ja.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(Qr.length)))):12+ja.mem,Na,Aa)),Ia=Oa.length;return(function(La,Ba){var Ma=Ba.filename;if(La[0]=31,La[1]=139,La[2]=8,La[8]=2>Ba.level?4:Ba.level==9?2:0,La[9]=3,Ba.mtime!=0&&Vs(La,4,Math.floor(new Date(Ba.mtime||Date.now())/1e3)),Ma){La[3]=8;for(var qa=0;Ma.length>=qa;++qa)La[qa+10]=Ma.charCodeAt(qa)}})(Oa,$),Vs(Oa,Ia-8,ts.d()),Vs(Oa,Ia-4,is),Oa}var Gs=!!o||!!n,Ys="text/plain",Js=!1,Ks=function(es,$,ts){var is;ts===void 0&&(ts=!0);var[cs,Qr]=es.split("?"),ja=f({},$),Na=(is=Qr==null?void 0:Qr.split("&").map((Oa=>{var Ia,[La,Ba]=Oa.split("="),Ma=ts&&(Ia=ja[La])!==null&&Ia!==void 0?Ia:Ba;return delete ja[La],La+"="+Ma})))!==null&&is!==void 0?is:[],Aa=(function(Oa,Ia){var La,Ba;Ia===void 0&&(Ia="&");var Ma=[];return Hi(Oa,(function(qa,Fa){C(qa)||C(Fa)||Fa==="undefined"||(La=encodeURIComponent((Ha=>Ha instanceof File)(qa)?qa.name:qa.toString()),Ba=encodeURIComponent(Fa),Ma[Ma.length]=Ba+"="+La)})),Ma.join(Ia)})(ja);return Aa&&Na.push(Aa),cs+"?"+Na.join("&")},Xs=(es,$)=>JSON.stringify(es,((ts,is)=>typeof is=="bigint"?is.toString():is),$),Qs=es=>{if(es.tr)return es.tr;var{data:$,compression:ts}=es;if($){if(ts===ps.GZipJS){var is=Ws((function(Na,Aa){var Oa=Na.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(Na);for(var Ia=new fs(Na.length+(Na.length>>>1)),La=0,Ba=function(Ha){Ia[La++]=Ha},Ma=0;Oa>Ma;++Ma){if(La+5>Ia.length){var qa=new fs(La+8+(Oa-Ma<<1));qa.set(Ia),Ia=qa}var Fa=Na.charCodeAt(Ma);128>Fa?Ba(Fa):2048>Fa?(Ba(192|Fa>>>6),Ba(128|63&Fa)):Fa>55295&&57344>Fa?(Ba(240|(Fa=65536+(1047552&Fa)|1023&Na.charCodeAt(++Ma))>>>18),Ba(128|Fa>>>12&63),Ba(128|Fa>>>6&63),Ba(128|63&Fa)):(Ba(224|Fa>>>12),Ba(128|Fa>>>6&63),Ba(128|63&Fa))}return As(Ia,0,La)})(Xs($)),{mtime:0});return{contentType:Ys,body:is.buffer.slice(is.byteOffset,is.byteOffset+is.byteLength),estimatedSize:is.byteLength}}if(ts===ps.Base64){var cs=(function(Na){return Na&&btoa(encodeURIComponent(Na).replace(/%([0-9A-F]{2})/g,((Aa,Oa)=>String.fromCharCode(parseInt(Oa,16)))))})(Xs($)),Qr=(Na=>"data="+encodeURIComponent(typeof Na=="string"?Na:Xs(Na)))(cs);return{contentType:"application/x-www-form-urlencoded",body:Qr,estimatedSize:new Blob([Qr]).size}}var ja=Xs($);return{contentType:"application/json",body:ja,estimatedSize:new Blob([ja]).size}}},Zs=(function(){var es=p((function*($){var ts=Xs($.data),is=yield(function(Qr,ja,Na){return g.apply(this,arguments)})(ts,v.DEBUG,{rethrow:!0});if(!is)return $;var cs=yield is.arrayBuffer();return f({},$,{tr:{contentType:Ys,body:cs,estimatedSize:cs.byteLength}})}));return function($){return es.apply(this,arguments)}})(),tn=(es,$)=>Ks(es,{_:new Date().getTime().toString(),ver:v.JS_SDK_VERSION,compression:$}),en=[];n&&en.push({transport:"fetch",method(es){var $,ts,{contentType:is,body:cs,estimatedSize:Qr}=($=Qs(es))!==null&&$!==void 0?$:{},ja=new Headers;Hi(es.headers,(function(Ia,La){ja.append(La,Ia)})),is&&ja.append("Content-Type",is);var Na=es.url,Aa=null;if(a){var Oa=new a;Aa={signal:Oa.signal,timeout:setTimeout((()=>Oa.abort()),es.timeout)}}n(Na,f({method:(es==null?void 0:es.method)||"GET",headers:ja,keepalive:es.method==="POST"&&52428.8>(Qr||0),body:cs,signal:(ts=Aa)==null?void 0:ts.signal},es.fetchOptions)).then((Ia=>Ia.text().then((La=>{var Ba={statusCode:Ia.status,text:La};if(Ia.status===200)try{Ba.json=JSON.parse(La)}catch(Ma){Ie.error(Ma)}es.callback==null||es.callback(Ba)})))).catch((Ia=>{Ie.error(Ia),es.callback==null||es.callback({statusCode:0,error:Ia})})).finally((()=>Aa?clearTimeout(Aa.timeout):null))}}),o&&en.push({transport:"XHR",method(es){var $,ts=new o;ts.open(es.method||"GET",es.url,!0);var{contentType:is,body:cs}=($=Qs(es))!==null&&$!==void 0?$:{};Hi(es.headers,(function(Qr,ja){ts.setRequestHeader(ja,Qr)})),is&&ts.setRequestHeader("Content-Type",is),es.timeout&&(ts.timeout=es.timeout),es.disableXHRCredentials||(ts.withCredentials=!0),ts.onreadystatechange=()=>{if(ts.readyState===4){var Qr={statusCode:ts.status,text:ts.responseText};if(ts.status===200)try{Qr.json=JSON.parse(ts.responseText)}catch{}es.callback==null||es.callback(Qr)}},ts.send(cs)}}),i!=null&&i.sendBeacon&&en.push({transport:"sendBeacon",method(es){var $=Ks(es.url,{beacon:"1"});try{var ts,{contentType:is,body:cs}=(ts=Qs(es))!==null&&ts!==void 0?ts:{};if(!cs)return;var Qr=cs instanceof Blob?cs:new Blob([cs],{type:is});i.sendBeacon($,Qr)}catch{}}});var rn=3e3;class sn{constructor($,ts){this.Pr=!0,this.Lr=[],this.Dr=Y((ts==null?void 0:ts.flush_interval_ms)||rn,250,5e3,Ie.createLogger("flush interval"),rn),this.Br=$}enqueue($){this.Lr.push($),this.jr||this.$r()}unload(){this.qr();var $=this.Lr.length>0?this.Zr():{},ts=Object.values($);[...ts.filter((is=>is.url.indexOf("/e")===0)),...ts.filter((is=>is.url.indexOf("/e")!==0))].map((is=>{this.Br(f({},is,{transport:"sendBeacon"}))}))}enable(){this.Pr=!1,this.$r()}$r(){var $=this;this.Pr||(this.jr=setTimeout((()=>{if(this.qr(),this.Lr.length>0){var ts=this.Zr(),is=function(){var Qr=ts[cs],ja=new Date().getTime();Qr.data&&R(Qr.data)&&Hi(Qr.data,(Na=>{Na.offset=Math.abs(Na.timestamp-ja),delete Na.timestamp})),$.Br(Qr)};for(var cs in ts)is()}}),this.Dr))}qr(){clearTimeout(this.jr),this.jr=void 0}Zr(){var $={};return Hi(this.Lr,(ts=>{var is,cs=ts,Qr=(cs?cs.batchKey:null)||cs.url;C($[Qr])&&($[Qr]=f({},cs,{data:[]})),(is=$[Qr].data)==null||is.push(cs.data)})),this.Lr=[],$}}var nn=["retriesPerformedSoFar"];class on{constructor($){this.Vr=!1,this.Hr=3e3,this.Lr=[],this._instance=$,this.Lr=[],this.zr=!0,!C(t)&&"onLine"in t.navigator&&(this.zr=t.navigator.onLine,this.Ur=()=>{this.zr=!0,this.Yr()},this.Gr=()=>{this.zr=!1},Xi(t,"online",this.Ur),Xi(t,"offline",this.Gr))}get length(){return this.Lr.length}retriableRequest($){var{retriesPerformedSoFar:ts}=$,is=_($,nn);U(ts)&&(is.url=Ks(is.url,{retry_count:ts})),this._instance._send_request(f({},is,{callback:cs=>{cs.statusCode===200||cs.statusCode>=400&&500>cs.statusCode||(ts??0)>=10?is.callback==null||is.callback(cs):this.Wr(f({retriesPerformedSoFar:ts},is))}}))}Wr($){var ts=$.retriesPerformedSoFar||0;$.retriesPerformedSoFar=ts+1;var is=(function(ja){var Na=3e3*Math.pow(2,ja),Aa=Na/2,Oa=Math.min(18e5,Na),Ia=Math.random()-.5;return Math.ceil(Oa+Ia*(Oa-Aa))})(ts),cs=Date.now()+is;this.Lr.push({retryAt:cs,requestOptions:$});var Qr="Enqueued failed request for retry in "+is;navigator.onLine||(Qr+=" (Browser is offline)"),Ie.warn(Qr),this.Vr||(this.Vr=!0,this.Xr())}Xr(){if(this.Jr&&clearTimeout(this.Jr),this.Lr.length===0)return this.Vr=!1,void(this.Jr=void 0);this.Jr=setTimeout((()=>{this.zr&&this.Lr.length>0&&this.Yr(),this.Xr()}),this.Hr)}Yr(){var $=Date.now(),ts=[],is=this.Lr.filter((Qr=>$>Qr.retryAt||(ts.push(Qr),!1)));if(this.Lr=ts,is.length>0)for(var{requestOptions:cs}of is)this.retriableRequest(cs)}unload(){for(var{requestOptions:$}of(this.Jr&&(clearTimeout(this.Jr),this.Jr=void 0),this.Vr=!1,C(t)||(this.Ur&&(t.removeEventListener("online",this.Ur),this.Ur=void 0),this.Gr&&(t.removeEventListener("offline",this.Gr),this.Gr=void 0)),this.Lr))try{this._instance._send_request(f({},$,{transport:"sendBeacon"}))}catch(ts){Ie.error(ts)}this.Lr=[]}}class an{constructor($){this.Kr=()=>{var ts,is,cs,Qr;this.Qr||(this.Qr={});var ja=this.scrollElement(),Na=this.scrollY(),Aa=ja?Math.max(0,ja.scrollHeight-ja.clientHeight):0,Oa=Na+((ja==null?void 0:ja.clientHeight)||0),Ia=(ja==null?void 0:ja.scrollHeight)||0;this.Qr.lastScrollY=Math.ceil(Na),this.Qr.maxScrollY=Math.max(Na,(ts=this.Qr.maxScrollY)!==null&&ts!==void 0?ts:0),this.Qr.maxScrollHeight=Math.max(Aa,(is=this.Qr.maxScrollHeight)!==null&&is!==void 0?is:0),this.Qr.lastContentY=Oa,this.Qr.maxContentY=Math.max(Oa,(cs=this.Qr.maxContentY)!==null&&cs!==void 0?cs:0),this.Qr.maxContentHeight=Math.max(Ia,(Qr=this.Qr.maxContentHeight)!==null&&Qr!==void 0?Qr:0)},this._instance=$}get ei(){return this._instance.config.scroll_root_selector}getContext(){return this.Qr}resetContext(){var $=this.Qr;return setTimeout(this.Kr,0),$}startMeasuringScrollPosition(){Xi(t,"scroll",this.Kr,{capture:!0}),Xi(t,"scrollend",this.Kr,{capture:!0}),Xi(t,"resize",this.Kr)}scrollElement(){if(!this.ei)return t==null?void 0:t.document.documentElement;var $=R(this.ei)?this.ei:[this.ei];for(var ts of $){var is=t==null?void 0:t.document.querySelector(ts);if(is)return is}}scrollY(){if(this.ei){var $=this.scrollElement();return $&&$.scrollTop||0}return t&&(t.scrollY||t.pageYOffset||t.document.documentElement.scrollTop)||0}scrollX(){if(this.ei){var $=this.scrollElement();return $&&$.scrollLeft||0}return t&&(t.scrollX||t.pageXOffset||t.document.documentElement.scrollLeft)||0}}var ln=es=>Hr(es==null?void 0:es.config.mask_personal_data_properties,es==null?void 0:es.config.custom_personal_data_properties);class un{constructor($,ts,is,cs){this.ti=Qr=>{var ja=this.ri();if(!ja||ja.sessionId!==Qr){var Na={sessionId:Qr,props:this.ii(this._instance)};this.ni.register({[bi]:Na})}},this._instance=$,this.si=ts,this.ni=is,this.ii=cs||ln,this.si.onSessionId(this.ti)}ri(){return this.ni.props[bi]}getSetOnceProps(){var $,ts=($=this.ri())==null?void 0:$.props;return ts?"r"in ts?qr(ts):{$referring_domain:ts.referringDomain,$pathname:ts.initialPathName,utm_source:ts.utm_source,utm_campaign:ts.utm_campaign,utm_medium:ts.utm_medium,utm_content:ts.utm_content,utm_term:ts.utm_term}:{}}getSessionProps(){var $={};return Hi(Yi(this.getSetOnceProps()),((ts,is)=>{is==="$current_url"&&(is="url"),$["$session_entry_"+E(is)]=ts})),$}}class hn{constructor(){this.oi={}}on($,ts){return this.oi[$]||(this.oi[$]=[]),this.oi[$].push(ts),()=>{this.oi[$]=this.oi[$].filter((is=>is!==ts))}}emit($,ts){for(var is of this.oi[$]||[])is(ts);for(var cs of this.oi["*"]||[])cs($,ts)}}var dn=Ce("[SessionId]");class vn{on($,ts){return this.ai.on($,ts)}constructor($,ts,is){var cs;if(this.li=[],this.ui=void 0,this.ai=new hn,this.hi=(Oa,Ia)=>!(!U(Oa)||!U(Ia))&&Math.abs(Oa-Ia)>this.sessionTimeoutMs,!$.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if($.config.cookieless_mode===Ci)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Bt=$.config,this.ni=$.persistence,this.ci=void 0,this.di=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.vi=ts||sr,this.fi=is||sr;var Qr=this.Bt.persistence_name||this.Bt.token;if(this._sessionTimeoutMs=1e3*Y(this.Bt.session_idle_timeout_seconds||1800,60,36e3,dn.createLogger("session_idle_timeout_seconds"),1800),$.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.pi(),this.gi="ph_"+Qr+"_window_id",this.mi="ph_"+Qr+"_primary_window_exists",this.yi()){var ja=fr.Z(this.gi),Na=fr.Z(this.mi);ja&&!Na?this.ci=ja:fr.F(this.gi),fr.M(this.mi,!0)}if((cs=this.Bt.bootstrap)!=null&&cs.sessionID)try{var Aa=(Oa=>{var Ia=this.Bt.bootstrap.sessionID.replace(/-/g,"");if(Ia.length!==32)throw new Error("Not a valid UUID");if(Ia[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(Ia.substring(0,12),16)})();this.bi(this.Bt.bootstrap.sessionID,new Date().getTime(),Aa)}catch(Oa){dn.error("Invalid sessionID in bootstrap",Oa)}this.wi()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId($){return C(this.li)&&(this.li=[]),this.li.push($),this.di&&$(this.di,this.ci),()=>{this.li=this.li.filter((ts=>ts!==$))}}yi(){return this.Bt.persistence!=="memory"&&!this.ni._r&&fr.R()}Ii($){$!==this.ci&&(this.ci=$,this.yi()&&fr.M(this.gi,$))}Ci(){return this.ci?this.ci:this.yi()?fr.Z(this.gi):null}bi($,ts,is){$===this.di&&ts===this._sessionActivityTimestamp&&is===this._sessionStartTimestamp||(this._sessionStartTimestamp=is,this._sessionActivityTimestamp=ts,this.di=$,this.ni.register({[Ze]:[ts,$,is]}))}Si(){var $=this.ni.props[Ze];return R($)&&$.length===2&&$.push($[0]),$||[0,null,0]}resetSessionId(){this.bi(null,null,null)}destroy(){clearTimeout(this.xi),this.xi=void 0,this.ui&&t&&(t.removeEventListener(Li,this.ui,{capture:!1}),this.ui=void 0),this.li=[]}wi(){this.ui=()=>{this.yi()&&fr.F(this.mi)},Xi(t,Li,this.ui,{capture:!1})}checkAndGetSessionAndWindowId($,ts){if($===void 0&&($=!1),ts===void 0&&(ts=null),this.Bt.cookieless_mode===Ci)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var is=ts||new Date().getTime(),[cs,Qr,ja]=this.Si(),Na=this.Ci(),Aa=U(ja)&&Math.abs(is-ja)>864e5,Oa=!1,Ia=!Qr,La=!Ia&&!$&&this.hi(is,cs);Ia||La||Aa?(Qr=this.vi(),Na=this.fi(),dn.info("new session ID generated",{sessionId:Qr,windowId:Na,changeReason:{noSessionId:Ia,activityTimeout:La,sessionPastMaximumLength:Aa}}),ja=is,Oa=!0):Na||(Na=this.fi(),Oa=!0);var Ba=U(cs)&&$&&!Aa?cs:is,Ma=U(ja)?ja:new Date().getTime();return this.Ii(Na),this.bi(Qr,Ba,Ma),$||this.pi(),Oa&&this.li.forEach((qa=>qa(Qr,Na,Oa?{noSessionId:Ia,activityTimeout:La,sessionPastMaximumLength:Aa}:void 0))),{sessionId:Qr,windowId:Na,sessionStartTimestamp:Ma,changeReason:Oa?{noSessionId:Ia,activityTimeout:La,sessionPastMaximumLength:Aa}:void 0,lastActivityTimestamp:cs}}pi(){clearTimeout(this.xi),this.xi=setTimeout((()=>{var[$]=this.Si();if(this.hi(new Date().getTime(),$)){var ts=this.di;this.resetSessionId(),this.ai.emit("forcedIdleReset",{idleSessionId:ts})}}),1.1*this.sessionTimeoutMs)}}var cn=function(es,$){if(!es)return!1;var ts=es.userAgent;if(ts&&b(ts,$))return!0;try{var is=es==null?void 0:es.userAgentData;if(is!=null&&is.brands&&is.brands.some((cs=>b(cs==null?void 0:cs.brand,$))))return!0}catch{}return!!es.webdriver},pn=function(es,$){if(!(function(ts){try{new RegExp(ts)}catch{return!1}return!0})($))return!1;try{return new RegExp($).test(es)}catch{return!1}};function fn(es,$,ts){return Xs({distinct_id:es,userPropertiesToSet:$,userPropertiesToSetOnce:ts})}var _n={exact:(es,$)=>$.some((ts=>es.some((is=>ts===is)))),is_not:(es,$)=>$.every((ts=>es.every((is=>ts!==is)))),regex:(es,$)=>$.some((ts=>es.some((is=>pn(ts,is))))),not_regex:(es,$)=>$.every((ts=>es.every((is=>!pn(ts,is))))),icontains:(es,$)=>$.map(gn).some((ts=>es.map(gn).some((is=>ts.includes(is))))),not_icontains:(es,$)=>$.map(gn).every((ts=>es.map(gn).every((is=>!ts.includes(is))))),gt:(es,$)=>$.some((ts=>{var is=parseFloat(ts);return!isNaN(is)&&es.some((cs=>is>parseFloat(cs)))})),lt:(es,$)=>$.some((ts=>{var is=parseFloat(ts);return!isNaN(is)&&es.some((cs=>is<parseFloat(cs)))}))},gn=es=>es.toLowerCase();function mn(es,$){return!es||Object.entries(es).every((ts=>{var[is,cs]=ts,Qr=$==null?void 0:$[is];if(C(Qr)||M(Qr))return!1;var ja=[String(Qr)],Na=_n[cs.operator];return!!Na&&Na(cs.values,ja)}))}var bn="custom",yn="i.posthog.com",wn=/^\/static\//;class xn{constructor($){this.ki={},this.instance=$}get apiHost(){var $=this.instance.config.api_host.trim().replace(/\/$/,"");return $==="https://app.posthog.com"?"https://us.i.posthog.com":$}get flagsApiHost(){var $=this.instance.config.flags_api_host;return $?$.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var $,ts=($=this.instance.config.ui_host)==null?void 0:$.replace(/\/$/,"");return ts||(ts=this.apiHost.replace("."+yn,".posthog.com")),ts==="https://app.posthog.com"?"https://us.posthog.com":ts}get region(){return this.ki[this.apiHost]||(this.ki[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":bn),this.ki[this.apiHost]}Ti($){var ts=this.instance.config.__preview_external_dependency_versioned_paths;if(typeof ts=="string"&&wn.test($))return ts.trim().replace(/\/$/,"")||void 0}endpointFor($,ts){if(ts===void 0&&(ts=""),ts&&(ts=ts[0]==="/"?ts:"/"+ts),$==="ui")return this.uiHost+ts;if($==="flags")return this.flagsApiHost+ts;if($==="assets"){var is=this.Ti(ts);if(is)return""+is+ts}if(this.region===bn)return this.apiHost+ts;var cs=yn+ts;switch($){case"assets":return"https://"+this.region+"-assets."+cs;case"api":return"https://"+this.region+"."+cs}}}var En=Ce("[Surveys]"),Sn="seenSurvey_",$n=[Zr.Popover,Zr.Widget,Zr.API],Tn={ignoreConditions:!1,ignoreDelay:!1,displayType:ns.Popover},kn=Ce("[PostHog ExternalIntegrations]"),Rn={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Pn{constructor($){this._instance=$}ur($,ts){var is;(is=h.__PosthogExtensions__)==null||is.loadExternalDependency==null||is.loadExternalDependency(this._instance,$,(cs=>{if(cs)return kn.error("failed to load script",cs);ts()}))}startIfEnabledOrStop(){var $=this,ts=function(ja){var Na,Aa,Oa;!cs||(Na=h.__PosthogExtensions__)!=null&&(Na=Na.integrations)!=null&&Na[ja]||$.ur(Rn[ja],(()=>{var Ia;(Ia=h.__PosthogExtensions__)==null||(Ia=Ia.integrations)==null||(Ia=Ia[ja])==null||Ia.start($._instance)})),!cs&&(Aa=h.__PosthogExtensions__)!=null&&(Aa=Aa.integrations)!=null&&Aa[ja]&&((Oa=h.__PosthogExtensions__)==null||(Oa=Oa.integrations)==null||(Oa=Oa[ja])==null||Oa.stop())};for(var[is,cs]of Object.entries((Qr=this._instance.config.integrations)!==null&&Qr!==void 0?Qr:{})){var Qr;ts(is)}}}var On,In={},Cn=0,Fn=()=>{},An='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Mn="Surveys module not available",Dn="sanitize_properties is deprecated. Use before_send instead",Ln="Invalid value for property_denylist config: ",Un="posthog",Nn=!Gs&&(u==null?void 0:u.indexOf("MSIE"))===-1&&(u==null?void 0:u.indexOf("Mozilla"))===-1,jn=es=>{var $;return f({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ki(r==null?void 0:r.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Fn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:es??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,debug:s&&F(s==null?void 0:s.search)&&s.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(t==null||($=t.location)==null?void 0:$.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(ts){Ie.error("Bad HTTP status: "+ts.statusCode+" "+ts.text)},get_device_id:ts=>ts,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Mi,before_send:void 0,request_queue_config:{flush_interval_ms:rn},error_tracking:{},_onCapture:Fn,__preview_eager_load_replay:!1},(ts=>({rageclick:!ts||"2025-11-30">ts||{content_ignorelist:!0},capture_pageview:!ts||"2025-05-24">ts||"history_change",session_recording:ts&&ts>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:ts&&ts>="2026-01-30"?"head":"body",internal_or_test_user_hostname:ts&&ts>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(es))},zn=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["store_google","save_campaign_params"],["verbose","debug"]],Bn=es=>{var $={};for(var[ts,is]of zn)C(es[ts])||($[is]=es[ts]);var cs=qi({},$,es);return R(es.property_blacklist)&&(C(es.property_denylist)?cs.property_denylist=es.property_blacklist:R(es.property_denylist)?cs.property_denylist=[...es.property_blacklist,...es.property_denylist]:Ie.error(Ln+es.property_denylist)),cs};class Hn{constructor(){this.__forceAllowLocalhost=!1}get Ai(){return this.__forceAllowLocalhost}set Ai($){Ie.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=$}}class qn{Ei($,ts){if($){var is=this.Ri.indexOf($);is!==-1&&this.Ri.splice(is,1)}return this.Ri.push(ts),ts.initialize==null||ts.initialize(),ts}Ni(){return this.config.cookieless_mode===Ci||this.config.cookieless_mode===Ii&&this.consent.isRejected()}get decideEndpointWasHit(){var $,ts;return($=(ts=this.featureFlags)==null?void 0:ts.hasLoadedFlags)!==null&&$!==void 0&&$}get flagsEndpointWasHit(){var $,ts;return($=(ts=this.featureFlags)==null?void 0:ts.hasLoadedFlags)!==null&&$!==void 0&&$}constructor(){var $;this.webPerformance=new Hn,this.Mi=!1,this.version=v.LIB_VERSION,this.Fi=new hn,this.Ri=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=jn(),this.SentryIntegration=Sr,this.sentryIntegration=is=>(function(cs,Qr){var ja=Er(cs,Qr);return{name:xr,processEvent:Na=>ja(Na)}})(this,is),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Oi=!1,this.Pi=null,this.Li=null,this.Di=null,this.scrollManager=new an(this),this.pageViewManager=new $r(this),this.rateLimiter=new hs(this),this.requestRouter=new xn(this),this.consent=new _r(this),this.externalIntegrations=new Pn(this);var ts=($=qn.__defaultExtensionClasses)!==null&&$!==void 0?$:{};this.featureFlags=ts.featureFlags&&new ts.featureFlags(this),this.toolbar=ts.toolbar&&new ts.toolbar(this),this.surveys=ts.surveys&&new ts.surveys(this),this.conversations=ts.conversations&&new ts.conversations(this),this.logs=ts.logs&&new ts.logs(this),this.experiments=ts.experiments&&new ts.experiments(this),this.exceptions=ts.exceptions&&new ts.exceptions(this),this.people={set:(is,cs,Qr)=>{var ja=F(is)?{[is]:cs}:is;this.setPersonProperties(ja),Qr==null||Qr({})},set_once:(is,cs,Qr)=>{var ja=F(is)?{[is]:cs}:is;this.setPersonProperties(void 0,ja),Qr==null||Qr({})}},this.on("eventCaptured",(is=>Ie.info('send "'+(is==null?void 0:is.event)+'"',is)))}init($,ts,is){if(is&&is!==Un){var cs,Qr=(cs=In[is])!==null&&cs!==void 0?cs:new qn;return Qr._init($,ts,is),In[is]=Qr,In[Un][is]=Qr,Qr}return this._init($,ts,is)}_init($,ts,is){var cs,Qr;if(ts===void 0&&(ts={}),C($)||A($))return Ie.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={},ts.debug=this.Bi(ts.debug),this.ji=ts,this.$i=[],ts.person_profiles?this.Li=ts.person_profiles:ts.process_person&&(this.Li=ts.process_person),this.set_config(qi({},jn(ts.defaults),Bn(ts),{name:is,token:$})),this.config.on_xhr_error&&Ie.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=ts.disable_compression?void 0:ps.GZipJS;var ja=this.qi();this.persistence=new Yr(this.config,ja),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Yr(f({},this.config,{persistence:"sessionStorage"}),ja);var Na=f({},this.persistence.props),Aa=f({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zi=new sn((Ha=>this.Vi(Ha)),this.config.request_queue_config),this.Hi=new on(this),this.__request_queue=[];var Oa=this.Ni();if(Oa||(this.sessionManager=new vn(this),this.sessionPropsManager=new un(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(Ie.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.zi(Oa)}),0)):(Ie.info("Initializing extensions synchronously"),this.zi(Oa)),v.DEBUG=v.DEBUG||this.config.debug,v.DEBUG&&Ie.info("Starting in debug mode",{this:this,config:ts,thisC:f({},this.config),p:Na,s:Aa}),!this.config.identity_distinct_id||(cs=ts.bootstrap)!=null&&cs.distinctID||(ts.bootstrap=f({},ts.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((Qr=ts.bootstrap)==null?void 0:Qr.distinctID)!==void 0){var Ia=ts.bootstrap.distinctID,La=this.get_distinct_id(),Ba=this.persistence.get_property(mi);if(ts.bootstrap.isIdentifiedID&&La!=null&&La!==Ia&&Ba===Fi)this.identify(Ia);else if(ts.bootstrap.isIdentifiedID&&La!=null&&La!==Ia&&Ba===Ai)Ie.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var Ma=this.config.get_device_id(sr()),qa=ts.bootstrap.isIdentifiedID?Ma:Ia;this.persistence.set_property(mi,ts.bootstrap.isIdentifiedID?Ai:Fi),this.register({distinct_id:Ia,$device_id:qa})}}if(Oa)this.register_once({distinct_id:Ti,$device_id:null},"");else if(!this.get_distinct_id()){var Fa=this.config.get_device_id(sr());this.register_once({distinct_id:Fa,$device_id:Fa},""),this.persistence.set_property(mi,Fi)}return Xi(t,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),ts.segment?(function(Ha,Ka){var Ga=Ha.config.segment;if(!Ga)return Ka();(function(Va,Ja){var Ya=Va.config.segment;if(!Ya)return Ja();var el=rl=>{var cl=()=>rl.anonymousId()||sr();Va.config.get_device_id=cl,rl.id()&&(Va.register({distinct_id:rl.id(),$device_id:cl()}),Va.persistence.set_property(mi,Ai)),Ja()},tl=Ya.user();"then"in tl&&P(tl.then)?tl.then(el):el(tl)})(Ha,(()=>{Ga.register((Va=>{Promise&&Promise.resolve||wr.warn("This browser does not have Promise support, and can not use the segment integration");var Ja=(Ya,el)=>{if(!el)return Ya;Ya.event.userId||Ya.event.anonymousId===Va.get_distinct_id()||(wr.info("No userId set, resetting PostHog"),Va.reset()),Ya.event.userId&&Ya.event.userId!==Va.get_distinct_id()&&(wr.info("UserId set, identifying with PostHog"),Va.identify(Ya.event.userId));var tl=Va.calculateEventProperties(el,Ya.event.properties);return Ya.event.properties=Object.assign({},tl,Ya.event.properties),Ya};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:Ya=>Ja(Ya,Ya.event.event),page:Ya=>Ja(Ya,Ui),identify:Ya=>Ja(Ya,ji),screen:Ya=>Ja(Ya,"$screen")}})(Ha)).then((()=>{Ka()}))}))})(this,(()=>this.Ui())):this.Ui(),P(this.config._onCapture)&&this.config._onCapture!==Fn&&(Ie.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(Ha=>this.config._onCapture(Ha.event,Ha)))),this.config.ip&&Ie.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}zi($){var ts,is,cs,Qr,ja,Na,Aa,Oa=performance.now(),Ia=f({},qn.__defaultExtensionClasses,this.config.__extensionClasses),La=[];Ia.featureFlags&&this.Ri.push(this.featureFlags=(ts=this.featureFlags)!==null&&ts!==void 0?ts:new Ia.featureFlags(this)),Ia.exceptions&&this.Ri.push(this.exceptions=(is=this.exceptions)!==null&&is!==void 0?is:new Ia.exceptions(this)),Ia.historyAutocapture&&this.Ri.push(this.historyAutocapture=new Ia.historyAutocapture(this)),Ia.tracingHeaders&&this.Ri.push(new Ia.tracingHeaders(this)),Ia.siteApps&&this.Ri.push(this.siteApps=new Ia.siteApps(this)),Ia.sessionRecording&&!$&&this.Ri.push(this.sessionRecording=new Ia.sessionRecording(this)),this.config.disable_scroll_properties||La.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),Ia.autocapture&&this.Ri.push(this.autocapture=new Ia.autocapture(this)),Ia.surveys&&this.Ri.push(this.surveys=(cs=this.surveys)!==null&&cs!==void 0?cs:new Ia.surveys(this)),Ia.logs&&this.Ri.push(this.logs=(Qr=this.logs)!==null&&Qr!==void 0?Qr:new Ia.logs(this)),Ia.conversations&&this.Ri.push(this.conversations=(ja=this.conversations)!==null&&ja!==void 0?ja:new Ia.conversations(this)),Ia.productTours&&this.Ri.push(this.productTours=new Ia.productTours(this)),Ia.heatmaps&&this.Ri.push(this.heatmaps=new Ia.heatmaps(this)),Ia.webVitalsAutocapture&&this.Ri.push(this.webVitalsAutocapture=new Ia.webVitalsAutocapture(this)),Ia.exceptionObserver&&this.Ri.push(this.exceptionObserver=new Ia.exceptionObserver(this)),Ia.deadClicksAutocapture&&this.Ri.push(this.deadClicksAutocapture=new Ia.deadClicksAutocapture(this,br)),Ia.toolbar&&this.Ri.push(this.toolbar=(Na=this.toolbar)!==null&&Na!==void 0?Na:new Ia.toolbar(this)),Ia.experiments&&this.Ri.push(this.experiments=(Aa=this.experiments)!==null&&Aa!==void 0?Aa:new Ia.experiments(this)),this.Ri.forEach((Ba=>{Ba.initialize&&La.push((()=>{Ba.initialize==null||Ba.initialize()}))})),La.push((()=>{if(this.Yi){var Ba=this.Yi;this.Yi=void 0,this.Nr(Ba)}})),this.Gi(La,Oa)}Gi($,ts){for(;$.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-ts>=30&&$.length>0)return void setTimeout((()=>{this.Gi($,ts)}),0);var is=$.shift();if(is)try{is()}catch(Qr){Ie.error("Error initializing extension:",Qr)}}var cs=Math.round(performance.now()-ts);this.register_for_session({[ki]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Ri]:cs}),this.config.__preview_deferred_init_extensions&&Ie.info("PostHog extensions initialized ("+cs+"ms)")}Nr($){var ts;if(!r||!r.body)return Ie.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Nr($)}),500);this.config.__preview_deferred_init_extensions&&(this.Yi=$),this.Wi=$,this.compression=void 0,$.supportedCompression&&!this.config.disable_compression&&(this.compression=w($.supportedCompression,ps.GZipJS)?ps.GZipJS:w($.supportedCompression,ps.Base64)?ps.Base64:void 0),(ts=$.analytics)!=null&&ts.endpoint&&(this.analyticsDefaultEndpoint=$.analytics.endpoint),this.set_config({person_profiles:this.Li?this.Li:Mi}),this.Ri.forEach((is=>is.onRemoteConfig==null?void 0:is.onRemoteConfig($)))}Ui(){try{this.config.loaded(this)}catch(is){Ie.critical("`loaded` function failed",is)}if(this.Xi(),this.config.internal_or_test_user_hostname&&s!=null&&s.hostname){var $=s.hostname,ts=this.config.internal_or_test_user_hostname;(typeof ts=="string"?$===ts:ts.test($))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.Ni())&&this.Ji()}),1),this.Ki=new vs(this),this.Ki.load()}Xi(){var $;this.is_capturing()&&this.config.request_batching&&(($=this.Zi)==null||$.enable())}_dom_loaded(){this.is_capturing()&&Bi(this.__request_queue,($=>this.Vi($))),this.__request_queue=[],this.Xi()}_handle_unload(){var $,ts,is,cs;($=this.surveys)==null||$.handlePageUnload(),this.config.request_batching?(this.Qi()&&this.capture(Ni),(ts=this.logs)==null||ts.flushLogs("sendBeacon"),(is=this.Zi)==null||is.unload(),(cs=this.Hi)==null||cs.unload()):this.Qi()&&this.capture(Ni,null,{transport:"sendBeacon"})}_send_request($){this.__loaded&&(Nn?this.__request_queue.push($):this.rateLimiter.isServerRateLimited($.batchKey)||($.transport=$.transport||this.config.api_transport,$.url=Ks($.url,{ip:this.config.ip?1:0}),$.headers=f({},this.config.request_headers,$.headers),$.compression=$.compression==="best-available"?this.compression:$.compression,$.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&($.disableTransport=["sendBeacon"]),$.fetchOptions=$.fetchOptions||this.config.fetch_options,(ts=>{var is,cs,Qr,ja=f({},ts);ja.timeout=ja.timeout||6e4,ja.url=tn(ja.url,ja.compression);var Na=(is=ja.transport)!==null&&is!==void 0?is:"fetch",Aa=en.filter((Ia=>!ja.disableTransport||!Ia.transport||!ja.disableTransport.includes(Ia.transport))),Oa=(cs=(Qr=(function(Ia,La){for(var Ba=0;Ia.length>Ba;Ba++)if(Ia[Ba].transport===Na)return Ia[Ba]})(Aa))==null?void 0:Qr.method)!==null&&cs!==void 0?cs:Aa[0].method;if(!Oa)throw new Error("No available transport method");Na!=="sendBeacon"&&ja.data&&ja.compression===ps.GZipJS&&l&&!Js?Zs(ja).then((Ia=>{Oa(Ia)})).catch((Ia=>{if((La=>!(!La||typeof La!="object")&&("name"in La?String(La.name):"")==="NotReadableError")(Ia))return Js=!0,void Oa(f({},ja,{compression:void 0,url:tn(ts.url,void 0)}));Oa(ja)})):Oa(ja)})(f({},$,{callback:ts=>{var is,cs;this.rateLimiter.checkForLimiting(ts),400>ts.statusCode||(is=(cs=this.config).on_request_error)==null||is.call(cs,ts),$.callback==null||$.callback(ts)}}))))}Vi($){this.Hi?this.Hi.retriableRequest($):this._send_request($)}_execute_array($){Cn++;try{var ts,is=[],cs=[],Qr=[];Bi($,(Na=>{Na&&(R(ts=Na[0])?Qr.push(Na):P(Na)?Na.call(this):R(Na)&&ts==="alias"?is.push(Na):R(Na)&&ts.indexOf("capture")!==-1&&P(this[ts])?Qr.push(Na):cs.push(Na))}));var ja=function(Na,Aa){Bi(Na,(function(Oa){if(R(Oa[0])){var Ia=Aa;Hi(Oa,(function(La){Ia=Ia[La[0]].apply(Ia,La.slice(1))}))}else Aa[Oa[0]].apply(Aa,Oa.slice(1))}))};ja(is,this),ja(cs,this),ja(Qr,this)}finally{Cn--}}push($){if(Cn>0&&R($)&&F($[0])){var ts=qn.prototype[$[0]];P(ts)&&ts.apply(this,$.slice(1))}else this._execute_array([$])}capture($,ts,is){var cs,Qr,ja,Na,Aa;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zi){if(this.is_capturing())if(!C($)&&F($)){var Oa=!this.config.opt_out_useragent_filter&&this._is_bot();if(!Oa||this.config.__preview_capture_bot_pageviews){var Ia=is!=null&&is.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(Ia==null||!Ia.isRateLimited){ts!=null&&ts.$current_url&&!F(ts==null?void 0:ts.$current_url)&&(Ie.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),ts==null||delete ts.$current_url),$!=="$exception"||is!=null&&is.en||Ie.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var La=new Date,Ba=(is==null?void 0:is.timestamp)||La,Ma=sr(),qa={uuid:Ma,event:$,properties:this.calculateEventProperties($,ts||{},Ba,Ma)};$===Ui&&this.config.__preview_capture_bot_pageviews&&Oa&&(qa.event="$bot_pageview",qa.properties.$browser_type="bot"),Ia&&(qa.properties.$lib_rate_limit_remaining_tokens=Ia.remainingTokens),is!=null&&is.$set&&(qa.$set=is==null?void 0:is.$set);var Fa,Ha,Ka,Ga=this.tn(is==null?void 0:is.$set_once,$!==zi,$===ji);if(Ga&&(qa.$set_once=Ga),is!=null&&is._noTruncate||(Qr=this.config.properties_string_max_length,ja=qa,Na=cl=>F(cl)?cl.slice(0,Qr):cl,Aa=new Set,qa=(function cl(dl,fl){return dl!==Object(dl)?Na?Na(dl):dl:Aa.has(dl)?void 0:(Aa.add(dl),R(dl)?(nl=[],Bi(dl,(ol=>{nl.push(cl(ol))}))):(nl={},Hi(dl,((ol,pl)=>{Aa.has(ol)||(nl[pl]=cl(ol))}))),nl);var nl})(ja)),qa.timestamp=Ba,C(is==null?void 0:is.timestamp)||(qa.properties.$event_time_override_provided=!0,qa.properties.$event_time_override_system_time=La),$===rs.DISMISSED||$===rs.SENT){var Va=ts==null?void 0:ts[ss.SURVEY_ID],Ja=ts==null?void 0:ts[ss.SURVEY_ITERATION];(cl=>{try{var dl=(fl=>((nl,ol)=>{var pl=""+Sn+ol.id;return ol.current_iteration&&ol.current_iteration>0&&(pl=""+Sn+ol.id+"_"+ol.current_iteration),pl})(0,fl))(cl);if(localStorage.getItem(dl))return;localStorage.setItem(dl,"true")}catch(fl){En.error("Failed to persist survey seen state",fl)}})({id:Va,current_iteration:Ja}),qa.$set=f({},qa.$set,{[(Fa={id:Va,current_iteration:Ja},Ha=$===rs.SENT?"responded":"dismissed",Ka="$survey_"+Ha+"/"+Fa.id,Fa.current_iteration&&Fa.current_iteration>0&&(Ka="$survey_"+Ha+"/"+Fa.id+"/"+Fa.current_iteration),Ka)]:!0})}else $===rs.SHOWN&&(qa.$set=f({},qa.$set,{[ss.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if($===as.SHOWN){var Ya=ts==null?void 0:ts[ls.TOUR_TYPE];Ya&&(qa.$set=f({},qa.$set,{[ls.TOUR_LAST_SEEN_DATE+"/"+Ya]:new Date().toISOString()}))}var el=f({},qa.properties.$set,qa.$set);if(I(el)||this.setPersonPropertiesForFlags(el),!D(this.config.before_send)){var tl=this.rn(qa);if(!tl)return;qa=tl}this.Fi.emit("eventCaptured",qa);var rl={method:"POST",url:(cs=is==null?void 0:is._url)!==null&&cs!==void 0?cs:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:qa,compression:"best-available",batchKey:is==null?void 0:is._batchKey};return!this.config.request_batching||is&&(is==null||!is._batchKey)||is!=null&&is.send_instantly?this.Vi(rl):this.Zi.enqueue(rl),qa}Ie.critical("This capture call is ignored due to client rate limiting.")}}else Ie.error("No event name provided to posthog.capture")}else Ie.uninitializedWarning("posthog.capture")}_addCaptureHook($){return this.on("eventCaptured",(ts=>$(ts.event,ts)))}calculateEventProperties($,ts,is,cs,Qr){if(is=is||new Date,!this.persistence||!this.sessionPersistence)return ts;var ja=Qr?void 0:this.persistence.remove_event_timer($),Na=f({},ts);if(Na.token=this.config.token,Na.$config_defaults=this.config.defaults,this.Ni()&&(Na.$cookieless_mode=!0),$==="$snapshot"){var Aa=f({},this.persistence.properties(),this.sessionPersistence.properties());return Na.distinct_id=Aa.distinct_id,(!F(Na.distinct_id)&&!L(Na.distinct_id)||A(Na.distinct_id))&&Ie.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),Na}var Oa,Ia=(function(Ka,Ga){var Va,Ja,Ya,el;if(!u)return{};var tl,rl,cl,dl,fl,nl,ol,pl,Tl=Ka?[...Fr,...Ga||[]]:[],[ul,hl]=(function(jl){for(var Nl=0;Wt.length>Nl;Nl++){var[zl,Zl]=Wt[Nl],Dl=zl.exec(jl),Il=Dl&&(P(Zl)?Zl(Dl,jl):Zl);if(Il)return Il}return["",""]})(u);return qi(Yi({$os:ul,$os_version:hl,$browser:Ht(u,navigator.vendor),$device:Gt(u),$device_type:(rl=u,cl={userAgentDataPlatform:(Va=navigator)==null||(Va=Va.userAgentData)==null?void 0:Va.platform,maxTouchPoints:(Ja=navigator)==null?void 0:Ja.maxTouchPoints,screenWidth:t==null||(Ya=t.screen)==null?void 0:Ya.width,screenHeight:t==null||(el=t.screen)==null?void 0:el.height,devicePixelRatio:t==null?void 0:t.devicePixelRatio},pl=Gt(rl),pl===st||pl===rt||pl==="Kobo"||pl==="Kindle Fire"||pl===At?it:pl===Et||pl===$t||pl===St||pl===It?"Console":pl===ot?"Wearable":pl?Z:(cl==null?void 0:cl.userAgentDataPlatform)==="Android"&&((dl=cl==null?void 0:cl.maxTouchPoints)!==null&&dl!==void 0?dl:0)>0?600>Math.min((fl=cl==null?void 0:cl.screenWidth)!==null&&fl!==void 0?fl:0,(nl=cl==null?void 0:cl.screenHeight)!==null&&nl!==void 0?nl:0)/((ol=cl==null?void 0:cl.devicePixelRatio)!==null&&ol!==void 0?ol:1)?Z:it:"Desktop"),$timezone:Vr(),$timezone_offset:Wr()}),{$current_url:Or(s==null?void 0:s.href,Tl,Mr),$host:s==null?void 0:s.host,$pathname:s==null?void 0:s.pathname,$raw_user_agent:u.length>1e3?u.substring(0,997)+"...":u,$browser_version:Vt(u,navigator.vendor),$browser_language:jr(),$browser_language_prefix:(tl=jr(),typeof tl=="string"?tl.split("-")[0]:void 0),$screen_height:t==null?void 0:t.screen.height,$screen_width:t==null?void 0:t.screen.width,$viewport_height:t==null?void 0:t.innerHeight,$viewport_width:t==null?void 0:t.innerWidth,$lib:v.LIB_NAME,$lib_version:v.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:La,windowId:Ba}=this.sessionManager.checkAndGetSessionAndWindowId(Qr,is.getTime());Na.$session_id=La,Na.$window_id=Ba}this.sessionPropsManager&&qi(Na,this.sessionPropsManager.getSessionProps());try{var Ma;this.sessionRecording&&qi(Na,this.sessionRecording.sdkDebugProperties),Na.$sdk_debug_retry_queue_size=(Ma=this.Hi)==null?void 0:Ma.length}catch(Ka){Na.$sdk_debug_error_capturing_properties=String(Ka)}if(this.requestRouter.region===bn&&(Na.$lib_custom_api_host=this.config.api_host),Oa=$!==Ui||Qr?$!==Ni||Qr?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(is):this.pageViewManager.doPageView(is,cs),Na=qi(Na,Oa),$===Ui&&r&&(Na.title=r.title),!C(ja)){var qa=is.getTime()-ja;Na.$duration=parseFloat((qa/1e3).toFixed(3))}u&&this.config.opt_out_useragent_filter&&(Na.$browser_type=this._is_bot()?"bot":"browser"),(Na=qi({},Ia,this.persistence.properties(),this.sessionPersistence.properties(),Na)).$is_identified=this._isIdentified(),R(this.config.property_denylist)?Hi(this.config.property_denylist,(function(Ka){delete Na[Ka]})):Ie.error(Ln+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var Fa=this.config.sanitize_properties;Fa&&(Ie.error(Dn),Na=Fa(Na,$));var Ha=this.nn();return Na.$process_person_profile=Ha,Ha&&!Qr&&this.sn("_calculate_event_properties"),Na}tn($,ts,is){var cs;if(ts===void 0&&(ts=!0),is===void 0&&(is=!1),!this.persistence||!this.nn()||this.Mi&&!is)return $;var Qr=this.persistence.get_initial_props(),ja=(cs=this.sessionPropsManager)==null?void 0:cs.getSetOnceProps(),Na=qi({},Qr,ja||{},$||{}),Aa=this.config.sanitize_properties;return Aa&&(Ie.error(Dn),Na=Aa(Na,"$set_once")),ts&&(this.Mi=!0),I(Na)?void 0:Na}register($,ts){var is;(is=this.persistence)==null||is.register($,ts)}register_once($,ts,is){var cs;(cs=this.persistence)==null||cs.register_once($,ts,is)}register_for_session($){var ts;(ts=this.sessionPersistence)==null||ts.register($)}unregister($){var ts;(ts=this.persistence)==null||ts.unregister($)}unregister_for_session($){var ts;(ts=this.sessionPersistence)==null||ts.unregister($)}an($,ts){this.register({[$]:ts})}getFeatureFlag($,ts){var is;return(is=this.featureFlags)==null?void 0:is.getFeatureFlag($,ts)}getFeatureFlagPayload($){var ts;return(ts=this.featureFlags)==null?void 0:ts.getFeatureFlagPayload($)}getFeatureFlagResult($,ts){var is;return(is=this.featureFlags)==null?void 0:is.getFeatureFlagResult($,ts)}isFeatureEnabled($,ts){var is;return(is=this.featureFlags)==null?void 0:is.isFeatureEnabled($,ts)}reloadFeatureFlags(){var $;($=this.featureFlags)==null||$.reloadFeatureFlags()}updateFlags($,ts,is){var cs;(cs=this.featureFlags)==null||cs.updateFlags($,ts,is)}updateEarlyAccessFeatureEnrollment($,ts,is){var cs;(cs=this.featureFlags)==null||cs.updateEarlyAccessFeatureEnrollment($,ts,is)}getEarlyAccessFeatures($,ts,is){var cs;return ts===void 0&&(ts=!1),(cs=this.featureFlags)==null?void 0:cs.getEarlyAccessFeatures($,ts,is)}on($,ts){return this.Fi.on($,ts)}onFeatureFlags($){return this.featureFlags?this.featureFlags.onFeatureFlags($):($([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded($){return this.surveys?this.surveys.onSurveysLoaded($):($([],{isLoaded:!1,error:Mn}),()=>{})}onSessionId($){var ts,is;return(ts=(is=this.sessionManager)==null?void 0:is.onSessionId($))!==null&&ts!==void 0?ts:()=>{}}getSurveys($,ts){ts===void 0&&(ts=!1),this.surveys?this.surveys.getSurveys($,ts):$([],{isLoaded:!1,error:Mn})}getActiveMatchingSurveys($,ts){ts===void 0&&(ts=!1),this.surveys?this.surveys.getActiveMatchingSurveys($,ts):$([],{isLoaded:!1,error:Mn})}renderSurvey($,ts){var is;(is=this.surveys)==null||is.renderSurvey($,ts)}displaySurvey($,ts){var is;ts===void 0&&(ts=Tn),(is=this.surveys)==null||is.displaySurvey($,ts)}cancelPendingSurvey($){var ts;(ts=this.surveys)==null||ts.cancelPendingSurvey($)}canRenderSurvey($){var ts,is;return(ts=(is=this.surveys)==null?void 0:is.canRenderSurvey($))!==null&&ts!==void 0?ts:{visible:!1,disabledReason:Mn}}canRenderSurveyAsync($,ts){var is,cs;return ts===void 0&&(ts=!1),(is=(cs=this.surveys)==null?void 0:cs.canRenderSurveyAsync($,ts))!==null&&is!==void 0?is:Promise.resolve({visible:!1,disabledReason:Mn})}ln($){return!$||A($)?(Ie.critical("Unique user id has not been set in posthog.identify"),!1):$===Ti?(Ie.critical('The string "'+$+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes($.toLowerCase())&&!["undefined","null"].includes($.toLowerCase())||(Ie.critical('The string "'+$+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify($,ts,is){if(!this.__loaded||!this.persistence)return Ie.uninitializedWarning("posthog.identify");if(L($)&&($=$.toString(),Ie.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.ln($)&&this.sn("posthog.identify")){var cs=this.get_distinct_id();this.register({$user_id:$}),this.get_property(De)||this.register_once({$had_persisted_distinct_id:!0,$device_id:cs},""),$!==cs&&$!==this.get_property(Le)&&(this.unregister(Le),this.register({distinct_id:$}));var Qr,ja=(this.persistence.get_property(mi)||Fi)===Fi;$!==cs&&ja?(this.persistence.set_property(mi,Ai),this.setPersonPropertiesForFlags({$set:ts||{},$set_once:is||{}},!1),this.capture(ji,{distinct_id:$,$anon_distinct_id:cs},{$set:ts||{},$set_once:is||{}}),this.Di=fn($,ts,is),(Qr=this.featureFlags)==null||Qr.setAnonymousDistinctId(cs)):(ts||is)&&this.setPersonProperties(ts,is),$!==cs&&(this.reloadFeatureFlags(),this.unregister(pi))}}setPersonProperties($,ts){if(($||ts)&&this.sn("posthog.setPersonProperties")){var is=fn(this.get_distinct_id(),$,ts);this.Di!==is?(this.setPersonPropertiesForFlags({$set:$||{},$set_once:ts||{}},!0),this.capture("$set",{$set:$||{},$set_once:ts||{}}),this.Di=is):Ie.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group($,ts,is){if($&&ts){var cs=this.getGroups(),Qr=cs[$]!==ts;if(Qr&&this.resetGroupPropertiesForFlags($),this.register({$groups:f({},cs,{[$]:ts})}),Qr||is){var ja={$group_type:$,$group_key:ts};is&&(ja.$group_set=is),this.capture(zi,ja)}is&&this.setGroupPropertiesForFlags({[$]:is}),Qr&&!is&&this.reloadFeatureFlags()}else Ie.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags($,ts){var is;ts===void 0&&(ts=!0),(is=this.featureFlags)==null||is.setPersonPropertiesForFlags($,ts)}resetPersonPropertiesForFlags(){var $;($=this.featureFlags)==null||$.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags($,ts){var is;ts===void 0&&(ts=!0),this.sn("posthog.setGroupPropertiesForFlags")&&((is=this.featureFlags)==null||is.setGroupPropertiesForFlags($,ts))}resetGroupPropertiesForFlags($){var ts;(ts=this.featureFlags)==null||ts.resetGroupPropertiesForFlags($)}reset($){var ts,is,cs,Qr,ja,Na,Aa,Oa;if(Ie.info("reset"),!this.__loaded)return Ie.uninitializedWarning("posthog.reset");var Ia=this.get_property(De);if(this.consent.reset(),(ts=this.persistence)==null||ts.clear(),(is=this.sessionPersistence)==null||is.clear(),(cs=this.surveys)==null||cs.reset(),(Qr=this.Ki)==null||Qr.stop(),(ja=this.featureFlags)==null||ja.reset(),(Na=this.conversations)==null||Na.reset(),(Aa=this.persistence)==null||Aa.set_property(mi,Fi),(Oa=this.sessionManager)==null||Oa.resetSessionId(),this.Di=null,this.config.cookieless_mode===Ci)this.register_once({distinct_id:Ti,$device_id:null},"");else{var La=this.config.get_device_id(sr());this.register_once({distinct_id:La,$device_id:$?La:Ia},"")}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}setIdentity($,ts){var is;this.config.identity_distinct_id=$,this.config.identity_hash=ts,this.alias($),(is=this.conversations)==null||is.un()}clearIdentity(){var $;delete this.config.identity_distinct_id,delete this.config.identity_hash,($=this.conversations)==null||$.hn()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var $,ts;return($=(ts=this.sessionManager)==null?void 0:ts.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&$!==void 0?$:""}get_session_replay_url($){if(!this.sessionManager)return"";var{sessionId:ts,sessionStartTimestamp:is}=this.sessionManager.checkAndGetSessionAndWindowId(!0),cs=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+ts);if($!=null&&$.withTimestamp&&is){var Qr,ja=(Qr=$.timestampLookBack)!==null&&Qr!==void 0?Qr:10;if(!is)return cs;cs+="?t="+Math.max(Math.floor((new Date().getTime()-is)/1e3)-ja,0)}return cs}alias($,ts){return $===this.get_property(Me)?(Ie.critical("Attempting to create alias for existing People user - aborting."),-2):this.sn("posthog.alias")?(C(ts)&&(ts=this.get_distinct_id()),$!==ts?(this.an(Le,$),this.capture("$create_alias",{alias:$,distinct_id:ts})):(Ie.warn("alias matches current distinct_id - skipping api call."),this.identify($),-1)):void 0}set_config($){var ts=f({},this.config);if(O($)){var is,cs,Qr,ja,Na,Aa,Oa,Ia,La,Ba;qi(this.config,Bn($));var Ma=this.qi();(is=this.persistence)==null||is.update_config(this.config,ts,Ma),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Yr(f({},this.config,{persistence:"sessionStorage"}),Ma);var qa=this.Bi(this.config.debug);N(qa)&&(this.config.debug=qa),N(this.config.debug)&&(this.config.debug?(v.DEBUG=!0,hr.R()&&hr.M("ph_debug",!0),Ie.info("set_config",{config:$,oldConfig:ts,newConfig:f({},this.config)})):(v.DEBUG=!1,hr.R()&&hr.F("ph_debug"))),(cs=this.exceptionObserver)==null||cs.onConfigChange(),(Qr=this.exceptions)==null||Qr.onConfigChange(),(ja=this.sessionRecording)==null||ja.startIfEnabledOrStop(),(Na=this.autocapture)==null||Na.startIfEnabled(),(Aa=this.heatmaps)==null||Aa.startIfEnabled(),(Oa=this.exceptionObserver)==null||Oa.startIfEnabledOrStop(),(Ia=this.deadClicksAutocapture)==null||Ia.startIfEnabledOrStop(),(La=this.surveys)==null||La.loadIfEnabled(),this.cn(),(Ba=this.externalIntegrations)==null||Ba.startIfEnabledOrStop()}}_overrideSDKInfo($,ts){v.LIB_NAME=$,v.LIB_VERSION=ts}startSessionRecording($){var ts,is,cs,Qr,ja,Na=$===!0,Aa={sampling:Na||!($==null||!$.sampling),linked_flag:Na||!($==null||!$.linked_flag),url_trigger:Na||!($==null||!$.url_trigger),event_trigger:Na||!($==null||!$.event_trigger)};Object.values(Aa).some(Boolean)&&((ts=this.sessionManager)==null||ts.checkAndGetSessionAndWindowId(),Aa.sampling&&((is=this.sessionRecording)==null||is.overrideSampling()),Aa.linked_flag&&((cs=this.sessionRecording)==null||cs.overrideLinkedFlag()),Aa.url_trigger&&((Qr=this.sessionRecording)==null||Qr.overrideTrigger("url")),Aa.event_trigger&&((ja=this.sessionRecording)==null||ja.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var $;return!(($=this.sessionRecording)==null||!$.started)}captureException($,ts){if(this.exceptions){var is=new Error("PostHog syntheticException"),cs=this.exceptions.buildProperties($,{handled:!0,syntheticException:is});return this.exceptions.sendExceptionEvent(f({},cs,ts))}}addExceptionStep($,ts){var is;(is=this.exceptions)==null||is.addExceptionStep($,ts)}captureLog($){var ts;(ts=this.logs)==null||ts.captureLog($)}get logger(){var $,ts;return($=(ts=this.logs)==null?void 0:ts.logger)!==null&&$!==void 0?$:qn.dn}startExceptionAutocapture($){this.set_config({capture_exceptions:$==null||$})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar($){var ts,is;return(ts=(is=this.toolbar)==null?void 0:is.loadToolbar($))!==null&&ts!==void 0&&ts}get_property($){var ts;return(ts=this.persistence)==null?void 0:ts.props[$]}getSessionProperty($){var ts;return(ts=this.sessionPersistence)==null?void 0:ts.props[$]}toString(){var $,ts=($=this.config.name)!==null&&$!==void 0?$:Un;return ts!==Un&&(ts=Un+"."+ts),ts}_isIdentified(){var $,ts;return(($=this.persistence)==null?void 0:$.get_property(mi))===Ai||((ts=this.sessionPersistence)==null?void 0:ts.get_property(mi))===Ai}nn(){var $,ts;return!(this.config.person_profiles==="never"||this.config.person_profiles===Mi&&!this._isIdentified()&&I(this.getGroups())&&(($=this.persistence)==null||($=$.props)==null||!$[Le])&&((ts=this.persistence)==null||(ts=ts.props)==null||!ts[Si]))}Qi(){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.nn()||this.sn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.sn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}sn($){return this.config.person_profiles==="never"?(Ie.error($+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.an(Si,!0),!0)}qi(){if(this.config.cookieless_mode==="always")return!0;var $=this.consent.isOptedOut();return this.config.disable_persistence||$&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==Ii)}cn(){var $,ts,is,cs,Qr=this.qi();return(($=this.persistence)==null?void 0:$._r)!==Qr&&((is=this.persistence)==null||is.set_disabled(Qr)),((ts=this.sessionPersistence)==null?void 0:ts._r)!==Qr&&((cs=this.sessionPersistence)==null||cs.set_disabled(Qr)),Qr}opt_in_capturing($){var ts;if(this.config.cookieless_mode!==Ci){if(this.Ni()){var is,cs,Qr,ja,Na;this.reset(!0),(is=this.sessionManager)==null||is.destroy(),(cs=this.pageViewManager)==null||cs.destroy(),this.sessionManager=new vn(this),this.pageViewManager=new $r(this),this.persistence&&(this.sessionPropsManager=new un(this,this.sessionManager,this.persistence));var Aa,Oa=(Qr=(ja=this.config.__extensionClasses)==null?void 0:ja.sessionRecording)!==null&&Qr!==void 0?Qr:(Na=qn.__defaultExtensionClasses)==null?void 0:Na.sessionRecording;Oa&&(this.sessionRecording=this.Ei(this.sessionRecording,new Oa(this)),this.Wi&&((Aa=this.sessionRecording)==null||Aa.onRemoteConfig==null||Aa.onRemoteConfig(this.Wi)))}var Ia,La;this.consent.optInOut(!0),this.cn(),this.Xi(),(ts=this.sessionRecording)==null||ts.startIfEnabledOrStop(),this.config.cookieless_mode==Ii&&((Ia=this.surveys)==null||Ia.loadIfEnabled()),(C($==null?void 0:$.captureEventName)||$!=null&&$.captureEventName)&&this.capture((La=$==null?void 0:$.captureEventName)!==null&&La!==void 0?La:"$opt_in",$==null?void 0:$.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Ji()}else Ie.warn(An)}opt_out_capturing(){var $,ts,is;this.config.cookieless_mode!==Ci?(this.config.cookieless_mode===Ii&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.cn(),this.config.cookieless_mode===Ii&&(this.register({distinct_id:Ti,$device_id:null}),($=this.sessionManager)==null||$.destroy(),(ts=this.pageViewManager)==null||ts.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(is=this.sessionRecording)==null||is.stopRecording(),this.sessionRecording=void 0,this.Ji())):Ie.warn(An)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var $=this.consent.consent;return $===1?"granted":$===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Ci||(this.config.cookieless_mode===Ii?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.cn()}_is_bot(){return i?cn(i,this.config.custom_blocked_useragents):void 0}Ji(){r&&(r.visibilityState==="visible"?this.Oi||(this.Oi=!0,this.capture(Ui,{title:r.title},{send_instantly:!0}),this.Pi&&(r.removeEventListener(Di,this.Pi),this.Pi=null)):this.Pi||(this.Pi=this.Ji.bind(this),Xi(r,Di,this.Pi)))}debug($){$===!1?(t==null||t.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(t==null||t.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}))}Fr(){var $,ts,is,cs,Qr,ja,Na=this.ji||{};return"advanced_disable_flags"in Na?!!Na.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(Ie.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):(is="advanced_disable_decide",cs=Ie,Qr=(ts="advanced_disable_flags")in($=Na)&&!D($[ts]),ja=is in $&&!D($[is]),Qr?$[ts]:!!ja&&(cs&&cs.warn("Config field '"+is+"' is deprecated. Please use '"+ts+"' instead. The old field will be removed in a future major version."),$[is]))}rn($){if(D(this.config.before_send))return $;var ts=R(this.config.before_send)?this.config.before_send:[this.config.before_send],is=$;for(var cs of ts){if(is=cs(is),D(is)){var Qr="Event '"+$.event+"' was rejected in beforeSend function";return z($.event)?Ie.warn(Qr+". This can cause unexpected behavior."):Ie.info(Qr),null}is.properties&&!I(is.properties)||Ie.warn("Event '"+$.event+"' has no properties after beforeSend function, this is likely an error.")}return is}getPageViewId(){var $;return($=this.pageViewManager.dr)==null?void 0:$.pageViewId}captureTraceFeedback($,ts){this.capture("$ai_feedback",{$ai_trace_id:String($),$ai_feedback_text:ts})}captureTraceMetric($,ts,is){this.capture("$ai_metric",{$ai_trace_id:String($),$ai_metric_name:ts,$ai_metric_value:String(is)})}Bi($){var ts=N($)&&!$,is=hr.R()&&hr.O("ph_debug")==="true";return!ts&&(!!is||$)}}qn.__defaultExtensionClasses={},qn.dn={trace:On=()=>{},debug:On,info:On,warn:On,error:On,fatal:On},(function(es,$){for(var ts=0;$.length>ts;ts++)es.prototype[$[ts]]=Gi(es.prototype[$[ts]])})(qn,["identify"]);var Vn=1,Wn=3,Gn=11;function Yn(es){return es instanceof Element&&(es.id===$i||!(es.closest==null||!es.closest(".toolbar-global-fade-container")))}function Jn(es){return!!es&&es.nodeType===Vn}function Kn(es,$){return!!es&&!!es.tagName&&es.tagName.toLowerCase()===$.toLowerCase()}function Xn(es){return!!es&&es.nodeType===Wn}function Qn(es){return!!es&&es.nodeType===Gn&&Jn(es.host)}function Zn(es){return es?x(es).split(/\s+/):[]}function to(es){var $=t==null?void 0:t.location.href;return!!($&&es&&es.some((ts=>$.match(ts))))}function eo(es){var $="";switch(typeof es.className){case"string":$=es.className;break;case"object":$=(es.className&&"baseVal"in es.className?es.className.baseVal:null)||es.getAttribute("class")||"";break;default:$=""}return Zn($)}function io(es){return D(es)?null:x(es).split(/(\s+)/).filter(($=>wo($))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function ro(es){var $="";return co(es)&&!po(es)&&es.childNodes&&es.childNodes.length&&Hi(es.childNodes,(function(ts){var is;Xn(ts)&&ts.textContent&&($+=(is=io(ts.textContent))!==null&&is!==void 0?is:"")})),x($)}function so(es){return C(es.target)?es.srcElement||null:($=es.target)!=null&&$.shadowRoot?es.composedPath()[0]||null:es.target||null;var $}var no=["a","button","form","input","select","textarea","label"];function oo(es,$){if(C($))return!0;var ts,is=function(Qr){if($.some((ja=>Qr.matches(ja))))return{v:!0}};for(var cs of es)if(ts=is(cs))return ts.v;return!1}function ao(es){var $=es.parentNode;return!(!$||!Jn($))&&$}var lo=["next","previous","prev",">","<"],uo=[".ph-no-rageclick",".ph-no-capture"],ho=es=>!es||Kn(es,"html")||!Jn(es),vo=(es,$)=>{if(!t||ho(es))return{parentIsUsefulElement:!1,targetElementList:[]};for(var ts=!1,is=[es],cs=es;cs.parentNode&&!Kn(cs,"body");)if(Qn(cs.parentNode))is.push(cs.parentNode.host),cs=cs.parentNode.host;else{var Qr=ao(cs);if(!Qr)break;if($||no.indexOf(Qr.tagName.toLowerCase())>-1)ts=!0;else{var ja=t.getComputedStyle(Qr);ja&&ja.getPropertyValue("cursor")==="pointer"&&(ts=!0)}is.push(Qr),cs=Qr}return{parentIsUsefulElement:ts,targetElementList:is}};function co(es){for(var $=es;$.parentNode&&!Kn($,"body");$=$.parentNode){var ts=eo($);if(w(ts,"ph-sensitive")||w(ts,"ph-no-capture"))return!1}if(w(eo(es),"ph-include"))return!0;var is=es.type||"";if(F(is))switch(is.toLowerCase()){case"hidden":case"password":return!1}var cs=es.name||es.id||"";return!F(cs)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(cs.replace(/[^a-zA-Z0-9]/g,""))}function po(es){return!!(Kn(es,"input")&&!["button","checkbox","submit","reset"].includes(es.type)||Kn(es,"select")||Kn(es,"textarea")||es.getAttribute("contenteditable")==="true")}var fo="(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})",_o=new RegExp("^(?:"+fo+")$"),go=new RegExp(fo),mo="\\d{3}-?\\d{2}-?\\d{4}",bo=new RegExp("^("+mo+")$"),yo=new RegExp("("+mo+")");function wo(es,$){return $===void 0&&($=!0),!(D(es)||F(es)&&(es=x(es),($?_o:go).test((es||"").replace(/[- ]/g,""))||($?bo:yo).test(es)))}function xo(es){var $=ro(es);return wo($=($+" "+Eo(es)).trim())?$:""}function Eo(es){var $="";return es&&es.childNodes&&es.childNodes.length&&Hi(es.childNodes,(function(ts){var is;if(ts&&((is=ts.tagName)==null?void 0:is.toLowerCase())==="span")try{var cs=ro(ts);$=($+" "+cs).trim(),ts.childNodes&&ts.childNodes.length&&($=($+" "+Eo(ts)).trim())}catch(Qr){Ie.error("[AutoCapture]",Qr)}})),$}function So(es){return es.replace(/"|\\"/g,'\\"')}function $o(es){var $=es.attr__class;return $?R($)?$:Zn($):void 0}class To{constructor($){this.disabled=$===!1;var ts=O($)?$:{};this.thresholdPx=ts.threshold_px||30,this.timeoutMs=ts.timeout_ms||1e3,this.clickCount=ts.click_count||3,this.clicks=[]}isRageClick($,ts,is){if(this.disabled)return!1;var cs=this.clicks[this.clicks.length-1];if(cs&&Math.abs($-cs.x)+Math.abs(ts-cs.y)<this.thresholdPx&&this.timeoutMs>is-cs.timestamp){if(this.clicks.push({x:$,y:ts,timestamp:is}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:$,y:ts,timestamp:is}];return!1}}var ko="$copy_autocapture",Ro=Ce("[AutoCapture]");function Po(es,$){return $.length>es?$.slice(0,es)+"...":$}function Oo(es){if(es.previousElementSibling)return es.previousElementSibling;var $=es;do $=$.previousSibling;while($&&!Jn($));return $}function Io(es,$){var ts,is,{e:cs,maskAllElementAttributes:Qr,maskAllText:ja,elementAttributeIgnoreList:Na,elementsChainAsString:Aa}=$;if(!Jn(es))return{props:{}};for(var Oa=[es],Ia=es;Ia.parentNode&&!Kn(Ia,"body");)if(Qn(Ia.parentNode))Oa.push(Ia.parentNode.host),Ia=Ia.parentNode.host;else{if(!Jn(Ia.parentNode))break;Oa.push(Ia.parentNode),Ia=Ia.parentNode}var La,Ba,Ma=[],qa={},Fa=!1,Ha=!1;if(Hi(Oa,(Ya=>{var el=co(Ya);if(Kn(Ya,"a")){var tl=Ya.getAttribute("href");Fa=el&&!!tl&&wo(tl)&&tl}w(eo(Ya),"ph-no-capture")&&(Ha=!0),Ma.push((function(cl,dl,fl,nl){var ol=cl.tagName.toLowerCase(),pl={tag_name:ol};no.indexOf(ol)>-1&&!fl&&(pl.$el_text=ol.toLowerCase()==="a"||ol.toLowerCase()==="button"?Po(1024,xo(cl)):Po(1024,ro(cl)));var Tl=eo(cl);Tl.length>0&&(pl.classes=Tl.filter((function(Nl){return Nl!==""}))),Hi(cl.attributes,(function(Nl){var zl;if((!po(cl)||["name","id","class","aria-label"].indexOf(Nl.name)!==-1)&&(nl==null||!nl.includes(Nl.name))&&!dl&&wo(Nl.value)&&(!F(zl=Nl.name)||zl.substring(0,10)!=="_ngcontent"&&zl.substring(0,7)!=="_nghost")){var Zl=Nl.value;Nl.name==="class"&&(Zl=Zn(Zl).join(" ")),pl["attr__"+Nl.name]=Po(1024,Zl)}}));for(var ul=1,hl=1,jl=cl;jl=Oo(jl);)ul++,jl.tagName===cl.tagName&&hl++;return pl.nth_child=ul,pl.nth_of_type=hl,pl})(Ya,Qr,ja,Na));var rl=(function(cl){if(!co(cl))return{};var dl={};return Hi(cl.attributes,(function(fl){if(fl.name&&fl.name.indexOf("data-ph-capture-attribute")===0){var nl=fl.name.replace("data-ph-capture-attribute-",""),ol=fl.value;nl&&ol&&wo(ol)&&(dl[nl]=ol)}})),dl})(Ya);qi(qa,rl)})),Ha)return{props:{},explicitNoCapture:Ha};if(ja||(Ma[0].$el_text=Kn(es,"a")||Kn(es,"button")?xo(es):ro(es)),Fa){var Ka,Ga;Ma[0].attr__href=Fa;var Va=(Ka=Rr(Fa))==null?void 0:Ka.host,Ja=t==null||(Ga=t.location)==null?void 0:Ga.host;Va&&Ja&&Va!==Ja&&(La=Fa)}return{props:qi({$event_type:cs.type,$ce_version:1},Aa?{}:{$elements:Ma},{$elements_chain:(Ba=Ma,(function(Ya){return Ya.map((el=>{var tl,rl,cl="";if(el.tag_name&&(cl+=el.tag_name),el.attr_class)for(var dl of(el.attr_class.sort(),el.attr_class))cl+="."+dl.replace(/"/g,"");var fl=f({},el.text?{text:el.text}:{},{"nth-child":(tl=el.nth_child)!==null&&tl!==void 0?tl:0,"nth-of-type":(rl=el.nth_of_type)!==null&&rl!==void 0?rl:0},el.href?{href:el.href}:{},el.attr_id?{attr_id:el.attr_id}:{},el.attributes),nl={};return Vi(fl).sort(((ol,pl)=>{var[Tl]=ol,[ul]=pl;return Tl.localeCompare(ul)})).forEach((ol=>{var[pl,Tl]=ol;return nl[So(pl.toString())]=So(Tl.toString())})),(cl+=":")+Vi(nl).map((ol=>{var[pl,Tl]=ol;return pl+'="'+Tl+'"'})).join("")})).join(";")})((function(Ya){return Ya.map((el=>{var tl,rl,cl={text:(tl=el.$el_text)==null?void 0:tl.slice(0,400),tag_name:el.tag_name,href:(rl=el.attr__href)==null?void 0:rl.slice(0,2048),attr_class:$o(el),attr_id:el.attr__id,nth_child:el.nth_child,nth_of_type:el.nth_of_type,attributes:{}};return Vi(el).filter((dl=>{var[fl]=dl;return fl.indexOf("attr__")===0})).forEach((dl=>{var[fl,nl]=dl;return cl.attributes[fl]=nl})),cl}))})(Ba)))},(ts=Ma[0])!=null&&ts.$el_text?{$el_text:(is=Ma[0])==null?void 0:is.$el_text}:{},La&&cs.type==="click"?{$external_click_url:La}:{},qa)}}var Co=Ce("[ExceptionAutocapture]");function Fo(es,$,ts){try{if(!($ in es))return()=>{};var is=es[$],cs=ts(is);return P(cs)&&(cs.prototype=cs.prototype||{},Object.defineProperties(cs,{__posthog_wrapped__:{enumerable:!1,value:!0}})),es[$]=cs,()=>{es[$]=is}}catch{return()=>{}}}var Ao=Ce("[TracingHeaders]"),Mo=Ce("[Web Vitals]"),Do=9e5,Lo="disabled",Uo="lazy_loading",No="awaiting_config",jo="missing_config";Ce("[SessionRecording]"),Ce("[SessionRecording]");var zo="[SessionRecording]",Bo=Ce(zo),Ho=Ce("[Heatmaps]");function qo(es){return O(es)&&"clientX"in es&&"clientY"in es&&L(es.clientX)&&L(es.clientY)}var Vo=Ce("[Product Tours]"),Wo=["$set_once","$set"],Go=Ce("[SiteApps]"),Yo="Error while initializing PostHog app with config id ";function Jo(es,$,ts){if(D(es))return!1;switch(ts){case"exact":return es===$;case"contains":var is=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(is,"i").test(es);case"regex":try{return new RegExp($).test(es)}catch{return!1}default:return!1}}class Ko{constructor($){this.vn=new hn,this.fn=(ts,is)=>this.pn(ts,is)&&this.gn(ts,is)&&this.mn(ts,is)&&this.yn(ts,is),this.pn=(ts,is)=>is==null||!is.event||(ts==null?void 0:ts.event)===(is==null?void 0:is.event),this._instance=$,this.bn=new Set,this._n=new Set}init(){var $,ts;C(($=this._instance)==null?void 0:$._addCaptureHook)||(ts=this._instance)==null||ts._addCaptureHook(((is,cs)=>{this.on(is,cs)}))}register($){var ts,is;if(!C((ts=this._instance)==null?void 0:ts._addCaptureHook)&&($.forEach((ja=>{var Na,Aa;(Na=this._n)==null||Na.add(ja),(Aa=ja.steps)==null||Aa.forEach((Oa=>{var Ia;(Ia=this.bn)==null||Ia.add((Oa==null?void 0:Oa.event)||"")}))})),(is=this._instance)!=null&&is.autocapture)){var cs,Qr=new Set;$.forEach((ja=>{var Na;(Na=ja.steps)==null||Na.forEach((Aa=>{Aa!=null&&Aa.selector&&Qr.add(Aa==null?void 0:Aa.selector)}))})),(cs=this._instance)==null||cs.autocapture.setElementSelectors(Qr)}}on($,ts){var is;ts!=null&&$.length!=0&&(this.bn.has($)||this.bn.has(ts==null?void 0:ts.event))&&this._n&&((is=this._n)==null?void 0:is.size)>0&&this._n.forEach((cs=>{this.wn(ts,cs)&&this.vn.emit("actionCaptured",cs.name)}))}In($){this.onAction("actionCaptured",(ts=>$(ts)))}wn($,ts){if((ts==null?void 0:ts.steps)==null)return!1;for(var is of ts.steps)if(this.fn($,is))return!0;return!1}onAction($,ts){return this.vn.on($,ts)}gn($,ts){if(ts!=null&&ts.url){var is,cs=$==null||(is=$.properties)==null?void 0:is.$current_url;if(!cs||typeof cs!="string"||!Jo(cs,ts.url,ts.url_matching||"contains"))return!1}return!0}mn($,ts){return!!this.Cn($,ts)&&!!this.Sn($,ts)&&!!this.xn($,ts)}Cn($,ts){var is;if(ts==null||!ts.href)return!0;var cs=this.kn($);if(cs.length>0)return cs.some((Na=>Jo(Na.href,ts.href,ts.href_matching||"exact")));var Qr,ja=($==null||(is=$.properties)==null?void 0:is.$elements_chain)||"";return!!ja&&Jo((Qr=ja.match(/(?::|")href="(.*?)"/))?Qr[1]:"",ts.href,ts.href_matching||"exact")}Sn($,ts){var is;if(ts==null||!ts.text)return!0;var cs=this.kn($);if(cs.length>0)return cs.some((Oa=>Jo(Oa.text,ts.text,ts.text_matching||"exact")||Jo(Oa.$el_text,ts.text,ts.text_matching||"exact")));var Qr,ja,Na,Aa=($==null||(is=$.properties)==null?void 0:is.$elements_chain)||"";return!!Aa&&(Qr=(function(Oa){for(var Ia,La=[],Ba=/(?::|")text="(.*?)"/g;!D(Ia=Ba.exec(Oa));)La.includes(Ia[1])||La.push(Ia[1]);return La})(Aa),ja=ts.text,Na=ts.text_matching||"exact",Qr.some((Oa=>Jo(Oa,ja,Na))))}xn($,ts){var is,cs;if(ts==null||!ts.selector)return!0;var Qr=$==null||(is=$.properties)==null?void 0:is.$element_selectors;if(Qr!=null&&Qr.includes(ts.selector))return!0;var ja=($==null||(cs=$.properties)==null?void 0:cs.$elements_chain)||"";if(ts.selector_regex&&ja)try{return new RegExp(ts.selector_regex).test(ja)}catch{return!1}return!1}kn($){var ts;return($==null||(ts=$.properties)==null?void 0:ts.$elements)==null?[]:$==null?void 0:$.properties.$elements}yn($,ts){return ts==null||!ts.properties||ts.properties.length===0||mn(ts.properties.reduce(((is,cs)=>{var Qr=R(cs.value)?cs.value.map(String):cs.value!=null?[String(cs.value)]:[];return is[cs.key]={values:Qr,operator:cs.operator||"exact"},is}),{}),$==null?void 0:$.properties)}}class Xo{constructor($){this._instance=$,this.Tn=new Map,this.An=new Map,this.En=new Map}Rn($,ts){return!!$&&mn($.propertyFilters,ts==null?void 0:ts.properties)}Nn($,ts){var is=new Map;return $.forEach((cs=>{var Qr;(Qr=cs.conditions)==null||(Qr=Qr[ts])==null||(Qr=Qr.values)==null||Qr.forEach((ja=>{if(ja!=null&&ja.name){var Na=is.get(ja.name)||[];Na.push(cs.id),is.set(ja.name,Na)}}))})),is}Mn($,ts,is){var cs=(is===Jr.Activation?this.Tn:this.An).get($),Qr=[];return this.Fn((ja=>{Qr=ja.filter((Na=>cs==null?void 0:cs.includes(Na.id)))})),Qr.filter((ja=>{var Na,Aa=(Na=ja.conditions)==null||(Na=Na[is])==null||(Na=Na.values)==null?void 0:Na.find((Oa=>Oa.name===$));return this.Rn(Aa,ts)}))}register($){var ts;C((ts=this._instance)==null?void 0:ts._addCaptureHook)||(this.On($),this.Pn($))}Pn($){var ts=$.filter((is=>{var cs,Qr;return((cs=is.conditions)==null?void 0:cs.actions)&&((Qr=is.conditions)==null||(Qr=Qr.actions)==null||(Qr=Qr.values)==null?void 0:Qr.length)>0}));ts.length!==0&&(this.Ln==null&&(this.Ln=new Ko(this._instance),this.Ln.init(),this.Ln.In((is=>{this.onAction(is)}))),ts.forEach((is=>{var cs,Qr,ja,Na,Aa;is.conditions&&(cs=is.conditions)!=null&&cs.actions&&(Qr=is.conditions)!=null&&(Qr=Qr.actions)!=null&&Qr.values&&((ja=is.conditions)==null||(ja=ja.actions)==null||(ja=ja.values)==null?void 0:ja.length)>0&&((Na=this.Ln)==null||Na.register(is.conditions.actions.values),(Aa=is.conditions)==null||(Aa=Aa.actions)==null||(Aa=Aa.values)==null||Aa.forEach((Oa=>{if(Oa&&Oa.name){var Ia=this.En.get(Oa.name);Ia&&Ia.push(is.id),this.En.set(Oa.name,Ia||[is.id])}})))})))}On($){var ts,is=$.filter((Qr=>{var ja,Na;return((ja=Qr.conditions)==null?void 0:ja.events)&&((Na=Qr.conditions)==null||(Na=Na.events)==null||(Na=Na.values)==null?void 0:Na.length)>0})),cs=$.filter((Qr=>{var ja,Na;return((ja=Qr.conditions)==null?void 0:ja.cancelEvents)&&((Na=Qr.conditions)==null||(Na=Na.cancelEvents)==null||(Na=Na.values)==null?void 0:Na.length)>0}));is.length===0&&cs.length===0||((ts=this._instance)==null||ts._addCaptureHook(((Qr,ja)=>{this.onEvent(Qr,ja)})),this.Tn=this.Nn($,Jr.Activation),this.An=this.Nn($,Jr.Cancellation))}onEvent($,ts){var is,cs=this.le(),Qr=this.Dn(),ja=this.Bn(),Na=((is=this._instance)==null||(is=is.persistence)==null?void 0:is.props[Qr])||[];if(ja===$&&ts&&Na.length>0){var Aa,Oa;cs.info("event matched, removing item from activated items",{event:$,eventPayload:ts,existingActivatedItems:Na});var Ia=(ts==null||(Aa=ts.properties)==null?void 0:Aa.$survey_id)||(ts==null||(Oa=ts.properties)==null?void 0:Oa.$product_tour_id);if(Ia){var La=Na.indexOf(Ia);0>La||(Na.splice(La,1),this.jn(Na))}}else{if(this.An.has($)){var Ba=this.Mn($,ts,Jr.Cancellation);Ba.length>0&&(cs.info("cancel event matched, cancelling items",{event:$,itemsToCancel:Ba.map((qa=>qa.id))}),Ba.forEach((qa=>{var Fa=Na.indexOf(qa.id);0>Fa||Na.splice(Fa,1),this.$n(qa.id)})),this.jn(Na))}if(this.Tn.has($)){cs.info("event name matched",{event:$,eventPayload:ts,items:this.Tn.get($)});var Ma=this.Mn($,ts,Jr.Activation);this.jn(Na.concat(Ma.map((qa=>qa.id))||[]))}}}onAction($){var ts,is=this.Dn(),cs=((ts=this._instance)==null||(ts=ts.persistence)==null?void 0:ts.props[is])||[];this.En.has($)&&this.jn(cs.concat(this.En.get($)||[]))}jn($){var ts=this.le(),is=[...new Set($)].filter((cs=>!this.qn(cs)));ts.info("updating activated items",{activatedItems:is}),this.Zn(is)}getActivatedIds(){var $,ts=this.Dn();return(($=this._instance)==null||($=$.persistence)==null?void 0:$.props[ts])||[]}getEventToItemsMap(){return this.Tn}Vn(){return this.Ln}}class Qo extends Xo{constructor($){super($)}Dn(){return vi}Bn(){return rs.SHOWN}Fn($){var ts;(ts=this._instance)==null||ts.getSurveys($)}$n($){var ts;(ts=this._instance)==null||ts.cancelPendingSurvey($)}le(){return En}Zn($){var ts;(ts=this._instance)==null||(ts=ts.persistence)==null||ts.register({[vi]:$})}qn(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Zo="SDK is not enabled or survey functionality is not yet loaded",ta="Disabled. Not loading surveys.",ea=t!=null&&t.location?Ir(t.location.hash,"__posthog")||Ir(location.hash,"state"):null,ia="_postHogToolbarParams",ra=Ce("[Toolbar]"),sa=Ce("[FeatureFlags]"),na=Ce("[FeatureFlags]",{debugEnabled:!0}),oa=`" failed. Feature flags didn't load in time.`,aa=es=>{for(var $={},ts=0;es.length>ts;ts++)$[es[ts]]=!0;return $},la=es=>{var $={};for(var[ts,is]of Vi(es||{}))is&&($[ts]=is);return $},ua=Ce("[Error tracking]"),ha="Refusing to render web experiment since the viewer is a likely bot",da={icontains:(es,$)=>!!t&&$.href.toLowerCase().indexOf(es.toLowerCase())>-1,not_icontains:(es,$)=>!!t&&$.href.toLowerCase().indexOf(es.toLowerCase())===-1,regex:(es,$)=>!!t&&pn($.href,es),not_regex:(es,$)=>!!t&&!pn($.href,es),exact:(es,$)=>$.href===es,is_not:(es,$)=>$.href!==es};class va{get Bt(){return this._instance.config}constructor($){var ts=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(is){is===void 0&&(is=!1),ts.getWebExperiments((cs=>{va.Hn("retrieved web experiments from the server"),ts.zn=new Map,cs.forEach((Qr=>{if(Qr.feature_flag_key){var ja;ts.zn&&(va.Hn("setting flag key ",Qr.feature_flag_key," to web experiment ",Qr),(ja=ts.zn)==null||ja.set(Qr.feature_flag_key,Qr));var Na=ts._instance.getFeatureFlag(Qr.feature_flag_key);F(Na)&&Qr.variants[Na]&&ts.Un(Qr.name,Na,Qr.variants[Na].transforms)}else if(Qr.variants)for(var Aa in Qr.variants){var Oa=Qr.variants[Aa];va.Yn(Oa)&&ts.Un(Qr.name,Aa,Oa.transforms)}}))}),is)},this._instance=$,this._instance.onFeatureFlags((is=>{this.onFeatureFlags(is)}))}initialize(){}onFeatureFlags($){if(this._is_bot())va.Hn(ha);else if(!this.Bt.disable_web_experiments){if(D(this.zn))return this.zn=new Map,this.loadIfEnabled(),void this.previewWebExperiment();va.Hn("applying feature flags",$),$.forEach((ts=>{var is;if(this.zn&&(is=this.zn)!=null&&is.has(ts)){var cs,Qr=this._instance.getFeatureFlag(ts),ja=(cs=this.zn)==null?void 0:cs.get(ts);Qr&&ja!=null&&ja.variants[Qr]&&this.Un(ja.name,Qr,ja.variants[Qr].transforms)}}))}}previewWebExperiment(){var $=va.getWindowLocation();if($!=null&&$.search){var ts=Pr($==null?void 0:$.search,"__experiment_id"),is=Pr($==null?void 0:$.search,"__experiment_variant");ts&&is&&(va.Hn("previewing web experiments "+ts+" && "+is),this.getWebExperiments((cs=>{this.Gn(parseInt(ts),is,cs)}),!1,!0))}}loadIfEnabled(){this.Bt.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments($,ts,is){if(this.Bt.disable_web_experiments&&!is)return $([]);var cs=this._instance.get_property("$web_experiments");if(cs&&!ts)return $(cs);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Bt.token),method:"GET",callback:Qr=>$(Qr.statusCode===200&&Qr.json&&Qr.json.experiments||[])})}Gn($,ts,is){var cs=is.filter((Qr=>Qr.id===$));cs&&cs.length>0&&(va.Hn("Previewing web experiment ["+cs[0].name+"] with variant ["+ts+"]"),this.Un(cs[0].name,ts,cs[0].variants[ts].transforms))}static Yn($){return!D($.conditions)&&va.Wn($)&&va.Xn($)}static Wn($){var ts;if(D($.conditions)||D((ts=$.conditions)==null?void 0:ts.url))return!0;var is,cs,Qr,ja=va.getWindowLocation();return!!ja&&((is=$.conditions)==null||!is.url||da[(cs=(Qr=$.conditions)==null?void 0:Qr.urlMatchType)!==null&&cs!==void 0?cs:"icontains"]($.conditions.url,ja))}static getWindowLocation(){return t==null?void 0:t.location}static Xn($){var ts;if(D($.conditions)||D((ts=$.conditions)==null?void 0:ts.utm))return!0;var is=Lr();if(is.utm_source){var cs,Qr,ja,Na,Aa,Oa,Ia,La,Ba=(cs=$.conditions)==null||(cs=cs.utm)==null||!cs.utm_campaign||((Qr=$.conditions)==null||(Qr=Qr.utm)==null?void 0:Qr.utm_campaign)==is.utm_campaign,Ma=(ja=$.conditions)==null||(ja=ja.utm)==null||!ja.utm_source||((Na=$.conditions)==null||(Na=Na.utm)==null?void 0:Na.utm_source)==is.utm_source,qa=(Aa=$.conditions)==null||(Aa=Aa.utm)==null||!Aa.utm_medium||((Oa=$.conditions)==null||(Oa=Oa.utm)==null?void 0:Oa.utm_medium)==is.utm_medium,Fa=(Ia=$.conditions)==null||(Ia=Ia.utm)==null||!Ia.utm_term||((La=$.conditions)==null||(La=La.utm)==null?void 0:La.utm_term)==is.utm_term;return Ba&&qa&&Fa&&Ma}return!1}static Hn($){for(var ts=arguments.length,is=new Array(ts>1?ts-1:0),cs=1;ts>cs;cs++)is[cs-1]=arguments[cs];Ie.info("[WebExperiments] "+$,is)}Un($,ts,is){this._is_bot()?va.Hn(ha):ts!=="control"?is.forEach((cs=>{if(cs.selector){var Qr;va.Hn("applying transform of variant "+ts+" for experiment "+$+" ",cs);var ja=(Qr=document)==null?void 0:Qr.querySelectorAll(cs.selector);ja==null||ja.forEach((Na=>{var Aa=Na;cs.html&&(Aa.innerHTML=cs.html),cs.css&&Aa.setAttribute("style",cs.css)}))}})):va.Hn("Control variants leave the page unmodified.")}_is_bot(){return i&&this._instance?cn(i,this.Bt.custom_blocked_useragents):void 0}}var ca=Ce("[Conversations]"),pa="Conversations not available yet.",fa={featureFlags:class{constructor(es){this.Jn=!1,this.Kn=!1,this.Qn=!1,this.es=!1,this.ts=!1,this.rs=!1,this.ns=!1,this.ss=!1,this._instance=es,this.featureFlagEventHandlers=[]}get Bt(){return this._instance.config}get ni(){return this._instance.persistence}os(es){return this._instance.get_property(es)}ls(){var es,$;return(es=($=this.ni)==null?void 0:$.wr(this.Bt.feature_flag_cache_ttl_ms))!==null&&es!==void 0&&es}us(){return!!this.ls()&&(this.ss||this.Qn||(this.ss=!0,sa.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}hs(){var es,$=(es=this.Bt.evaluation_contexts)!==null&&es!==void 0?es:this.Bt.evaluation_environments;return!this.Bt.evaluation_environments||this.Bt.evaluation_contexts||this.ns||(sa.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ns=!0),$!=null&&$.length?$.filter((ts=>{var is=ts&&typeof ts=="string"&&ts.trim().length>0;return is||sa.error("Invalid evaluation context found:",ts,"Expected non-empty string"),is})):[]}cs(){return this.hs().length>0}initialize(){var es,$,{config:ts}=this._instance,is=(es=($=ts.bootstrap)==null?void 0:$.featureFlags)!==null&&es!==void 0?es:{};if(Object.keys(is).length){var cs,Qr,ja=(cs=(Qr=ts.bootstrap)==null?void 0:Qr.featureFlagPayloads)!==null&&cs!==void 0?cs:{},Na=Object.keys(is).filter((Oa=>!!is[Oa])).reduce(((Oa,Ia)=>(Oa[Ia]=is[Ia]||!1,Oa)),{}),Aa=Object.keys(ja).filter((Oa=>Na[Oa])).reduce(((Oa,Ia)=>(ja[Ia]&&(Oa[Ia]=ja[Ia]),Oa)),{});this.receivedFeatureFlags({featureFlags:Na,featureFlagPayloads:Aa})}}updateFlags(es,$,ts){var is=ts!=null&&ts.merge?this.getFlagVariants():{},cs=ts!=null&&ts.merge?this.getFlagPayloads():{},Qr=f({},is,es),ja=f({},cs,$),Na={};for(var[Aa,Oa]of Object.entries(Qr)){var Ia=typeof Oa=="string";Na[Aa]={key:Aa,enabled:!!Ia||!!Oa,variant:Ia?Oa:void 0,reason:void 0,metadata:C(ja==null?void 0:ja[Aa])?void 0:{id:0,version:void 0,description:void 0,payload:ja[Aa]}}}this.receivedFeatureFlags({flags:Na})}get hasLoadedFlags(){return this.Kn}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var es=this.os(si),$=this.os(ai),ts=this.os(li);if(!ts&&!$)return es||{};var is=qi({},es||{}),cs=[...new Set([...Object.keys(ts||{}),...Object.keys($||{})])];for(var Qr of cs){var ja,Na,Aa=is[Qr],Oa=$==null?void 0:$[Qr],Ia=C(Oa)?(ja=Aa==null?void 0:Aa.enabled)!==null&&ja!==void 0&&ja:!!Oa,La=C(Oa)?Aa.variant:typeof Oa=="string"?Oa:void 0,Ba=ts==null?void 0:ts[Qr],Ma=f({},Aa,{enabled:Ia,variant:Ia?La??(Aa==null?void 0:Aa.variant):void 0});Ia!==(Aa==null?void 0:Aa.enabled)&&(Ma.original_enabled=Aa==null?void 0:Aa.enabled),La!==(Aa==null?void 0:Aa.variant)&&(Ma.original_variant=Aa==null?void 0:Aa.variant),Ba&&(Ma.metadata=f({},Aa==null?void 0:Aa.metadata,{payload:Ba,original_payload:Aa==null||(Na=Aa.metadata)==null?void 0:Na.payload})),is[Qr]=Ma}return this.Jn||(sa.warn(" Overriding feature flag details!",{flagDetails:es,overriddenPayloads:ts,finalDetails:is}),this.Jn=!0),is}getFlagVariants(){var es=this.os(ei),$=this.os(ai);if(!$)return es||{};for(var ts=qi({},es),is=Object.keys($),cs=0;is.length>cs;cs++)ts[is[cs]]=$[is[cs]];return this.Jn||(sa.warn(" Overriding feature flags!",{enabledFlags:es,overriddenFlags:$,finalFlags:ts}),this.Jn=!0),ts}getFlagPayloads(){var es=this.os(ni),$=this.os(li);if(!$)return es||{};for(var ts=qi({},es||{}),is=Object.keys($),cs=0;is.length>cs;cs++)ts[is[cs]]=$[is[cs]];return this.Jn||(sa.warn(" Overriding feature flag payloads!",{flagPayloads:es,overriddenPayloads:$,finalPayloads:ts}),this.Jn=!0),ts}reloadFeatureFlags(){this.es||this.Bt.advanced_disable_feature_flags||this.ds||(this._instance.Fi.emit("featureFlagsReloading",!0),this.ds=setTimeout((()=>{this.vs()}),5))}fs(){clearTimeout(this.ds),this.ds=void 0}ensureFlagsLoaded(){this.Kn||this.Qn||this.ds||this.reloadFeatureFlags()}setAnonymousDistinctId(es){this.$anon_distinct_id=es}setReloadingPaused(es){this.es=es}vs(es){var $;if(this.fs(),!this._instance.Fr())if(this.Qn)this.ts=!0;else{var ts=this.Bt.token,is=this.os(De),cs={token:ts,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:f({},(($=this.ni)==null?void 0:$.get_initial_props())||{},this.os(ui)||{}),group_properties:this.os(hi),timezone:Vr()};M(is)||C(is)||(cs.$device_id=is),(es!=null&&es.disableFlags||this.Bt.advanced_disable_feature_flags)&&(cs.disable_flags=!0),this.cs()&&(cs.evaluation_contexts=this.hs());var Qr=this._instance.requestRouter.endpointFor("flags","/flags/?v=2"+(this.Bt.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":""));this.Qn=!0,this._instance._send_request({method:"POST",url:Qr,data:cs,compression:this.Bt.disable_compression?void 0:ps.Base64,timeout:this.Bt.feature_flag_request_timeout_ms,callback:ja=>{var Na,Aa,Oa,Ia=!0;if(ja.statusCode===200&&(this.ts||(this.$anon_distinct_id=void 0),Ia=!1),this.Qn=!1,!cs.disable_flags||this.ts){this.rs=!Ia;var La=[];ja.error?ja.error instanceof Error?La.push(ja.error.name==="AbortError"?"timeout":"connection_error"):La.push("unknown_error"):ja.statusCode!==200&&La.push("api_error_"+ja.statusCode),(Na=ja.json)!=null&&Na.errorsWhileComputingFlags&&La.push("errors_while_computing_flags");var Ba,Ma=!((Aa=ja.json)==null||(Aa=Aa.quotaLimited)==null||!Aa.includes("feature_flags"));Ma&&La.push("quota_limited"),(Oa=this.ni)==null||Oa.register({[_i]:La}),Ma?sa.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."):(cs.disable_flags||this.receivedFeatureFlags((Ba=ja.json)!==null&&Ba!==void 0?Ba:{},Ia,{partialResponse:!!this.Bt.advanced_only_evaluate_survey_feature_flags}),this.ts&&(this.ts=!1,this.vs()))}}})}}getFeatureFlag(es,$){var ts;if($===void 0&&($={}),!$.fresh||this.rs)if(this.Kn||this.getFlags()&&this.getFlags().length>0){if(!this.us()){var is=this.getFeatureFlagResult(es,$);return(ts=is==null?void 0:is.variant)!==null&&ts!==void 0?ts:is==null?void 0:is.enabled}}else sa.warn('getFeatureFlag for key "'+es+oa)}getFeatureFlagDetails(es){return this.getFlagsWithDetails()[es]}getFeatureFlagPayload(es){var $=this.getFeatureFlagResult(es,{send_event:!1});return $==null?void 0:$.payload}getFeatureFlagResult(es,$){if($===void 0&&($={}),!$.fresh||this.rs)if(this.Kn||this.getFlags()&&this.getFlags().length>0){if(!this.us()){var ts=this.getFlagVariants(),is=es in ts,cs=ts[es],Qr=this.getFlagPayloads()[es],ja=String(cs),Na=this.os(oi)||void 0,Aa=this.os(gi)||void 0,Oa=this.os(pi)||{};if(this.Bt.advanced_feature_flags_dedup_per_session){var Ia,La=this._instance.get_session_id(),Ba=this.os(fi);La&&La!==Ba&&(Oa={},(Ia=this.ni)==null||Ia.register({[pi]:Oa,[fi]:La}))}if(($.send_event||!("send_event"in $))&&(!(es in Oa)||!Oa[es].includes(ja))){var Ma,qa,Fa,Ha,Ka,Ga,Va,Ja,Ya,el;R(Oa[es])?Oa[es].push(ja):Oa[es]=[ja],(Ma=this.ni)==null||Ma.register({[pi]:Oa});var tl=this.getFeatureFlagDetails(es),rl=[...(qa=this.os(_i))!==null&&qa!==void 0?qa:[]];C(cs)&&rl.push("flag_missing");var cl={$feature_flag:es,$feature_flag_response:cs,$feature_flag_payload:Qr||null,$feature_flag_request_id:Na,$feature_flag_evaluated_at:Aa,$feature_flag_bootstrapped_response:((Fa=this.Bt.bootstrap)==null||(Fa=Fa.featureFlags)==null?void 0:Fa[es])||null,$feature_flag_bootstrapped_payload:((Ha=this.Bt.bootstrap)==null||(Ha=Ha.featureFlagPayloads)==null?void 0:Ha[es])||null,$used_bootstrap_value:!this.rs};C(tl==null||(Ka=tl.metadata)==null?void 0:Ka.version)||(cl.$feature_flag_version=tl.metadata.version);var dl,fl=(Ga=tl==null||(Va=tl.reason)==null?void 0:Va.description)!==null&&Ga!==void 0?Ga:tl==null||(Ja=tl.reason)==null?void 0:Ja.code;fl&&(cl.$feature_flag_reason=fl),tl!=null&&(Ya=tl.metadata)!=null&&Ya.id&&(cl.$feature_flag_id=tl.metadata.id),C(tl==null?void 0:tl.original_variant)&&C(tl==null?void 0:tl.original_enabled)||(cl.$feature_flag_original_response=C(tl.original_variant)?tl.original_enabled:tl.original_variant),tl!=null&&(el=tl.metadata)!=null&&el.original_payload&&(cl.$feature_flag_original_payload=tl==null||(dl=tl.metadata)==null?void 0:dl.original_payload),rl.length&&(cl.$feature_flag_error=rl.join(",")),this._instance.capture("$feature_flag_called",cl)}if(is){var nl=Qr;if(!C(Qr))try{nl=JSON.parse(Qr)}catch{}return{key:es,enabled:!!cs,variant:typeof cs=="string"?cs:void 0,payload:nl}}}}else sa.warn('getFeatureFlagResult for key "'+es+oa)}getRemoteConfigPayload(es,$){var ts=this.Bt.token,is={distinct_id:this._instance.get_distinct_id(),token:ts};this.cs()&&(is.evaluation_contexts=this.hs()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2"),data:is,compression:this.Bt.disable_compression?void 0:ps.Base64,timeout:this.Bt.feature_flag_request_timeout_ms,callback(cs){var Qr,ja=(Qr=cs.json)==null?void 0:Qr.featureFlagPayloads;$((ja==null?void 0:ja[es])||void 0)}})}isFeatureEnabled(es,$){if($===void 0&&($={}),!$.fresh||this.rs){if(this.Kn||this.getFlags()&&this.getFlags().length>0){var ts=this.getFeatureFlag(es,$);return C(ts)?void 0:!!ts}sa.warn('isFeatureEnabled for key "'+es+oa)}}addFeatureFlagsHandler(es){this.featureFlagEventHandlers.push(es)}removeFeatureFlagsHandler(es){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(($=>$!==es))}receivedFeatureFlags(es,$,ts){if(this.ni){this.Kn=!0;var is=this.getFlagVariants(),cs=this.getFlagPayloads(),Qr=this.getFlagsWithDetails();(function(ja,Na,Aa,Oa,Ia,La){Aa===void 0&&(Aa={}),Oa===void 0&&(Oa={}),Ia===void 0&&(Ia={});var Ba=(rl=>{var cl=rl.flags;return cl?(rl.featureFlags=Object.fromEntries(Object.keys(cl).map((dl=>{var fl;return[dl,(fl=cl[dl].variant)!==null&&fl!==void 0?fl:cl[dl].enabled]}))),rl.featureFlagPayloads=Object.fromEntries(Object.keys(cl).filter((dl=>cl[dl].enabled)).filter((dl=>{var fl;return(fl=cl[dl].metadata)==null?void 0:fl.payload})).map((dl=>{var fl;return[dl,(fl=cl[dl].metadata)==null?void 0:fl.payload]})))):sa.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),rl})(ja),Ma=Ba.flags,qa=Ba.featureFlags,Fa=Ba.featureFlagPayloads;if(qa){var Ha=ja.requestId,Ka=ja.evaluatedAt;if(R(qa)){sa.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var Ga={};if(qa)for(var Va=0;qa.length>Va;Va++)Ga[qa[Va]]=!0;Na&&Na.register({[ii]:qa,[ei]:Ga})}else{var Ja=qa,Ya=Fa,el=Ma;if(La!=null&&La.partialResponse)Ja=f({},Aa,Ja),Ya=f({},Oa,Ya),el=f({},Ia,el);else if(ja.errorsWhileComputingFlags)if(Ma){var tl=new Set(Object.keys(Ma).filter((rl=>{var cl;return!((cl=Ma[rl])!=null&&cl.failed)})));Ja=f({},Aa,Object.fromEntries(Object.entries(Ja).filter((rl=>{var[cl]=rl;return tl.has(cl)})))),Ya=f({},Oa,Object.fromEntries(Object.entries(Ya||{}).filter((rl=>{var[cl]=rl;return tl.has(cl)})))),el=f({},Ia,Object.fromEntries(Object.entries(el||{}).filter((rl=>{var[cl]=rl;return tl.has(cl)}))))}else Ja=f({},Aa,Ja),Ya=f({},Oa,Ya),el=f({},Ia,el);Na&&Na.register(f({[ii]:Object.keys(la(Ja)),[ei]:Ja||{},[ni]:Ya||{},[si]:el||{}},Ha?{[oi]:Ha}:{},Ka?{[gi]:Ka}:{}))}}})(es,this.ni,is,cs,Qr,ts),$||(this.ss=!1),this.ps($)}}override(es,$){$===void 0&&($=!1),sa.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:es,suppressWarning:$})}overrideFeatureFlags(es){if(!this._instance.__loaded||!this.ni)return sa.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(es===!1)return this.ni.unregister(ai),this.ni.unregister(li),this.ps(),na.info("All overrides cleared");if(R(es)){var $=aa(es);return this.ni.register({[ai]:$}),this.ps(),na.info("Flag overrides set",{flags:es})}if(es&&typeof es=="object"&&("flags"in es||"payloads"in es)){var ts,is=es;if(this.Jn=!!((ts=is.suppressWarning)!==null&&ts!==void 0&&ts),"flags"in is){if(is.flags===!1)this.ni.unregister(ai),na.info("Flag overrides cleared");else if(is.flags){if(R(is.flags)){var cs=aa(is.flags);this.ni.register({[ai]:cs})}else this.ni.register({[ai]:is.flags});na.info("Flag overrides set",{flags:is.flags})}}return"payloads"in is&&(is.payloads===!1?(this.ni.unregister(li),na.info("Payload overrides cleared")):is.payloads&&(this.ni.register({[li]:is.payloads}),na.info("Payload overrides set",{payloads:is.payloads}))),void this.ps()}if(es&&typeof es=="object")return this.ni.register({[ai]:es}),this.ps(),na.info("Flag overrides set",{flags:es});sa.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:es})}onFeatureFlags(es){if(this.addFeatureFlagsHandler(es),this.Kn){var{flags:$,flagVariants:ts}=this.gs();es($,ts)}return()=>this.removeFeatureFlagsHandler(es)}updateEarlyAccessFeatureEnrollment(es,$,ts){var is,cs=(this.os(ri)||[]).find((Aa=>Aa.flagKey===es)),Qr={["$feature_enrollment/"+es]:$},ja={$feature_flag:es,$feature_enrollment:$,$set:Qr};cs&&(ja.$early_access_feature_name=cs.name),ts&&(ja.$feature_enrollment_stage=ts),this._instance.capture("$feature_enrollment_update",ja),this.setPersonPropertiesForFlags(Qr,!1);var Na=f({},this.getFlagVariants(),{[es]:$});(is=this.ni)==null||is.register({[ii]:Object.keys(la(Na)),[ei]:Na}),this.ps()}getEarlyAccessFeatures(es,$,ts){$===void 0&&($=!1);var is=this.os(ri),cs=ts?"&"+ts.map((Qr=>"stage="+Qr)).join("&"):"";if(is&&!$)return es(is);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this.Bt.token+cs),method:"GET",callback:Qr=>{var ja,Na;if(Qr.json){var Aa=Qr.json.earlyAccessFeatures;return(ja=this.ni)==null||ja.unregister(ri),(Na=this.ni)==null||Na.register({[ri]:Aa}),es(Aa)}}})}gs(){var es=this.getFlags(),$=this.getFlagVariants();return{flags:es.filter((ts=>$[ts])),flagVariants:Object.keys($).filter((ts=>$[ts])).reduce(((ts,is)=>(ts[is]=$[is],ts)),{})}}ps(es){var{flags:$,flagVariants:ts}=this.gs();this.featureFlagEventHandlers.forEach((is=>is($,ts,{errorsLoading:es})))}setPersonPropertiesForFlags(es,$){$===void 0&&($=!0);var ts=this.os(ui)||{},is=(es==null?void 0:es.$set)||(es!=null&&es.$set_once?{}:es),cs=es==null?void 0:es.$set_once,Qr={};if(cs)for(var ja in cs)({}).hasOwnProperty.call(cs,ja)&&(ja in ts||(Qr[ja]=cs[ja]));this._instance.register({[ui]:f({},ts,Qr,is)}),$&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(ui)}setGroupPropertiesForFlags(es,$){$===void 0&&($=!0);var ts=this.os(hi)||{};Object.keys(ts).length!==0&&Object.keys(ts).forEach((is=>{ts[is]=f({},ts[is],es[is]),delete es[is]})),this._instance.register({[hi]:f({},ts,es)}),$&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(es){if(es){var $=this.os(hi)||{};this._instance.register({[hi]:f({},$,{[es]:{}})})}else this._instance.unregister(hi)}reset(){this.Kn=!1,this.Qn=!1,this.es=!1,this.ts=!1,this.rs=!1,this.$anon_distinct_id=void 0,this.fs(),this.Jn=!1}}},_a={sessionRecording:class{get Bt(){return this._instance.config}get ni(){return this._instance.persistence}get started(){var es;return!((es=this.ys)==null||!es.isStarted)}get status(){var es,$;return this.bs===No||this.bs===jo?this.bs:(es=($=this.ys)==null?void 0:$.status)!==null&&es!==void 0?es:this.bs}constructor(es){if(this._forceAllowLocalhostNetworkCapture=!1,this.bs=Lo,this._s=void 0,this._instance=es,!this._instance.sessionManager)throw Bo.error("started without valid sessionManager"),new Error(zo+" started without valid sessionManager. This is a bug.");if(this.Bt.cookieless_mode===Ci)throw new Error(zo+' cannot be used with cookieless_mode="always"')}initialize(){this.startIfEnabledOrStop()}get ws(){var es,$=!((es=this._instance.get_property(Ye))==null||!es.enabled),ts=!this.Bt.disable_session_recording,is=this.Bt.disable_session_recording||this._instance.consent.isOptedOut();return t&&$&&ts&&!is}startIfEnabledOrStop(es){var $;if(!this.ws||($=this.ys)==null||!$.isStarted){var ts=!C(Object.assign)&&!C(Array.from);this.ws&&ts?(this.Is(es),Bo.info("starting")):(this.bs=Lo,this.stopRecording())}}Is(es){var $,ts,is;this.ws&&(this.bs!==No&&this.bs!==jo&&(this.bs=Uo),h!=null&&($=h.__PosthogExtensions__)!=null&&($=$.rrweb)!=null&&$.record&&(ts=h.__PosthogExtensions__)!=null&&ts.initSessionRecording?this.Cs(es):(is=h.__PosthogExtensions__)==null||is.loadExternalDependency==null||is.loadExternalDependency(this._instance,this.Ss,(cs=>{if(cs)return Bo.error("could not load recorder",cs);this.Cs(es)})))}stopRecording(){var es,$;(es=this._s)==null||es.call(this),this._s=void 0,($=this.ys)==null||$.stop()}xs(){var es,$;(es=this._s)==null||es.call(this),this._s=void 0,($=this.ys)==null||$.discard()}ks(){var es;(es=this.ni)==null||es.unregister(ti)}Ts(es,$){if(D(es))return null;var ts,is=L(es)?es:parseFloat(es);return typeof(ts=is)!="number"||!Number.isFinite(ts)||0>ts||ts>1?(Bo.warn($+" must be between 0 and 1. Ignoring invalid value:",es),null):is}As(es){if(this.ni){var $,ts,is=this.ni,cs=()=>{var Qr,ja=es.sessionRecording===!1?void 0:es.sessionRecording,Na=this.Ts((Qr=this.Bt.session_recording)==null?void 0:Qr.sampleRate,"session_recording.sampleRate"),Aa=this.Ts(ja==null?void 0:ja.sampleRate,"remote config sampleRate"),Oa=Na??Aa;D(Oa)&&this.ks();var Ia=ja==null?void 0:ja.minimumDurationMilliseconds;is.register({[Ye]:f({cache_timestamp:Date.now(),enabled:!!ja},ja,{networkPayloadCapture:f({capturePerformance:es.capturePerformance},ja==null?void 0:ja.networkPayloadCapture),canvasRecording:{enabled:ja==null?void 0:ja.recordCanvas,fps:ja==null?void 0:ja.canvasFps,quality:ja==null?void 0:ja.canvasQuality},sampleRate:Oa,minimumDurationMilliseconds:C(Ia)?null:Ia,endpoint:ja==null?void 0:ja.endpoint,triggerMatchType:ja==null?void 0:ja.triggerMatchType,masking:ja==null?void 0:ja.masking,urlTriggers:ja==null?void 0:ja.urlTriggers,version:ja==null?void 0:ja.version,triggerGroups:ja==null?void 0:ja.triggerGroups})})};cs(),($=this._s)==null||$.call(this),this._s=(ts=this._instance.sessionManager)==null?void 0:ts.onSessionId(cs)}}onRemoteConfig(es){return"sessionRecording"in es?es.sessionRecording===!1?(this.As(es),void this.xs()):(this.As(es),void this.startIfEnabledOrStop()):(this.bs===No&&(this.bs=jo,Bo.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(es,$){var ts;$===void 0&&($="log"),(ts=this.ys)!=null&&ts.log?this.ys.log(es,$):Bo.warn("log called before recorder was ready")}get Ss(){var es,$,ts=(es=this._instance)==null||(es=es.persistence)==null?void 0:es.get_property(Ye);return(ts==null||($=ts.scriptConfig)==null?void 0:$.script)||"lazy-recorder"}Es(){var es,$=this._instance.get_property(Ye);if(!$)return!1;var ts=(es=(typeof $=="object"?$:JSON.parse($)).cache_timestamp)!==null&&es!==void 0?es:Date.now();return 36e5>=Date.now()-ts}Cs(es){var $,ts;if(($=h.__PosthogExtensions__)==null||!$.initSessionRecording)return Bo.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Pi]:!0});if(this.ys||(this.ys=(ts=h.__PosthogExtensions__)==null?void 0:ts.initSessionRecording(this._instance),this.ys._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.Es())return this.bs===jo||this.bs===No?void 0:(this.bs=No,Bo.info("persisted remote config is stale, requesting fresh config before starting"),void new vs(this._instance).load());this.bs=Uo,this.ys.start(es)}onRRwebEmit(es){var $;($=this.ys)==null||$.onRRwebEmit==null||$.onRRwebEmit(es)}overrideLinkedFlag(){var es,$;this.ys||($=this.ni)==null||$.register({[Ke]:!0}),(es=this.ys)==null||es.overrideLinkedFlag()}overrideSampling(){var es,$;this.ys||($=this.ni)==null||$.register({[Je]:!0}),(es=this.ys)==null||es.overrideSampling()}overrideTrigger(es){var $,ts;this.ys||(ts=this.ni)==null||ts.register({[es==="url"?Xe:Qe]:!0}),($=this.ys)==null||$.overrideTrigger(es)}get sdkDebugProperties(){var es;return((es=this.ys)==null?void 0:es.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(es,$){var ts;return!((ts=this.ys)==null||!ts.tryAddCustomEvent(es,$))}}},ga={autocapture:class{constructor(es){this.Rs=!1,this.Ns=null,this.Ms=!1,this.instance=es,this.rageclicks=new To(es.config.rageclick),this.Fs=null}initialize(){this.startIfEnabled()}get Bt(){var es,$,ts=O(this.instance.config.autocapture)?this.instance.config.autocapture:{};return ts.url_allowlist=(es=ts.url_allowlist)==null?void 0:es.map((is=>new RegExp(is))),ts.url_ignorelist=($=ts.url_ignorelist)==null?void 0:$.map((is=>new RegExp(is))),ts}Os(){if(this.isBrowserSupported()){if(t&&r){var es=ts=>{ts=ts||(t==null?void 0:t.event);try{this.Ps(ts)}catch(is){Ro.error("Failed to capture event",is)}};if(Xi(r,"submit",es,{capture:!0}),Xi(r,"change",es,{capture:!0}),Xi(r,"click",es,{capture:!0}),this.Bt.capture_copied_text){var $=ts=>{ts=ts||(t==null?void 0:t.event);try{this.Ps(ts,ko)}catch(is){Ro.error("Failed to capture copy/cut event",is)}};Xi(r,"copy",$,{capture:!0}),Xi(r,"cut",$,{capture:!0})}}}else Ro.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.Rs&&(this.Os(),this.Rs=!0)}onRemoteConfig(es){es.elementsChainAsString&&(this.Ms=es.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Ne]:!!es.autocapture_opt_out}),this.Ns=!!es.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(es){this.Fs=es}getElementSelectors(es){var $,ts=[];return($=this.Fs)==null||$.forEach((is=>{var cs=r==null?void 0:r.querySelectorAll(is);cs==null||cs.forEach((Qr=>{es===Qr&&ts.push(is)}))})),ts}get isEnabled(){var es,$,ts=(es=this.instance.persistence)==null?void 0:es.props[Ne];if(M(this.Ns)&&!N(ts)&&!this.instance.Fr())return!1;var is=($=this.Ns)!==null&&$!==void 0?$:!!ts;return!!this.instance.config.autocapture&&!is}Ps(es,$){if($===void 0&&($="$autocapture"),this.isEnabled){var ts,is=so(es);Xn(is)&&(is=is.parentNode||null),$==="$autocapture"&&es.type==="click"&&es instanceof MouseEvent&&this.instance.config.rageclick&&(ts=this.rageclicks)!=null&&ts.isRageClick(es.clientX,es.clientY,es.timeStamp||new Date().getTime())&&(function(La,Ba){if(!t||ho(La))return!1;var Ma,qa,Fa;if(N(Ba)?(Ma=!!Ba&&uo,qa=void 0):(Ma=(Fa=Ba==null?void 0:Ba.css_selector_ignorelist)!==null&&Fa!==void 0?Fa:uo,qa=Ba==null?void 0:Ba.content_ignorelist),Ma===!1)return!1;var{targetElementList:Ha}=vo(La,!1);return!(function(Ka,Ga){if(Ka===!1||C(Ka))return!1;var Va;if(Ka===!0)Va=lo;else{if(!R(Ka))return!1;if(Ka.length>10)return Ie.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;Va=Ka.map((Ja=>Ja.toLowerCase()))}return Ga.some((Ja=>{var{safeText:Ya,ariaLabel:el}=Ja;return Va.some((tl=>Ya.includes(tl)||el.includes(tl)))}))})(qa,Ha.map((Ka=>{var Ga;return{safeText:ro(Ka).toLowerCase(),ariaLabel:((Ga=Ka.getAttribute("aria-label"))==null?void 0:Ga.toLowerCase().trim())||""}})))&&!oo(Ha,Ma)})(is,this.instance.config.rageclick)&&this.Ps(es,"$rageclick");var cs=$===ko;if(is&&(function(La,Ba,Ma,qa,Fa){var Ha,Ka,Ga,Va;if(Ma===void 0&&(Ma=void 0),!t||ho(La)||(Ha=Ma)!=null&&Ha.url_allowlist&&!to(Ma.url_allowlist)||(Ka=Ma)!=null&&Ka.url_ignorelist&&to(Ma.url_ignorelist))return!1;if((Ga=Ma)!=null&&Ga.dom_event_allowlist){var Ja=Ma.dom_event_allowlist;if(Ja&&!Ja.some((cl=>Ba.type===cl)))return!1}var{parentIsUsefulElement:Ya,targetElementList:el}=vo(La,qa);if(!(function(cl,dl){var fl=dl==null?void 0:dl.element_allowlist;if(C(fl))return!0;var nl,ol=function(Tl){if(fl.some((ul=>Tl.tagName.toLowerCase()===ul)))return{v:!0}};for(var pl of cl)if(nl=ol(pl))return nl.v;return!1})(el,Ma)||!oo(el,(Va=Ma)==null?void 0:Va.css_selector_allowlist))return!1;var tl=t.getComputedStyle(La);if(tl&&tl.getPropertyValue("cursor")==="pointer"&&Ba.type==="click")return!0;var rl=La.tagName.toLowerCase();switch(rl){case"html":return!1;case"form":return(Fa||["submit"]).indexOf(Ba.type)>=0;case"input":case"select":case"textarea":return(Fa||["change","click"]).indexOf(Ba.type)>=0;default:return Ya?(Fa||["click"]).indexOf(Ba.type)>=0:(Fa||["click"]).indexOf(Ba.type)>=0&&(no.indexOf(rl)>-1||La.getAttribute("contenteditable")==="true")}})(is,es,this.Bt,cs,cs?["copy","cut"]:void 0)){var{props:Qr,explicitNoCapture:ja}=Io(is,{e:es,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Bt.element_attribute_ignorelist,elementsChainAsString:this.Ms});if(ja)return!1;var Na=this.getElementSelectors(is);if(Na&&Na.length>0&&(Qr.$element_selectors=Na),$===ko){var Aa,Oa=io(t==null||(Aa=t.getSelection())==null?void 0:Aa.toString()),Ia=es.type||"clipboard";if(!Oa)return!1;Qr.$selected_content=Oa,Qr.$copy_type=Ia}return this.instance.capture($,Qr),!0}}}isBrowserSupported(){return P(r==null?void 0:r.querySelectorAll)}},historyAutocapture:class{constructor(es){var $;this._instance=es,this.Ls=(t==null||($=t.location)==null?void 0:$.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(Ie.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.Ds&&this.Ds(),this.Ds=void 0,Ie.info("History API monitoring stopped")}monitorHistoryChanges(){var es,$;if(t&&t.history){var ts=this;(es=t.history.pushState)!=null&&es.__posthog_wrapped__||Fo(t.history,"pushState",(is=>function(cs,Qr,ja){is.call(this,cs,Qr,ja),ts.Bs("pushState")})),($=t.history.replaceState)!=null&&$.__posthog_wrapped__||Fo(t.history,"replaceState",(is=>function(cs,Qr,ja){is.call(this,cs,Qr,ja),ts.Bs("replaceState")})),this.js()}}Bs(es){try{var $,ts=t==null||($=t.location)==null?void 0:$.pathname;if(!ts)return;ts!==this.Ls&&this.isEnabled&&this._instance.capture(Ui,{navigation_type:es}),this.Ls=ts}catch(is){Ie.error("Error capturing "+es+" pageview",is)}}js(){if(!this.Ds){var es=()=>{this.Bs("popstate")};Xi(t,"popstate",es),this.Ds=()=>{t&&t.removeEventListener("popstate",es)}}}},heatmaps:class{get Bt(){return this.instance.config}constructor(es){var $;this.$s=!1,this.Rs=!1,this.qs=null,this.instance=es,this.$s=!(($=this.instance.persistence)==null||!$.props[je]),this.rageclicks=new To(es.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var es=5e3;return O(this.Bt.capture_heatmaps)&&this.Bt.capture_heatmaps.flush_interval_milliseconds&&(es=this.Bt.capture_heatmaps.flush_interval_milliseconds),es}get isEnabled(){return D(this.Bt.capture_heatmaps)?D(this.Bt.enable_heatmaps)?this.$s:this.Bt.enable_heatmaps:this.Bt.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.Rs)return;Ho.info("starting..."),this.Zs(),this.Ft()}else{var es;clearInterval((es=this.qs)!==null&&es!==void 0?es:void 0),this.Vs(),this.getAndClearBuffer()}}onRemoteConfig(es){if("heatmaps"in es){var $=!!es.heatmaps;this.instance.persistence&&this.instance.persistence.register({[je]:$}),this.$s=$,this.startIfEnabled()}}getAndClearBuffer(){var es=this.T;return this.T=void 0,es}Hs(es){this.Tt(es.originalEvent,"deadclick")}Ft(){this.qs&&clearInterval(this.qs),this.qs=(r==null?void 0:r.visibilityState)==="visible"?setInterval(this.Yr.bind(this),this.flushIntervalMilliseconds):null}Zs(){t&&r&&(this.zs=this.Yr.bind(this),Xi(t,Li,this.zs),this.Us=es=>this.Tt(es||(t==null?void 0:t.event)),Xi(r,"click",this.Us,{capture:!0}),this.Ys=es=>this.Gs(es||(t==null?void 0:t.event)),Xi(r,"mousemove",this.Ys,{capture:!0}),this.Ws=new yr(this.instance,mr,this.Hs.bind(this)),this.Ws.startIfEnabledOrStop(),this.Xs=this.Ft.bind(this),Xi(r,Di,this.Xs),this.Rs=!0)}Vs(){var es;t&&r&&(this.zs&&t.removeEventListener(Li,this.zs),this.Us&&r.removeEventListener("click",this.Us,{capture:!0}),this.Ys&&r.removeEventListener("mousemove",this.Ys,{capture:!0}),this.Xs&&r.removeEventListener(Di,this.Xs),clearTimeout(this.Js),(es=this.Ws)==null||es.stop(),this.Rs=!1)}Ks(es,$){var ts=this.instance.scrollManager.scrollY(),is=this.instance.scrollManager.scrollX(),cs=this.instance.scrollManager.scrollElement(),Qr=(function(ja,Na,Aa){for(var Oa=ja;Oa&&Jn(Oa)&&!Kn(Oa,"body");){if(Oa===Aa)return!1;if(w(Na,t==null?void 0:t.getComputedStyle(Oa).position))return!0;Oa=ao(Oa)}return!1})(so(es),["fixed","sticky"],cs);return{x:es.clientX+(Qr?0:is),y:es.clientY+(Qr?0:ts),target_fixed:Qr,type:$}}Tt(es,$){var ts;if($===void 0&&($="click"),!Yn(es.target)&&qo(es)){var is=this.Ks(es,$);(ts=this.rageclicks)!=null&&ts.isRageClick(es.clientX,es.clientY,new Date().getTime())&&this.Qs(f({},is,{type:"rageclick"})),this.Qs(is)}}Gs(es){!Yn(es.target)&&qo(es)&&(clearTimeout(this.Js),this.Js=setTimeout((()=>{this.Qs(this.Ks(es,"mousemove"))}),500))}Qs(es){if(t){var $=t.location.href,ts=this.Bt.custom_personal_data_properties,is=this.Bt.mask_personal_data_properties?[...Fr,...ts||[]]:[],cs=Or($,is,Mr);this.T=this.T||{},this.T[cs]||(this.T[cs]=[]),this.T[cs].push(es)}}Yr(){this.T&&!I(this.T)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:yr,webVitalsAutocapture:class{constructor(es){var $;this.$s=!1,this.Rs=!1,this.T={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.eo=()=>{clearTimeout(this.ro),this.T.metrics.length!==0&&(this._instance.capture("$web_vitals",this.T.metrics.reduce(((ts,is)=>f({},ts,{["$web_vitals_"+is.name+"_event"]:f({},is),["$web_vitals_"+is.name+"_value"]:is.value})),{})),this.T={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.ht=ts=>{var is,cs=(is=this._instance.sessionManager)==null?void 0:is.checkAndGetSessionAndWindowId(!0);if(C(cs))Mo.error("Could not read session ID. Dropping metrics!");else{this.T=this.T||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var Qr=this.io();C(Qr)||(D(ts==null?void 0:ts.name)||D(ts==null?void 0:ts.value)?Mo.error("Invalid metric received",ts):!this.no||this.no>ts.value?(this.T.url!==Qr&&(this.eo(),this.ro=setTimeout(this.eo,this.flushToCaptureTimeoutMs)),C(this.T.url)&&(this.T.url=Qr),this.T.firstMetricTimestamp=C(this.T.firstMetricTimestamp)?Date.now():this.T.firstMetricTimestamp,ts.attribution&&ts.attribution.interactionTargetElement&&(ts.attribution.interactionTargetElement=void 0),this.T.metrics.push(f({},ts,{$current_url:Qr,$session_id:cs.sessionId,$window_id:cs.windowId,timestamp:Date.now()})),this.T.metrics.length===this.allowedMetrics.length&&this.eo()):Mo.error("Ignoring metric with value >= "+this.no,ts))}},this.so=()=>{if(!this.Rs){var ts,is,cs,Qr,ja=h.__PosthogExtensions__;C(ja)||C(ja.postHogWebVitalsCallbacks)||({onLCP:ts,onCLS:is,onFCP:cs,onINP:Qr}=ja.postHogWebVitalsCallbacks),ts&&is&&cs&&Qr?(this.allowedMetrics.indexOf("LCP")>-1&&ts(this.ht.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&is(this.ht.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&cs(this.ht.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&Qr(this.ht.bind(this)),this.Rs=!0):Mo.error("web vitals callbacks not loaded - not starting")}},this._instance=es,this.$s=!(($=this._instance.persistence)==null||!$.props[qe]),this.startIfEnabled()}get oo(){return this._instance.config.capture_performance}get allowedMetrics(){var es,$,ts=O(this.oo)?(es=this.oo)==null?void 0:es.web_vitals_allowed_metrics:void 0;return D(ts)?(($=this._instance.persistence)==null?void 0:$.props[Ge])||["CLS","FCP","INP","LCP"]:ts}get flushToCaptureTimeoutMs(){return(O(this.oo)?this.oo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var es=O(this.oo)?this.oo.web_vitals_attribution:void 0;return es!=null&&es}get no(){var es=O(this.oo)&&L(this.oo.__web_vitals_max_value)?this.oo.__web_vitals_max_value:Do;return es>0&&6e4>=es?Do:es}get isEnabled(){var es=s==null?void 0:s.protocol;if(es!=="http:"&&es!=="https:")return Mo.info("Web Vitals are disabled on non-http/https protocols"),!1;var $=O(this.oo)?this.oo.web_vitals:N(this.oo)?this.oo:void 0;return N($)?$:this.$s}startIfEnabled(){this.isEnabled&&!this.Rs&&(Mo.info("enabled, starting..."),this.ur(this.so))}onRemoteConfig(es){if("capturePerformance"in es){var $=O(es.capturePerformance)&&!!es.capturePerformance.web_vitals,ts=O(es.capturePerformance)?es.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[qe]:$}),this._instance.persistence.register({[Ge]:ts})),this.$s=$,this.startIfEnabled()}}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.postHogWebVitalsCallbacks?es():(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,this.useAttribution?"web-vitals-with-attribution":"web-vitals",(is=>{is?Mo.error("failed to load script",is):es()}))}io(){var es=t?t.location.href:void 0;if(es){var $=this._instance.config.custom_personal_data_properties,ts=this._instance.config.mask_personal_data_properties?[...Fr,...$||[]]:[];return Or(es,ts,Mr)}Mo.error("Could not determine current URL")}}},ma={exceptionObserver:class{constructor(es){var $,ts,is;this.so=()=>{var cs;if(t&&this.isEnabled&&(cs=h.__PosthogExtensions__)!=null&&cs.errorWrappingFunctions){var Qr=h.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,ja=h.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,Na=h.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.ao&&this.Bt.capture_unhandled_errors&&(this.ao=Qr(this.captureException.bind(this))),!this.lo&&this.Bt.capture_unhandled_rejections&&(this.lo=ja(this.captureException.bind(this))),!this.uo&&this.Bt.capture_console_errors&&(this.uo=Na(this.captureException.bind(this)))}catch(Aa){Co.error("failed to start",Aa),this.ho()}}},this._instance=es,this.co=!(($=this._instance.persistence)==null||!$.props[ze]),this.do=new J({refillRate:(ts=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&ts!==void 0?ts:1,bucketSize:(is=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&is!==void 0?is:10,refillInterval:1e4,Gt:Co}),this.Bt=this.vo(),this.startIfEnabledOrStop()}vo(){var es=this._instance.config.capture_exceptions,$={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return O(es)?$=f({},$,es):(C(es)?this.co:es)&&($=f({},$,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),$}get isEnabled(){return this.Bt.capture_console_errors||this.Bt.capture_unhandled_errors||this.Bt.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Co.info("enabled"),this.ho(),this.ur(this.so)):this.ho()}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.errorWrappingFunctions&&es(),(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,"exception-autocapture",(is=>{if(is)return Co.error("failed to load script",is);es()}))}ho(){var es,$,ts;(es=this.ao)==null||es.call(this),this.ao=void 0,($=this.lo)==null||$.call(this),this.lo=void 0,(ts=this.uo)==null||ts.call(this),this.uo=void 0}onRemoteConfig(es){"autocaptureExceptions"in es&&(this.co=!!es.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ze]:this.co}),this.Bt=this.vo(),this.startIfEnabledOrStop())}onConfigChange(){this.Bt=this.vo()}captureException(es){var $,ts,is,cs=($=es==null||(ts=es.$exception_list)==null||(ts=ts[0])==null?void 0:ts.type)!==null&&$!==void 0?$:"Exception";this.do.consumeRateLimit(cs)?Co.info("Skipping exception capture because of client rate limiting.",{exception:cs}):(is=this._instance.exceptions)==null||is.sendExceptionEvent(es)}},exceptions:class{constructor(es){var $,ts;this.fo=[],this.po=new te([new ve,new xe,new pe,new ce,new ye,new be,new _e,new we],(function(is){for(var cs=arguments.length,Qr=new Array(cs>1?cs-1:0),ja=1;cs>ja;ja++)Qr[ja-1]=arguments[ja];return function(Na,Aa){Aa===void 0&&(Aa=0);for(var Oa=[],Ia=Na.split(`
|
|
120
|
+
`),La=Aa;Ia.length>La;La++){var Ba=Ia[La];if(1024>=Ba.length){var Ma=de.test(Ba)?Ba.replace(de,"$1"):Ba;if(!Ma.match(/\S*Error: /)){for(var qa of Qr){var Fa=qa(Ma,is);if(Fa){Oa.push(Fa);break}}if(Oa.length>=50)break}}}return(function(Ha){if(!Ha.length)return[];var Ka=Array.from(Ha);return Ka.reverse(),Ka.slice(0,50).map((Ga=>{return f({},Ga,{filename:Ga.filename||(Va=Ka,Va[Va.length-1]||{}).filename,function:Ga.function||ee});var Va}))})(Oa)}})("web:javascript",ae,he)),this._instance=es,this.fo=($=(ts=this._instance.persistence)==null?void 0:ts.get_property(Be))!==null&&$!==void 0?$:[],this.mo=ke(this.yo()),this.bo=new Re(this.mo)}onConfigChange(){this.mo=ke(this.yo()),this.bo.setConfig(this.mo)}onRemoteConfig(es){var $,ts,is;if("errorTracking"in es){var cs=($=(ts=es.errorTracking)==null?void 0:ts.suppressionRules)!==null&&$!==void 0?$:[],Qr=(is=es.errorTracking)==null?void 0:is.captureExtensionExceptions;this.fo=cs,this._instance.persistence&&this._instance.persistence.register({[Be]:this.fo,[He]:Qr})}}get _o(){var es,$=!!this._instance.get_property(He),ts=this._instance.config.error_tracking.captureExtensionExceptions;return(es=ts??$)!==null&&es!==void 0&&es}buildProperties(es,$){return this.po.buildFromUnknown(es,{syntheticException:$==null?void 0:$.syntheticException,mechanism:{handled:$==null?void 0:$.handled}})}addExceptionStep(es,$){if(this.mo.enabled)try{if(!F(es)||es.trim().length===0)return void ua.warn("Ignoring exception step because message must be a non-empty string");var ts=this.wo($),{sanitizedProperties:is,droppedKeys:cs}=(function(Qr){if(!Qr)return{sanitizedProperties:{},droppedKeys:[]};var ja=[];return{sanitizedProperties:Object.keys(Qr).reduce(((Na,Aa)=>$e.has(Aa)?(ja.push(Aa),Na):(Na[Aa]=Qr[Aa],Na)),{}),droppedKeys:ja}})(ts);cs.length>0&&ua.warn("Ignoring reserved exception step fields",{droppedKeys:cs}),this.bo.add(f({[Ee]:es,[Se]:new Date().toISOString()},is))}catch(Qr){ua.error("Failed to add exception step. Ignoring breadcrumb.",Qr)}}sendExceptionEvent(es){try{var $=es.$exception_list;if(this.Io($)){if(this.Co($))return this.So("Exception dropped: matched a suppression rule"),void ua.info("Skipping exception capture because a suppression rule matched");if(!this._o&&this.xo($))return this.So("Exception dropped: thrown by a browser extension"),void ua.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ko($))return this.So("Exception dropped: thrown by the PostHog SDK"),void ua.info("Skipping exception capture because it was thrown by the PostHog SDK")}var ts=this.mo.enabled&&D(es.$exception_steps)?this.To(es):es;try{var is=this._instance.capture("$exception",ts,{_noTruncate:!0,_batchKey:"exceptionEvent",en:!0});return is&&this.bo.clear(),is}catch(cs){return ua.error("Failed to capture exception event. Dropping this exception.",cs),void this.bo.clear()}}catch(cs){return void ua.error("Failed to process exception event. Ignoring this exception.",cs)}}To(es){try{var $=this.bo.getAttachable();return $.length===0?es:f({},es,{$exception_steps:$})}catch(ts){return ua.error("Failed to read buffered exception steps. Capturing exception without steps.",ts),es}}So(es){this.mo.enabled&&this.bo.add({[Ee]:es,[Se]:new Date().toISOString()})}wo(es){return O(es)?f({},es):{}}yo(){var es,$;return(es=($=this._instance.config.error_tracking)==null?void 0:$.exception_steps)!==null&&es!==void 0?es:{}}Co(es){if(es.length===0)return!1;var $=es.reduce(((ts,is)=>{var{type:cs,value:Qr}=is;return F(cs)&&cs.length>0&&ts.$exception_types.push(cs),F(Qr)&&Qr.length>0&&ts.$exception_values.push(Qr),ts}),{$exception_types:[],$exception_values:[]});return this.fo.some((ts=>{var is=ts.values.map((cs=>{var Qr,ja=_n[cs.operator],Na=R(cs.value)?cs.value:[cs.value],Aa=(Qr=$[cs.key])!==null&&Qr!==void 0?Qr:[];return Na.length>0&&ja(Na,Aa)}));return ts.type==="OR"?is.some(Boolean):is.every(Boolean)}))}xo(es){return es.flatMap(($=>{var ts,is;return(ts=(is=$.stacktrace)==null?void 0:is.frames)!==null&&ts!==void 0?ts:[]})).some(($=>$.filename&&$.filename.startsWith("chrome-extension://")))}ko(es){if(es.length>0){var $,ts,is,cs,Qr=($=(ts=es[0].stacktrace)==null?void 0:ts.frames)!==null&&$!==void 0?$:[],ja=Qr[Qr.length-1];return(is=ja==null||(cs=ja.filename)==null?void 0:cs.includes("posthog.com/static"))!==null&&is!==void 0&&is}return!1}Io(es){return!D(es)&&R(es)}}},ba=f({productTours:class{get ni(){return this._instance.persistence}constructor(es){this.Ao=null,this.Eo=null,this._instance=es}initialize(){this.loadIfEnabled()}onRemoteConfig(es){"productTours"in es&&(this.ni&&this.ni.register({[We]:!!es.productTours}),this.loadIfEnabled())}loadIfEnabled(){var es,$;this.Ao||(es=this._instance).config.disable_product_tours||($=es.persistence)==null||!$.get_property(We)||this.ur((()=>this.Ro()))}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.generateProductTours?es():(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,"product-tours",(is=>{is?Vo.error("Could not load product tours script",is):es()}))}Ro(){var es;!this.Ao&&(es=h.__PosthogExtensions__)!=null&&es.generateProductTours&&(this.Ao=h.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(es,$){if($===void 0&&($=!1),!R(this.Eo)||$){var ts=this.ni;if(ts){var is=ts.props[ci];if(R(is)&&!$)return this.Eo=is,void es(is,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:cs=>{var Qr=cs.statusCode;if(Qr!==200||!cs.json){var ja="Product Tours API could not be loaded, status: "+Qr;return Vo.error(ja),void es([],{isLoaded:!1,error:ja})}var Na=R(cs.json.product_tours)?cs.json.product_tours:[];this.Eo=Na,ts&&ts.register({[ci]:Na}),es(Na,{isLoaded:!0})}})}else es(this.Eo,{isLoaded:!0})}getActiveProductTours(es){D(this.Ao)?es([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ao.getActiveProductTours(es)}showProductTour(es){var $;($=this.Ao)==null||$.showTourById(es)}previewTour(es){this.Ao?this.Ao.previewTour(es):this.ur((()=>{var $;this.Ro(),($=this.Ao)==null||$.previewTour(es)}))}dismissProductTour(){var es;(es=this.Ao)==null||es.dismissTour("user_clicked_skip")}nextStep(){var es;(es=this.Ao)==null||es.nextStep()}previousStep(){var es;(es=this.Ao)==null||es.previousStep()}clearCache(){var es;this.Eo=null,(es=this.ni)==null||es.unregister(ci)}resetTour(es){var $;($=this.Ao)==null||$.resetTour(es)}resetAllTours(){var es;(es=this.Ao)==null||es.resetAllTours()}cancelPendingTour(es){var $;($=this.Ao)==null||$.cancelPendingTour(es)}}},fa),ya={siteApps:class{constructor(es){this._instance=es,this.No=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Mo(es,$){if($){var ts=this.globalsForEvent($);this.No.push(ts),this.No.length>1e3&&(this.No=this.No.slice(10))}}get siteAppLoaders(){var es;return(es=h._POSTHOG_REMOTE_CONFIG)==null||(es=es[this._instance.config.token])==null?void 0:es.siteApps}initialize(){if(this.isEnabled){var es=this._instance._addCaptureHook(this.Mo.bind(this));this.Fo=()=>{es(),this.No=[],this.Fo=void 0}}}globalsForEvent(es){var $,ts,is,cs,Qr,ja,Na;if(!es)throw new Error("Event payload is required");var Aa={},Oa=this._instance.get_property("$groups")||[],Ia=this._instance.get_property("$stored_group_properties")||{};for(var[La,Ba]of Object.entries(Ia))Aa[La]={id:Oa[La],type:La,properties:Ba};var{$set_once:Ma,$set:qa}=es;return{event:f({},_(es,Wo),{properties:f({},es.properties,qa?{$set:f({},($=(ts=es.properties)==null?void 0:ts.$set)!==null&&$!==void 0?$:{},qa)}:{},Ma?{$set_once:f({},(is=(cs=es.properties)==null?void 0:cs.$set_once)!==null&&is!==void 0?is:{},Ma)}:{}),elements_chain:(Qr=(ja=es.properties)==null?void 0:ja.$elements_chain)!==null&&Qr!==void 0?Qr:"",distinct_id:(Na=es.properties)==null?void 0:Na.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:Aa}}setupSiteApp(es){var $=this.apps[es.id],ts=()=>{var ja;!$.errored&&this.No.length&&(Go.info("Processing "+this.No.length+" events for site app with id "+es.id),this.No.forEach((Na=>$.processEvent==null?void 0:$.processEvent(Na))),$.processedBuffer=!0),Object.values(this.apps).every((Na=>Na.processedBuffer||Na.errored))&&((ja=this.Fo)==null||ja.call(this))},is=!1,cs=ja=>{$.errored=!ja,$.loaded=!0,Go.info("Site app with id "+es.id+" "+(ja?"loaded":"errored")),is&&ts()};try{var{processEvent:Qr}=es.init({posthog:this._instance,callback(ja){cs(ja)}});Qr&&($.processEvent=Qr),is=!0}catch(ja){Go.error(Yo+es.id,ja),cs(!1)}if(is&&$.loaded)try{ts()}catch(ja){Go.error("Error while processing buffered events PostHog app with config id "+es.id,ja),$.errored=!0}}Oo(){var es=this.siteAppLoaders||[];for(var $ of es)this.apps[$.id]={id:$.id,loaded:!1,errored:!1,processedBuffer:!1};for(var ts of es)this.setupSiteApp(ts)}Po(es){if(Object.keys(this.apps).length!==0){var $=this.globalsForEvent(es);for(var ts of Object.values(this.apps))try{ts.processEvent==null||ts.processEvent($)}catch(is){Go.error("Error while processing event "+es.event+" for site app "+ts.id,is)}}}onRemoteConfig(es){var $,ts,is,cs=this;if(($=this.siteAppLoaders)!=null&&$.length)return this.isEnabled?(this.Oo(),void this._instance.on("eventCaptured",(Aa=>this.Po(Aa)))):void Go.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((ts=this.Fo)==null||ts.call(this),(is=es.siteApps)!=null&&is.length)if(this.isEnabled){var Qr=function(Aa){var Oa;h["__$$ph_site_app_"+Aa]=cs._instance,(Oa=h.__PosthogExtensions__)==null||Oa.loadSiteApp==null||Oa.loadSiteApp(cs._instance,Na,(Ia=>{if(Ia)return Go.error(Yo+Aa,Ia)}))};for(var{id:ja,url:Na}of es.siteApps)Qr(ja)}else Go.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},wa={tracingHeaders:class{constructor(es){this.Lo=void 0,this.Do=void 0,this.so=()=>{var $,ts,is=this.Bo()||[];C(this.Lo)&&(($=h.__PosthogExtensions__)==null||($=$.tracingHeadersPatchFns)==null||$._patchXHR(is,this._instance.get_distinct_id(),this._instance.sessionManager)),C(this.Do)&&((ts=h.__PosthogExtensions__)==null||(ts=ts.tracingHeadersPatchFns)==null||ts._patchFetch(is,this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=es}initialize(){this.startIfEnabledOrStop()}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.tracingHeadersPatchFns&&es(),(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,"tracing-headers",(is=>{if(is)return Ao.error("failed to load script",is);es()}))}Bo(){var es;return(es=this._instance.config.addTracingHeaders)!==null&&es!==void 0?es:this._instance.config.__add_tracing_headers}startIfEnabledOrStop(){var es,$;this.Bo()?this.ur(this.so):((es=this.Lo)==null||es.call(this),($=this.Do)==null||$.call(this),this.Lo=void 0,this.Do=void 0)}}},xa=f({surveys:class{get Bt(){return this._instance.config}constructor(es){this.jo=void 0,this._surveyManager=null,this.$o=!1,this.qo=[],this.Zo=null,this._instance=es,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(es){if(!this.Bt.disable_surveys){var $=es.surveys;if(D($))return En.warn("Flags not loaded yet. Not loading surveys.");var ts=R($);this.jo=ts?$.length>0:$,En.info("flags response received, isSurveysEnabled: "+this.jo),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var es=[],$=0;$<localStorage.length;$++){var ts=localStorage.key($);(ts!=null&&ts.startsWith(Sn)||ts!=null&&ts.startsWith("inProgressSurvey_"))&&es.push(ts)}es.forEach((is=>localStorage.removeItem(is)))}loadIfEnabled(){if(!this._surveyManager)if(this.$o)En.info("Already initializing surveys, skipping...");else if(this.Bt.disable_surveys)En.info(ta);else if(this.Bt.cookieless_mode&&this._instance.consent.isOptedOut())En.info("Not loading surveys in cookieless mode without consent.");else{var es=h==null?void 0:h.__PosthogExtensions__;if(es){if(!C(this.jo)||this.Bt.advanced_enable_surveys){var $=this.jo||this.Bt.advanced_enable_surveys;this.$o=!0;try{var ts=es.generateSurveys;if(ts)return void this.Vo(ts,$);var is=es.loadExternalDependency;if(!is)return void this.Ho(Oi);is(this._instance,"surveys",(cs=>{cs||!es.generateSurveys?this.Ho("Could not load surveys script",cs):this.Vo(es.generateSurveys,$)}))}catch(cs){throw this.Ho("Error initializing surveys",cs),cs}finally{this.$o=!1}}}else En.error("PostHog Extensions not found.")}}Vo(es,$){this._surveyManager=es(this._instance,$),this._surveyEventReceiver=new Qo(this._instance),En.info("Surveys loaded successfully"),this.zo({isLoaded:!0})}Ho(es,$){En.error(es,$),this.zo({isLoaded:!1,error:es})}onSurveysLoaded(es){return this.qo.push(es),this._surveyManager&&this.zo({isLoaded:!0}),()=>{this.qo=this.qo.filter(($=>$!==es))}}getSurveys(es,$){if($===void 0&&($=!1),this.Bt.disable_surveys)return En.info(ta),es([]);var ts,is=this._instance.get_property(di);if(is&&!$)return es(is,{isLoaded:!0});typeof Promise<"u"&&this.Zo?this.Zo.then((cs=>{var{surveys:Qr,context:ja}=cs;return es(Qr,ja)})):(typeof Promise<"u"&&(this.Zo=new Promise((cs=>{ts=cs}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Bt.token),method:"GET",timeout:this.Bt.surveys_request_timeout_ms,callback:cs=>{var Qr;this.Zo=null;var ja=cs.statusCode;if(ja!==200||!cs.json){var Na="Surveys API could not be loaded, status: "+ja;En.error(Na);var Aa={isLoaded:!1,error:Na};return es([],Aa),void(ts==null||ts({surveys:[],context:Aa}))}var Oa,Ia=cs.json.surveys||[],La=Ia.filter((Ma=>(function(qa){return!(!qa.start_date||qa.end_date)})(Ma)&&((function(qa){var Fa;return!((Fa=qa.conditions)==null||(Fa=Fa.events)==null||(Fa=Fa.values)==null||!Fa.length)})(Ma)||(function(qa){var Fa;return!((Fa=qa.conditions)==null||(Fa=Fa.actions)==null||(Fa=Fa.values)==null||!Fa.length)})(Ma))));La.length>0&&((Oa=this._surveyEventReceiver)==null||Oa.register(La)),(Qr=this._instance.persistence)==null||Qr.register({[di]:Ia});var Ba={isLoaded:!0};es(Ia,Ba),ts==null||ts({surveys:Ia,context:Ba})}}))}zo(es){for(var $ of this.qo)try{if(!es.isLoaded)return $([],es);this.getSurveys($)}catch(ts){En.error("Error in survey callback",ts)}}getActiveMatchingSurveys(es,$){if($===void 0&&($=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(es,$);En.warn("init was not called")}Uo(es){var $=null;return this.getSurveys((ts=>{var is;$=(is=ts.find((cs=>cs.id===es)))!==null&&is!==void 0?is:null})),$}Yo(es){if(D(this._surveyManager))return{eligible:!1,reason:Zo};var $=typeof es=="string"?this.Uo(es):es;return $?this._surveyManager.checkSurveyEligibility($):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(es){if(D(this._surveyManager))return En.warn("init was not called"),{visible:!1,disabledReason:Zo};var $=this.Yo(es);return{visible:$.eligible,disabledReason:$.reason}}canRenderSurveyAsync(es,$){return D(this._surveyManager)?(En.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Zo})):new Promise((ts=>{this.getSurveys((is=>{var cs,Qr=(cs=is.find((Na=>Na.id===es)))!==null&&cs!==void 0?cs:null;if(Qr){var ja=this.Yo(Qr);ts({visible:ja.eligible,disabledReason:ja.reason})}else ts({visible:!1,disabledReason:"Survey not found"})}),$)}))}renderSurvey(es,$,ts){var is;if(D(this._surveyManager))En.warn("init was not called");else{var cs=typeof es=="string"?this.Uo(es):es;if(cs!=null&&cs.id)if($n.includes(cs.type)){var Qr=r==null?void 0:r.querySelector($);if(Qr)return(is=cs.appearance)!=null&&is.surveyPopupDelaySeconds?(En.info("Rendering survey "+cs.id+" with delay of "+cs.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var ja,Na;En.info("Rendering survey "+cs.id+" with delay of "+((ja=cs.appearance)==null?void 0:ja.surveyPopupDelaySeconds)+" seconds"),(Na=this._surveyManager)==null||Na.renderSurvey(cs,Qr,ts),En.info("Survey "+cs.id+" rendered")}),1e3*cs.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(cs,Qr,ts);En.warn("Survey element not found")}else En.warn("Surveys of type "+cs.type+" cannot be rendered in the app");else En.warn("Survey not found")}}displaySurvey(es,$){var ts;if(D(this._surveyManager))En.warn("init was not called");else{var is=this.Uo(es);if(is){var cs=is;if((ts=is.appearance)!=null&&ts.surveyPopupDelaySeconds&&$.ignoreDelay&&(cs=f({},is,{appearance:f({},is.appearance,{surveyPopupDelaySeconds:0})})),$.displayType!==ns.Popover&&$.initialResponses&&En.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),$.ignoreConditions===!1){var Qr=this.canRenderSurvey(is);if(!Qr.visible)return void En.warn("Survey is not eligible to be displayed: ",Qr.disabledReason)}$.displayType!==ns.Inline?this._surveyManager.handlePopoverSurvey(cs,$):this.renderSurvey(cs,$.selector,$.properties)}else En.warn("Survey not found")}}cancelPendingSurvey(es){D(this._surveyManager)?En.warn("init was not called"):this._surveyManager.cancelSurvey(es)}handlePageUnload(){var es;(es=this._surveyManager)==null||es.handlePageUnload()}}},fa),Ea={toolbar:class{constructor(es){this.instance=es}Go(es){h.ph_toolbar_state=es}Wo(){var es;return(es=h.ph_toolbar_state)!==null&&es!==void 0?es:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(es,$,ts){if(es===void 0&&(es=void 0),$===void 0&&($=void 0),ts===void 0&&(ts=void 0),Qi(this.instance.config)||!t||!r)return!1;es=es??t.location,ts=ts??t.history;try{if(!$){try{t.localStorage.setItem("test","test"),t.localStorage.removeItem("test")}catch{return!1}$=t==null?void 0:t.localStorage}var is,cs=ea||Ir(es.hash,"__posthog")||Ir(es.hash,"state"),Qr=cs?Wi((()=>JSON.parse(atob(decodeURIComponent(cs)))))||Wi((()=>JSON.parse(decodeURIComponent(cs)))):null;return Qr&&Qr.action==="ph_authorize"?((is=Qr).source="url",is&&Object.keys(is).length>0&&(Qr.desiredHash?es.hash=Qr.desiredHash:ts?ts.replaceState(ts.state,"",es.pathname+es.search):es.hash="")):((is=JSON.parse($.getItem(ia)||"{}")).source="localstorage",delete is.userIntent),!(!is.token||this.instance.config.token!==is.token||(this.loadToolbar(is),0))}catch{return!1}}Xo(es){var $=h.ph_load_toolbar||h.ph_load_editor;!D($)&&P($)?$(es,this.instance):ra.warn("No toolbar load function found")}loadToolbar(es){var $=!(r==null||!r.getElementById($i));if(!t||$)return!1;var ts=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,is=f({token:this.instance.config.token},es,{apiURL:this.instance.requestRouter.endpointFor("ui")},ts?{instrument:!1}:{});if(t.localStorage.setItem(ia,JSON.stringify(f({},is,{source:void 0}))),this.Wo()===2)this.Xo(is);else if(this.Wo()===0){var cs;this.Go(1),(cs=h.__PosthogExtensions__)==null||cs.loadExternalDependency==null||cs.loadExternalDependency(this.instance,"toolbar",(Qr=>{if(Qr)return ra.error("[Toolbar] Failed to load",Qr),void this.Go(0);this.Go(2),this.Xo(is)})),Xi(t,"turbolinks:load",(()=>{this.Go(0),this.loadToolbar(is)}))}return!0}Jo(es){return this.loadToolbar(es)}maybeLoadEditor(es,$,ts){return es===void 0&&(es=void 0),$===void 0&&($=void 0),ts===void 0&&(ts=void 0),this.maybeLoadToolbar(es,$,ts)}}},Sa=f({experiments:va},fa),$a={conversations:class{constructor(es){this.Ko=void 0,this._conversationsManager=null,this.Qo=!1,this.ea=null,this._instance=es}initialize(){this.loadIfEnabled()}onRemoteConfig(es){if(!this._instance.config.disable_conversations){var $=es.conversations;D($)||(N($)?this.Ko=$:(this.Ko=$.enabled,this.ea=$),this.loadIfEnabled())}}reset(){var es;(es=this._conversationsManager)==null||es.reset(),this._conversationsManager=null,this.Ko=void 0,this.ea=null}loadIfEnabled(){if(!(this._conversationsManager||this.Qo||this._instance.config.disable_conversations||Qi(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var es=h==null?void 0:h.__PosthogExtensions__;if(es&&!C(this.Ko)&&this.Ko)if(this.ea&&this.ea.token){this.Qo=!0;try{var $=es.initConversations;if($)return this.ta($),void(this.Qo=!1);var ts=es.loadExternalDependency;if(!ts)return void this.ra(Oi);ts(this._instance,"conversations",(is=>{is||!es.initConversations?this.ra("Could not load conversations script",is):this.ta(es.initConversations),this.Qo=!1}))}catch(is){this.ra("Error initializing conversations",is),this.Qo=!1}}else ca.error("Conversations enabled but missing token in remote config.")}}ta(es){if(this.ea)try{this._conversationsManager=es(this.ea,this._instance),ca.info("Conversations loaded successfully")}catch($){this.ra("Error completing conversations initialization",$)}else ca.error("Cannot complete initialization: remote config is null")}ra(es,$){ca.error(es,$),this._conversationsManager=null,this.Qo=!1}show(){this._conversationsManager?this._conversationsManager.show():ca.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ko===!0&&!M(this._conversationsManager)}isVisible(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.isVisible())!==null&&es!==void 0&&es}sendMessage(es,$,ts){var is=this;return p((function*(){return is._conversationsManager?is._conversationsManager.sendMessage(es,$,ts):(ca.warn(pa),null)}))()}getMessages(es,$){var ts=this;return p((function*(){return ts._conversationsManager?ts._conversationsManager.getMessages(es,$):(ca.warn(pa),null)}))()}markAsRead(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.markAsRead(es):(ca.warn(pa),null)}))()}getTickets(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.getTickets(es):(ca.warn(pa),null)}))()}requestRestoreLink(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.requestRestoreLink(es):(ca.warn(pa),null)}))()}restoreFromToken(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.restoreFromToken(es):(ca.warn(pa),null)}))()}restoreFromUrlToken(){var es=this;return p((function*(){return es._conversationsManager?es._conversationsManager.restoreFromUrlToken():(ca.warn(pa),null)}))()}getCurrentTicketId(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.getCurrentTicketId())!==null&&es!==void 0?es:null}getWidgetSessionId(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.getWidgetSessionId())!==null&&es!==void 0?es:null}un(){var es;(es=this._conversationsManager)==null||es.setIdentity()}hn(){var es;(es=this._conversationsManager)==null||es.clearIdentity()}}},Ta={logs:class{constructor(es){var $;this.ia=!1,this.na=!1,this.Gt=Ce("[logs]"),this.sa=[],this.oa=0,this.aa=0,this.la=!1,this._instance=es,this._instance&&($=this._instance.config.logs)!=null&&$.captureConsoleLogs&&(this.ia=!0)}initialize(){this.loadIfEnabled()}onRemoteConfig(es){var $,ts=($=es.logs)==null?void 0:$.captureConsoleLogs;!D(ts)&&ts&&(this.ia=!0,this.loadIfEnabled())}reset(){this.sa=[],this.jr&&(clearTimeout(this.jr),this.jr=void 0),this.oa=0,this.aa=0,this.la=!1}loadIfEnabled(){if(this.ia&&!this.na){var es=h==null?void 0:h.__PosthogExtensions__;if(es){var $=es.loadExternalDependency;$?$(this._instance,"logs",(ts=>{var is;ts||(is=es.logs)==null||!is.initializeLogs?this.Gt.error("Could not load logs script",ts):(es.logs.initializeLogs(this._instance),this.na=!0)})):this.Gt.error(Oi)}else this.Gt.error("PostHog Extensions not found.")}}captureLog(es){var $,ts,is,cs,Qr,ja;if(this._instance.is_capturing())if(es&&es.body){var Na=($=(ts=this._instance.config.logs)==null?void 0:ts.flushIntervalMs)!==null&&$!==void 0?$:3e3,Aa=(is=(cs=this._instance.config.logs)==null?void 0:cs.maxLogsPerInterval)!==null&&is!==void 0?is:1e3,Oa=Date.now();if(Na>Oa-this.aa||(this.aa=Oa,this.oa=0,this.la=!1),Aa>this.oa){this.oa++;var Ia=(function(La,Ba){var Ma=La.level||"info",{text:qa,number:Fa}=Jt[Ma]||Kt,Ha=String(Date.now())+"000000",Ka={};Ba.distinctId&&(Ka.posthogDistinctId=Ba.distinctId),Ba.sessionId&&(Ka.sessionId=Ba.sessionId),Ba.currentUrl&&(Ka["url.full"]=Ba.currentUrl),Ba.screenName&&(Ka["screen.name"]=Ba.screenName),Ba.appState&&(Ka["app.state"]=Ba.appState),Ba.activeFeatureFlags&&Ba.activeFeatureFlags.length>0&&(Ka.feature_flags=Ba.activeFeatureFlags);var Ga=f({},Ka,La.attributes||{}),Va={timeUnixNano:Ha,observedTimeUnixNano:Ha,severityNumber:Fa,severityText:qa,body:{stringValue:La.body},attributes:Qt(Ga)};return La.trace_id&&(Va.traceId=La.trace_id),La.span_id&&(Va.spanId=La.span_id),C(La.trace_flags)||(Va.flags=La.trace_flags),Va})(es,this.ua());this.sa.push({record:Ia}),((Qr=(ja=this._instance.config.logs)==null?void 0:ja.maxBufferSize)!==null&&Qr!==void 0?Qr:100)>this.sa.length?this.ha():this.flushLogs()}else this.la||(this.Gt.warn("captureLog dropping logs: exceeded "+Aa+" logs per "+Na+"ms"),this.la=!0)}else this.Gt.warn("captureLog requires a body")}get logger(){return this.ca||(this.ca={trace:(es,$)=>this.captureLog({body:es,level:"trace",attributes:$}),debug:(es,$)=>this.captureLog({body:es,level:"debug",attributes:$}),info:(es,$)=>this.captureLog({body:es,level:"info",attributes:$}),warn:(es,$)=>this.captureLog({body:es,level:"warn",attributes:$}),error:(es,$)=>this.captureLog({body:es,level:"error",attributes:$}),fatal:(es,$)=>this.captureLog({body:es,level:"fatal",attributes:$})}),this.ca}flushLogs(es){if(this.jr&&(clearTimeout(this.jr),this.jr=void 0),this.sa.length!==0){var $=this.sa;this.sa=[];var ts=this._instance.config.logs,is=f({"service.name":(ts==null?void 0:ts.serviceName)||"unknown_service"},(ts==null?void 0:ts.environment)&&{"deployment.environment":ts.environment},(ts==null?void 0:ts.serviceVersion)&&{"service.version":ts.serviceVersion},ts==null?void 0:ts.resourceAttributes),cs=(function(ja,Na,Aa,Oa){return{resourceLogs:[{resource:{attributes:Qt(Na)},scopeLogs:[{scope:{name:Aa,version:Oa},logRecords:ja}]}]}})($.map((ja=>ja.record)),is,v.LIB_NAME,v.LIB_VERSION),Qr=this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token);this._instance.Vi({method:"POST",url:Qr,data:cs,compression:"best-available",batchKey:"logs",transport:es})}}ha(){var es,$;this.jr||(this.jr=setTimeout((()=>{this.jr=void 0,this.flushLogs()}),(es=($=this._instance.config.logs)==null?void 0:$.flushIntervalMs)!==null&&es!==void 0?es:3e3))}ua(){var es,$={};if($.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var{sessionId:ts}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);$.sessionId=ts}if(h!=null&&(es=h.location)!=null&&es.href&&($.currentUrl=h.location.href),this._instance.featureFlags){var is=this._instance.featureFlags.getFlags();is&&is.length>0&&($.activeFeatureFlags=is)}return $}}},ka=f({},fa,_a,ga,ma,ba,ya,xa,wa,Ea,Sa,$a,Ta);qn.__defaultExtensionClasses=f({},ka);var Ra;Ra=In[Un]=new qn,(function(){function es(){es.done||(es.done=!0,Nn=!1,Hi(In,(function($){$._dom_loaded()})))}r!=null&&r.addEventListener?r.readyState==="complete"?es():Xi(r,"DOMContentLoaded",es,{capture:!1}):t&&Ie.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})();function PostHogProvider({children:es}){const{user:$}=useAuth(),ts=useLocation();return reactExports.useRef(null),reactExports.useEffect(()=>{},[]),reactExports.useEffect(()=>{},[$]),reactExports.useEffect(()=>{},[ts.pathname]),jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:es})}function Separator({className:es,orientation:$="horizontal",decorative:ts=!0,...is}){return jsxRuntimeExports.jsx(Root,{"data-slot":"separator",decorative:ts,orientation:$,className:cn$1("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",es),...is})}function usePendingSuggestionCount(){return useQuery({queryKey:["instruction-suggestions","pending-count"],queryFn:()=>apiGet("/api/instruction-suggestions/pending-count"),staleTime:300*1e3})}function useProjectPaths(){return useQuery({queryKey:["sessions","project-paths"],queryFn:()=>apiGet("/api/sessions/project-paths?limit=20"),select:es=>es.projectPaths})}function useSuggestionsForProjects(es){return useQueries({queries:es.map($=>({queryKey:["instruction-suggestions",$],queryFn:()=>apiGet(`/api/instruction-suggestions?projectPath=${encodeURIComponent($)}&limit=10&groupByKind=true`).then(ts=>({projectPath:$,suggestions:ts.suggestions,experiments:ts.experiments??{},crossProject:ts.crossProject??{}}))}))})}function useSuggestionImpacts(es){const $=[...new Set(es)].sort().join(",");return useQuery({queryKey:["insights","suggestion-impact",$],queryFn:()=>apiGet(`/api/insights/suggestion-impact?instructionIds=${encodeURIComponent($)}`),select:ts=>ts.impacts,enabled:$.length>0})}function useLogSuggestionEvent(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/instruction-suggestions/${$.suggestionId}/events`,{eventType:$.eventType,projectPath:$.projectPath,tool:$.tool}),onSuccess:()=>{es.invalidateQueries({queryKey:["instruction-suggestions"]})}})}function usePromoteFromPublic(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/instructions/${$.sourceInstructionId}/promote-from-public`,{targetScope:$.targetScope,targetScopeRef:$.targetScopeRef,name:$.name}),onSuccess:()=>{es.invalidateQueries({queryKey:["instructions"]}),es.invalidateQueries({queryKey:["catalog"]})}})}const PUBLIC_PAGE_SIZE=50;function usePublicCatalog(es){return useInfiniteQuery({queryKey:["catalog","public",es??""],initialPageParam:0,queryFn:({pageParam:$})=>{const ts=new URLSearchParams({scope:"public",limit:String(PUBLIC_PAGE_SIZE),offset:String($)});return es&&ts.set("search",es),apiGet(`/api/catalog?${ts.toString()}`)},getNextPageParam:($,ts)=>{if(!($.length<PUBLIC_PAGE_SIZE))return ts.length*PUBLIC_PAGE_SIZE}})}function useNominateExperiment(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/instruction-experiments",$),onSuccess:()=>{es.invalidateQueries({queryKey:["instruction-suggestions"]}),es.invalidateQueries({queryKey:["instruction-experiments"]})}})}function useInstructionDetail(es,$){return useQuery({queryKey:["instruction",es],queryFn:()=>apiGet(`/api/instructions/${es}`),enabled:$,staleTime:300*1e3})}const ADOPTED_PAGE_SIZE=20;function useAdoptedSuggestions(es){return useInfiniteQuery({queryKey:["instruction-suggestions","adopted",es],initialPageParam:null,queryFn:({pageParam:$})=>{const ts=new URLSearchParams({projectPath:es,limit:String(ADOPTED_PAGE_SIZE)});return $&&ts.set("cursor",$),apiGet(`/api/instruction-suggestions/adopted?${ts.toString()}`)},getNextPageParam:$=>$.nextCursor??void 0,staleTime:60*1e3})}function formatRelativeTime(es,$={}){if(!es)return $.fallback??"—";const ts=Math.floor((Date.now()-new Date(es).getTime())/6e4);if(ts<1)return"just now";if(ts<60)return`${ts}m ago`;const is=Math.floor(ts/60);return is<24?`${is}h ago`:`${Math.floor(is/24)}d ago`}function formatDistanceToFuture(es){const ts=new Date(es).getTime()-Date.now();if(ts<=0)return"expired";const is=Math.floor(ts/6e4),cs=Math.floor(ts/36e5),Qr=Math.floor(ts/864e5);return is<1?"<1m":is<60?`in ${is}m`:cs<24?`in ${cs}h`:`in ${Qr}d`}function formatDistanceToNow(es){const $=new Date(es),is=new Date().getTime()-$.getTime(),cs=Math.floor(is/6e4),Qr=Math.floor(is/36e5),ja=Math.floor(is/864e5);return cs<1?"just now":cs<60?`${cs}m ago`:Qr<24?`${Qr}h ago`:ja<30?`${ja}d ago`:$.toLocaleDateString()}const POLL={LIVE:5e3,ACTIVE:1e4,BACKGROUND:15e3,HEARTBEAT:3e4,SLOW:6e4,DAILY:3600*1e3};function useWorkerStatus(es){const $=useQuery({queryKey:["worker-status"],queryFn:()=>apiGet("/api/workers/status"),refetchInterval:POLL.HEARTBEAT}),ts=$.data??[],is=es?ts.filter(Qr=>Qr.workerType===es):ts,cs=is.filter(Qr=>Qr.status==="active");return{...$,workers:is,activeWorkers:cs,isConnected:cs.length>0,workerCount:cs.length}}const typeLabels={mcp:"MCP","cli-worker":"CLI Worker",gateway:"Gateway",proxy:"Proxy"};function WorkerStatus(){const{workers:es,activeWorkers:$,isConnected:ts,isLoading:is}=useWorkerStatus();return is||es.length===0?jsxRuntimeExports.jsx("div",{className:"px-2 py-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full shrink-0 bg-muted-foreground/30"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"No workers connected"})]})}):jsxRuntimeExports.jsx("div",{className:"px-2 py-2",children:jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border px-3 py-2 text-xs space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:cn$1("h-2 w-2 rounded-full shrink-0",ts?"bg-teal-500":"bg-amber-500")}),jsxRuntimeExports.jsx("span",{className:"font-medium",children:ts?`${$.length} worker${$.length>1?"s":""} online`:"Workers offline"})]}),es.map(cs=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-muted-foreground pl-4",children:[jsxRuntimeExports.jsx("span",{children:typeLabels[cs.workerType]??cs.workerType}),jsxRuntimeExports.jsx("span",{children:cs.status==="active"?formatRelativeTime(cs.lastHeartbeat):"offline"})]},cs.id))]})})}const navItems=[{to:"/dashboard",label:"Dashboard",icon:LayoutDashboard},{to:"/connect",label:"Connect",icon:Plug},{to:"/sessions",label:"Sessions",icon:Activity},{to:"/projects",label:"Projects",icon:Layers},{to:"/eval-targets",label:"Evals",icon:FlaskConical},{to:"/insights",label:"Insights",icon:TrendingUp},{to:"/memories",label:"Memories",icon:Brain},{to:"/usage",label:"Usage",icon:DollarSign},{to:"/skills",label:"Skills",icon:Sparkles},{to:"/catalog/public",label:"Public Catalog",icon:Globe},{to:"/suggestions",label:"Suggestions",icon:Lightbulb},{to:"/experiments",label:"Experiments",icon:TestTube},{to:"/loop",label:"Loop",icon:Activity},{to:"/settings",label:"Settings",icon:SlidersHorizontal},{to:"/docs",label:"Docs",icon:BookOpen}];function Sidebar({className:es}){const $=useLocation(),{profile:ts}=useActiveOrg(),{data:is}=usePendingSuggestionCount();return jsxRuntimeExports.jsxs("aside",{className:cn$1("flex h-full w-60 flex-col border-r border-border bg-background p-4",es),children:[jsxRuntimeExports.jsxs("div",{className:"mb-6 flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("h1",{className:"font-mono text-lg font-semibold tracking-tight",children:"RuleMetric"})]}),jsxRuntimeExports.jsx("nav",{className:"flex flex-col gap-1",children:navItems.map(cs=>{const Qr=$.pathname.startsWith(cs.to);return jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",Qr&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:cs.to,children:[jsxRuntimeExports.jsx(cs.icon,{className:cn$1("mr-2 h-4 w-4",Qr&&"text-primary")}),cs.label,cs.to==="/suggestions"&&((is==null?void 0:is.total)??0)>0&&jsxRuntimeExports.jsx("span",{className:"ml-auto rounded-full bg-primary/15 px-2 py-0.5 font-mono text-xs text-primary",children:is.total>99?"99+":is.total})]})},cs.to)})}),(ts==null?void 0:ts.isSuperadmin)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Separator,{className:"my-4"}),jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",$.pathname.startsWith("/superadmin")&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/superadmin/users",children:[jsxRuntimeExports.jsx(Shield,{className:"mr-2 h-4 w-4"}),"Superadmin"]})}),jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",$.pathname.startsWith("/admin/announcements")&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/admin/announcements",children:[jsxRuntimeExports.jsx(Megaphone,{className:"mr-2 h-4 w-4"}),"Announcements"]})})]}),jsxRuntimeExports.jsx("div",{className:"mt-auto",children:jsxRuntimeExports.jsx(WorkerStatus,{})})]})}function DropdownMenu({...es}){return jsxRuntimeExports.jsx(Root2,{"data-slot":"dropdown-menu",...es})}function DropdownMenuTrigger({...es}){return jsxRuntimeExports.jsx(Trigger,{"data-slot":"dropdown-menu-trigger",...es})}function DropdownMenuContent({className:es,sideOffset:$=4,...ts}){return jsxRuntimeExports.jsx(Portal2,{children:jsxRuntimeExports.jsx(Content2,{"data-slot":"dropdown-menu-content",sideOffset:$,className:cn$1("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",es),...ts})})}function DropdownMenuItem({className:es,inset:$,variant:ts="default",...is}){return jsxRuntimeExports.jsx(Item2,{"data-slot":"dropdown-menu-item","data-inset":$,"data-variant":ts,className:cn$1("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",es),...is})}function DropdownMenuLabel({className:es,inset:$,...ts}){return jsxRuntimeExports.jsx(Label2,{"data-slot":"dropdown-menu-label","data-inset":$,className:cn$1("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",es),...ts})}function DropdownMenuSeparator({className:es,...$}){return jsxRuntimeExports.jsx(Separator2,{"data-slot":"dropdown-menu-separator",className:cn$1("bg-border -mx-1 my-1 h-px",es),...$})}function Avatar({className:es,size:$="default",...ts}){return jsxRuntimeExports.jsx(Root$1,{"data-slot":"avatar","data-size":$,className:cn$1("group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",es),...ts})}function AvatarFallback({className:es,...$}){return jsxRuntimeExports.jsx(Fallback,{"data-slot":"avatar-fallback",className:cn$1("bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs",es),...$})}function Sheet({...es}){return jsxRuntimeExports.jsx(Root$2,{"data-slot":"sheet",...es})}function SheetTrigger({...es}){return jsxRuntimeExports.jsx(Trigger$1,{"data-slot":"sheet-trigger",...es})}function SheetPortal({...es}){return jsxRuntimeExports.jsx(Portal,{"data-slot":"sheet-portal",...es})}function SheetOverlay({className:es,...$}){return jsxRuntimeExports.jsx(Overlay,{"data-slot":"sheet-overlay",className:cn$1("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",es),...$})}function SheetContent({className:es,children:$,side:ts="right",showCloseButton:is=!0,...cs}){return jsxRuntimeExports.jsxs(SheetPortal,{children:[jsxRuntimeExports.jsx(SheetOverlay,{}),jsxRuntimeExports.jsxs(Content,{"data-slot":"sheet-content",className:cn$1("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",ts==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",ts==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",ts==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",ts==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",es),...cs,children:[$,is&&jsxRuntimeExports.jsxs(Close,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary 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",children:[jsxRuntimeExports.jsx(X$1,{className:"size-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function SheetHeader({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"sheet-header",className:cn$1("flex flex-col gap-1.5 p-4",es),...$})}function SheetTitle({className:es,...$}){return jsxRuntimeExports.jsx(Title,{"data-slot":"sheet-title",className:cn$1("text-foreground font-semibold",es),...$})}function SheetDescription({className:es,...$}){return jsxRuntimeExports.jsx(Description,{"data-slot":"sheet-description",className:cn$1("text-muted-foreground text-sm",es),...$})}const NOTIFICATIONS_QUERY_KEY=["notifications"];function useNotifications(){var Qr,ja;const es=useQueryClient(),{user:$}=useAuth(),ts=useQuery({queryKey:NOTIFICATIONS_QUERY_KEY,queryFn:()=>apiGet("/api/notifications?limit=20"),enabled:!!$}),is=useMutation({mutationFn:Na=>apiPost(`/api/notifications/${Na}/read`,{}),onSuccess:()=>es.invalidateQueries({queryKey:NOTIFICATIONS_QUERY_KEY})}),cs=useMutation({mutationFn:()=>apiPost("/api/notifications/read-all",{}),onSuccess:()=>es.invalidateQueries({queryKey:NOTIFICATIONS_QUERY_KEY})});return{items:((Qr=ts.data)==null?void 0:Qr.items)??[],unreadCount:((ja=ts.data)==null?void 0:ja.unreadCount)??0,isLoading:ts.isLoading,markRead:Na=>is.mutate(Na),markAllRead:()=>cs.mutate()}}function NotificationsListener(){const{user:es}=useAuth(),$=useQueryClient();return reactExports.useEffect(()=>{if(!(es!=null&&es.id))return;(async()=>{if(!(typeof Notification>"u")&&Notification.permission==="default")try{await Notification.requestPermission()}catch{}})();let is=null;const cs=setTimeout(()=>{is=supabase.channel(`notifications-${es.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"notifications",filter:`user_id=eq.${es.id}`},Qr=>{const ja=Qr.new,Na={id:ja.id,userId:ja.user_id,type:ja.type,title:ja.title,body:ja.body??null,url:ja.url??null,sourceTable:ja.source_table??null,sourceId:ja.source_id??null,metadata:ja.metadata??{},readAt:ja.read_at??null,createdAt:ja.created_at};$.setQueryData(NOTIFICATIONS_QUERY_KEY,Aa=>{const Oa=(Aa==null?void 0:Aa.items)??[];return Oa.some(Ia=>Ia.id===Na.id)?Aa??{items:Oa,unreadCount:0}:{items:[Na,...Oa].slice(0,20),unreadCount:((Aa==null?void 0:Aa.unreadCount)??0)+1}}),fireOsNotification(Na)}).subscribe()},50);return()=>{clearTimeout(cs),is&&supabase.removeChannel(is)}},[es==null?void 0:es.id,$]),null}async function fireOsNotification(es){if(typeof Notification>"u"||Notification.permission!=="granted")return;const $={body:es.body??void 0,icon:"/favicon-192.png",badge:"/favicon-48.png",tag:`notif-${es.id}`,data:{url:es.url??"/",notificationId:es.id}};if("serviceWorker"in navigator)try{await(await navigator.serviceWorker.ready).showNotification(es.title,$);return}catch{}new Notification(es.title,$)}function typeIcon(es){if(es.startsWith("usage_")){const $=es==="usage_imminent"||es==="usage_hit";return jsxRuntimeExports.jsx(TriangleAlert,{className:cn$1("h-3.5 w-3.5",$?"text-red-500":"text-amber-500")})}return es.endsWith("_failed")?jsxRuntimeExports.jsx(CircleAlert,{className:"h-3.5 w-3.5 text-red-500"}):es==="insights_ready"?jsxRuntimeExports.jsx(Sparkles,{className:"h-3.5 w-3.5 text-amber-500"}):es==="labels_needed"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-amber-500"}):es==="calibration_ready"?jsxRuntimeExports.jsx(BadgeCheck,{className:"h-3.5 w-3.5 text-teal-500"}):es==="second_engine_needed"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-blue-500"}):es==="second_opinions_flagged"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-amber-500"}):jsxRuntimeExports.jsx(BellRing,{className:"h-3.5 w-3.5 text-blue-500"})}function formatRelative(es){const $=Date.now()-new Date(es).getTime(),ts=Math.floor($/6e4);if(ts<1)return"just now";if(ts<60)return`${ts}m ago`;const is=Math.floor(ts/60);return is<24?`${is}h ago`:`${Math.floor(is/24)}d ago`}function NotificationBell(){const es=useNavigate(),{items:$,unreadCount:ts,markRead:is,markAllRead:cs}=useNotifications(),Qr=ja=>{ja.readAt||is(ja.id),ja.url&&es(ja.url)};return jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"relative cursor-pointer",children:[jsxRuntimeExports.jsx(Bell,{className:"h-4 w-4"}),ts>0&&jsxRuntimeExports.jsx("span",{className:"absolute top-1 right-1 inline-flex h-4 min-w-[1rem] items-center justify-center rounded-full bg-blue-500 px-1 text-[10px] font-medium text-white",children:ts>9?"9+":ts})]})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",className:"w-80",children:[jsxRuntimeExports.jsxs(DropdownMenuLabel,{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{children:"Notifications"}),ts>0&&jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(),className:"flex items-center gap-1 text-[10px] font-normal text-muted-foreground hover:text-foreground",children:[jsxRuntimeExports.jsx(CheckCheck,{className:"h-3 w-3"}),"Mark all read"]})]}),jsxRuntimeExports.jsx(DropdownMenuSeparator,{}),$.length===0?jsxRuntimeExports.jsx(DropdownMenuItem,{disabled:!0,children:jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"No notifications yet"})}):$.map(ja=>jsxRuntimeExports.jsx(DropdownMenuItem,{className:"cursor-pointer",onClick:()=>Qr(ja),children:jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 w-full",children:[jsxRuntimeExports.jsx("div",{className:"mt-0.5",children:typeIcon(ja.type)}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium truncate",children:ja.title}),ja.body&&jsxRuntimeExports.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:ja.body}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground",children:formatRelative(ja.createdAt)})]}),!ja.readAt&&jsxRuntimeExports.jsx("span",{className:"mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-blue-500"})]})},ja.id))]})]})}function OrgSwitcher(){return useActiveOrg(),useSetActiveOrg(),useNavigate(),null}function Header$1(){var is;const{user:es,signOut:$}=useAuth(),ts=((is=es==null?void 0:es.email)==null?void 0:is.slice(0,2).toUpperCase())??"?";return jsxRuntimeExports.jsxs("header",{className:"flex h-12 items-center border-b border-border px-2 gap-1 sm:px-4 sm:gap-4 bg-background",children:[jsxRuntimeExports.jsxs(Sheet,{children:[jsxRuntimeExports.jsx(SheetTrigger,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"md:hidden cursor-pointer",children:jsxRuntimeExports.jsx(Menu,{className:"h-5 w-5"})})}),jsxRuntimeExports.jsxs(SheetContent,{side:"left",className:"w-60 p-0",children:[jsxRuntimeExports.jsx(SheetTitle,{className:"sr-only",children:"Navigation"}),jsxRuntimeExports.jsx(Sidebar,{})]})]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsx(OrgSwitcher,{}),jsxRuntimeExports.jsx(NotificationBell,{}),jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"rounded-full cursor-pointer shrink-0",children:jsxRuntimeExports.jsx(Avatar,{className:"h-8 w-8",children:jsxRuntimeExports.jsx(AvatarFallback,{className:"text-xs bg-secondary text-muted-foreground",children:ts})})})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",children:[jsxRuntimeExports.jsxs(DropdownMenuItem,{disabled:!0,children:[jsxRuntimeExports.jsx(User,{className:"mr-2 h-4 w-4"}),es==null?void 0:es.email]}),jsxRuntimeExports.jsx(DropdownMenuSeparator,{}),jsxRuntimeExports.jsxs(DropdownMenuItem,{onClick:()=>$(),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4"}),"Sign out"]})]})]})]})}function useComputedInsights(es,$,ts){const is=(ts==null?void 0:ts.projectId)??void 0,cs=new URLSearchParams;return es&&cs.set("projectPath",es),is&&cs.set("projectId",is),$&&cs.set("tool",$),ts!=null&&ts.since&&cs.set("since",ts.since),useQuery({queryKey:["insights","computed",es,is??null,$,(ts==null?void 0:ts.since)??null],queryFn:()=>apiGet(`/api/insights/compute?${cs}`),refetchInterval:ts==null?void 0:ts.refetchIntervalMs})}function useInstructionImpact(es){return useQuery({queryKey:["insights","instruction-impact",es],queryFn:()=>apiGet(`/api/insights/instruction-impact?instructionId=${es}`),enabled:!!es})}function useGroomCandidates(){return useQuery({queryKey:["insights","groom-candidates"],queryFn:()=>apiGet("/api/insights/groom-candidates")})}function useRestoreInstruction(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/instructions/${$}/restore`,{}),onSuccess:()=>{es.invalidateQueries({queryKey:["insights","groom-candidates"]}),es.invalidateQueries({queryKey:["insights"]}),es.invalidateQueries({queryKey:["instructions"]}),es.invalidateQueries({queryKey:["instruction-suggestions"]})}})}function useArchiveInstruction(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/instructions/${$}`),onSuccess:()=>{es.invalidateQueries({queryKey:["insights","groom-candidates"]}),es.invalidateQueries({queryKey:["insights"]})}})}function useLinkedInstructions(es){const $=new URLSearchParams;return es&&$.set("projectPath",es),useQuery({queryKey:["insights","linked-instructions",es],queryFn:()=>apiGet(`/api/insights/linked-instructions?${$}`)})}function useInsightsProjects(){return useQuery({queryKey:["insights","projects"],queryFn:()=>apiGet("/api/insights/projects")})}function useInsightsJobs(es,$){const ts=new URLSearchParams;return es&&ts.set("projectPath",es),$&&ts.set("limit",String($)),useQuery({queryKey:["insights-jobs",es,$],queryFn:()=>apiGet(`/api/insights-jobs?${ts}`),refetchInterval:POLL.LIVE})}const STALE_JOB_MS=600*1e3;function useActiveInsightsJobs(es){const{data:$}=useInsightsJobs(es),ts=Date.now();return($??[]).filter(is=>{if(!["pending","claimed","running"].includes(is.status))return!1;const cs=is.claimedAt?new Date(is.claimedAt).getTime():0;return!cs||ts-cs<=STALE_JOB_MS})}function useCreateInsightsJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/insights-jobs",{projectPath:$}),onSuccess:()=>{es.invalidateQueries({queryKey:["insights-jobs"]})}})}function useRegenerateAllInsights(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/insights-jobs/regenerate-all",$!=null&&$.force?{force:!0}:{}),onSuccess:()=>{es.invalidateQueries({queryKey:["insights-jobs"]})}})}function useDismissRecommendation(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/insights/recommendations/dismiss",$),onSuccess:()=>{es.invalidateQueries({queryKey:["insights","computed"]})}})}function useAutoAddSuggestion(){return useMutation({mutationFn:es=>apiPost("/api/insights/auto-add",es)})}function useProjectInsights(es,$,ts,is){var Ya;const{data:cs}=useInsightsProjects(),Qr=$?cs==null?void 0:cs.find(el=>el.projectPath===$):void 0,ja=ts??(Qr==null?void 0:Qr.projectId)??void 0,{data:Na,isLoading:Aa}=useComputedInsights($,is,{projectId:ja}),Oa=$?(Qr==null?void 0:Qr.name)??$.split("/").filter(Boolean).slice(-2).join("/"):void 0,Ia=useActiveInsightsJobs($),{data:La}=useInsightsJobs($),Ba=useCreateInsightsJob(),Ma=Na??null,qa=(Ya=Ia[0])==null?void 0:Ya.progress,Fa=qa!=null&&qa.partial&&Object.keys(qa.partial).length>0?qa.partial:void 0,Ha=(Ma==null?void 0:Ma.recommendations)??Fa,Ka=(La??[]).filter(el=>el.status==="completed"&&el.completedAt).sort((el,tl)=>new Date(tl.completedAt).getTime()-new Date(el.completedAt).getTime())[0],Ga=(Na==null?void 0:Na.sessions_with_meta)??0,Va=Oa??"Live Insights",Ja=`Computed from ${Ga} enriched sessions`;return{data:Ma,recommendations:Ha,isLoading:Aa,fullProjectPath:$,title:Va,subtitle:Ja,lastCompletedJob:Ka,activeJobs:Ia,createJob:Ba}}function InsightsJobsListener(){const{user:es}=useAuth(),$=useQueryClient();return reactExports.useEffect(()=>{if(!(es!=null&&es.id))return;let ts=null;const is=setTimeout(()=>{ts=supabase.channel(`insights-jobs-${es.id}`).on("postgres_changes",{event:"UPDATE",schema:"public",table:"insights_jobs",filter:`user_id=eq.${es.id}`},cs=>{const Qr=cs.new,ja={id:Qr.id,status:Qr.status,projectPath:Qr.project_path??null,progress:Qr.progress??{},error:Qr.error??null,updatedAt:Qr.updated_at,completedAt:Qr.completed_at??null};$.setQueriesData({queryKey:["insights-jobs"]},Na=>{if(!Na)return Na;const Aa=Na.findIndex(Ia=>Ia.id===ja.id);if(Aa===-1)return Na;const Oa=Na.slice();return Oa[Aa]={...Na[Aa],...ja},Oa}),ja.status==="completed"&&$.invalidateQueries({queryKey:["insights","computed"]})}).subscribe()},50);return()=>{clearTimeout(is),ts&&supabase.removeChannel(ts)}},[es==null?void 0:es.id,$]),null}const SEVERITY_LABEL={soft:"soft warning",approaching:"approaching limit",imminent:"imminent limit",hit:"limit reached"};function formatTimeLeft(es,$){if(!es)return"soon";const ts=new Date(es).getTime()-$;if(ts<=0)return"now";const is=Math.round(ts/6e4);if(is<60)return`in ${is} min`;const cs=Math.floor(is/60),Qr=is%60;return Qr>0?`in ${cs}h ${Qr}m`:`in ${cs}h`}function formatAlertMessage(es,$,ts,is,cs=Date.now()){const Qr=formatTimeLeft(is,cs);if(es==="hit")return`Claude ${$} reached 100% — requests will fail. Resets ${Qr}.`;const ja=ts!=null?`${ts.toFixed(0)}%`:"limit";return`Claude ${$} at ${ja} — ${SEVERITY_LABEL[es]}. Resets ${Qr}.`}const ACTIVE_WINDOW_MS=600*1e3,POLL_MS=3e4,SEVERITY_STYLES={soft:"bg-yellow-100 border-yellow-300 text-yellow-900",approaching:"bg-amber-200 border-amber-400 text-amber-950",imminent:"bg-orange-300 border-orange-500 text-orange-950",hit:"bg-red-400 border-red-600 text-red-950"};function dismissKey$1(es){return`alert-dismissed:${es}`}function AlertBanner(){var Ba,Ma,qa;const{data:es}=useQuery({queryKey:["alerts-recent"],queryFn:()=>apiGet("/api/alerts/recent"),refetchInterval:POLL_MS,refetchOnWindowFocus:!0}),[,$]=reactExports.useState(0);reactExports.useEffect(()=>{const Fa=setInterval(()=>$(Ha=>Ha+1),6e4);return()=>clearInterval(Fa)},[]);const ts=(es==null?void 0:es.items)??[];reactExports.useEffect(()=>{if(typeof window>"u"||!es)return;const Fa=new Set(ts.map(Ha=>Ha.id));for(let Ha=localStorage.length-1;Ha>=0;Ha--){const Ka=localStorage.key(Ha);Ka!=null&&Ka.startsWith("alert-dismissed:")&&!Fa.has(Ka.slice(16))&&localStorage.removeItem(Ka)}},[es,ts]);const is=Date.now(),cs=ts.find(Fa=>!(is-new Date(Fa.lastDispatchedAt).getTime()>ACTIVE_WINDOW_MS||typeof window<"u"&&localStorage.getItem(dismissKey$1(Fa.id)))),[,Qr]=reactExports.useState(0);if(!cs)return null;const ja=cs.severity,Na=(Ba=cs.lastState)==null?void 0:Ba.usedPercentage,Aa=(Ma=cs.lastState)==null?void 0:Ma.resetsAt,[,,Oa]=cs.alertKey.split(":"),Ia=((qa=cs.lastState)==null?void 0:qa.message)??formatAlertMessage(ja,Oa,Na,Aa);function La(){typeof window<"u"&&localStorage.setItem(dismissKey$1(cs.id),"1"),Qr(Fa=>Fa+1)}return jsxRuntimeExports.jsxs("div",{role:ja==="hit"?"alert":"status",className:cn$1("flex items-center gap-3 border-b px-4 py-2 text-sm",SEVERITY_STYLES[ja]),children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 flex-shrink-0"}),jsxRuntimeExports.jsx("span",{className:"flex-1 font-mono",children:Ia}),jsxRuntimeExports.jsx("button",{type:"button",onClick:La,"aria-label":"Dismiss alert",className:"rounded p-1 hover:bg-black/10",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}function useLatestVersion(){return useQuery({queryKey:["cli-latest-version"],queryFn:()=>apiGet("/api/cli/latest-version"),staleTime:3600*1e3,refetchInterval:POLL.DAILY,refetchOnWindowFocus:!1})}function compareVersions(es,$){const ts=ja=>ja.split(".").map(Na=>Number.parseInt(Na,10)||0),is=ts(es),cs=ts($),Qr=Math.max(is.length,cs.length);for(let ja=0;ja<Qr;ja++){const Na=is[ja]??0,Aa=cs[ja]??0;if(Na<Aa)return-1;if(Na>Aa)return 1}return 0}function cliUpdateStatus(es,$){if(!$)return null;const ts=es.filter(cs=>typeof cs=="string"&&cs.length>0);if(ts.length===0)return null;const is=ts.reduce((cs,Qr)=>compareVersions(Qr,cs)>0?Qr:cs,ts[0]);return compareVersions($,is)<=0?null:{current:is,latest:$}}const CLI_WORKER_TYPES=new Set(["cli-worker","gateway","proxy"]);function dismissKey(es){return`cli-update-dismissed:${es}`}function CliUpdateBanner(){const{activeWorkers:es}=useWorkerStatus(),{data:$}=useLatestVersion(),[,ts]=reactExports.useState(0),is=cliUpdateStatus(es.filter(Qr=>CLI_WORKER_TYPES.has(Qr.workerType)).map(Qr=>Qr.clientVersion),$==null?void 0:$.latest);if(!is||typeof window<"u"&&localStorage.getItem(dismissKey(is.latest)))return null;function cs(){typeof window<"u"&&localStorage.setItem(dismissKey(is.latest),"1"),ts(Qr=>Qr+1)}return jsxRuntimeExports.jsxs("div",{role:"status",className:"flex items-center gap-3 border-b border-primary/20 bg-primary/5 px-4 py-2 text-sm text-foreground",children:[jsxRuntimeExports.jsx(CircleArrowUp,{className:"h-4 w-4 flex-shrink-0 text-primary"}),jsxRuntimeExports.jsxs("span",{className:"flex-1",children:["RuleMetric CLI ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:is.current})," →"," ",jsxRuntimeExports.jsx("span",{className:"font-mono font-semibold text-primary",children:is.latest})," available. Upgrade:"," ",jsxRuntimeExports.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:UPDATE_CLI_SHORT}),", then re-run"," ",jsxRuntimeExports.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:"rulemetric hooks install"})," ","to pick up new capture hooks."]}),jsxRuntimeExports.jsx("button",{type:"button",onClick:cs,"aria-label":"Dismiss CLI update notice",className:"flex h-9 w-9 flex-shrink-0 cursor-pointer items-center justify-center rounded hover:bg-secondary",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}function useWorkerHealth(){return useQuery({queryKey:["worker-health"],queryFn:()=>apiGet("/api/workers/health"),staleTime:6e4,refetchInterval:POLL.SLOW,refetchOnWindowFocus:!0})}const DISMISS_TTL_MS=1440*60*1e3;function conditionKey(es){return`${es.severity}:${es.headline}`}function dismissStorageKey(es){return`worker-health-dismissed:${es}`}function bannerFor(es){return!es||es.severity==="ok"?null:{severity:es.severity,headline:es.headline,hints:es.hints,key:conditionKey(es)}}function isDismissed(es,$=Date.now(),ts=DISMISS_TTL_MS){if(!es)return!1;const is=Number(es);if(!Number.isFinite(is)||is<=0)return!1;const cs=$-is;return cs<0?!1:cs<ts}function WorkerHealthBanner(){const{data:es}=useWorkerHealth(),[,$]=reactExports.useState(0),ts=bannerFor(es==null?void 0:es.verdict);if(!ts)return null;const is=dismissStorageKey(ts.key),cs=typeof window>"u"?null:localStorage.getItem(is);if(isDismissed(cs))return null;function Qr(){typeof window<"u"&&localStorage.setItem(is,String(Date.now())),$(Aa=>Aa+1)}const ja=ts.severity==="fail",Na=ja?CircleX:TriangleAlert;return jsxRuntimeExports.jsxs("div",{role:"alert","data-testid":"worker-health-banner","data-severity":ts.severity,className:"flex items-start gap-3 border-b px-4 py-2 text-sm text-foreground "+(ja?"border-destructive/30 bg-destructive/10":"border-amber-500/40 bg-amber-500/10"),children:[jsxRuntimeExports.jsx(Na,{className:"mt-0.5 h-4 w-4 flex-shrink-0 "+(ja?"text-destructive":"text-amber-500")}),jsxRuntimeExports.jsxs("div",{className:"flex-1 space-y-1",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:ts.headline}),ts.hints.map(Aa=>jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Aa},Aa))]}),jsxRuntimeExports.jsx("button",{type:"button",onClick:Qr,"aria-label":"Dismiss worker health notice",title:"Hidden for 24 hours — reappears if the problem persists",className:"flex h-9 w-9 flex-shrink-0 cursor-pointer items-center justify-center rounded hover:bg-secondary",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}const CORE_ORDER$1=["install","auth","hooks","worker"];function deriveSetupProgress(es){const $=Na=>Na?"detected":es.loading?"loading":"waiting",ts=es.authenticated?"detected":es.loading?"loading":"attention",is=es.cliEverConnected||es.anyCapturedSession||es.workerHeartbeat,cs={install:{id:"install",label:"Install the CLI",optional:!1,state:$(is),command:INSTALL_CLI,waitingFor:"first CLI connection",hint:"Requires Node. No Node? A standalone installer is coming — for now, install Node first."},auth:{id:"auth",label:"Authenticated",optional:!1,state:ts,waitingFor:"an active session"},hooks:{id:"hooks",label:"Hooks installed",optional:!1,state:$(es.anyCapturedSession),command:"rulemetric hooks install",waitingFor:"first captured session",hint:"Hooks capture your Claude Code sessions directly — no CA cert or proxy required. Optional: add the local proxy to also record the exact system prompt each model saw, capture your other AI tools (Copilot, Cursor, Codex), and track live cost & rate limits — which unlocks full cross-tool instruction-effectiveness analysis."},worker:{id:"worker",label:"Worker running",optional:!1,state:$(es.workerHeartbeat),command:"rulemetric service install --worker-only",waitingFor:"a worker heartbeat"},tmux:{id:"tmux",label:"Tmux available",optional:!0,state:$(es.hasActiveTmux),waitingFor:"a Claude Code session running inside tmux"},target:{id:"target",label:"First live target detected",optional:!0,state:$(es.hasAnyTarget),waitingFor:"your first terminal target"},judge:{id:"judge",label:"Judge validation engine",optional:!0,state:$(es.llmEngines!=null&&es.llmEngines.claude&&es.llmEngines.codex),command:"npm install -g @openai/codex",waitingFor:es.llmEngines==null?"a worker heartbeat reporting your installed engines":"a second LLM engine (claude + codex)",hint:"Optional — hand labels + one judge already give you calibrated verdicts. A second engine (e.g. the Codex CLI) unlocks cross-vendor judge validation: two vendors checking each other's blind spots."}},Qr=CORE_ORDER$1.every(Na=>cs[Na].state==="detected"),ja=Qr?null:CORE_ORDER$1.find(Na=>cs[Na].state!=="detected")??null;return{steps:cs,coreComplete:Qr,currentStepId:ja}}function useSetupProgress(es=3e4){var ja,Na,Aa,Oa,Ia;const{session:$}=useAuth(),ts=useQuery({queryKey:["setup-status",es],queryFn:()=>apiGet("/api/setup/status"),refetchInterval:es}),is=useQuery({queryKey:["terminal-targets","all",es],queryFn:()=>apiGet("/api/terminal-targets"),refetchInterval:es}),cs=ts.isLoading||is.isLoading,Qr=((ja=is.data)==null?void 0:ja.targets)??[];return deriveSetupProgress({loading:cs,authenticated:!!$,cliEverConnected:((Na=ts.data)==null?void 0:Na.cliEverConnected)??!1,anyCapturedSession:((Aa=ts.data)==null?void 0:Aa.anyCapturedSession)??!1,workerHeartbeat:((Oa=ts.data)==null?void 0:Oa.workerActive)??!1,hasActiveTmux:Qr.some(La=>La.kind==="tmux"&&La.status==="active"),hasAnyTarget:Qr.length>0,llmEngines:((Ia=ts.data)==null?void 0:Ia.llmEngines)??null})}function track(es,$){}const CORE_STEP_IDS=["install","auth","hooks","worker"],DISMISSED_KEY="rm.setupWalkthrough.dismissed";function readDismissed(){try{return sessionStorage.getItem(DISMISSED_KEY)==="1"}catch{return!1}}function writeDismissed(){try{sessionStorage.setItem(DISMISSED_KEY,"1")}catch{}}const SetupWalkthroughContext=reactExports.createContext(null);function SetupWalkthroughProvider({children:es}){const{session:$}=useAuth(),ts=!!$,is=useQueryClient(),{profile:cs,isLoading:Qr}=useActiveOrg(),[ja,Na]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState("welcome"),[Ia,La]=reactExports.useState(readDismissed),Ba=(cs==null?void 0:cs.setupCompletedAt)!=null,Ma=useSetupProgress(ja||!Ba?4e3:!1),qa=reactExports.useRef(!1),Fa=reactExports.useRef(null),Ha=reactExports.useRef(null),Ka=reactExports.useRef({}),Ga=reactExports.useRef(new Set),Va=reactExports.useRef(!1),Ja=reactExports.useCallback(()=>{Na(!0)},[]),Ya=reactExports.useCallback(()=>{writeDismissed(),La(!0),Na(!1)},[Aa]),el=reactExports.useCallback(rl=>{Oa(rl)},[]);reactExports.useEffect(()=>{ts&&(Ia||Qr||Ma.steps.install.state==="loading"||(cs==null?void 0:cs.setupCompletedAt)==null&&(Ma.coreComplete||Na(!0)))},[ts,Ia,Qr,cs==null?void 0:cs.setupCompletedAt,Ma.coreComplete,Ma.steps.install.state]),reactExports.useEffect(()=>{const rl=Fa.current;if(Fa.current=Ma.coreComplete,!!ts&&Ma.coreComplete&&!qa.current){if((cs==null?void 0:cs.setupCompletedAt)!=null){qa.current=!0;return}rl===!1&&(qa.current=!0,Va.current||(Va.current=!0),apiPatch("/api/profile",{setupCompletedAt:new Date().toISOString()}).then(()=>{is.invalidateQueries({queryKey:["profile"]})}).catch(()=>{}),Oa("payoff"))}},[ts,Ma.coreComplete,cs==null?void 0:cs.setupCompletedAt,is]),reactExports.useEffect(()=>{if(!ja)return;const rl=`${Aa}::${Ma.currentStepId??""}`;Ha.current!==rl&&(Ha.current=rl,Ma.currentStepId,void 0)},[ja,Aa,Ma.currentStepId]),reactExports.useEffect(()=>{const rl=Date.now();for(const cl of CORE_STEP_IDS){const dl=Ma.steps[cl].state;if(dl!=="loading")if(dl==="detected"){if(Ga.current.has(cl))continue;Ga.current.add(cl),Ka.current[cl]}else Ka.current[cl]==null&&(Ka.current[cl]=rl)}},[Ma.steps.install.state,Ma.steps.auth.state,Ma.steps.hooks.state,Ma.steps.worker.state]);const tl={open:ja,stage:Aa,progress:Ma,openModal:Ja,dismiss:Ya,goTo:el,authenticated:ts};return reactExports.createElement(SetupWalkthroughContext.Provider,{value:tl},es)}function useSetupWalkthrough(){const es=reactExports.useContext(SetupWalkthroughContext);if(!es)throw new Error("useSetupWalkthrough must be used within a SetupWalkthroughProvider");return es}function Dialog({...es}){return jsxRuntimeExports.jsx(Root$2,{"data-slot":"dialog",...es})}function DialogPortal({...es}){return jsxRuntimeExports.jsx(Portal,{"data-slot":"dialog-portal",...es})}function DialogOverlay({className:es,...$}){return jsxRuntimeExports.jsx(Overlay,{"data-slot":"dialog-overlay",className:cn$1("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",es),...$})}function DialogContent({className:es,children:$,showCloseButton:ts=!0,...is}){return jsxRuntimeExports.jsxs(DialogPortal,{"data-slot":"dialog-portal",children:[jsxRuntimeExports.jsx(DialogOverlay,{}),jsxRuntimeExports.jsxs(Content,{"data-slot":"dialog-content",className:cn$1("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 outline-none sm:max-w-lg",es),...is,children:[$,ts&&jsxRuntimeExports.jsxs(Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-2 right-2 flex size-8 items-center justify-center rounded-sm 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:[jsxRuntimeExports.jsx(X$1,{}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function DialogHeader({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"dialog-header",className:cn$1("flex flex-col gap-2 text-center sm:text-left",es),...$})}function DialogFooter({className:es,showCloseButton:$=!1,children:ts,...is}){return jsxRuntimeExports.jsxs("div",{"data-slot":"dialog-footer",className:cn$1("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",es),...is,children:[ts,$&&jsxRuntimeExports.jsx(Close,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"outline",children:"Close"})})]})}function DialogTitle({className:es,...$}){return jsxRuntimeExports.jsx(Title,{"data-slot":"dialog-title",className:cn$1("text-lg leading-none font-semibold",es),...$})}function DialogDescription({className:es,...$}){return jsxRuntimeExports.jsx(Description,{"data-slot":"dialog-description",className:cn$1("text-muted-foreground text-sm",es),...$})}function CopyButton$3({text:es}){const{copied:$,copy:ts}=useCopyToClipboard();return jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>ts(es),className:"cursor-pointer",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Check,{className:"mr-1 h-3 w-3"}),"Copied"]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Copy,{className:"mr-1 h-3 w-3"}),"Copy"]})})}const CC_SETUP_PROMPT=`Set up RuleMetric on this machine, agentically and transparently.
|
|
121
|
+
|
|
122
|
+
STEP 0 — install or UPGRADE the CLI first. The \`setup\` command requires
|
|
123
|
+
@rulemetric/cli 0.5.0+; older global installs do NOT have it, so always run:
|
|
124
|
+
${INSTALL_CLI_LATEST}
|
|
125
|
+
|
|
126
|
+
Then CONFIRM the command actually exists before doing anything else:
|
|
127
|
+
rulemetric --version (must be 0.5.0 or newer)
|
|
128
|
+
rulemetric setup --help (must print the plan/show/apply usage)
|
|
129
|
+
If \`setup\` is "not found", the upgrade didn't take (stale global install, PATH,
|
|
130
|
+
or npm prefix) — fix that and re-verify. Do NOT fabricate diffs or pretend to run
|
|
131
|
+
steps against a command that isn't there.
|
|
132
|
+
|
|
133
|
+
Then run \`rulemetric setup plan\` and show me everything it would install.
|
|
134
|
+
|
|
135
|
+
Then, for each step in order (install, auth, hooks, worker):
|
|
136
|
+
1. run \`rulemetric setup <step> --show\` and show me the exact diff,
|
|
137
|
+
2. ask me to confirm,
|
|
138
|
+
3. on yes, run \`rulemetric setup <step> --apply\`.
|
|
139
|
+
|
|
140
|
+
Finish by running \`rulemetric setup --json\` and report the final green/red
|
|
141
|
+
status. If any step fails, diagnose it from its output before continuing.`,CORE_ORDER=["install","auth","hooks","worker"];function stateBadge(es){switch(es){case"detected":return jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-400 border-teal-500/30",children:"Detected"});case"loading":return jsxRuntimeExports.jsx(Badge,{variant:"outline",children:"Checking…"});case"attention":return jsxRuntimeExports.jsx(Badge,{className:"bg-amber-500/15 text-amber-400 border-amber-500/30",children:"Action needed"});default:return jsxRuntimeExports.jsx(Badge,{variant:"outline",children:"Waiting"})}}function CoreSteps(){const{progress:es}=useSetupWalkthrough(),$=useQueryClient(),[ts,is]=reactExports.useState(!1),cs=es.currentStepId,Qr=CORE_ORDER.slice(1).find(Fa=>es.steps[Fa].state!=="detected")??cs,ja=ts&&cs==="install"?Qr:cs;reactExports.useEffect(()=>{cs!=="install"&&ts&&is(!1)},[cs,ts]);const Na=reactExports.useRef(ja),[Aa,Oa]=reactExports.useState(null);reactExports.useEffect(()=>{const Fa=Na.current;if(Na.current=ja,Fa==null||Fa===ja)return;const Ha=es.steps[Fa];if(Ha.state!=="detected")return;Oa({label:Ha.label});const Ka=setTimeout(()=>Oa(null),800);return()=>clearTimeout(Ka)},[ja,es.steps]);function Ia(){$.invalidateQueries({queryKey:["worker-status"]}),$.invalidateQueries({queryKey:["sessions"]}),$.invalidateQueries({queryKey:["terminal-targets"]})}if(es.coreComplete||ja==null)return null;const La=es.steps[ja],Ba=CORE_ORDER.indexOf(ja)+1,Ma=La.state==="attention",qa=La.state==="loading";return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Set me up with Claude Code"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste into Claude Code — it installs step by step, showing exactly what it writes and asking before each change."})]}),jsxRuntimeExports.jsx(CopyButton$3,{text:CC_SETUP_PROMPT})]})}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"h-px flex-1 bg-border"}),"or do it yourself",jsxRuntimeExports.jsx("span",{className:"h-px flex-1 bg-border"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5",children:CORE_ORDER.map(Fa=>{const Ha=es.steps[Fa],Ka=Ha.state==="detected",Ga=Fa===ja;return jsxRuntimeExports.jsx("span",{className:cn$1("h-2 w-2 rounded-full transition-colors",Ka?"bg-teal-500":Ga?"bg-primary ring-2 ring-primary/30":"bg-muted"),"aria-label":`${Ha.label}: ${Ha.state}`},Fa)})}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["Step ",Ba," of ",CORE_ORDER.length]})]}),Aa&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-400",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0"}),jsxRuntimeExports.jsxs("span",{className:"font-medium",children:[Aa.label," done"]})]}),jsxRuntimeExports.jsxs("div",{className:cn$1("rounded-lg border bg-background p-4 space-y-3",Ma?"border-amber-500/40":"border-border"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[qa?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 shrink-0 animate-spin text-muted-foreground"}):Ma?jsxRuntimeExports.jsx(CircleAlert,{className:"h-4 w-4 shrink-0 text-amber-400"}):jsxRuntimeExports.jsx(Hourglass,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium truncate",children:La.label})]}),stateBadge(La.state)]}),qa?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Checking current state…"]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[La.command&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"Run this"}),jsxRuntimeExports.jsx(CopyButton$3,{text:La.command})]}),jsxRuntimeExports.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-[#0B1120] p-3 text-xs font-mono whitespace-pre-wrap",children:La.command})]}),La.waitingFor&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Waiting for ",La.waitingFor,"…"]}),La.hint&&jsxRuntimeExports.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground/80",children:La.hint}),Ma&&!La.command&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400",children:"Sign in to continue capturing sessions."})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center justify-end pt-1",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[ja==="install"&&jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>is(!0),className:"cursor-pointer text-muted-foreground",children:"I've installed it →"}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:Ia,className:"cursor-pointer",children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-1 h-3 w-3"}),"Check again"]})]})})]})]})}const CURRENT_LIMITS_POLL_MS=15e3;function useCurrentLimits(es="anthropic"){return useQuery({queryKey:["usage","current-limits",es],queryFn:()=>apiGet(`/api/usage/current-limits?provider=${encodeURIComponent(es)}`),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",refetchOnReconnect:"always",refetchInterval:CURRENT_LIMITS_POLL_MS})}function useInferredCaps(){return useQuery({queryKey:["usage","inferred-caps"],queryFn:()=>apiGet("/api/usage/inferred-caps"),staleTime:5*6e4})}function assessLimitWindow(es){const{usedPercentage:$,resetsAt:ts,now:is}=es;if($==null||!Number.isFinite($))return{kind:"never-observed"};if(ts==null)return{kind:"current",usedPercentage:$};const cs=Date.parse(ts);if(!Number.isFinite(cs))return{kind:"current",usedPercentage:$};const Qr=is.getTime()-cs;return Qr>=0?{kind:"expired",lastPercentage:$,endedMsAgo:Qr}:{kind:"current",usedPercentage:$}}function formatElapsed(es){const $=Math.floor(Math.max(0,es)/6e4);if($<60)return`${$}m`;const ts=Math.floor($/60);return ts<48?`${ts}h`:`${Math.floor(ts/24)}d`}const PLAN_OPTIONS=[{code:"free",label:"Free"},{code:"pro",label:"Pro"},{code:"max_5x",label:"Max 5x"},{code:"max_20x",label:"Max 20x"}],PLAN_LABEL=Object.fromEntries(PLAN_OPTIONS.map(es=>[es.code,es.label]));function planLabel$1(es){return PLAN_LABEL[es]??es}function startOfMonthIso$1(){const es=new Date;return new Date(es.getFullYear(),es.getMonth(),1).toISOString()}function formatUsd$1(es){return es>=1e3?`$${(es/1e3).toFixed(2)}K`:es>=1?`$${es.toFixed(2)}`:es>0?`$${es.toFixed(3)}`:"$0.00"}function Payoff(){const{goTo:es}=useSetupWalkthrough(),$=useCurrentLimits(),ts=useInferredCaps(),is=useComputedInsights(void 0,void 0,{since:startOfMonthIso$1(),refetchIntervalMs:3e4});return jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold",children:[jsxRuntimeExports.jsx(PartyPopper,{className:"h-5 w-5 text-primary"}),"You're capturing! 🎉"]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"RuleMetric is now watching your Claude Code sessions. Here's your usage so far."})]}),jsxRuntimeExports.jsx(UsageSummary,{limits:$,insights:is}),jsxRuntimeExports.jsx(PlanDetection,{caps:ts}),jsxRuntimeExports.jsx("div",{className:"flex justify-end pt-1",children:jsxRuntimeExports.jsx(Button,{onClick:()=>es("livesend"),children:"Continue"})})]})}function UsageSummary({limits:es,insights:$}){var Ma,qa,Fa,Ha,Ka,Ga,Va;if(es.isLoading&&!es.data||$.isLoading&&!$.data)return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border bg-muted/30 px-4 py-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}),"Checking your usage…"]});const is=((Ma=es.data)==null?void 0:Ma.five_hour)??null,cs=((qa=es.data)==null?void 0:qa.seven_day)??null,Qr=((Fa=es.data)==null?void 0:Fa.seven_day_opus)??null,ja=is!=null||cs!=null||Qr!=null,Na=(Ha=$.data)==null?void 0:Ha.estimated_cost_usd,Aa=((Ka=$.data)==null?void 0:Ka.total_input_tokens)??0,Oa=((Ga=$.data)==null?void 0:Ga.total_output_tokens)??0,Ia=(Va=$.data)==null?void 0:Va.estimated_cost_by_model,La=typeof Na=="number"&&Na>0||Aa>0||Oa>0;if(!ja&&!La)return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-dashed border-primary/40 bg-primary/5 px-4 py-6 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"relative flex h-3 w-3 shrink-0",children:[jsxRuntimeExports.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-primary/60"}),jsxRuntimeExports.jsx("span",{className:"relative inline-flex h-3 w-3 rounded-full bg-primary"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-0.5",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:"Watching for your first session…"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Run Claude Code and this fills in automatically."})]})]});const Ba=Ia?Object.entries(Ia).sort(([,Ja],[,Ya])=>Ya.cost_usd-Ja.cost_usd):[];return jsxRuntimeExports.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-background p-4",children:[ja&&jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Rate limits"}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs font-mono",children:[jsxRuntimeExports.jsx(LimitChip,{label:"5h",obs:is}),jsxRuntimeExports.jsx(LimitChip,{label:"7d",obs:cs}),jsxRuntimeExports.jsx(LimitChip,{label:"7d Opus",obs:Qr})]})]}),La&&jsxRuntimeExports.jsxs("div",{className:cn$1("space-y-1.5",ja&&"border-t border-border pt-3"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Cost this month"}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-lg",children:[jsxRuntimeExports.jsx("span",{className:"mr-1 text-muted-foreground",children:"≈"}),formatUsd$1(Na??0)]})]}),Ba.length>0&&jsxRuntimeExports.jsx("div",{className:"space-y-1",children:Ba.slice(0,3).map(([Ja,Ya])=>{const el=Na&&Na>0?Math.round(Ya.cost_usd/Na*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"truncate max-w-[60%] font-mono text-muted-foreground",children:Ja}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd$1(Ya.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"w-8 text-right text-muted-foreground",children:[el,"%"]})]})]},Ja)})})]})]})}function LimitChip({label:es,obs:$}){const ts=assessLimitWindow({usedPercentage:($==null?void 0:$.used_percentage)??null,resetsAt:($==null?void 0:$.resets_at)??null,now:new Date});return ts.kind!=="current"?jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[es," ",jsxRuntimeExports.jsx("span",{className:"opacity-60",children:"—"})]}):jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:es})," ",jsxRuntimeExports.jsxs("span",{className:"font-semibold",children:[Math.round(ts.usedPercentage),"%"]})]})}function PlanDetection({caps:es}){var Oa,Ia;const $=useQueryClient(),[ts,is]=reactExports.useState(!1),[cs,Qr]=reactExports.useState(null),ja=useMutation({mutationFn:La=>apiPatch("/api/profile",{claudeCodePlan:La}),onError:()=>{Qr(null)},onSuccess:()=>{$.invalidateQueries({queryKey:["usage","inferred-caps"]}),$.invalidateQueries({queryKey:["profile"]}),is(!1)}});if(es.isLoading&&!es.data)return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}),"Detecting your plan…"]});const Na=((Oa=es.data)==null?void 0:Oa.plan)??"max_20x",Aa=((Ia=es.data)==null?void 0:Ia.assumed)??!0;return!Aa&&!ts?jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-teal-500/30 bg-teal-500/5 px-4 py-3 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 text-teal-400"}),"Detected your plan:"," ",jsxRuntimeExports.jsx("span",{className:"font-semibold",children:planLabel$1(Na)})]}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>is(!0),className:"text-xs text-primary underline-offset-2 hover:underline",children:"not right? change"})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-background p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[jsxRuntimeExports.jsx(Radar,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Which Claude Code plan are you on?"})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick yours so your limits are accurate."}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-2 pt-1",role:"radiogroup","aria-label":"Claude Code plan",children:PLAN_OPTIONS.map(La=>{const Ba=cs===La.code||!Aa&&La.code===Na,Ma=ja.isPending&&ja.variables===La.code;return jsxRuntimeExports.jsxs(Button,{role:"radio","aria-checked":Ba,variant:Ba?"default":"outline",size:"sm",disabled:Ma,onClick:()=>{Qr(La.code),ja.mutate(La.code)},children:[Ma&&jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-3 w-3 animate-spin"}),Ba&&!Ma&&jsxRuntimeExports.jsx(Check,{className:"mr-1 h-3 w-3"}),La.label]},La.code)})}),ja.isError&&jsxRuntimeExports.jsx("p",{className:"text-xs text-destructive",role:"alert",children:"Couldn't save your plan — please try again."})]})}function LivesendEpilogue(){const{progress:es,goTo:$}=useSetupWalkthrough(),ts=useQueryClient(),is=es.steps.tmux,cs=es.steps.target,Qr=is.state==="detected"&&cs.state==="detected",ja=useMutation({mutationFn:()=>apiPatch("/api/profile",{liveSendSkipped:!0}),onSettled:()=>{ts.invalidateQueries({queryKey:["profile"]}),$("labeling")}});return jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold",children:[jsxRuntimeExports.jsx(Send,{className:"h-5 w-5 text-primary"}),"Control sessions from the browser?"]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Want to control sessions from the browser? This needs tmux. With it, RuleMetric can detect your running Claude Code sessions as live targets and send prompts to them straight from the dashboard — no terminal switching."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-background p-4",children:[jsxRuntimeExports.jsx(OptionalStepRow,{step:is}),jsxRuntimeExports.jsx(OptionalStepRow,{step:cs})]}),Qr?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-2 text-sm text-teal-400",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0"}),"Live-send is ready — you can drive sessions from the dashboard."]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx(Button,{onClick:()=>$("labeling"),children:"Continue"})})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center justify-end gap-2",children:jsxRuntimeExports.jsxs(Button,{onClick:()=>ja.mutate(),disabled:ja.isPending,children:[ja.isPending&&jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-3 w-3 animate-spin"}),"Skip for now"]})}),jsxRuntimeExports.jsxs("p",{className:"text-right text-xs text-muted-foreground",children:["You can enable this anytime from"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"/connect"}),"."]})]})]})}function optionalIcon(es){switch(es){case"detected":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-teal-400"});case"loading":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 shrink-0 animate-spin text-muted-foreground"});default:return jsxRuntimeExports.jsx(Hourglass,{className:"h-4 w-4 shrink-0 text-muted-foreground"})}}function OptionalStepRow({step:es}){const $=es.state==="detected";return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[optionalIcon(es.state),jsxRuntimeExports.jsx("span",{className:cn$1("text-sm font-medium truncate",$?"text-foreground":"text-muted-foreground"),children:es.label})]}),$?jsxRuntimeExports.jsx("span",{className:"shrink-0 text-xs text-teal-400",children:"Detected"}):jsxRuntimeExports.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:es.state==="loading"?"Checking…":`Waiting for ${es.waitingFor}`})]})}function LabelingEpilogue(){const{progress:es,goTo:$,dismiss:ts}=useSetupWalkthrough(),is=useNavigate(),cs=es.steps.judge;function Qr(){ts(),is("/eval-targets")}return jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold",children:[jsxRuntimeExports.jsx(ClipboardCheck,{className:"h-5 w-5 text-primary"}),'Teach the judge what "good" means']}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["RuleMetric grades your agent's outputs with an LLM judge — but only ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"your hand labels"})," can prove the judge is trustworthy. Review a few graded outputs (approve/reject, keyboard-fast) on any eval target's Review tab and you unlock calibrated verdicts. We'll notify you whenever outputs are waiting for review."]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-background p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[stateIcon(cs.state),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium truncate",children:cs.label})]}),cs.state==="detected"?jsxRuntimeExports.jsx("span",{className:"shrink-0 text-xs text-teal-400",children:"Detected"}):jsxRuntimeExports.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:cs.state==="loading"?"Checking…":`Waiting for ${cs.waitingFor}`})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:cs.hint}),cs.state!=="detected"&&cs.command&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Recommended:"," ",jsxRuntimeExports.jsx("span",{className:"font-mono text-foreground",children:cs.command})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",onClick:()=>$("done"),children:"Skip for now"}),jsxRuntimeExports.jsx(Button,{onClick:Qr,children:"Show me labeling"})]}),jsxRuntimeExports.jsx("p",{className:"text-right text-xs text-muted-foreground",children:"The bell will remind you when graded outputs need review."})]})]})}function stateIcon(es){switch(es){case"detected":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-teal-400"});case"loading":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 shrink-0 animate-spin text-muted-foreground"});default:return jsxRuntimeExports.jsx(Hourglass,{className:"h-4 w-4 shrink-0 text-muted-foreground"})}}function SetupWalkthroughModal(){const{open:es,stage:$,authenticated:ts,dismiss:is,goTo:cs}=useSetupWalkthrough();return!ts||!es?null:jsxRuntimeExports.jsx(Dialog,{open:!0,onOpenChange:Qr=>{Qr||is()},children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-lg",children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsxs(DialogTitle,{className:"flex items-center gap-2 pr-6",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-4 w-4 text-primary"}),"Get set up with RuleMetric"]}),jsxRuntimeExports.jsx(DialogDescription,{children:"A quick walkthrough to connect Claude Code and start seeing your usage and cost."})]}),jsxRuntimeExports.jsx("div",{className:"py-2",children:jsxRuntimeExports.jsx(StageBody,{stage:$,onStart:()=>cs("core"),dismiss:is})}),$!=="done"&&jsxRuntimeExports.jsx(DialogFooter,{className:"sm:justify-between",children:jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:is,className:"text-muted-foreground",children:"I'll finish later"})})]})})}function StageBody({stage:es,onStart:$,dismiss:ts}){switch(es){case"welcome":return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"In a couple of minutes you'll have RuleMetric watching your Claude Code sessions — tracking real token usage, cost, and which instructions actually help."}),jsxRuntimeExports.jsx(Button,{onClick:$,className:"w-full sm:w-auto",children:"Let's get set up"})]});case"core":return jsxRuntimeExports.jsx(CoreSteps,{});case"payoff":return jsxRuntimeExports.jsx(Payoff,{});case"livesend":return jsxRuntimeExports.jsx(LivesendEpilogue,{});case"labeling":return jsxRuntimeExports.jsx(LabelingEpilogue,{});case"done":return jsxRuntimeExports.jsx(Done,{dismiss:ts})}}function Done({dismiss:es}){const $=useNavigate();function ts(){es(),$("/usage")}return jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-5 w-5 text-teal-400"}),"You're all set ✓"]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"RuleMetric is capturing your Claude Code sessions — head to the usage page to watch your real token spend and cost roll in."})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",onClick:es,children:"Done"}),jsxRuntimeExports.jsx(Button,{onClick:ts,children:"View usage"})]})]})}function RootLayout({children:es}={}){return jsxRuntimeExports.jsx(SetupWalkthroughProvider,{children:jsxRuntimeExports.jsxs("div",{className:"flex h-screen",children:[jsxRuntimeExports.jsx(NotificationsListener,{}),jsxRuntimeExports.jsx(InsightsJobsListener,{}),jsxRuntimeExports.jsx(Sidebar,{className:"hidden md:flex"}),jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:[jsxRuntimeExports.jsx(Header$1,{}),jsxRuntimeExports.jsx(AlertBanner,{}),jsxRuntimeExports.jsx(WorkerHealthBanner,{}),jsxRuntimeExports.jsx(CliUpdateBanner,{}),jsxRuntimeExports.jsx("main",{className:"min-w-0 flex-1 overflow-y-auto p-4 md:p-6",children:es??jsxRuntimeExports.jsx(Outlet,{})})]}),jsxRuntimeExports.jsx(SetupWalkthroughModal,{})]})})}const steps=[{icon:CircleDot,title:"Observe the baseline",text:"Session trends show where to investigate. They are observational signals, not proof that an instruction caused an outcome."},{icon:FlaskConical,title:"Hold the setup fixed",text:"Compare a prepared change using the same harness, model, tasks, and grading approach."},{icon:Gauge,title:"Inspect the tradeoffs",text:"Read quality alongside actor and grader cost, latency, sample size, uncertainty, and missing prices."},{icon:GitCompareArrows,title:"Keep what earns trust",text:"A small positive result is a reason to gather more evidence—not a guarantee that the change generalizes."}];function LandingPage(){return reactExports.useEffect(()=>{var es;document.title="Measure agent instruction changes | RuleMetric",(es=document.querySelector('meta[name="description"]'))==null||es.setAttribute("content","Compare prompt, rule, and memory changes inside the harnesses and models you already use.")},[]),jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx("nav",{className:"sticky top-0 z-50 border-b border-border bg-background/90 backdrop-blur",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto flex h-14 max-w-6xl items-center justify-between px-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"font-mono text-sm font-semibold",children:[jsxRuntimeExports.jsx("span",{className:"mr-2 text-primary",children:"●"}),"RuleMetric"]}),jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-1 sm:gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",className:"hidden sm:inline-flex",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/login",children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/signup",children:[jsxRuntimeExports.jsx("span",{className:"sm:hidden",children:"Start measuring"}),jsxRuntimeExports.jsx("span",{className:"hidden sm:inline",children:"Measure your first change"})]})})]})]})}),jsxRuntimeExports.jsxs("main",{children:[jsxRuntimeExports.jsx("section",{className:"px-4 py-24",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto grid max-w-6xl items-center gap-12 lg:grid-cols-[1.1fr_.9fr]",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"max-w-3xl text-4xl font-bold leading-tight lg:text-6xl",children:"Your agent instructions changed. Did your results improve?"}),jsxRuntimeExports.jsx("p",{className:"mt-6 max-w-2xl text-lg leading-8 text-muted-foreground",children:"RuleMetric measures prompt, rule, and memory changes inside the harnesses and models you already use. Compare quality, cost, and latency before deciding what to keep."}),jsxRuntimeExports.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[jsxRuntimeExports.jsx(Button,{size:"lg",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/signup",children:["Measure your first change",jsxRuntimeExports.jsx(ArrowRight,{className:"ml-2 h-4 w-4"})]})}),jsxRuntimeExports.jsx(Button,{size:"lg",variant:"outline",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/play/token-triage",children:"Play the instruction challenge"})})]})]}),jsxRuntimeExports.jsxs("aside",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between border-b border-border pb-3 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:"Evidence example"}),jsxRuntimeExports.jsx("span",{className:"rounded-full border border-primary/30 px-2 py-1 text-xs text-primary",children:"Illustrative"})]}),jsxRuntimeExports.jsxs("div",{className:"py-7",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Prepared variant versus baseline"}),jsxRuntimeExports.jsx("p",{className:"mt-2 font-mono text-3xl",children:"+4.2 quality points"}),jsxRuntimeExports.jsx("div",{className:"mt-5 h-2 rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full w-[58%] rounded-full bg-primary"})})]}),jsxRuntimeExports.jsxs("dl",{className:"mt-5 grid grid-cols-2 gap-4 border-t border-border pt-4 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{className:"text-muted-foreground",children:"Tasks"}),jsxRuntimeExports.jsx("dd",{className:"font-mono",children:"24 per variant"})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{className:"text-muted-foreground",children:"95% interval"}),jsxRuntimeExports.jsx("dd",{className:"font-mono",children:"−1.1 to +9.5"})]})]}),jsxRuntimeExports.jsx("p",{className:"mt-5 text-xs leading-5 text-muted-foreground",children:"Illustrative data, not a customer result. The interval crosses zero, so this example is insufficient evidence to call the change an improvement."})]})]})}),jsxRuntimeExports.jsx("section",{className:"border-y border-border bg-card/50 px-4 py-20",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-bold",children:"Instructions accumulate. Evidence should too."}),jsxRuntimeExports.jsx("p",{className:"mt-4 max-w-2xl text-muted-foreground",children:"Separate clues in normal sessions from controlled comparisons designed to answer whether a particular change helped."}),jsxRuntimeExports.jsx("div",{className:"mt-10 grid gap-px overflow-hidden rounded-lg border border-border bg-border md:grid-cols-2",children:steps.map(({icon:es,title:$,text:ts})=>jsxRuntimeExports.jsxs("article",{className:"bg-background p-7",children:[jsxRuntimeExports.jsx(es,{className:"h-5 w-5 text-primary"}),jsxRuntimeExports.jsx("h3",{className:"mt-5 text-lg font-semibold",children:$}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:ts})]},$))})]})}),jsxRuntimeExports.jsx("section",{className:"px-4 py-20",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto flex max-w-6xl flex-col justify-between gap-8 rounded-lg border border-border bg-card p-8 md:flex-row md:items-center",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold",children:"Does your agent memory actually help?"}),jsxRuntimeExports.jsx("p",{className:"mt-2 max-w-xl text-muted-foreground",children:"Presence, absence, and formatting are different questions. Learn how to frame a useful comparison."})]}),jsxRuntimeExports.jsx(Button,{variant:"outline",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/agent-memory",children:"Explore memory measurement"})})]})}),jsxRuntimeExports.jsx("section",{className:"border-t border-border px-4 py-20",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto grid max-w-6xl gap-10 md:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold",children:"Works with the harness you already run"}),jsxRuntimeExports.jsx("p",{className:"mt-4 leading-7 text-muted-foreground",children:"RuleMetric captures sessions from supported Claude Code, Cursor, and Copilot integrations. Controlled eval work can run through configured Claude, Codex, or Pi-compatible paths; support depends on the selected worker, provider, and workload."})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"Start with the setup you can verify"}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"The setup guide documents hooks, proxy capture, workers, local mode, measurement costs, and current limitations."}),jsxRuntimeExports.jsxs("div",{className:"mt-5 flex flex-wrap gap-4 text-sm",children:[jsxRuntimeExports.jsx(Link,{className:"text-primary underline-offset-4 hover:underline",to:"/docs",children:"Read setup and support docs"}),jsxRuntimeExports.jsx(Link,{className:"text-primary underline-offset-4 hover:underline",to:"/login",children:"Sign in"})]})]})]})})]}),jsxRuntimeExports.jsx("footer",{className:"border-t border-border px-4 py-8",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto flex max-w-6xl justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{children:"RuleMetric"}),jsxRuntimeExports.jsx("span",{children:"Measure changes before you trust them."})]})})]})}function AgentMemoryPage(){return reactExports.useEffect(()=>{var es;document.title="Does your agent memory actually help? | RuleMetric",(es=document.querySelector('meta[name="description"]'))==null||es.setAttribute("content","Measure agent memory presence, absence, and prepared formatting variants with controlled comparisons.")},[]),jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx("header",{className:"border-b border-border",children:jsxRuntimeExports.jsxs("nav",{className:"mx-auto flex h-14 max-w-5xl items-center justify-between px-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"font-mono font-semibold",children:[jsxRuntimeExports.jsx("span",{className:"mr-2 text-primary",children:"●"}),"RuleMetric"]}),jsxRuntimeExports.jsx(Link,{to:"/play/token-triage",className:"text-sm text-primary",children:"Play Token Triage"})]})}),jsxRuntimeExports.jsxs("main",{className:"mx-auto max-w-5xl px-4 py-16",children:[jsxRuntimeExports.jsx("h1",{className:"max-w-3xl text-4xl font-bold lg:text-5xl",children:"Does your agent memory actually help?"}),jsxRuntimeExports.jsx("p",{className:"mt-6 max-w-3xl text-lg leading-8 text-muted-foreground",children:"Memory being present is not the same as memory improving a task. Compare outcomes with the harness and model held fixed, then inspect quality, actor and grader cost, latency, and uncertainty together."}),jsxRuntimeExports.jsxs("div",{className:"mt-12 grid gap-5 md:grid-cols-3",children:[jsxRuntimeExports.jsxs("article",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-lg font-semibold",children:"Presence versus absence"}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"Prepare tasks that reveal whether memory adds useful context. Session trends can suggest a question, but controlled trials provide stronger evidence."})]}),jsxRuntimeExports.jsxs("article",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-lg font-semibold",children:"Formatting experiments"}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"Prepare each formatting variant yourself, then compare it under the same setup. RuleMetric does not automatically invent arbitrary A/B formats."})]}),jsxRuntimeExports.jsxs("article",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-lg font-semibold",children:"Insufficient evidence"}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"Missing prices, wide intervals, few tasks, or conflicting metrics should stay visible. A small positive result is not proof."})]})]}),jsxRuntimeExports.jsxs("section",{className:"mt-12 rounded-lg border border-primary/30 bg-primary/5 p-7",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-semibold",children:"Optimize instructions and harnesses—not model weights."}),jsxRuntimeExports.jsx("p",{className:"mt-3 max-w-3xl text-muted-foreground",children:"Background trials are bounded and require configured eval targets, compatible workers, and enablement. They are not free and do not guarantee an improvement."}),jsxRuntimeExports.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/signup",children:"Measure your first change"})}),jsxRuntimeExports.jsx(Button,{variant:"outline",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/docs",children:"Read measurement documentation"})})]})]})]})]})}function ChecklistCapture(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(!1),[cs,Qr]=reactExports.useState("idle"),[ja,Na]=reactExports.useState("");async function Aa(Oa){Oa==null||Oa.preventDefault(),Qr("loading"),Na("");try{const Ia=await fetch("/api/marketing/leads",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({email:es,marketingConsent:ts,source:"token-triage"})}),La=await Ia.json();if(!Ia.ok)throw new Error(La.error||"The request could not be saved. Try again.");Qr("success")}catch(Ia){Na(Ia instanceof Error?Ia.message:"The request could not be saved. Try again."),Qr("error")}}return cs==="success"?jsxRuntimeExports.jsxs("section",{className:"min-w-0 rounded-lg border border-primary/30 bg-primary/5 p-6","aria-live":"polite",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:"Your checklist is ready"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Open it now and use it with any instruction file."}),jsxRuntimeExports.jsx(Button,{asChild:!0,className:"mt-4",children:jsxRuntimeExports.jsx(Link,{to:"/instruction-audit",children:"Open the checklist"})})]}):jsxRuntimeExports.jsxs("section",{className:"min-w-0 rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:"Get the instruction-audit checklist"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"The checklist is available immediately. Email is used to record this request."}),jsxRuntimeExports.jsxs("form",{className:"mt-5 space-y-4",onSubmit:Aa,children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("label",{htmlFor:"checklist-email",className:"mb-1 block text-sm",children:"Email"}),jsxRuntimeExports.jsx("input",{id:"checklist-email",required:!0,type:"email",value:es,onChange:Oa=>$(Oa.target.value),className:"w-full rounded-md border border-input bg-background px-3 py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),jsxRuntimeExports.jsxs("label",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",className:"mt-1",checked:ts,onChange:Oa=>is(Oa.target.checked)}),jsxRuntimeExports.jsx("span",{children:"Send me occasional RuleMetric product updates. Optional."})]}),cs==="error"&&jsxRuntimeExports.jsx("div",{role:"alert",className:"text-sm text-destructive",children:ja}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:cs==="loading",children:cs==="loading"?"Requesting…":cs==="error"?"Retry":"Get the checklist"})]}),jsxRuntimeExports.jsx(Link,{className:"mt-4 inline-block text-sm text-primary underline-offset-4 hover:underline",to:"/instruction-audit",children:"Skip the form and open the checklist"})]})}const GAME_VERSION=1,STORAGE_KEY="rulemetric:token-triage:v1",scenarios=[{task:"Return a JSON object with the answer and cite the source line.",budget:200,cards:[{id:"tone",title:"Friendly voice",text:"Use a warm, conversational tone.",tokens:44,compressedTokens:18,compressedText:"Be friendly."},{id:"format",title:"Output contract",text:"Return valid JSON with answer and source_line keys.",tokens:32,compressedTokens:13,compressedText:"Return JSON with the answer.",required:!0,compressionLoses:!0},{id:"scope",title:"Evidence boundary",text:"Use only the supplied file and cite its exact line.",tokens:40,compressedTokens:17,compressedText:"Use supplied evidence; cite line.",required:!0}]},{task:"Fix the defect without changing the public API.",budget:82,cards:[{id:"tone",title:"Narrate first",text:"Explain your entire thought process before editing.",tokens:38,compressedTokens:14,compressedText:"Explain first."},{id:"format",title:"Compatibility",text:"Preserve exported names and argument shapes.",tokens:42,compressedTokens:17,compressedText:"Keep the public API.",required:!0},{id:"scope",title:"Verification",text:"Run the focused regression test after the edit.",tokens:35,compressedTokens:15,compressedText:"Run focused test.",required:!0}]},{task:"Summarize a customer incident without exposing personal data.",budget:74,cards:[{id:"tone",title:"Decorative opener",text:"Begin with an imaginative metaphor.",tokens:31,compressedTokens:12,compressedText:"Use a metaphor."},{id:"format",title:"Privacy rule",text:"Remove names, emails, tokens, and account identifiers.",tokens:39,compressedTokens:16,compressedText:"Remove names and emails.",required:!0,compressionLoses:!0},{id:"scope",title:"Incident shape",text:"State impact, timeline, cause, and follow-up.",tokens:34,compressedTokens:14,compressedText:"Give incident essentials.",required:!0}]},{task:"Review a migration and report only release-blocking risks.",budget:66,cards:[{id:"tone",title:"Praise the author",text:"Open with two sentences of encouragement.",tokens:29,compressedTokens:10,compressedText:"Be encouraging."},{id:"format",title:"Severity filter",text:"Report only data-loss, outage, or rollback blockers.",tokens:36,compressedTokens:15,compressedText:"Only release blockers.",required:!0},{id:"scope",title:"Evidence",text:"Give the affected statement and concrete failure mode.",tokens:37,compressedTokens:16,compressedText:"Cite statement and failure.",required:!0}]},{task:"Prepare a safe deployment decision from incomplete evidence.",budget:58,cards:[{id:"tone",title:"Sound confident",text:"Avoid uncertain language and make a firm claim.",tokens:27,compressedTokens:9,compressedText:"Be confident."},{id:"format",title:"Decision gate",text:"Return go only when tests and rollback checks pass.",tokens:34,compressedTokens:14,compressedText:"Return go when checks pass.",required:!0,compressionLoses:!0},{id:"scope",title:"Unknowns",text:"List missing evidence and return no-go when unresolved.",tokens:33,compressedTokens:13,compressedText:"Unknowns mean no-go.",required:!0}]}];function utcDailySeed(es=new Date){return es.toISOString().slice(0,10)}function getChallengeId(es=utcDailySeed()){return`v${GAME_VERSION}-${es}`}function scenarioForRound(es,$){const ts=Math.max(0,Math.min(scenarios.length-1,$)),is=[...es].reduce((ja,Na)=>ja*31+Na.charCodeAt(0)>>>0,0),cs=scenarios[ts].cards.map(ja=>({...ja})),Qr=is%cs.length;return{...scenarios[ts],id:`${es}-r${$+1}`,cards:[...cs.slice(Qr),...cs.slice(0,Qr)]}}function createGame(es=utcDailySeed()){return{version:GAME_VERSION,challengeId:getChallengeId(es),round:0,completedRounds:0,failures:0,score:0,status:"playing",lastResult:null}}function restartGame(es){const $=es.challengeId.replace(/^v\d+-/,"");return createGame($)}function applyRound(es,$){if(es.status!=="playing")return es;const ts=scenarioForRound(es.challengeId,es.round),is=ts.cards.reduce((Ha,Ka)=>{const Ga=$[Ka.id]??"discard";return Ha+(Ga==="keep"?Ka.tokens:Ga==="compress"?Ka.compressedTokens:0)},0),cs=ts.cards.filter(Ha=>Ha.required),Qr=cs.filter(Ha=>{const Ka=$[Ha.id]??"discard";return Ka==="discard"||Ka==="compress"&&Ha.compressionLoses}),ja=Qr.length===0,Na=is<=ts.budget,Aa=ja&&Na,Oa=Aa?Math.max(1,Math.min(200,ts.budget-is)):0,Ia=es.failures+(Aa?0:1),La=es.completedRounds+1,Ba=Ia>=2?"failed":La>=5?"complete":"playing",Ma=cs.map(Ha=>Ha.title).join(" and "),qa=Qr.map(Ha=>($[Ha.id]??"discard")==="compress"?`${Ha.title} became “${Ha.compressedText}” and lost the required detail “${Ha.text}”`:`${Ha.title} was discarded, removing “${Ha.text}”`).join("; "),Fa=Aa?`${Ma} protected the task with ${ts.budget-is} tokens to spare.`:ja?`${Ma} protected the requirements, but the context used ${is} tokens—${is-ts.budget} above the ${ts.budget}-token budget.`:`${qa}.`;return{...es,round:Math.min(4,es.round+1),completedRounds:La,failures:Ia,score:es.score+Oa,status:Ba,lastResult:{passed:Aa,score:Oa,usedTokens:is,explanation:Fa}}}function loadGame(es,$=utcDailySeed()){var is,cs,Qr,ja,Na,Aa,Oa;const ts=createGame($);if(!es)return ts;try{const Ia=JSON.parse(es),La=Ia.lastResult===null||typeof Ia.lastResult=="object"&&typeof Ia.lastResult.passed=="boolean"&&Number.isInteger(Ia.lastResult.score)&&Ia.lastResult.score>=0&&Ia.lastResult.score<=200&&Number.isInteger(Ia.lastResult.usedTokens)&&Ia.lastResult.usedTokens>=0&&Ia.lastResult.usedTokens<=1e3&&typeof Ia.lastResult.explanation=="string"&&Ia.lastResult.explanation.length>0&&Ia.lastResult.explanation.length<=1e3&&(Ia.lastResult.passed?Ia.lastResult.score>0:Ia.lastResult.score===0);if(Ia.version!==GAME_VERSION||Ia.challengeId!==ts.challengeId||!Number.isInteger(Ia.round)||!Number.isInteger(Ia.failures)||!Number.isInteger(Ia.completedRounds)||typeof Ia.score!="number"||!Number.isInteger(Ia.score)||Ia.score<0||Ia.score>1e3||!["playing","failed","complete"].includes(Ia.status??"")||!La)return ts;const Ba=Ia.completedRounds-Ia.failures,Ma=scenarioForRound(ts.challengeId,Math.max(0,Ia.completedRounds-1)),qa=(is=Ia.lastResult)!=null&&is.passed?Math.max(1,Math.min(200,Ma.budget-Ia.lastResult.usedTokens)):0;return(Ia.round??-1)<0||(Ia.round??6)>4||(Ia.failures??-1)<0||(Ia.failures??3)>2||(Ia.completedRounds??-1)<0||(Ia.completedRounds??6)>5||Ia.round!==Math.min(Ia.completedRounds??-1,4)||(Ia.failures??3)>(Ia.completedRounds??-1)||Ia.score>(Ia.completedRounds??0)*200||Ia.score>Ba*200||Ia.score<(((cs=Ia.lastResult)==null?void 0:cs.score)??0)||Ia.completedRounds===1&&Ia.score!==((Qr=Ia.lastResult)==null?void 0:Qr.score)||((ja=Ia.lastResult)==null?void 0:ja.passed)===!1&&Ia.failures===0||Ia.failures===0&&Ia.completedRounds>0&&((Na=Ia.lastResult)==null?void 0:Na.passed)!==!0||((Aa=Ia.lastResult)==null?void 0:Aa.passed)===!0&&Ia.lastResult.usedTokens>Ma.budget||Ia.lastResult!==null&&((Oa=Ia.lastResult)==null?void 0:Oa.score)!==qa||(Ia.completedRounds===0?Ia.lastResult!==null:Ia.lastResult==null)||Ia.status!==((Ia.failures??0)>=2?"failed":(Ia.completedRounds??0)>=5?"complete":"playing")?ts:{...ts,...Ia}}catch{return ts}}function Header(){return jsxRuntimeExports.jsx("header",{className:"border-b border-border",children:jsxRuntimeExports.jsxs("nav",{"aria-label":"Public",className:"mx-auto flex h-14 max-w-6xl items-center justify-between px-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"font-mono font-semibold",children:[jsxRuntimeExports.jsx("span",{className:"mr-2 text-primary",children:"●"}),"RuleMetric"]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-4 text-sm",children:[jsxRuntimeExports.jsx(Link,{to:"/agent-memory",children:"Agent memory"}),jsxRuntimeExports.jsx(Link,{to:"/signup",className:"text-primary",children:"Sign up"})]})]})})}function TokenTriagePage(){const[es,$]=reactExports.useState(()=>{const Ka=typeof location>"u"?null:new URLSearchParams(location.search).get("challenge"),Ga=Ka==null?void 0:Ka.match(/^v1-(\d{4}-\d{2}-\d{2})$/);if(Ga)return createGame(Ga[1]);try{return typeof localStorage>"u"?createGame():loadGame(localStorage.getItem(STORAGE_KEY))}catch{return createGame()}}),[ts,is]=reactExports.useState({}),[cs,Qr]=reactExports.useState(!1),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),Ia=reactExports.useMemo(()=>scenarioForRound(es.challengeId,es.round),[es.challengeId,es.round]),La=Ia.cards.reduce((Ka,Ga)=>Ka+(ts[Ga.id]==="keep"?Ga.tokens:ts[Ga.id]==="compress"?Ga.compressedTokens:0),0);reactExports.useEffect(()=>{var Ka;document.title="Token Triage | RuleMetric",(Ka=document.querySelector('meta[name="description"]'))==null||Ka.setAttribute("content","A simulated instruction challenge: protect task requirements while working within a context budget.")},[]),reactExports.useEffect(()=>{try{localStorage.setItem(STORAGE_KEY,JSON.stringify(es))}catch{}},[es]);function Ba(Ka,Ga){is(Va=>({...Va,[Ka]:Ga}))}function Ma(){$(Ka=>applyRound(Ka,ts)),Qr(!0)}function qa(){is({}),Qr(!1)}function Fa(){$(Ka=>restartGame(Ka)),is({}),Qr(!1)}async function Ha(){Na(""),Oa("");const Ka=`${location.origin}/play/token-triage?challenge=${encodeURIComponent(es.challengeId)}`,Ga=`I scored ${es.score} in Token Triage. Beat the same simulated challenge: ${Ka}`;try{typeof navigator.share=="function"?await navigator.share({title:"Token Triage",text:Ga,url:Ka}):await navigator.clipboard.writeText(Ga),Na(typeof navigator.share=="function"?"Challenge shared.":"Challenge copied.")}catch(Va){(Va==null?void 0:Va.name)!=="AbortError"&&(Na("Sharing is unavailable. Copy this challenge link manually:"),Oa(Ka))}}return jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx(Header,{}),jsxRuntimeExports.jsxs("main",{className:"mx-auto max-w-4xl px-4 py-12",children:[jsxRuntimeExports.jsxs("div",{className:"mb-8 flex flex-wrap items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-primary",children:"Simulated challenge · no live model calls"}),jsxRuntimeExports.jsx("h1",{className:"mt-2 text-4xl font-bold",children:"Token Triage"}),jsxRuntimeExports.jsx("p",{className:"mt-3 max-w-2xl text-muted-foreground",children:"Keep task-critical meaning while spending less of the context window. Compression is useful—until it deletes the detail that makes an instruction work."})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-card px-4 py-3 font-mono text-sm",children:["Round ",Math.min(es.completedRounds+1,5)," / 5",jsxRuntimeExports.jsx("br",{}),"Score ",es.score," · Strikes ",es.failures,"/2"]})]}),cs&&es.lastResult?jsxRuntimeExports.jsxs("section",{className:`rounded-lg border p-6 ${es.lastResult.passed?"border-primary/40 bg-primary/5":"border-destructive/40 bg-destructive/5"}`,children:[jsxRuntimeExports.jsxs("p",{role:"status",className:"font-semibold",children:[es.lastResult.passed?"Task protected.":"Regression introduced."," ",es.lastResult.explanation]}),jsxRuntimeExports.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Round score: ",es.lastResult.score,". Correctness is evaluated before efficiency."]}),jsxRuntimeExports.jsx(Button,{className:"mt-4",onClick:qa,children:es.status==="playing"?"Next round":"See final result"})]}):es.status!=="playing"?jsxRuntimeExports.jsxs("section",{className:"rounded-lg border border-border bg-card p-8 text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-bold",children:es.status==="failed"?"Run ended":"Five rounds complete"}),jsxRuntimeExports.jsxs("p",{className:"mt-3 text-muted-foreground",children:["Final simulated score: ",es.score,". Game results are not evidence about a real harness."]}),jsxRuntimeExports.jsxs("div",{className:"mt-6 flex justify-center gap-3",children:[jsxRuntimeExports.jsx(Button,{onClick:Fa,children:"Restart"}),jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:Ha,children:"Share challenge"})]}),jsxRuntimeExports.jsxs("p",{role:"status",className:"mt-3 text-sm",children:[ja,Aa&&jsxRuntimeExports.jsx("a",{"aria-label":"Copy this challenge link manually",className:"mt-2 block break-all text-primary underline underline-offset-4",href:Aa,children:Aa})]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("section",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:Ia.task}),jsxRuntimeExports.jsxs("div",{className:"mt-5",children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex justify-between font-mono text-sm",children:[jsxRuntimeExports.jsx("span",{children:"Context meter"}),jsxRuntimeExports.jsxs("span",{children:[La," / ",Ia.budget," tokens"]})]}),jsxRuntimeExports.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-muted",role:"meter","aria-label":"Context used","aria-valuemin":0,"aria-valuemax":Ia.budget,"aria-valuenow":Math.min(La,Ia.budget),"aria-valuetext":`${La} of ${Ia.budget} tokens${La>Ia.budget?`, ${La-Ia.budget} over budget`:""}`,children:jsxRuntimeExports.jsx("div",{className:`h-full transition-[width] motion-reduce:transition-none ${La>Ia.budget?"bg-destructive":"bg-primary"}`,style:{width:`${Math.min(100,La/Ia.budget*100)}%`}})})]})]}),jsxRuntimeExports.jsxs("div",{className:"mt-5 space-y-4",children:[Ia.cards.map(Ka=>jsxRuntimeExports.jsxs("fieldset",{className:"rounded-lg border border-border bg-card p-5",children:[jsxRuntimeExports.jsx("legend",{className:"px-1 font-mono font-semibold",children:Ka.title}),jsxRuntimeExports.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:Ka.text}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-3 gap-2",children:["keep","compress","discard"].map(Ga=>jsxRuntimeExports.jsxs("label",{className:`rounded-md border p-3 text-center text-sm capitalize focus-within:ring-2 focus-within:ring-ring ${ts[Ka.id]===Ga?"border-primary bg-primary/10":"border-border"}`,children:[jsxRuntimeExports.jsx("input",{className:"sr-only",type:"radio",name:Ka.id,"aria-label":`${Ga} ${Ka.title}`,checked:ts[Ka.id]===Ga,onChange:()=>Ba(Ka.id,Ga)}),Ga,jsxRuntimeExports.jsxs("span",{className:"block text-xs text-muted-foreground",children:[Ga==="keep"?Ka.tokens:Ga==="compress"?Ka.compressedTokens:0," ","tokens"]}),Ga==="compress"&&jsxRuntimeExports.jsxs("span",{className:"mt-1 block text-[11px] normal-case text-muted-foreground",children:["“",Ka.compressedText,"”"]})]},Ga))})]},Ka.id)),jsxRuntimeExports.jsx(Button,{className:"w-full",disabled:Ia.cards.some(Ka=>!ts[Ka.id]),onClick:Ma,children:"Run instruction set"})]})]}),es.status!=="playing"&&!cs&&jsxRuntimeExports.jsxs("div",{className:"mt-10 grid min-w-0 gap-6 md:grid-cols-2",children:[jsxRuntimeExports.jsx("div",{className:"min-w-0",children:jsxRuntimeExports.jsx(ChecklistCapture,{})}),jsxRuntimeExports.jsxs("section",{className:"min-w-0 rounded-lg border border-border p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:"That was a simulation."}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Test your real instructions with the harness and model held fixed."}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"mt-4 h-auto max-w-full whitespace-normal text-center",children:jsxRuntimeExports.jsx(Link,{to:"/signup",children:"Test real instructions with RuleMetric"})})]})]})]})]})}const checks=["Name the task outcome the instruction should change.","Record the harness, model, task set, grader, and versions.","Prepare one change at a time when practical.","Track quality, actor cost, grader cost, latency, and missing prices.","Keep observational trends separate from controlled trial evidence.","Check sample size and uncertainty before calling a winner.","Document failure modes and preserve a rollback path.","Repeat on representative tasks before generalizing."];function InstructionAuditPage(){return reactExports.useEffect(()=>{var es;document.title="Instruction-audit checklist | RuleMetric",(es=document.querySelector('meta[name="description"]'))==null||es.setAttribute("content","A practical checklist for evaluating agent instruction changes with evidence.")},[]),jsxRuntimeExports.jsx("div",{className:"min-h-screen bg-background text-foreground",children:jsxRuntimeExports.jsxs("main",{className:"mx-auto max-w-3xl px-4 py-16",children:[jsxRuntimeExports.jsx(Link,{to:"/",className:"font-mono text-sm text-primary",children:"← RuleMetric"}),jsxRuntimeExports.jsx("p",{className:"mt-12 text-sm text-primary",children:"Accessible now · no email required"}),jsxRuntimeExports.jsx("h1",{className:"mt-2 text-4xl font-bold",children:"Instruction-audit checklist"}),jsxRuntimeExports.jsx("p",{className:"mt-4 text-muted-foreground",children:"Use this before deciding that a prompt, rule, or memory change improved your agent."}),jsxRuntimeExports.jsx("ol",{className:"mt-10 space-y-3",children:checks.map((es,$)=>jsxRuntimeExports.jsxs("li",{className:"flex gap-4 rounded-lg border border-border bg-card p-4",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-primary",children:$+1}),jsxRuntimeExports.jsx("span",{children:es})]},es))}),jsxRuntimeExports.jsx("p",{className:"mt-8 text-sm text-muted-foreground",children:"This checklist structures an evaluation; it does not turn a simulated score or a small positive result into proof."})]})})}const REDIRECT_DECISION_TIMEOUT_MS=2500;async function getPostAuthRedirect(){try{return(await api("/api/sessions?summary=exists",{timeoutMs:REDIRECT_DECISION_TIMEOUT_MS})).exists?"/sessions":"/connect"}catch{return"/sessions"}}function useSocialAuthProviders(){const[es,$]=reactExports.useState([]),[ts,is]=reactExports.useState(!0);return reactExports.useEffect(()=>{const cs=new AbortController;return fetchEnabledSocialAuthProviders(cs.signal).then($).finally(()=>{cs.signal.aborted||is(!1)}),()=>cs.abort()},[]),{providers:es,loading:ts}}function GoogleIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",className:"h-4 w-4",children:[jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M21.6 12.2c0-.7-.1-1.4-.2-2.1H12v4h5.4a4.6 4.6 0 0 1-2 3v2.6h3.3c1.9-1.8 2.9-4.4 2.9-7.5Z"}),jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M12 22c2.7 0 5-.9 6.7-2.3l-3.3-2.6c-.9.6-2.1 1-3.4 1a5.9 5.9 0 0 1-5.5-4.1H3.1v2.7A10 10 0 0 0 12 22Z",opacity:".8"}),jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M6.5 14a6 6 0 0 1 0-3.9V7.4H3.1a10 10 0 0 0 0 9.3L6.5 14Z",opacity:".6"}),jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M12 6.1c1.5 0 2.8.5 3.9 1.5l2.9-2.9A9.8 9.8 0 0 0 3.1 7.4l3.4 2.7A5.9 5.9 0 0 1 12 6.1Z",opacity:".9"})]})}function OAuthButtons({next:es}){const{signInWithProvider:$}=useAuth(),{providers:ts,loading:is}=useSocialAuthProviders(),[cs,Qr]=reactExports.useState(null),[ja,Na]=reactExports.useState(null);if(is)return jsxRuntimeExports.jsx("div",{className:"h-20 animate-pulse rounded-md bg-muted/40","aria-label":"Loading social sign-in options"});if(ts.length===0)return null;async function Aa(Oa){Na(null),Qr(Oa);try{await $(Oa,es)}catch(Ia){Na(Ia instanceof Error?Ia.message:"Social sign-in failed"),Qr(null)}}return jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative py-1",children:[jsxRuntimeExports.jsx("div",{className:"absolute inset-0 flex items-center","aria-hidden":"true",children:jsxRuntimeExports.jsx("div",{className:"w-full border-t border-border"})}),jsxRuntimeExports.jsx("div",{className:"relative flex justify-center",children:jsxRuntimeExports.jsx("span",{className:"bg-card px-2 text-xs text-muted-foreground",children:"or continue with"})})]}),ja&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:ja}),jsxRuntimeExports.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:SOCIAL_AUTH_PROVIDERS.filter(({id:Oa})=>ts.includes(Oa)).map(({id:Oa,label:Ia})=>jsxRuntimeExports.jsxs(Button,{type:"button",variant:"outline",disabled:cs!==null,onClick:()=>void Aa(Oa),"aria-label":`Continue with ${Ia}`,children:[Oa==="github"?jsxRuntimeExports.jsx(Github,{className:"h-4 w-4"}):jsxRuntimeExports.jsx(GoogleIcon,{}),cs===Oa?"Redirecting...":Ia]},Oa))})]})}function Input({className:es,type:$,...ts}){return jsxRuntimeExports.jsx("input",{type:$,"data-slot":"input",className:cn$1("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input 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",es),...ts})}function Label({className:es,...$}){return jsxRuntimeExports.jsx(Root$3,{"data-slot":"label",className:cn$1("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",es),...$})}function LoginPage(){const{signIn:es}=useAuth(),$=useNavigate(),[ts]=useSearchParams(),[is,cs]=reactExports.useState(""),[Qr,ja]=reactExports.useState(""),[Na,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(!1);async function La(qa){qa.preventDefault(),Aa(""),Ia(!0);try{await es(is,Qr);const Fa=safeNext(ts.get("next"));if(Fa){$(Fa,{replace:!0});return}const Ha=await getPostAuthRedirect();$(Ha)}catch(Fa){Aa(Fa instanceof Error?Fa.message:"Login failed")}finally{Ia(!1)}}const Ba=safeNext(ts.get("next")),Ma=Ba?`/signup?next=${encodeURIComponent(Ba)}`:"/signup";return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono mt-2",children:"Sign in"}),jsxRuntimeExports.jsx(CardDescription,{children:"Enter your credentials to continue"})]}),jsxRuntimeExports.jsxs("form",{onSubmit:La,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Na&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:Na}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"email",type:"email",value:is,onChange:qa=>cs(qa.target.value),required:!0,autoComplete:"email",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"password",children:"Password"}),jsxRuntimeExports.jsx(Link,{to:"/forgot-password",className:"text-sm font-medium text-muted-foreground hover:text-primary transition-colors",children:"Forgot password?"})]}),jsxRuntimeExports.jsx(Input,{id:"password",type:"password",value:Qr,onChange:qa=>ja(qa.target.value),required:!0,autoComplete:"current-password",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsxs(CardFooter,{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90 mt-8",disabled:Oa,children:Oa?"Signing in...":"Sign in"}),jsxRuntimeExports.jsx(OAuthButtons,{next:Ba}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Don't have an account?"," ",jsxRuntimeExports.jsx(Link,{to:Ma,className:"text-primary underline",children:"Sign up"})]})]})]})]})})}function SignupPage(){const{signUp:es}=useAuth(),$=useNavigate(),[ts]=useSearchParams(),is=safeNext(ts.get("next")),cs=is?`/login?next=${encodeURIComponent(is)}`:"/login",[Qr,ja]=reactExports.useState(""),[Na,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(""),[La,Ba]=reactExports.useState(""),[Ma,qa]=reactExports.useState(!1),[Fa,Ha]=reactExports.useState(!1),[Ka,Ga]=reactExports.useState(!1);async function Va(Ja){if(Ja.preventDefault(),Ba(""),qa(!1),Na!==Oa){Ba("Passwords do not match");return}if(Na.length<6){Ba("Password must be at least 6 characters");return}Ga(!0);try{const{needsConfirmation:Ya,alreadyRegistered:el}=await es(Qr,Na,is??void 0);if(el){qa(!0);return}if(Ya){Ha(!0);return}if(is){$(is,{replace:!0});return}const tl=await getPostAuthRedirect();$(tl,{replace:!0})}catch(Ya){Ba(Ya instanceof Error?Ya.message:"Signup failed")}finally{Ga(!1)}}return Fa?jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Check your email"}),jsxRuntimeExports.jsxs(CardDescription,{children:["We sent a confirmation link to ",jsxRuntimeExports.jsx("strong",{children:Qr}),". Click it to activate your account."]})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Link,{to:cs,className:"text-primary underline text-sm",children:"Back to login"})})]})}):jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Sign up"}),jsxRuntimeExports.jsx(CardDescription,{children:"Create a new account"})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Va,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[La&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:La}),Ma&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm",children:[jsxRuntimeExports.jsx("p",{className:"text-foreground",children:"An account with this email already exists."}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-muted-foreground",children:[jsxRuntimeExports.jsx(Link,{to:cs,className:"text-primary underline",children:"Sign in"})," ","instead, or"," ",jsxRuntimeExports.jsx(Link,{to:"/forgot-password",className:"text-primary underline",children:"reset your password"})," ","if you've forgotten it."]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"email",type:"email",value:Qr,onChange:Ja=>ja(Ja.target.value),required:!0,autoComplete:"email",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"password",children:"Password"}),jsxRuntimeExports.jsx(Input,{id:"password",type:"password",value:Na,onChange:Ja=>Aa(Ja.target.value),required:!0,minLength:6,autoComplete:"new-password",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"confirm-password",children:"Confirm password"}),jsxRuntimeExports.jsx(Input,{id:"confirm-password",type:"password",value:Oa,onChange:Ja=>Ia(Ja.target.value),required:!0,autoComplete:"new-password",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsxs(CardFooter,{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",disabled:Ka,children:Ka?"Creating account...":"Sign up"}),jsxRuntimeExports.jsx(OAuthButtons,{next:is}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Already have an account?"," ",jsxRuntimeExports.jsx(Link,{to:cs,className:"text-primary underline",children:"Sign in"})]})]})]})]})})}function ConfirmPage(){const es=useNavigate(),[$]=useSearchParams(),{session:ts,loading:is}=useAuth(),[cs,Qr]=reactExports.useState(null);return reactExports.useEffect(()=>{const ja=oauthCallbackError(window.location.hash);if(ja){Qr(ja);return}if(is)return;if(ts){const Aa=window.location.hash;if(Aa.includes("type=recovery")||Aa.includes("type=invite")){es("/reset-password",{replace:!0});return}const Oa=safeNext($.get("next"));Oa?es(Oa,{replace:!0}):getPostAuthRedirect().then(Ia=>{es(Ia,{replace:!0})});return}const Na=window.location.hash;(!Na||!Na.includes("access_token"))&&Qr("Invalid confirmation link")},[ts,is,es,$]),jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),cs?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Confirmation failed"}),jsxRuntimeExports.jsx(CardDescription,{children:cs})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Confirming..."}),jsxRuntimeExports.jsx(CardDescription,{children:"Verifying your email address"})]})]}),cs&&jsxRuntimeExports.jsxs(CardContent,{className:"flex gap-4 text-sm",children:[jsxRuntimeExports.jsx(Link,{className:"text-primary hover:underline",to:"/login",children:"Try signing in again"}),jsxRuntimeExports.jsx(Link,{className:"text-muted-foreground hover:underline",to:"/signup",children:"Create an account"})]})]})})}const ALLOWED_EDITOR_SCHEMES=new Set(["vscode","vscode-insiders","cursor","windsurf"]),ALLOWED_EXTENSION_IDS=new Set(["rulemetric.rulemetric-vscode"]),mintedNonces=new Set;function ExtensionAuthPage(){const{session:es,loading:$}=useAuth(),[ts]=useSearchParams(),is=ts.get("editor")??"",cs=ts.get("extension_id")??"",Qr=ts.get("nonce")??"",[ja,Na]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(!1),[Ia,La]=reactExports.useState(null),Ba=ALLOWED_EDITOR_SCHEMES.has(is)&&ALLOWED_EXTENSION_IDS.has(cs)&&/^[A-Za-z0-9_-]{8,128}$/.test(Qr);if(reactExports.useEffect(()=>{var Ma;if(!$&&es){if(!Ba){Na("Invalid sign-in request — missing or malformed editor/extension/nonce parameters.");return}mintedNonces.has(Qr)||(mintedNonces.add(Qr),apiPost("/api/auth/extension/code",{email:((Ma=es.user)==null?void 0:Ma.email)??null,editor:is}).then(({code:qa})=>{const Fa=`${is}://${cs}/auth?nonce=${encodeURIComponent(Qr)}&code=${encodeURIComponent(qa)}`;La(Fa),window.location.href=Fa,Oa(!0)}).catch(qa=>{mintedNonces.delete(Qr),Na(qa instanceof Error?qa.message:"Failed to mint auth code")}))}},[$,es,is,cs,Qr,Ba]),$)return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center",children:jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Loading…"})});if(!es){const Ma=ts.toString(),qa=`/auth/extension${Ma?`?${Ma}`:""}`;return jsxRuntimeExports.jsx(Navigate,{to:`/login?next=${encodeURIComponent(qa)}`,replace:!0})}return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-md border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{children:"Connecting to your editor…"}),jsxRuntimeExports.jsx(CardDescription,{children:ja?"Something went wrong":Aa?"We've handed off to your editor. You can close this tab.":"Generating a one-time sign-in code."})]}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:ja?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:ja}):Aa&&Ia?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"If your editor didn't open automatically, click below."}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"default",children:jsxRuntimeExports.jsx("a",{href:Ia,children:"Open in editor"})})]}):null})]})})}function ForgotPasswordPage(){const{resetPassword:es}=useAuth(),[$,ts]=reactExports.useState(""),[is,cs]=reactExports.useState(""),[Qr,ja]=reactExports.useState(!1),[Na,Aa]=reactExports.useState(!1);async function Oa(Ia){Ia.preventDefault(),cs(""),Aa(!0);try{await es($),ja(!0)}catch(La){cs(La instanceof Error?La.message:"Failed to send reset email")}finally{Aa(!1)}}return Qr?jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Check your email"}),jsxRuntimeExports.jsxs(CardDescription,{children:["We sent a password reset link to ",jsxRuntimeExports.jsx("strong",{children:$}),"."]})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Link,{to:"/login",className:"text-primary underline text-sm",children:"Back to login"})})]})}):jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Reset password"}),jsxRuntimeExports.jsx(CardDescription,{children:"Enter your email and we'll send you a reset link"})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Oa,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[is&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:is}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"email",type:"email",value:$,onChange:Ia=>ts(Ia.target.value),required:!0,autoComplete:"email",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsxs(CardFooter,{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",disabled:Na,children:Na?"Sending...":"Send reset link"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Remember your password?"," ",jsxRuntimeExports.jsx(Link,{to:"/login",className:"text-primary underline",children:"Sign in"})]})]})]})]})})}const verifyPromises=new Map;function ResetPasswordPage(){const{updatePassword:es,session:$,loading:ts}=useAuth(),is=useNavigate(),[cs,Qr]=reactExports.useState(""),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),[Ia,La]=reactExports.useState(!1),[Ba,Ma]=reactExports.useState(()=>{const Ka=new URLSearchParams(window.location.search);return!!(Ka.get("token_hash")&&Ka.get("type"))}),[qa,Fa]=reactExports.useState(null);if(reactExports.useEffect(()=>{const Ka=new URLSearchParams(window.location.search),Ga=Ka.get("token_hash"),Va=Ka.get("type");if(!Ga||!Va)return;let Ja=!1,Ya=verifyPromises.get(Ga);return Ya||(Ya=supabase.auth.verifyOtp({token_hash:Ga,type:Va}),verifyPromises.set(Ga,Ya)),Ya.then(({error:el})=>{Ja||(el&&Fa(el.message||"This reset link is invalid or has expired."),window.history.replaceState({},"","/reset-password"),Ma(!1))}),()=>{Ja=!0}},[]),Ba||ts)return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsx(Card,{className:"w-full max-w-sm border-border bg-card",children:jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Verifying..."}),jsxRuntimeExports.jsx(CardDescription,{children:"Checking your reset link"})]})})});if(qa||!$)return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Invalid or expired link"}),jsxRuntimeExports.jsx(CardDescription,{children:qa??"This password reset link is no longer valid. Please request a new one."})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Link,{to:"/forgot-password",className:"text-primary underline text-sm",children:"Request new reset link"})})]})});async function Ha(Ka){if(Ka.preventDefault(),Oa(""),cs!==ja){Oa("Passwords do not match");return}if(cs.length<6){Oa("Password must be at least 6 characters");return}La(!0);try{await es(cs),is("/sessions",{replace:!0})}catch(Ga){Oa(Ga instanceof Error?Ga.message:"Failed to update password")}finally{La(!1)}}return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Set password"}),jsxRuntimeExports.jsx(CardDescription,{children:"Secure your account with a strong password"})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Ha,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Aa&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:Aa}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"password",children:"Password"}),jsxRuntimeExports.jsx(Input,{id:"password",type:"password",value:cs,onChange:Ka=>Qr(Ka.target.value),required:!0,minLength:6,autoComplete:"new-password",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"confirm-password",children:"Confirm password"}),jsxRuntimeExports.jsx(Input,{id:"confirm-password",type:"password",value:ja,onChange:Ka=>Na(Ka.target.value),required:!0,autoComplete:"new-password",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",disabled:Ia,children:Ia?"Saving...":"Save password"})})]})]})})}function useInstructions(){return useQuery({queryKey:["instructions"],queryFn:()=>apiGet("/api/instructions")})}function useSessions(es={}){const $=new URLSearchParams;es.tool&&$.set("tool",es.tool),es.outcome&&$.set("outcome",es.outcome),es.friction&&$.set("friction",es.friction),es.instructionId&&$.set("instructionId",es.instructionId),es.hasAnalysis&&$.set("hasAnalysis","true"),es.projectPath&&$.set("projectPath",es.projectPath),es.projectId&&$.set("projectId",es.projectId),es.limit&&$.set("limit",String(es.limit)),es.hideEmpty===!1&&$.set("hideEmpty","false");const ts=$.toString();return useQuery({queryKey:["sessions",es],queryFn:()=>apiGet(`/api/sessions${ts?`?${ts}`:""}`),refetchInterval:POLL.LIVE})}function useSessionCount(es={}){const $=new URLSearchParams({summary:"count"});return es.tool&&$.set("tool",es.tool),es.projectPath&&$.set("projectPath",es.projectPath),es.projectId&&$.set("projectId",es.projectId),es.hideEmpty===!1&&$.set("hideEmpty","false"),useQuery({queryKey:["sessions","count",es],queryFn:()=>apiGet(`/api/sessions?${$.toString()}`),refetchInterval:POLL.LIVE})}function useSession(es){return useQuery({queryKey:["sessions",es],queryFn:()=>apiGet(`/api/sessions/${es}`),enabled:!!es,refetchInterval:POLL.LIVE})}const PAGE_SIZE$2=100;function useSessionEventsInfinite(es){return useInfiniteQuery({queryKey:["sessions",es,"events-infinite"],queryFn:({pageParam:$=0})=>apiGet(`/api/sessions/${es}/events?limit=${PAGE_SIZE$2}&offset=${$}&sort=desc`),initialPageParam:0,getNextPageParam:($,ts,is)=>$.length===PAGE_SIZE$2?is+PAGE_SIZE$2:void 0,enabled:!!es,refetchInterval:POLL.LIVE})}function useAnalyzeSession(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/sessions/${$}/analyze`,{}),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["sessions",ts]})}})}function useInsightsJob(es){const $=useQueryClient();return useQuery({queryKey:["insights-job",es],queryFn:()=>apiGet(`/api/insights-jobs/${es}`),enabled:!!es,refetchInterval:ts=>{var cs;const is=(cs=ts.state.data)==null?void 0:cs.status;return is==="completed"||is==="failed"||is==="cancelled"?(is==="completed"&&$.invalidateQueries({queryKey:["sessions"]}),!1):2e3}})}function useDeleteSession(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/sessions/${$}`),onSuccess:()=>{es.invalidateQueries({queryKey:["sessions"]})}})}function useSkillsRegistry(){return useQuery({queryKey:["skills-registry"],queryFn:()=>apiGet("/api/skills"),staleTime:300*1e3})}function useSkill(es){return useQuery({queryKey:["skills-registry",es],queryFn:()=>apiGet(`/api/skills/${es}`),enabled:!!es})}function CopyButton$2({text:es}){const{copied:$,copy:ts}=useCopyToClipboard();return jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",onClick:async is=>{is.stopPropagation(),await ts(es)||ue$1.error("Couldn't copy to clipboard",{description:"Select the text and copy it manually."})},children:$?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"})})}function RunCommandButton({prompt:es,label:$="Copy"}){const{copied:ts,copy:is}=useCopyToClipboard(),Qr=/^(claude|rulemetric|pnpm|npm|npx|git)\s/.test(es.trim())?es.trim():`claude -p '${es.replace(/'/g,"'\\''")}'`;return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-teal-500/30 text-teal-600 hover:bg-teal-500/10 hover:text-teal-600",onClick:async ja=>{ja.stopPropagation(),await is(Qr)||ue$1.error("Couldn't copy to clipboard",{description:"Select the text and copy it manually."})},title:`Copy command: ${Qr.slice(0,80)}...`,children:[ts?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),ts?"Copied!":$]})}function TooltipProvider({delayDuration:es=0,...$}){return jsxRuntimeExports.jsx(Provider,{"data-slot":"tooltip-provider",delayDuration:es,...$})}function Tooltip({...es}){return jsxRuntimeExports.jsx(Root3,{"data-slot":"tooltip",...es})}function TooltipTrigger({...es}){return jsxRuntimeExports.jsx(Trigger$2,{"data-slot":"tooltip-trigger",...es})}function TooltipContent({className:es,sideOffset:$=0,children:ts,...is}){return jsxRuntimeExports.jsx(Portal$1,{children:jsxRuntimeExports.jsxs(Content2$1,{"data-slot":"tooltip-content",sideOffset:$,className:cn$1("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",es),...is,children:[ts,jsxRuntimeExports.jsx(Arrow2,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}function canonicalToolKey(es){return es.toLowerCase().replace(/-/g,"_")}const TOOL_LABELS={claude_code:"Claude Code",cursor:"Cursor",vscode_copilot:"VS Code Copilot",copilot:"Copilot",copilot_cli:"Copilot CLI",copilot_agent:"Copilot Agent",github_copilot_chat:"GitHub Copilot Chat",github_copilot_fim:"GitHub Copilot FIM",codex:"Codex",aider:"Aider",gemini:"Gemini",windsurf:"Windsurf",cline:"Cline",openclaw:"OpenClaw",opencode:"OpenCode",antigravity:"Antigravity",rulemetric_mcp:"RuleMetric MCP"},TOOLS_WITHOUT_WORKING_ANALYSIS=new Set(["cursor"]);function canAnalyzeWithToolCli(es){return es?!TOOLS_WITHOUT_WORKING_ANALYSIS.has(canonicalToolKey(es)):!0}function displayTool(es){const $=canonicalToolKey(es);return TOOL_LABELS[$]?TOOL_LABELS[$]:$.split("_").filter(Boolean).map(ts=>ts.charAt(0).toUpperCase()+ts.slice(1)).join(" ")}function captureToolKey(es){return canonicalToolKey(es)}function formatUsd(es){return es>=1e3?`$${(es/1e3).toFixed(2)}K`:es>=1?`$${es.toFixed(2)}`:es>0?`$${es.toFixed(3)}`:"$0.00"}function formatTokens$1(es){return es?es>=1e6?`${(es/1e6).toFixed(1)}M`:es>=1e3?`${(es/1e3).toFixed(0)}K`:String(es):"0"}function Row$1({label:es,usd:$,detail:ts}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground w-20 text-right",children:ts})]})]})}function CostBreakdownCard({totalUsd:es,breakdown:$,inputTokens:ts=0,outputTokens:is=0,cacheReadTokens:cs=0,cacheWriteTokens:Qr=0,byModel:ja,byTool:Na}){const Aa=$??{inputUsd:0,outputUsd:0,cacheReadUsd:0,cacheWriteUsd:0},Oa=ja?Object.entries(ja).sort(([,La],[,Ba])=>Ba.cost_usd-La.cost_usd):[],Ia=Na?Object.entries(Na).sort(([,La],[,Ba])=>Ba.cost_usd-La.cost_usd):[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Zap,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{children:"Estimated cost"}),jsxRuntimeExports.jsxs("span",{className:"ml-auto font-mono text-base",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground mr-1",children:"≈"}),formatUsd(es)]})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Row$1,{label:"Input",usd:Aa.inputUsd,detail:`${formatTokens$1(ts)} tok`}),jsxRuntimeExports.jsx(Row$1,{label:"Output",usd:Aa.outputUsd,detail:`${formatTokens$1(is)} tok`}),jsxRuntimeExports.jsx(Row$1,{label:"Cache read",usd:Aa.cacheReadUsd,detail:cs>0?`${formatTokens$1(cs)} tok`:"no cache"}),jsxRuntimeExports.jsx(Row$1,{label:"Cache write",usd:Aa.cacheWriteUsd,detail:Qr>0?`${formatTokens$1(Qr)} tok`:"no cache"})]}),Ia.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"By tool"}),Ia.map(([La,Ba])=>{const Ma=es>0?Math.round(Ba.cost_usd/es*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[55%]",children:displayTool(La)}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd(Ba.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground w-8 text-right",children:[Ma,"%"]})]})]},La)})]})]}),Oa.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"By model"}),Oa.map(([La,Ba])=>{const Ma=es>0?Math.round(Ba.cost_usd/es*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[55%]",children:La}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd(Ba.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground w-8 text-right",children:[Ma,"%"]})]})]},La)})]})]}),jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground cursor-help",children:[jsxRuntimeExports.jsx("span",{className:"mr-1",children:"≈"}),"estimated · derived from token usage × current published rates"]})}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-xs",children:jsxRuntimeExports.jsx("p",{className:"text-xs",children:"Computed from each model's token usage × its provider's published pricing (Anthropic, OpenAI, Google, and others). May differ from actual billing by ±5% due to per-request rounding; unrecognised models fall back to a Sonnet-equivalent estimate."})})]})})]})]})}const GLOSSARY={anchorSet:"A set of runs a human has reviewed — for each, you said whether the AI judge graded it correctly. These 'anchors' measure how trustworthy the judge is; no calibrated verdict is shown until you've collected enough.",humanLabeledRuns:"Runs where you've reviewed the AI judge's grade (approve = judge was right, reject = judge was wrong). Each review is one anchor. Only you can add these — an AI can't grade its own grader.",pilotTarget:"How many human-labeled runs are needed before a bias-corrected verdict is claimed (default 50), with a minimum in each of the with/without groups.",cohort:"The two groups being compared: runs WITH the instruction applied vs WITHOUT it. Each group needs enough labeled runs on its own for the comparison to hold.",mde:"Minimum Detectable Effect — the smallest with-vs-without difference this sample size could reliably detect. Lower is better; once MDE ≤ your target effect the result is 'powered'.",targetEffect:"The size of with-vs-without difference you care about detecting (default ±20 percentage points). The result is 'powered' once the MDE drops to this or below.",powered:"The sample is now precise enough to detect your target effect (MDE ≤ target). This is about PRECISION only — it does NOT mean the effect is real, nor that the AI judge has been calibrated yet.",adequate:"Enough human labels have been collected — across both groups and above the pilot floor — that a bias-corrected verdict can be published at the required precision.",judge:"The LLM that grades each eval output against its expectations. Fast and cheap, but it can be biased — which is exactly what your human labels measure and correct.",rectifier:"The AI judge's measured bias: the average gap between your human labels and the judge's own grades. It's subtracted back out to correct the judge's scores across every unlabeled run.",ppi:"Prediction-Powered Inference — grade everything cheaply with the AI judge, then correct its bias using a small RANDOM set of human labels. Gives tighter results than human-labels-alone.",discrimination:"Whether each test case actually responds to the instruction. A case 'discriminates' if its pass rate MOVES between the with- and without-instruction runs; one that always passes or always fails measures nothing.",discriminate:"This case's pass rate moves between with- and without-instruction runs, so it carries real signal about whether the instruction helps.",flat:"This case passes (or fails) at the same rate with and without the instruction — it measures nothing, and adding more runs of it will never help. Replace it.",unpaired:"This case has runs in only one group (e.g. every baseline run failed), so no with-vs-without comparison can be made for it.",separation:"The 'Δ' — with% minus without% for a case. The larger it is, the more sensitive the case is to the instruction.",significance:"Whether the measured effect is statistically distinguishable from zero — i.e. its confidence interval excludes 0. Without this, an apparent difference could just be noise.",confidenceInterval:"The range the true value most likely falls within. A wider interval means more uncertainty; it narrows as you collect more data.",delta:"The difference between the two conditions being compared (e.g. with-instruction pass rate minus without-instruction pass rate). Positive = the instruction helped.",verdict:"The overall read on whether an instruction helps, hurts, or shows no measurable effect — shown only once there's enough data to say honestly (otherwise 'insufficient data').",outcome:"An AI-graded score for how a real captured session went (from clean success to abandoned). It's the signal the observational effect estimate is built from.",totalSessionHours:"Every session's own length, added together. One session's length is the time from its first captured event to its last, so waiting and thinking inside a session count — it is elapsed time, not billed or active time. Sessions you ran side by side are each counted in full, so this total can exceed the hours on the clock: two sessions running the same hour contribute two hours, not one.",sessionSpan:"One session's length: last captured event minus the first. Idle stretches inside the session are included, so a session you left open and came back to counts the whole gap.",burnRate:"How fast you're consuming a rate-limit window relative to time elapsed — >100% means you're on track to hit the cap before the window resets.",rateLimitWindow:"A rolling period (e.g. 5-hour or weekly) over which a usage cap applies. Usage resets when the window rolls over."};function InfoTip({term:es,content:$,children:ts,className:is,size:cs=13,plain:Qr=!1}){const ja=$??(es?GLOSSARY[es]:null);if(!ja)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:ts});const Na=ts!=null?jsxRuntimeExports.jsx("span",{tabIndex:0,className:cn$1("cursor-help rounded-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",!Qr&&"underline decoration-dotted decoration-muted-foreground/50 underline-offset-2",is),children:ts}):jsxRuntimeExports.jsx("span",{tabIndex:0,"aria-label":"More information",className:cn$1("inline-flex shrink-0 items-center justify-center align-middle text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:text-foreground cursor-help",is),children:jsxRuntimeExports.jsx(Info,{style:{width:cs,height:cs},"aria-hidden":!0})});return jsxRuntimeExports.jsx(TooltipProvider,{delayDuration:150,children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:Na}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-[19rem] whitespace-normal text-xs font-normal leading-relaxed",children:ja})]})})}function activatable(es){return{role:"button",tabIndex:0,onClick:es,onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),es())}}}const FRIENDLY_LABELS={debug_investigate:"Debug/Investigate",implement_feature:"Implement Feature",fix_bug:"Fix Bug",write_script_tool:"Write Script/Tool",refactor_code:"Refactor Code",configure_system:"Configure System",create_pr_commit:"Create PR/Commit",understand_codebase:"Understand Codebase",write_tests:"Write Tests",write_docs:"Write Docs",analyze_data:"Analyze Data",deploy_infra:"Deploy/Infra",warmup_minimal:"Cache Warmup",fully_achieved:"Fully Achieved",mostly_achieved:"Mostly Achieved",partially_achieved:"Partially Achieved",not_achieved:"Not Achieved",unclear_from_transcript:"Unclear",frustrated:"Frustrated",dissatisfied:"Dissatisfied",likely_satisfied:"Likely Satisfied",satisfied:"Satisfied",happy:"Happy",unsure:"Unsure",single_task:"Single Task",multi_task:"Multi Task",iterative_refinement:"Iterative Refinement",exploration:"Exploration",quick_question:"Quick Question",unhelpful:"Unhelpful",slightly_helpful:"Slightly Helpful",very_helpful:"Very Helpful",essential:"Essential",moderately_helpful:"Moderately Helpful",misunderstood_request:"Misunderstood Request",wrong_approach:"Wrong Approach",buggy_code:"Buggy Code",user_rejected_action:"User Rejected Action",excessive_changes:"Excessive Changes",wrong_file_or_location:"Wrong File/Location",slow_or_verbose:"Slow/Verbose",tool_failed:"Tool Failed",claude_code:"Claude Code",cursor:"Cursor",vscode_copilot:"VS Code Copilot",copilot_cli:"Copilot CLI",antigravity:"Antigravity",github_copilot_chat:"GitHub Copilot Chat",github_copilot_fim:"GitHub Copilot FIM"};function friendlyLabel(es){return FRIENDLY_LABELS[es]||es.replace(/_/g," ").replace(/\b\w/g,$=>$.toUpperCase())}function StatCard$2({icon:es,label:$,value:ts,sub:is,info:cs}){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[jsxRuntimeExports.jsx("div",{className:"shrink-0 rounded-lg bg-primary/10 p-2",children:jsxRuntimeExports.jsx(es,{className:"h-4 w-4 text-primary"})}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"break-words text-2xl font-bold font-mono",children:ts}),jsxRuntimeExports.jsxs("p",{className:"flex min-w-0 flex-wrap items-center gap-1 text-xs text-muted-foreground",children:[$,cs&&jsxRuntimeExports.jsx(InfoTip,{term:cs,size:12})]}),is&&jsxRuntimeExports.jsx("p",{className:"break-words text-xs text-muted-foreground mt-0.5",children:is})]})]})})})}function HorizontalBar({items:es,maxItems:$=8,onItemClick:ts}){const is=Object.entries(es).sort(([,Qr],[,ja])=>ja-Qr).slice(0,$);if(is.length===0)return jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data"});const cs=is[0][1];return jsxRuntimeExports.jsx("div",{className:"space-y-2",children:is.map(([Qr,ja])=>jsxRuntimeExports.jsxs("div",{className:`space-y-1 ${ts?"cursor-pointer hover:bg-muted/50 rounded px-1 -mx-1 py-0.5":""}`,...ts?activatable(()=>ts(Qr)):{},children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[200px]",children:friendlyLabel(Qr)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono",children:(ja??0).toLocaleString()})]}),jsxRuntimeExports.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${ja/cs*100}%`}})})]},Qr))})}function HourChart({hours:es}){const $=new Array(24).fill(0);for(const is of es)$[is]++;const ts=Math.max(...$,1);return jsxRuntimeExports.jsx("div",{className:"flex items-end gap-0.5 h-20",children:$.map((is,cs)=>jsxRuntimeExports.jsx("div",{className:"flex-1 bg-primary/60 rounded-t hover:bg-primary transition-colors cursor-default",style:{height:`${is/ts*100}%`,minHeight:is>0?2:0},title:`${cs}:00 — ${is} messages`},cs))})}function formatDurationSec(es){return es<60?`${Math.round(es)}s`:es<3600?`${Math.round(es/60)}m`:`${(es/3600).toFixed(1)}h`}function ResponseTimeChart({histogram:es}){const $=Object.entries(es),ts=Math.max(...$.map(([,is])=>is),1);return jsxRuntimeExports.jsx("div",{className:"space-y-1.5",children:$.map(([is,cs])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-14 text-right shrink-0",children:is}),jsxRuntimeExports.jsx("div",{className:"flex-1 h-4 bg-muted rounded overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary/70 rounded transition-all",style:{width:`${cs/ts*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-8 text-right",children:cs})]},is))})}function OverviewTab({data:es}){const $=es.estimated_cost_usd??0,ts=es.truncated??!1,is=es.response_time,cs=es.parallel_sessions,Qr=es.tools_used,ja=es.tool_error_categories??{},Na=es.total_interruptions??0,Aa=es.sessions_with_meta??es.total_sessions,Oa=es.sessions_using_task_agent??0,Ia=es.sessions_using_mcp??0;return jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-5",children:[jsxRuntimeExports.jsx(StatCard$2,{icon:MessageSquare,label:"Messages",value:(es.total_messages??0).toLocaleString(),sub:`${es.messages_per_day??0}/day avg`}),jsxRuntimeExports.jsx(StatCard$2,{icon:CodeXml,label:"Lines Changed",value:`+${(es.total_lines_added??0).toLocaleString()}`,sub:`-${(es.total_lines_removed??0).toLocaleString()} removed`}),jsxRuntimeExports.jsx(StatCard$2,{icon:CodeXml,label:"Files Modified",value:(es.total_files_modified??0).toLocaleString()}),jsxRuntimeExports.jsx(StatCard$2,{icon:ChartColumn,label:"Days Active",value:es.days_active,sub:`${es.total_sessions} sessions`}),jsxRuntimeExports.jsx(StatCard$2,{icon:GitCommitHorizontal,label:"Git Commits",value:es.git_commits,sub:`${es.git_pushes} pushes`})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[$>0&&jsxRuntimeExports.jsxs("div",{className:"md:col-span-2 space-y-2",children:[jsxRuntimeExports.jsx(CostBreakdownCard,{totalUsd:$,breakdown:es.estimated_cost_breakdown,inputTokens:es.total_input_tokens,outputTokens:es.total_output_tokens,cacheReadTokens:es.total_cache_read_tokens,cacheWriteTokens:es.total_cache_write_tokens,byModel:es.estimated_cost_by_model}),ts&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4",children:[jsxRuntimeExports.jsx(StatCard$2,{icon:Clock,label:"Total Session Hours",info:"totalSessionHours",value:Math.round(es.total_duration_hours).toLocaleString(),sub:[`summed over ${Aa.toLocaleString()} sessions`,Na>0?`${Na} interruptions`:null].filter(Boolean).join(" · ")}),Oa>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"Task Agents",value:Oa,sub:"sessions"}),Ia>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"MCP Sessions",value:Ia,sub:"sessions"})]})]}),cs&&cs.events>0&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Parallel Sessions"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-3 sm:gap-8",children:[jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:cs.events}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"overlap events"})]}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:cs.sessions_involved}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"sessions involved"})]}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsxs("p",{className:"text-2xl font-bold font-mono",children:[es.total_sessions>0?Math.round(cs.sessions_involved/es.total_sessions*100):0,"%"]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"of sessions"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Detected when messages from different sessions overlap within 30-minute windows."})]})]}),Qr&&Object.keys(Qr).length>1&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"AI Tools Used"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:Qr})})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[is&&is.total_samples>0&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"User Response Time Distribution"}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Median: ",formatDurationSec(is.median_seconds)," · Avg: ",formatDurationSec(is.avg_seconds)," · ",is.total_samples," samples"]})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ResponseTimeChart,{histogram:is.histogram})})]}),es.message_hours.length>0&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Messages by Time of Day (UTC)"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsx(HourChart,{hours:es.message_hours}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-1 font-mono",children:[jsxRuntimeExports.jsx("span",{children:"0:00"}),jsxRuntimeExports.jsx("span",{children:"6:00"}),jsxRuntimeExports.jsx("span",{children:"12:00"}),jsxRuntimeExports.jsx("span",{children:"18:00"}),jsxRuntimeExports.jsx("span",{children:"23:00"})]})]})]})]}),Object.keys(ja).length>0&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-red-500"}),"Tool Error Encounters"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:ja})})]})]})}function ToolsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Tool Usage"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.tool_counts,maxItems:12})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Languages"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.languages})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Feature Usage"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[{label:"Task Agents",value:es.sessions_using_task_agent},{label:"MCP Servers",value:es.sessions_using_mcp}].map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{className:"text-sm",children:$.label}),jsxRuntimeExports.jsxs(Badge,{variant:$.value>0?"default":"outline",children:[$.value," sessions"]})]},$.label))})})]})]})}function QualityTab({data:es,emptyAction:$}){const ts=useNavigate(),is=[{key:"goal_categories",title:"Goal Categories",items:es.goal_categories??{}},{key:"outcomes",title:"Outcomes",items:es.outcomes??{},onClick:cs=>ts(`/sessions?outcome=${cs}`)},{key:"satisfaction",title:"User Satisfaction",items:es.satisfaction??{}},{key:"session_types",title:"Session Types",items:es.session_types??{}},{key:"friction",title:"Friction Points",items:es.friction??{},icon:TriangleAlert,onClick:cs=>ts(`/sessions?friction=${cs}`)}].filter(cs=>Object.keys(cs.items).length>0);return is.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6 space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["No quality data yet. Session analysis runs automatically on your local worker — make sure ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"rulemetric evals agent"})," is running, then use Generate Recommendations to analyze recent sessions."]}),$]})}):jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:is.map(cs=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:cs.title})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:cs.items,onItemClick:cs.onClick})})]},cs.key))})}function GenerateInsightsButton({idleLabel:es="Generate Insights",successLabel:$="Insights queued!",className:ts}={}){const is=useMutation({mutationFn:()=>apiPost("/api/insights-jobs/regenerate-all",{})});return jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:cn$1("cursor-pointer",ts),onClick:()=>is.mutate(),disabled:is.isPending||is.isSuccess,children:is.isPending?"Queuing...":is.isSuccess?$:es})}function SkillDownloadButton({skillId:es,content:$}){return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-primary/30 text-primary hover:bg-primary/10",onClick:ts=>{ts.stopPropagation();const is=new Blob([$],{type:"text/markdown"}),cs=URL.createObjectURL(is),Qr=document.createElement("a");Qr.href=cs,Qr.download=`${es}.md`,Qr.click(),URL.revokeObjectURL(cs)},children:[jsxRuntimeExports.jsx(Download,{className:"h-3 w-3"}),"Download"]})}function SuggestionsTab({rec:es,isAuto:$}){var Aa,Oa,Ia;const{data:ts}=useSkillsRegistry(),cs=es.recommended_skills??[],Qr=((Aa=es.suggestions)==null?void 0:Aa.features_to_try)??[],ja=((Oa=es.suggestions)==null?void 0:Oa.usage_patterns)??[],Na=((Ia=es.on_the_horizon)==null?void 0:Ia.opportunities)??[];return Qr.length===0&&ja.length===0&&Na.length===0&&cs.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6 space-y-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No suggestions yet. Generate insights to get recommendations from your sessions."}),jsxRuntimeExports.jsx(GenerateInsightsButton,{})]})}):jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[$&&jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border bg-muted/30 px-4 py-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Auto-generated from your session data. Generate full AI-powered recommendations for deeper insights."}),jsxRuntimeExports.jsx(GenerateInsightsButton,{idleLabel:"Generate Full Insights",successLabel:"Queued!",className:"text-xs ml-4 shrink-0"})]}),Qr.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 text-blue-500"}),"Features to Try"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Qr.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:La.feature}),La.example_code&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:La.example_code,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:La.example_code})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:La.why_for_you}),La.example_code&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:La.example_code})]},Ba))})]}),ja.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-cyan-500"}),"Usage Patterns"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:ja.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:La.title}),La.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:La.copyable_prompt,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:La.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:La.suggestion}),La.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:La.copyable_prompt})]},Ba))})]}),Na.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-4 w-4 text-pink-500"}),"On the Horizon"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Na.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:La.title}),La.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:La.copyable_prompt,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:La.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:La.whats_possible}),La.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:La.copyable_prompt})]},Ba))})]}),cs.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Zap,{className:"h-4 w-4 text-amber-500"}),"Recommended Skills"]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[cs.map(La=>{var qa;const Ba=(qa=ts==null?void 0:ts.skills)==null?void 0:qa.find(Fa=>Fa.id===La.skillId),Ma=`rulemetric skills install ${La.skillId}`;return jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:(Ba==null?void 0:Ba.name)??La.skillId}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[(Ba==null?void 0:Ba.content)&&jsxRuntimeExports.jsx(SkillDownloadButton,{skillId:La.skillId,content:Ba.content}),jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ma,label:"Install"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:La.reason}),(Ba==null?void 0:Ba.description)&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:Ba.description})]},La.skillId)}),jsxRuntimeExports.jsx("div",{className:"pt-1",children:jsxRuntimeExports.jsx(Link,{to:"/skills",className:"text-xs text-primary hover:underline font-mono",children:"Browse all skills →"})})]})]})]})}function InsightsSection(){var Qr;const[es,$]=useTabParam(["overview","tools","quality","suggestions"],"overview"),{data:ts,isLoading:is,error:cs}=useComputedInsights();return is?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((ja,Na)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},Na))}):cs||!ts||ts.total_sessions===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-3 py-6",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-10 w-10 mx-auto text-muted-foreground/50"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"No insights yet"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Start capturing sessions to see insights here"})]})]})})}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-mono text-muted-foreground",children:"Session Insights"}),jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[ts.total_sessions," sessions · ",ts.days_active," days"]})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"overview",className:"cursor-pointer",children:"Overview"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"tools",className:"cursor-pointer",children:"Tools"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"quality",className:"cursor-pointer",children:"Quality"}),ts.recommendations&&jsxRuntimeExports.jsx(TabsTrigger,{value:"suggestions",className:"cursor-pointer",children:"Suggestions"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"mt-4",children:jsxRuntimeExports.jsx(OverviewTab,{data:ts})}),jsxRuntimeExports.jsx(TabsContent,{value:"tools",className:"mt-4",children:jsxRuntimeExports.jsx(ToolsTab,{data:ts})}),jsxRuntimeExports.jsx(TabsContent,{value:"quality",className:"mt-4",children:jsxRuntimeExports.jsx(QualityTab,{data:ts,emptyAction:jsxRuntimeExports.jsx(GenerateInsightsButton,{})})}),ts.recommendations&&jsxRuntimeExports.jsx(TabsContent,{value:"suggestions",className:"mt-4",children:jsxRuntimeExports.jsx(SuggestionsTab,{rec:ts.recommendations,isAuto:!!((Qr=ts.recommendations)!=null&&Qr._auto_generated)})})]})]})}function PendingSuggestionsCallout(){const{data:es}=usePendingSuggestionCount();if(!es||es.total===0)return null;const $=es.byProject.slice(0,3);return jsxRuntimeExports.jsx(Link,{to:"/suggestions",className:"block no-underline","data-testid":"pending-suggestions-callout",children:jsxRuntimeExports.jsxs("div",{className:"group flex flex-wrap items-center gap-3 rounded-lg border border-primary/40 bg-primary/[0.06] px-4 py-3 transition-colors hover:bg-primary/[0.1]",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 shrink-0 text-primary"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium",children:[es.total," instruction suggestion",es.total===1?"":"s"," await your review"]}),jsxRuntimeExports.jsxs("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:[$.map(ts=>`${ts.projectPath.split("/").pop()} (${ts.count})`).join(" · "),es.byProject.length>3&&" · …"]})]}),jsxRuntimeExports.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-sm font-medium text-primary",children:["Review",jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})})}function DashboardPage(){const{user:es}=useAuth(),{data:$,isLoading:ts}=useInstructions(),{data:is,isLoading:cs}=useSessionCount();return jsxRuntimeExports.jsxs("div",{className:"space-y-8",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Dashboard"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground break-words",children:["Welcome back, ",es==null?void 0:es.email]})]}),jsxRuntimeExports.jsx("div",{className:"flex gap-2"})]}),jsxRuntimeExports.jsx(PendingSuggestionsCallout,{}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-center justify-between pb-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium text-muted-foreground",children:"Instructions"}),jsxRuntimeExports.jsx(FileText,{className:"h-4 w-4 text-muted-foreground"})]}),jsxRuntimeExports.jsx(CardContent,{children:ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-16"}):jsxRuntimeExports.jsx("div",{className:"text-3xl font-mono font-bold text-primary",children:($==null?void 0:$.length)??0})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"flex flex-row items-center justify-between pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium text-muted-foreground",children:"Formats"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"text-3xl font-mono font-bold text-primary",children:"25+"})})]}),jsxRuntimeExports.jsx(Link,{to:"/sessions",className:"no-underline",children:jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-center justify-between pb-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium text-muted-foreground",children:"Sessions"}),jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4 text-muted-foreground"})]}),jsxRuntimeExports.jsx(CardContent,{children:cs?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-16"}):jsxRuntimeExports.jsx("div",{className:"text-3xl font-mono font-bold text-primary","data-testid":"dashboard-session-count",children:((is==null?void 0:is.count)??0).toLocaleString()})})]})})]}),jsxRuntimeExports.jsx(InsightsSection,{})]})}function useApiKeys(){return useQuery({queryKey:["api-keys"],queryFn:()=>apiGet("/api/auth/api-keys")})}function useCreateApiKey(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/auth/api-keys",$),onSuccess:()=>{es.invalidateQueries({queryKey:["api-keys"]})}})}function useRevokeApiKey(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/auth/api-keys/${$}`),onSuccess:()=>{es.invalidateQueries({queryKey:["api-keys"]})}})}const apiUrl=window.location.origin,toolGroups=[{label:"Instructions",tools:[{name:"rulemetric_list",desc:"List your instructions"},{name:"rulemetric_summary",desc:"Get instruction metadata and preview"},{name:"rulemetric_get",desc:"Get full instruction content"},{name:"rulemetric_search",desc:"Search instructions by name or content"},{name:"rulemetric_convert",desc:"Convert to any supported format"},{name:"rulemetric_formats",desc:"List all 25+ converter formats"}]},{label:"Collaboration",tools:[{name:"rulemetric_fork",desc:"Fork an instruction to personal scope"},{name:"rulemetric_promote",desc:"Promote to team or org scope"},{name:"rulemetric_upstream",desc:"Check for upstream updates"},{name:"rulemetric_pull_upstream",desc:"Pull upstream changes via 3-way merge"}]},{label:"Catalog & Recommendations",tools:[{name:"rulemetric_catalog",desc:"Browse org/team instruction catalog"},{name:"rulemetric_recommendations",desc:"AI-powered instruction suggestions"},{name:"rulemetric_apply_suggestion",desc:"Accept a precomputed instruction suggestion mid-session"}]},{label:"Sessions & Insights",tools:[{name:"rulemetric_session_list",desc:"List captured AI sessions"},{name:"rulemetric_session_import",desc:"Import session from JSONL or JSON"},{name:"rulemetric_instruction_insights",desc:"Session-based performance insights"},{name:"rulemetric_diagnostics",desc:"Diagnose hook install, config, and API connectivity"}]}];function SetupRow({state:es,label:$,helper:ts}){const is=es==="detected"?CircleCheck:es==="loading"?LoaderCircle:es==="waiting"?Hourglass:CircleAlert,cs=es==="detected"?"text-teal-400":es==="loading"||es==="waiting"?"text-muted-foreground":"text-amber-400";return jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border bg-background px-3 py-2",children:[jsxRuntimeExports.jsx(is,{className:cn$1("h-4 w-4 mt-0.5 shrink-0",cs,es==="loading"&&"animate-spin")}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsx("div",{className:"text-sm font-medium",children:$}),ts&&jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:ts})]})]})}function ConnectPage(){const[es,$]=useTabParam(["claude-code","copilot","manual"],"claude-code"),{session:ts,user:is}=useAuth();ts==null||ts.access_token;const{workers:cs,activeWorkers:Qr,isConnected:ja,isLoading:Na}=useWorkerStatus("mcp"),Aa=useSetupProgress(),{openModal:Oa,progress:Ia}=useSetupWalkthrough(),{data:La,isLoading:Ba}=useApiKeys(),Ma=useCreateApiKey(),qa=useRevokeApiKey(),[Fa,Ha]=reactExports.useState(""),[Ka,Ga]=reactExports.useState(null),[Va,Ja]=reactExports.useState(!0),[Ya,el]=reactExports.useState(null),{profile:tl}=useActiveOrg(),rl=(tl==null?void 0:tl.liveSendSkipped)??!1,cl=(La==null?void 0:La.filter(hl=>!hl.revokedAt))??[];function dl(){const hl=Fa.trim()||"default";Ma.mutate({name:hl},{onSuccess:jl=>{Ga(jl.key),Ja(!0),Ha("")}})}function fl(hl){qa.mutate(hl,{onSuccess:()=>el(null)})}const nl="<your-api-key>",ol=`claude mcp add rulemetric -e RULEMETRIC_API_KEY=${nl} -e RULEMETRIC_API_URL=${apiUrl} -e RULEMETRIC_CLIENT_NAME=claude-code -- node /path/to/apps/mcp/dist/index.js`,pl=JSON.stringify({mcpServers:{rulemetric:{command:"node",args:["/path/to/apps/mcp/dist/index.js"],env:{RULEMETRIC_API_KEY:nl,RULEMETRIC_API_URL:apiUrl,RULEMETRIC_CLIENT_NAME:"claude-code"}}}},null,2),Tl=JSON.stringify({"github.copilot.chat.mcp.servers":{rulemetric:{command:"node",args:["/path/to/apps/mcp/dist/index.js"],env:{RULEMETRIC_API_KEY:nl,RULEMETRIC_API_URL:apiUrl,RULEMETRIC_CLIENT_NAME:"vscode-copilot"}}}},null,2),ul=JSON.stringify({servers:{rulemetric:{command:"node",args:["/path/to/apps/mcp/dist/index.js"],env:{RULEMETRIC_API_KEY:nl,RULEMETRIC_API_URL:apiUrl,RULEMETRIC_CLIENT_NAME:"vscode-copilot"}}}},null,2);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Connect"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Connect RuleMetric to your AI coding tools via the MCP server"})]}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2 flex flex-row items-center justify-between space-y-0",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono text-muted-foreground",children:"Setup"}),!Ia.coreComplete&&jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",onClick:Oa,className:"cursor-pointer shrink-0",children:"Resume setup"})]}),jsxRuntimeExports.jsxs(CardContent,{className:"grid gap-2 md:grid-cols-2",children:[jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.install.state,label:"Install the CLI",helper:Aa.steps.install.state==="detected"?"Detected via captured session activity.":`Run: ${INSTALL_CLI}`}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.auth.state,label:"Authenticated",helper:Aa.steps.auth.state==="detected"?(is==null?void 0:is.email)??"Signed in":"Sign in to capture sessions."}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.hooks.state,label:"Hooks installed",helper:Aa.steps.hooks.state==="detected"?"Session hooks are firing — capturing Claude Code directly, no proxy needed. Add the optional proxy for the exact system prompt, other AI tools, and live cost.":"Run: rulemetric hooks install — no CA cert or proxy required."}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.worker.state,label:"Worker running",helper:Aa.steps.worker.state==="detected"?"Local worker is heartbeating.":"Run: rulemetric service install --worker-only"}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.tmux.state,label:"Tmux available",helper:Aa.steps.tmux.state==="detected"?"Live message send is enabled for active sessions.":rl?"Skipped during setup — start a Claude Code session in tmux to enable it anytime.":"Start a Claude Code session in tmux to enable live send."}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.target.state,label:"First live target detected",helper:Aa.steps.target.state==="detected"?"We've seen at least one terminal target from this user.":rl?"Skipped during setup — launch a session anytime to register your first target.":"Launch a session to register your first target."})]})]}),jsxRuntimeExports.jsx(Card,{className:ja?"border-teal-500/30 bg-teal-500/5":"border-border",children:jsxRuntimeExports.jsx(CardContent,{className:"py-4",children:Na?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 animate-pulse"}),"Checking connection status..."]}):ja?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-teal-400",children:[jsxRuntimeExports.jsx(Wifi,{className:"h-4 w-4"}),jsxRuntimeExports.jsxs("span",{className:"font-medium",children:[Qr.length," active connection",Qr.length>1?"s":""]})]}),jsxRuntimeExports.jsx("div",{className:"grid gap-2",children:Qr.map(hl=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-teal-500/20 bg-background px-3 py-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"h-2 w-2 rounded-full bg-teal-500 animate-pulse"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:hl.clientName}),hl.workerVersion&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs",children:["v",hl.workerVersion]})]}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last seen ",formatRelativeTime(hl.lastHeartbeat)]})]},hl.id))})]}):cs&&cs.length>0?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(WifiOff,{className:"h-4 w-4"}),jsxRuntimeExports.jsxs("span",{children:["No active connections — last seen ",formatRelativeTime(cs[0].lastHeartbeat)]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Start your AI coding tool with the RuleMetric MCP server configured to reconnect."})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(WifiOff,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"No MCP connections yet — follow the setup below to get started."})]})})}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono text-muted-foreground flex items-center gap-2",children:[jsxRuntimeExports.jsx(Key,{className:"h-4 w-4"}),"API Keys"]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"API keys authenticate your CLI, hooks, and proxy. They never expire and are more reliable than session tokens."}),Ka&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-teal-500/30 bg-teal-500/5 p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-teal-400",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"}),"Copy your API key now — it won't be shown again"]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("code",{className:"flex-1 text-xs font-mono bg-[#0B1120] rounded px-3 py-2 break-all",children:Va?Ka:"rm_"+"•".repeat(40)}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>Ja(!Va),className:"cursor-pointer shrink-0",children:Va?jsxRuntimeExports.jsx(EyeOff,{className:"h-4 w-4"}):jsxRuntimeExports.jsx(Eye,{className:"h-4 w-4"})}),jsxRuntimeExports.jsx(CopyButton$3,{text:Ka})]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>Ga(null),className:"cursor-pointer text-xs text-muted-foreground",children:"Dismiss"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Input,{placeholder:"Key name (e.g. laptop, work)",value:Fa,onChange:hl=>Ha(hl.target.value),onKeyDown:hl=>{hl.key==="Enter"&&!Ma.isPending&&dl()},className:"flex-1"}),jsxRuntimeExports.jsxs(Button,{onClick:dl,disabled:Ma.isPending,className:"cursor-pointer shrink-0",size:"sm",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-1 h-4 w-4"}),Ma.isPending?"Creating...":"Create Key"]})]}),Ba?jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading keys..."}):cl.length===0&&!Ka?jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground border border-dashed border-border rounded-lg p-4 text-center",children:"No API keys yet. Create one to get started."}):jsxRuntimeExports.jsx("div",{className:"space-y-2",children:cl.map(hl=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[jsxRuntimeExports.jsxs("code",{className:"text-xs font-mono text-muted-foreground shrink-0",children:[hl.keyPrefix,"..."]}),jsxRuntimeExports.jsx("span",{className:"text-sm truncate",children:hl.name})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:hl.lastUsedAt?`Used ${formatRelativeTime(hl.lastUsedAt)}`:"Never used"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["Created ",formatRelativeTime(hl.createdAt)]}),Ya===hl.id?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(Button,{variant:"destructive",size:"sm",onClick:()=>fl(hl.id),disabled:qa.isPending,className:"cursor-pointer text-xs h-7",children:"Confirm"}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>el(null),className:"cursor-pointer text-xs h-7",children:"Cancel"})]}):jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>el(hl.id),className:"cursor-pointer text-muted-foreground hover:text-destructive h-7",children:jsxRuntimeExports.jsx(Trash2,{className:"h-3 w-3"})})]})]},hl.id))})]})]}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono text-muted-foreground flex items-center gap-2",children:[jsxRuntimeExports.jsx(Plug,{className:"h-4 w-4"}),"MCP Server Setup"]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["The MCP server isn't published to npm yet — clone the RuleMetric repo and run"," ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"pnpm install && pnpm build"})," first, then point the config at ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"apps/mcp/dist/index.js"})," in your checkout."]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"claude-code",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"Claude Code"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"copilot",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(CodeXml,{className:"mr-2 h-4 w-4"}),"VS Code Copilot"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"manual",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(FileJson,{className:"mr-2 h-4 w-4"}),"Manual Config"]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"claude-code",className:"mt-4 space-y-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Run this command to add RuleMetric as an MCP server in Claude Code:"}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"Terminal"}),jsxRuntimeExports.jsx(CopyButton$3,{text:ol})]}),jsxRuntimeExports.jsx("pre",{className:"overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:ol})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Or add this to a ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:".mcp.json"})," file in your project root (Claude Code reads MCP servers from there, not from settings.json):"]}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:".mcp.json"}),jsxRuntimeExports.jsx(CopyButton$3,{text:pl})]}),jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:pl})]})]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"copilot",className:"mt-4 space-y-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:"Option 1: VS Code Settings"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Add this to your VS Code settings (",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"Cmd+Shift+P"}),' → "Preferences: Open User Settings (JSON)"):']}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"settings.json"}),jsxRuntimeExports.jsx(CopyButton$3,{text:Tl})]}),jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:Tl})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:"Option 2: Project-level .vscode/mcp.json"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Or create a ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:".vscode/mcp.json"})," file in your project root for per-project configuration:"]}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:".vscode/mcp.json"}),jsxRuntimeExports.jsx(CopyButton$3,{text:ul})]}),jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:ul})]})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-4 space-y-2",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Using RuleMetric in Copilot Chat"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Once configured, open Copilot Chat in Agent mode (",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"Cmd+Shift+I"}),") and RuleMetric tools will be available. You can ask Copilot to:"]}),jsxRuntimeExports.jsxs("ul",{className:"text-sm text-muted-foreground list-disc pl-5 space-y-1",children:[jsxRuntimeExports.jsx("li",{children:"List and search your instructions"}),jsxRuntimeExports.jsx("li",{children:"Convert instructions to any format"}),jsxRuntimeExports.jsx("li",{children:"Browse the org/team catalog"}),jsxRuntimeExports.jsx("li",{children:"Get AI-powered recommendations"}),jsxRuntimeExports.jsx("li",{children:"Import and review coding sessions"})]})]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"manual",className:"mt-4 space-y-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Use this JSON config for any MCP-compatible tool (Cursor, Windsurf, etc.):"}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"mcp.json"}),jsxRuntimeExports.jsx(CopyButton$3,{text:pl})]}),jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:pl})]})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-4 space-y-2",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Getting an API key"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate an API key via the CLI. It never expires and is saved automatically:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono text-muted-foreground bg-[#0B1120] rounded p-3 mt-2",children:`rulemetric auth login
|
|
142
|
+
rulemetric auth create-key --name "my-setup"`})]})]})]})]})]}),jsxRuntimeExports.jsx(Card,{className:"border-blue-500/30 bg-blue-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"py-3 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("strong",{className:"text-blue-400",children:"Tip:"})," Use an API key (",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"rm_..."}),") instead of a JWT for MCP server config. API keys never expire and work for all integrations. Create one in the API Keys section above, or via CLI:"," ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:'rulemetric auth create-key --name "my-setup"'})]})}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono text-muted-foreground",children:["Available Tools (",toolGroups.reduce((hl,jl)=>hl+jl.tools.length,0),")"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-6",children:toolGroups.map(hl=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:hl.label}),jsxRuntimeExports.jsx("div",{className:"grid gap-2",children:hl.tools.map(jl=>jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-lg border border-border bg-background p-3",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs shrink-0",children:jl.name}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words text-sm text-muted-foreground",children:jl.desc})]},jl.name))})]},hl.label))})]})]})}function projectDisplayName(es){var cs;if(es.projectName)return es.projectName;const $=lastTwoSegments(es.primaryCheckoutPath);if($)return $;const ts=nameFromRemote((cs=es.metadata)==null?void 0:cs.gitRemote);if(ts)return ts;const is=lastTwoSegments(es.projectPath);return is||"—"}function lastTwoSegments(es){if(!es)return null;const $=es.split("/").filter(Boolean);return $.length===0?null:$.slice(-2).join("/")}function nameFromRemote(es){if(typeof es!="string"||!es.trim())return null;const $=es.trim().replace(/\.git$/i,"").replace(/^(https?:\/\/|ssh:\/\/(?:[^@]+@)?|git:\/\/|[^@]+@)/,"").replace(/^([^/:]+):/,"$1/"),ts=$.split("/").filter(Boolean);return ts.length>=3?ts.slice(-2).join("/"):ts.length===2?ts[1]:$||null}function ClaudeCodeIcon(es){return jsxRuntimeExports.jsx("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",...es,children:jsxRuntimeExports.jsx("path",{d:"M12 2.5L13.4 9.2L20 8.5L14.8 12L20 15.5L13.4 14.8L12 21.5L10.6 14.8L4 15.5L9.2 12L4 8.5L10.6 9.2L12 2.5Z"})})}function CursorIcon(es){return jsxRuntimeExports.jsx("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",...es,children:jsxRuntimeExports.jsx("path",{d:"M12 2L13.5 10.5L22 12L13.5 13.5L12 22L10.5 13.5L2 12L10.5 10.5L12 2Z"})})}function VSCodeCopilotIcon(es){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round","aria-hidden":"true",...es,children:[jsxRuntimeExports.jsx("path",{d:"M17.5 2.5L21.5 4.5V19.5L17.5 21.5L8 13.5L4 16.5L2.5 15.5V8.5L4 7.5L8 10.5L17.5 2.5Z"}),jsxRuntimeExports.jsx("path",{d:"M17.5 2.5V21.5"})]})}const TOOL_ICON_COMPONENTS={claude_code:ClaudeCodeIcon,cursor:CursorIcon,vscode_copilot:VSCodeCopilotIcon};function ToolIcon({tool:es,...$}){const ts=TOOL_ICON_COMPONENTS[es];return ts?jsxRuntimeExports.jsx(ts,{...$}):jsxRuntimeExports.jsx(Activity,{...$})}function Table({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:jsxRuntimeExports.jsx("table",{"data-slot":"table",className:cn$1("w-full caption-bottom text-sm",es),...$})})}function TableHeader({className:es,...$}){return jsxRuntimeExports.jsx("thead",{"data-slot":"table-header",className:cn$1("[&_tr]:border-b",es),...$})}function TableBody({className:es,...$}){return jsxRuntimeExports.jsx("tbody",{"data-slot":"table-body",className:cn$1("[&_tr:last-child]:border-0",es),...$})}function TableRow({className:es,...$}){return jsxRuntimeExports.jsx("tr",{"data-slot":"table-row",className:cn$1("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",es),...$})}function TableHead({className:es,...$}){return jsxRuntimeExports.jsx("th",{"data-slot":"table-head",className:cn$1("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",es),...$})}function TableCell({className:es,...$}){return jsxRuntimeExports.jsx("td",{"data-slot":"table-cell",className:cn$1("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",es),...$})}function formatDuration(es,$){if(!$)return"—";const ts=new Date($).getTime()-new Date(es).getTime();if(!Number.isFinite(ts)||ts<0)return"—";const is=Math.floor(ts/6e4);if(is<1)return"<1m";if(is<60)return`${is}m`;const cs=Math.floor(is/60);return cs<24?`${cs}h ${is%60}m`:`${Math.floor(cs/24)}d ${cs%24}h`}function HeadlessBadge(){return jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-slate-500/10 text-slate-500 border border-slate-500/20",title:"Started via `claude -p` (non-interactive). Typically a script or pipeline invocation.",children:"headless"})}function DataTierBadge({tier:es}){return es==="full"?jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-teal-500/10 text-teal-600 border border-teal-500/20",children:"Full capture"}):es==="events"?jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-amber-500/10 text-amber-600 border border-amber-500/20",children:"Events only"}):null}function SortableHead({label:es,sortKey:$,currentKey:ts,currentDir:is,onSort:cs,className:Qr}){const ja=ts===$,Na=ja?is==="asc"?ArrowUp:ArrowDown:ArrowUpDown;return jsxRuntimeExports.jsx(TableHead,{className:`cursor-pointer select-none hover:text-foreground transition-colors ${Qr??""}`,onClick:()=>cs($),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[es,jsxRuntimeExports.jsx(Na,{className:`h-3 w-3 ${ja?"text-primary":"text-muted-foreground/50"}`})]})})}function SessionsListPage(){const es=useNavigate(),[$,ts]=useSearchParams(),is=$.get("outcome")??void 0,cs=$.get("friction")??void 0,Qr=$.get("instructionId")??void 0,ja=[is&&{key:"outcome",label:`outcome: ${is.replace(/_/g," ")}`},cs&&{key:"friction",label:`friction: ${cs.replace(/_/g," ")}`},Qr&&{key:"instructionId",label:"linked instruction"}].filter(Boolean),Na=dl=>{const fl=new URLSearchParams($);fl.delete(dl),ts(fl,{replace:!0})},{data:Aa,isLoading:Oa}=useSessions({hideEmpty:!0,outcome:is,friction:cs,instructionId:Qr}),[Ia,La]=reactExports.useState("date"),[Ba,Ma]=reactExports.useState("desc"),[qa,Fa]=reactExports.useState(new Set),[Ha,Ka]=reactExports.useState(new Set),Ga=useDeleteSession(),Va=dl=>{Ka(fl=>{const nl=new Set(fl);return nl.has(dl)?nl.delete(dl):nl.add(dl),nl})},Ja=dl=>{Fa(fl=>{const nl=new Set(fl);return nl.has(dl)?nl.delete(dl):nl.add(dl),nl})},Ya=()=>{rl&&(qa.size===rl.length?Fa(new Set):Fa(new Set(rl.map(dl=>dl.id))))},el=async()=>{const dl=[...qa];for(const fl of dl)await Ga.mutateAsync(fl);Fa(new Set)},tl=dl=>{dl===Ia?Ma(fl=>fl==="asc"?"desc":"asc"):(La(dl),Ma("desc"))},rl=Aa?[...Aa].sort((dl,fl)=>{const nl=Ba==="asc"?1:-1;switch(Ia){case"date":return nl*(new Date(dl.lastActivityAt??dl.startedAt).getTime()-new Date(fl.lastActivityAt??fl.startedAt).getTime());case"events":return nl*(dl.eventCount-fl.eventCount);case"project":return nl*projectDisplayName(dl).localeCompare(projectDisplayName(fl));default:return 0}}):void 0,cl=[];if(rl){let dl=null;for(const fl of rl){const nl=new Date(fl.startedAt).toISOString().slice(0,19),ol=`${fl.tool}|${fl.projectPath??"∅"}|${nl}`;dl&&dl.key===ol?dl.siblings.push(fl):(dl&&cl.push(dl),dl={key:ol,rep:fl,siblings:[]})}dl&&cl.push(dl)}return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-start justify-between",children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Sessions"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Review AI coding sessions and analyze instruction performance"}),ja.length>0&&jsxRuntimeExports.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:ja.map(dl=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"cursor-pointer font-mono text-xs",onClick:()=>Na(dl.key),title:"Clear this filter",children:[dl.label,jsxRuntimeExports.jsx(X$1,{className:"ml-1 h-3 w-3"})]},dl.key))})]})}),qa.size>0&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[qa.size," selected"]}),jsxRuntimeExports.jsxs(Button,{variant:"destructive",size:"sm",className:"h-8 text-xs cursor-pointer",onClick:el,disabled:Ga.isPending,children:[jsxRuntimeExports.jsx(Trash2,{className:"h-3 w-3 mr-1"}),Ga.isPending?"Deleting...":"Delete"]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"h-8 text-xs cursor-pointer",onClick:()=>Fa(new Set),children:"Cancel"})]}),Oa?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((dl,fl)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 w-full"},fl))}):rl!=null&&rl.length?jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{className:"w-10",children:jsxRuntimeExports.jsx("button",{role:"checkbox","aria-checked":!!rl&&qa.size===rl.length&&rl.length>0,"aria-label":"Select all sessions",className:"h-4 w-4 rounded border border-border cursor-pointer flex items-center justify-center text-xs hover:bg-secondary/50 transition-colors",onClick:Ya,children:rl&&qa.size===rl.length&&rl.length>0?"✓":""})}),jsxRuntimeExports.jsx(TableHead,{className:"w-48",children:"Tool"}),jsxRuntimeExports.jsx(SortableHead,{label:"Project",sortKey:"project",currentKey:Ia,currentDir:Ba,onSort:tl,className:"w-80"}),jsxRuntimeExports.jsx(TableHead,{className:"w-[28rem]",children:"Last message"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24",children:"Branch"}),jsxRuntimeExports.jsx(SortableHead,{label:"Events",sortKey:"events",currentKey:Ia,currentDir:Ba,onSort:tl,className:"text-right"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Duration"}),jsxRuntimeExports.jsx(SortableHead,{label:"Last activity",sortKey:"date",currentKey:Ia,currentDir:Ba,onSort:tl,className:"text-right"})]})}),jsxRuntimeExports.jsx(TableBody,{children:cl.flatMap(dl=>{const fl=Ha.has(dl.key),nl=dl.siblings.length>0;return[{session:dl.rep,isSibling:!1},...fl?dl.siblings.map(pl=>({session:pl,isSibling:!0})):[]].map(({session:pl,isSibling:Tl})=>{var hl,jl;const ul=pl.analysis;return jsxRuntimeExports.jsxs(TableRow,{className:`cursor-pointer hover:bg-secondary/50 transition-colors ${qa.has(pl.id)?"bg-primary/5":""} ${Tl?"bg-muted/20":""}`,onClick:()=>es(`/sessions/${pl.id}`),children:[jsxRuntimeExports.jsx(TableCell,{onClick:Nl=>Nl.stopPropagation(),children:jsxRuntimeExports.jsx("button",{type:"button",role:"checkbox","aria-checked":qa.has(pl.id),"aria-label":"Select session",className:"h-4 w-4 rounded border border-border flex items-center justify-center text-xs hover:bg-secondary/50 transition-colors",onClick:Nl=>{Nl.stopPropagation(),Ja(pl.id)},children:qa.has(pl.id)?"✓":""})}),jsxRuntimeExports.jsxs(TableCell,{className:"w-48 align-top",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[nl&&!Tl?jsxRuntimeExports.jsx("button",{type:"button",className:"flex h-4 w-4 items-center justify-center rounded hover:bg-muted cursor-pointer shrink-0",onClick:Nl=>{Nl.stopPropagation(),Va(dl.key)},title:fl?"Collapse parallel sessions":"Expand parallel sessions",children:fl?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"})}):Tl?jsxRuntimeExports.jsx("div",{className:"w-4 shrink-0"}):null,jsxRuntimeExports.jsx(ToolIcon,{tool:pl.tool,className:"h-4 w-4 text-muted-foreground shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm truncate",children:displayTool(pl.tool)})]}),(pl.dataTier||((hl=pl.metadata)==null?void 0:hl.headless)||nl&&!Tl)&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1 mt-1 ml-6",children:[pl.dataTier&&jsxRuntimeExports.jsx(DataTierBadge,{tier:pl.dataTier}),((jl=pl.metadata)==null?void 0:jl.headless)&&jsxRuntimeExports.jsx(HeadlessBadge,{}),nl&&!Tl&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[9px] font-mono px-1 py-0 gap-1",children:[jsxRuntimeExports.jsx(Layers,{className:"h-2.5 w-2.5"}),"+",dl.siblings.length," parallel"]})]})]}),jsxRuntimeExports.jsxs(TableCell,{className:"font-mono text-sm text-muted-foreground w-80 max-w-80 align-top",children:[jsxRuntimeExports.jsx("div",{className:"truncate text-foreground",children:projectDisplayName(pl)}),pl.projectName&&(pl.primaryCheckoutPath||pl.projectPath)&&jsxRuntimeExports.jsx("div",{className:"truncate text-[10px] text-muted-foreground/70",children:pl.primaryCheckoutPath??pl.projectPath}),pl.linkedInstructions&&pl.linkedInstructions.length>0&&jsxRuntimeExports.jsxs("div",{className:"flex gap-1 mt-0.5 flex-wrap",children:[pl.linkedInstructions.slice(0,3).map((Nl,zl)=>{var Fl;const Zl=((Fl=Nl.contextIdentity)==null?void 0:Fl.split("::").pop())??Nl.name,Dl=Zl.split("/").pop()??Zl,Il=isGenerated(classifyProvenance({source:Nl.source},null));return jsxRuntimeExports.jsx(Badge,{variant:"outline",className:Il?"text-[9px] font-mono px-1 py-0 border-teal-400/40 text-teal-400":"text-[9px] font-mono px-1 py-0",title:Il?PROVENANCE_TOOLTIP:void 0,"data-testid":Il?"provenance-chip":void 0,children:Dl.length>20?Dl.slice(0,20)+"...":Dl},zl)}),pl.linkedInstructions.length>3&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[9px] font-mono px-1 py-0",children:["+",pl.linkedInstructions.length-3]})]})]}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground w-[28rem] max-w-[28rem] align-top",children:jsxRuntimeExports.jsx("div",{className:"truncate",title:pl.lastMessagePreview??void 0,children:pl.lastMessagePreview??"—"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground w-24 max-w-24 truncate",title:pl.gitBranch??void 0,children:pl.gitBranch??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-right font-mono text-sm",children:pl.eventCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground",children:formatDuration(pl.startedAt,pl.lastActivityAt??pl.endedAt)}),jsxRuntimeExports.jsxs(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:[jsxRuntimeExports.jsx("div",{children:pl.lastActivityAt??pl.startedAt?new Date(pl.lastActivityAt??pl.startedAt).toLocaleString():"—"}),!!(ul!=null&&ul.outcome)&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[9px] mt-0.5",children:String(ul.outcome).replace(/_/g," ")})]})]},pl.id)})})})]})}):jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Activity,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No sessions yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm mt-1",children:"Import a session file or install Claude Code hooks to get started"})]})]})}function isAgentResponseEvent(es){return es.eventType==="assistant_response"||es.eventType==="assistant_message"}function eventUsage(es){var is;if(!es)return;const $=(is=es.metadata)==null?void 0:is.usage;if($&&typeof $=="object")return $;const ts=es.tokenUsage;if(ts)return{input_tokens:ts.input_tokens??ts.input,output_tokens:ts.output_tokens??ts.output,cache_read_input_tokens:ts.cache_read_input_tokens??ts.cacheRead,cache_creation_input_tokens:ts.cache_creation_input_tokens??ts.cacheWrite}}function isBlankAssistantMessage(es){return es.eventType==="assistant_message"&&(es.content==null||es.content.trim()==="")}function groupEventsIntoTurns(es){const $=[];let ts={userMessage:null,events:[],assistantResponse:null};for(const is of es)is.eventType==="user_message"?((ts.userMessage||ts.events.length>0)&&$.push(ts),ts={userMessage:is,events:[],assistantResponse:null}):(isAgentResponseEvent(is)&&(ts.assistantResponse=is),ts.events.push(is));return(ts.userMessage||ts.events.length>0)&&$.push(ts),$}function sessionEventCounts(es,$){if($)return{messages:$.messages,assistantResponses:$.assistantResponses,tools:$.toolCalls,total:$.total,partial:!1};const ts=es.filter(is=>is.eventType==="assistant_message"&&!isBlankAssistantMessage(is)).length;return{messages:es.filter(is=>is.eventType==="user_message").length+ts,assistantResponses:ts+es.filter(is=>{var cs;return is.eventType==="assistant_response"&&!!((cs=is.content)!=null&&cs.trim())}).length,tools:es.filter(is=>is.eventType==="tool_call").length,total:es.length,partial:!0}}const INJECTED_TYPES=new Set(["system_reminder","claude_md","agents_md","copilot_instructions","memory","skill_catalog","git_context","hook_output","deferred_tools"]);function getContextItems(es){const ts=(es.metadata??{}).contextItems??[];let is=0;for(const cs of ts)INJECTED_TYPES.has(cs.type)&&(cs.instruction_index==null&&(cs.instruction_index=is),is++);return ts}function useContextSnapshots(es){return useQuery({queryKey:["sessions",es,"context-snapshots"],queryFn:()=>apiGet(`/api/sessions/${es}/context-snapshots`),enabled:!!es,refetchInterval:POLL.ACTIVE})}function useContextSnapshotDetail(es){return useQuery({queryKey:["context-snapshots",es],queryFn:()=>apiGet(`/api/context-snapshots/${es}`),enabled:!!es})}function useLaunchJobs(){return useQuery({queryKey:["launch-jobs"],queryFn:()=>apiGet("/api/launch-jobs?limit=20"),refetchInterval:POLL.LIVE})}function useAvailableLaunchers(){return useQuery({queryKey:["launchers"],queryFn:()=>apiGet("/api/launchers"),staleTime:6e4})}function useCreateLaunchJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/launch-jobs",{tool:$.tool,config:{projectPath:$.projectPath,prompt:$.prompt,model:$.model,mode:$.mode,resumeSessionId:$.resumeSessionId}}),onSuccess:()=>{es.invalidateQueries({queryKey:["launch-jobs"]})}})}function useSessionTerminalTarget(es){return useQuery({queryKey:["terminal-target",es],queryFn:()=>apiGet(`/api/sessions/${es}/terminal-target`),enabled:!!es,refetchInterval:POLL.BACKGROUND})}function useSendMessage$1(es){const $=useQueryClient();return useMutation({mutationFn:ts=>apiPost(`/api/sessions/${es}/send`,ts),onSuccess:()=>{$.invalidateQueries({queryKey:["terminal-target",es]}),$.invalidateQueries({queryKey:["launch-jobs"]})}})}function SessionTargetSummary({target:es,capabilities:$,session:ts}){const is=(es==null?void 0:es.attachCommand)??(es!=null&&es.target?`tmux attach -t ${es.target}`:null),cs=ts.primaryCheckoutPath??ts.projectPath??null,Qr=displayTool(ts.tool);return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-md bg-card/60 px-4 py-3 text-xs space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono font-medium",children:[Qr,ts.externalSessionId&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" · ",ts.externalSessionId.slice(0,12)]})]}),cs&&jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono truncate max-w-[40ch]",children:cs}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsxs(Badge,{variant:$.workerOnline?"default":"destructive",className:"text-[10px] font-mono",children:["worker ",$.workerOnline?"online":"offline"]}),es?jsxRuntimeExports.jsxs(Badge,{variant:es.status==="active"?"default":"outline",className:"text-[10px] font-mono",children:["tmux ",es.status]}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono",children:"no tmux target"})]}),es&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-muted-foreground",children:[jsxRuntimeExports.jsx(Terminal,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:es.target}),is&&jsxRuntimeExports.jsx(CopyButton$1,{text:is,label:"Copy attach"})]}),!es&&$.fallbackResume&&ts.externalSessionId&&jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:["No live tmux target. Fallback resume will spawn a new terminal via"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"claude --resume"}),"."]})]})}function CopyButton$1({text:es,label:$}){const{copied:ts,copy:is}=useCopyToClipboard(1500);return jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] font-mono cursor-pointer gap-1",onClick:cs=>{cs.stopPropagation(),is(es)},children:[ts?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),jsxRuntimeExports.jsx("span",{className:"truncate max-w-[28ch]",children:ts?"Copied":$})]})}function ProvenanceBadge({source:es,frontmatter:$,className:ts}){const is=es==="insights"||es==="evolution"?es:readStampedSource($),cs=provenanceLabel(is);return!is||!cs?null:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("border-teal-400/40 text-teal-400 text-[10px] font-normal shrink-0",ts),title:PROVENANCE_TOOLTIP,"data-testid":`provenance-${is}`,children:cs})}const LINK_METHOD_LABELS={project_match:"Auto-linked via project",auto_capture:"Auto-captured",manual:"Manually linked",context_file:"Context file"};function InstructionCard({instruction:es}){const[$,ts]=reactExports.useState(!1),is=es.content.slice(0,200),cs=es.content.length>200;return jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs("div",{className:"px-4 py-3 cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(FileText,{className:"h-4 w-4 text-primary shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium",children:es.name}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:es.source}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:es.scope}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:LINK_METHOD_LABELS[es.linkMethod]??es.linkMethod}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),!$&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:[is,cs&&"..."]})]}),$&&jsxRuntimeExports.jsx(CardContent,{className:"pt-0 pb-3",children:jsxRuntimeExports.jsx("pre",{className:"p-3 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-96 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})})]})}const CATEGORY_ORDER=["instructions","memory","agents","commands","skills","settings"];function extractCategory(es){const $=es.frontmatter;if($&&typeof $.category=="string")return $.category;const ts=es.name.match(/\[([^\]]+)\]$/);return ts?ts[1]:"other"}function cleanName(es){return es.replace(/\s*\[[^\]]+\]$/,"")}function ContextFileRow({instruction:es}){const[$,ts]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 cursor-pointer hover:bg-secondary/30 transition-colors rounded",...activatable(()=>ts(!$)),children:[jsxRuntimeExports.jsx(FileText,{className:"h-3 w-3 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:cleanName(es.name)}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:es.source}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 text-muted-foreground"})]}),$&&jsxRuntimeExports.jsx("div",{className:"ml-5 mr-3 mb-2",children:jsxRuntimeExports.jsx("pre",{className:"p-3 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-96 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})})]})}function ContextBlock({instructions:es}){const[$,ts]=reactExports.useState(!1),is=reactExports.useMemo(()=>{const ja={};for(const Na of es){const Aa=extractCategory(Na);ja[Aa]||(ja[Aa]=[]),ja[Aa].push(Na)}return ja},[es]),cs=reactExports.useMemo(()=>es.filter(ja=>isGenerated(classifyProvenance({source:ja.source},null))).length,[es]),Qr=reactExports.useMemo(()=>Object.keys(is).sort((Na,Aa)=>{const Oa=CATEGORY_ORDER.indexOf(Na),Ia=CATEGORY_ORDER.indexOf(Aa);return(Oa===-1?999:Oa)-(Ia===-1?999:Ia)}),[is]);return jsxRuntimeExports.jsxs("div",{className:"mb-4",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-teal-500 rounded-lg bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[jsxRuntimeExports.jsx(FileText,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Session Context"}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-mono",children:es.length}),cs>0&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"border-teal-400/40 text-teal-400 text-[10px] font-normal shrink-0",title:PROVENANCE_TOOLTIP,"data-testid":"provenance-insights",children:cs===1?"from insights":`${cs} from insights`}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5",children:!$&&Qr.map(ja=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono",children:[ja," ",is[ja].length]},ja))}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-2 space-y-3",children:Qr.map(ja=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-medium uppercase tracking-wider mb-1 px-3",children:ja}),jsxRuntimeExports.jsx("div",{children:is[ja].map(Na=>jsxRuntimeExports.jsx(ContextFileRow,{instruction:Na},Na.instructionId))})]},ja))})]})}const PROVIDER_COLORS={anthropic:"bg-orange-500/10 text-orange-600 border-orange-500/20",openai:"bg-teal-500/10 text-teal-600 border-teal-500/20",azure_openai:"bg-blue-500/10 text-blue-600 border-blue-500/20",gemini:"bg-pink-500/10 text-pink-600 border-pink-500/20",bedrock:"bg-amber-500/10 text-amber-600 border-amber-500/20",ollama:"bg-gray-500/10 text-gray-600 border-gray-500/20"};function formatTokenCount(es){return es==null?"0":es>=1e3?`${(es/1e3).toFixed(1)}K`:String(es)}function formatEventTimestamp(es){const $=new Date(es),ts=new Date,is=ts.getTime()-$.getTime(),cs=Math.floor(is/6e4),Qr=$.toDateString()===ts.toDateString();return cs<1?"just now":cs<60?`${cs}m ago`:Qr?$.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):$.toLocaleDateString([],{month:"numeric",day:"numeric",year:"numeric"})+" "+$.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function UserBubble({event:es}){return jsxRuntimeExports.jsxs("div",{className:"mt-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[jsxRuntimeExports.jsx(User,{className:"h-4 w-4 text-blue-500"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"You"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),jsxRuntimeExports.jsx("div",{className:"bg-blue-500/10 border border-blue-500/20 rounded-lg px-4 py-3 max-w-[85%]",children:jsxRuntimeExports.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:es.content})})]})}function AssistantBubble({event:es}){const $=es.content??"",ts=/\[tool_use:\s*([^\]]+)\]/g,is=[];let cs=0,Qr;for(;(Qr=ts.exec($))!==null;)Qr.index>cs&&is.push({type:"text",value:$.slice(cs,Qr.index)}),is.push({type:"tool",value:Qr[1]}),cs=Qr.index+Qr[0].length;return cs<$.length&&is.push({type:"text",value:$.slice(cs)}),jsxRuntimeExports.jsxs("div",{className:"mt-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[jsxRuntimeExports.jsx(Brain,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Assistant"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),jsxRuntimeExports.jsx("div",{className:"bg-secondary/50 border border-border rounded-lg px-4 py-3",children:jsxRuntimeExports.jsx("div",{className:"text-sm whitespace-pre-wrap break-words",children:is.length>0?is.map((ja,Na)=>ja.type==="tool"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mx-1 text-xs font-mono",children:ja.value},Na):jsxRuntimeExports.jsx("span",{children:ja.value},Na)):$})})]})}function ToolCallCard({event:es}){const[$,ts]=reactExports.useState(!1),is=es.metadata??{},cs=is.durationMs,Qr=is.success;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-amber-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Terminal,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm",children:es.toolName}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),cs!=null&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:cs<1e3?`${cs}ms`:`${(cs/1e3).toFixed(1)}s`}),Qr!=null&&(Qr?jsxRuntimeExports.jsx(Check,{className:"h-3.5 w-3.5 text-teal-500"}):jsxRuntimeExports.jsx(X$1,{className:"h-3.5 w-3.5 text-destructive"})),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsxs("div",{className:"ml-4 mt-1 space-y-2",children:[es.toolInput&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Input"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto",children:JSON.stringify(es.toolInput,null,2)})]}),es.toolOutput&&Object.keys(es.toolOutput).length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Output"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto",children:JSON.stringify(es.toolOutput,null,2)})]}),es.content&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Content"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})]})]})]})}function ThinkingBubble({event:es}){const[$,ts]=reactExports.useState(!0),is=es.content??"",cs=is.slice(0,150);return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-rose-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Brain,{className:"h-3.5 w-3.5 text-rose-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground italic",children:$?"Thinking":`${cs}${is.length>150?"...":""}`}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-1",children:jsxRuntimeExports.jsx("p",{className:"text-sm italic text-muted-foreground whitespace-pre-wrap break-words",children:is})})]})}function ToolResultCard({event:es}){const[$,ts]=reactExports.useState(!0),is=es.content??"",cs=is.slice(0,200),ja=(es.metadata??{}).toolUseId??es.toolName;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-teal-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Check,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Result"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),ja&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:ja}),!$&&is&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground truncate max-w-xs",children:[cs,is.length>200?"...":""]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&is&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-1",children:jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap break-words",children:is})})]})}function GenericEvent({event:es}){return jsxRuntimeExports.jsx("div",{className:"mt-2 ml-4",children:jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg px-3 py-2 bg-card/50",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:es.eventType.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),es.content&&jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1 text-muted-foreground whitespace-pre-wrap break-words",children:[es.content.slice(0,300),es.content.length>300&&"..."]})]})})}function TokenUsageBar({usage:es}){const $=es.input_tokens??0,ts=es.output_tokens??0,is=es.cache_read_input_tokens??0,cs=es.cache_creation_input_tokens??0,Qr=$+ts+is+cs;if(Qr===0)return null;const ja=[{value:is,color:"bg-teal-500",label:"cache read"},{value:cs,color:"bg-amber-500",label:"cache write"},{value:$,color:"bg-blue-500",label:"input"},{value:ts,color:"bg-primary",label:"output"}].filter(Na=>Na.value>0);return jsxRuntimeExports.jsxs("div",{className:"mt-2",children:[jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-secondary overflow-hidden flex",children:ja.map(Na=>jsxRuntimeExports.jsx("div",{className:`${Na.color} h-full`,style:{width:`${Na.value/Qr*100}%`},title:`${Na.label}: ${formatTokenCount(Na.value)}`},Na.label))}),jsxRuntimeExports.jsx("div",{className:"flex gap-3 mt-1",children:ja.map(Na=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${Na.color}`}),formatTokenCount(Na.value)," ",Na.label]},Na.label))})]})}function AssistantResponseCard({event:es}){const $=es.metadata??{},ts=eventUsage(es),is=$.stop_reason,cs=$.content_block_types,Qr=$.model,ja=$.response_time_ms,Na=$.streaming;return jsxRuntimeExports.jsx("div",{className:"mt-3 ml-8",children:jsxRuntimeExports.jsxs("div",{className:"bg-primary/5 border border-primary/20 rounded-lg px-4 py-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-3.5 w-3.5 text-primary shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium text-primary",children:"Response"}),Qr&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono px-1.5 py-0 border-primary/30 text-primary/80",children:Qr}),ja!=null&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(Clock,{className:"h-3 w-3"}),ja<1e3?`${ja}ms`:`${(ja/1e3).toFixed(1)}s`]}),is&&jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] font-mono px-1.5 py-0",children:is}),Na&&jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"stream"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:formatEventTimestamp(es.timestamp)})]}),ts&&jsxRuntimeExports.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[ts.output_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-primary/10 text-primary px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.output_tokens)," out"]}),ts.input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-blue-500/10 text-blue-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.input_tokens)," in"]}),ts.cache_read_input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-teal-500/10 text-teal-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.cache_read_input_tokens)," cache"]}),ts.cache_creation_input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-amber-500/10 text-amber-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.cache_creation_input_tokens)," cached"]})]}),es.content&&jsxRuntimeExports.jsx("div",{className:"mt-2 text-sm text-foreground/90 whitespace-pre-wrap break-words leading-relaxed",children:es.content}),cs&&Object.keys(cs).length>0&&jsxRuntimeExports.jsx("div",{className:"flex gap-2 mt-2",children:Object.entries(cs).map(([Aa,Oa])=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[Aa,"(",Oa,")"]},Aa))}),ts&&jsxRuntimeExports.jsx(TokenUsageBar,{usage:ts})]})})}function renderEvent(es){switch(es.eventType){case"user_message":return jsxRuntimeExports.jsx(UserBubble,{event:es});case"assistant_message":return isBlankAssistantMessage(es)?jsxRuntimeExports.jsx(AssistantResponseCard,{event:es}):jsxRuntimeExports.jsx(AssistantBubble,{event:es});case"assistant_response":return jsxRuntimeExports.jsx(AssistantResponseCard,{event:es});case"tool_call":return jsxRuntimeExports.jsx(ToolCallCard,{event:es});case"thinking":return jsxRuntimeExports.jsx(ThinkingBubble,{event:es});case"tool_result":return jsxRuntimeExports.jsx(ToolResultCard,{event:es});default:return jsxRuntimeExports.jsx(GenericEvent,{event:es})}}function InlineTurnSnapshot({snapshot:es}){var Aa;const[$,ts]=reactExports.useState(!1),{data:is}=useContextSnapshotDetail($?es.id:void 0),cs=is??es,Qr=reactExports.useMemo(()=>$?getContextItems(cs):[],[$,cs]),ja=reactExports.useMemo(()=>{var Ia;return((es.metadata??{}).contextItems??[]).length||(((Ia=es.injectedInstructions)==null?void 0:Ia.length)??0)},[es]),Na=PROVIDER_COLORS[es.provider]??PROVIDER_COLORS.ollama;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-cyan-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Eye,{className:"h-3.5 w-3.5 text-cyan-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-xs font-medium text-cyan-600 dark:text-cyan-400",children:"Snapshot"}),jsxRuntimeExports.jsx(Badge,{className:`text-[10px] font-mono border ${Na} px-1.5 py-0`,children:es.provider}),jsxRuntimeExports.jsx("span",{className:"text-[11px] font-mono text-muted-foreground",children:es.model}),jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["~",(es.estimatedTokens??0).toLocaleString()," tok"]}),ja>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[ja," context items"]}),Array.isArray(es.tools)&&es.tools.length>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[es.tools.length," tools"]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-2 space-y-2",children:is?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Qr.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Context Items"}),Object.entries(Qr.reduce((Oa,Ia)=>{var La;return(Oa[La=Ia.type]??(Oa[La]=[])).push(Ia),Oa},{})).map(([Oa,Ia])=>jsxRuntimeExports.jsxs("div",{className:"mb-1",children:[jsxRuntimeExports.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/70 capitalize mb-0.5",children:[Oa.replace(/_/g," ")," (",Ia.length,")"]}),Ia.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 text-xs font-mono text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"truncate",children:La.name}),La.estimated_tokens!=null&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] shrink-0",children:["~",La.estimated_tokens.toLocaleString()," tok"]})]},Ba))]},Oa))]}),cs.systemPrompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:["System prompt: ",(cs.systemPrompt.length??0).toLocaleString()," chars"]}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-[10px]",children:["hash: ",((Aa=cs.systemHash)==null?void 0:Aa.slice(0,12))??"..."]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground flex-wrap",children:[cs.maxTokens!=null&&jsxRuntimeExports.jsxs("span",{children:["Max tokens: ",cs.maxTokens.toLocaleString()]}),cs.temperature!=null&&jsxRuntimeExports.jsxs("span",{children:["Temp: ",cs.temperature]}),Array.isArray(cs.tools)&&jsxRuntimeExports.jsxs("span",{children:[cs.tools.length," tools available"]})]})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}),"Loading snapshot..."]})})]})}function TurnContainer({turn:es,index:$,totalTurns:ts,snapshot:is,hideSnapshot:cs}){var Aa,Oa,Ia,La,Ba;const Qr=es.events.filter(Ma=>Ma.eventType==="tool_call").length,ja=eventUsage(es.assistantResponse)??((Aa=is==null?void 0:is.metadata)==null?void 0:Aa.usage),Na=ja==null?void 0:ja.output_tokens;return((Ia=(Oa=es.assistantResponse)==null?void 0:Oa.metadata)==null?void 0:Ia.response_time_ms)??((Ba=(La=is==null?void 0:is.metadata)==null?void 0:La.responseHeaders)==null||Ba["server-timing"]),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 pt-6 pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"text-xs font-mono text-muted-foreground/60",children:["Turn ",ts-$]}),jsxRuntimeExports.jsx("div",{className:"h-px flex-1 bg-border/50"}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[Qr>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[Qr," tool",Qr!==1?"s":""]}),Na!=null&&Na>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(Zap,{className:"h-2.5 w-2.5"}),formatTokenCount(Na)," tokens"]})]})]}),jsxRuntimeExports.jsxs("div",{className:"relative pl-6",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[11px] top-0 bottom-0 w-px bg-border/40"}),es.userMessage&&jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-4 w-2 h-2 rounded-full bg-blue-500 ring-2 ring-background"}),jsxRuntimeExports.jsx(UserBubble,{event:es.userMessage})]}),es.events.map(Ma=>{if(Ma.eventType==="assistant_response")return jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-4 w-2 h-2 rounded-full bg-primary ring-2 ring-background"}),jsxRuntimeExports.jsx(AssistantResponseCard,{event:Ma})]},Ma.id);const qa=Ma.eventType==="tool_call"?"bg-amber-500":Ma.eventType==="thinking"?"bg-rose-500":Ma.eventType==="tool_result"?"bg-teal-500":Ma.eventType==="assistant_message"?"bg-primary":"bg-muted-foreground";return jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:`absolute left-[-17px] top-3 w-2 h-2 rounded-full ${qa} ring-2 ring-background`}),renderEvent(Ma)]},Ma.id)}),is&&!cs&&jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-3 w-2 h-2 rounded-full bg-cyan-500 ring-2 ring-background"}),jsxRuntimeExports.jsx(InlineTurnSnapshot,{snapshot:is})]})]})]})}function SessionDetailPage(){var ic,Iu;const{id:es}=useParams(),[$,ts]=useSearchParams(),{data:is,isLoading:cs}=useSession(es),{data:Qr,isLoading:ja,hasNextPage:Na,fetchNextPage:Aa,isFetchingNextPage:Oa}=useSessionEventsInfinite(es),Ia=useAnalyzeSession(),La=useCreateLaunchJob(),Ba=(ic=Ia.data)==null?void 0:ic.jobId,{data:Ma}=useInsightsJob(Ba),[qa,Fa]=reactExports.useState(""),{data:Ha}=useContextSnapshots(es),Ka=$.get("filter"),[Ga,Va]=reactExports.useState(Ka??"turns"),Ja=$.get("layout"),[Ya,el]=reactExports.useState(Ja??"default"),tl=reactExports.useMemo(()=>(Qr==null?void 0:Qr.pages.flat())??[],[Qr]),rl=reactExports.useMemo(()=>{switch(Ga){case"conversation":return tl.filter(Bl=>Bl.eventType==="user_message"||isAgentResponseEvent(Bl));case"tools":return tl.filter(Bl=>Bl.eventType==="tool_call");case"responses":return tl.filter(isAgentResponseEvent);default:return tl}},[tl,Ga]),cl=reactExports.useMemo(()=>groupEventsIntoTurns([...tl].sort((Bl,ru)=>Bl.sequence-ru.sequence)),[tl]),dl=reactExports.useMemo(()=>((is==null?void 0:is.linkedInstructions)??[]).filter(Bl=>Bl.linkMethod==="context_file"),[is==null?void 0:is.linkedInstructions]),fl=reactExports.useMemo(()=>((is==null?void 0:is.linkedInstructions)??[]).filter(Bl=>Bl.linkMethod!=="context_file"),[is==null?void 0:is.linkedInstructions]),nl=reactExports.useMemo(()=>sessionEventCounts(tl,is==null?void 0:is.eventCounts),[is==null?void 0:is.eventCounts,tl]);if(cs)return jsxRuntimeExports.jsx(Skeleton,{className:"h-96 w-full"});if(!is)return jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Session not found"});const ol=is.analysis,pl=ol==null?void 0:ol.adherenceScore,Tl=ol==null?void 0:ol.summary,ul=ol==null?void 0:ol.suggestions,hl=ol==null?void 0:ol.brief_summary,jl=ol==null?void 0:ol.underlying_goal,Nl=ol==null?void 0:ol.outcome,zl=ol==null?void 0:ol.session_type,Zl=ol==null?void 0:ol.goal_categories,Dl=ol==null?void 0:ol.friction_counts,Il=ol==null?void 0:ol.friction_detail,Fl=ol==null?void 0:ol.primary_success,ql=ol==null?void 0:ol.tool,nu=is.analyzedAt??(ol==null?void 0:ol.analyzed_at),Gl=is.analyzedEventCount??(ol==null?void 0:ol.analyzed_event_count),cu=is.analyzedTurnCount??(ol==null?void 0:ol.analyzed_turn_count),Al=!!hl||!!jl,Ml=Object.values(Dl??{}).reduce((Bl,ru)=>Bl+ru,0),Ql=is.endedAt?Math.max(0,Math.round((new Date(is.endedAt).getTime()-new Date(is.startedAt).getTime())/6e4)):null,eu=ol?jsxRuntimeExports.jsxs("div",{className:`mt-2 flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs ${nu?"border-border bg-muted/40 text-foreground":"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300"}`,children:[jsxRuntimeExports.jsx(Clock,{className:"h-3.5 w-3.5 shrink-0"}),jsxRuntimeExports.jsx("div",{className:"flex-1 font-mono",children:nu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Analyzed"})," ",formatEventTimestamp(nu),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" ","(",new Date(nu).toLocaleString(),")"]}),(cu!=null||Gl!=null)&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" · ",cu!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["through turn ",cu]}),Gl!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cu!=null?" ":"","(",Gl," event",Gl===1?"":"s",")"]})]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Analyzed at unknown time"})," — ","this analysis predates timestamp tracking. Re-analyze to record when it ran and which turn it covered."]})}),!nu&&canAnalyzeWithToolCli(is.tool)&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-7 cursor-pointer text-xs",onClick:()=>Ia.mutate(is.id),disabled:Ia.isPending||Ia.isSuccess,children:Ia.isPending?"Submitting...":Ia.isSuccess?"Queued":"Re-analyze"})]}):null,fu=(is.metadata??{}).clientName,Ou=[{key:"turns",label:"Turns"},{key:"all",label:"All"},{key:"conversation",label:"Conversation"},{key:"tools",label:"Tools"},{key:"responses",label:"Responses"}],yu=(()=>{if(is.tool!=="claude_code"||!is.externalSessionId)return!1;if(!is.endedAt||new Date(is.endedAt).getTime()<new Date(is.startedAt).getTime())return!0;const Bl=10080*60*1e3;return Date.now()-new Date(is.endedAt).getTime()<Bl})();return jsxRuntimeExports.jsxs("div",{className:`space-y-6 ${yu?"pb-40":""}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"cursor-pointer shrink-0",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/sessions",children:jsxRuntimeExports.jsx(ArrowLeft,{className:"h-4 w-4"})})}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Session Detail"}),is.gitBranch&&jsxRuntimeExports.jsxs("span",{title:`git branch: ${is.gitBranch}`,className:"inline-flex items-center gap-1.5 rounded-md border border-primary/40 bg-primary/10 px-2.5 py-1 font-mono text-sm font-semibold text-primary max-w-[11rem] sm:max-w-[18rem] truncate",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-4 w-4 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:is.gitBranch})]})]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground font-mono text-sm flex items-center gap-1.5 flex-wrap",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:is.tool,className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:displayTool(is.tool)}),is.harnessVersion&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60",title:"harness version",children:["v",is.harnessVersion]}),fu&&jsxRuntimeExports.jsxs("span",{children:["(",fu,")"]}),is.model&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground/80",title:"model (rolled up from the transcript)",children:is.model})]}),jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{children:projectDisplayName(is)}),jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{children:formatEventTimestamp(is.startedAt)})," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60",children:["(",is.startedAt?new Date(is.startedAt).toLocaleString():"—",")"]})]}),nl.total>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[nl.partial&&"Loaded events: ",nl.messages," messages, ",nl.tools," tool calls",nl.assistantResponses>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[", ",nl.assistantResponses," responses"]})]})]})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2",children:!ol&&canAnalyzeWithToolCli(is.tool)&&jsxRuntimeExports.jsx(Button,{onClick:()=>Ia.mutate(is.id),disabled:Ia.isPending||Ia.isSuccess,className:"cursor-pointer bg-primary text-primary-foreground",children:Ia.isPending?"Submitting...":Ia.isSuccess?"Analysis queued...":`Analyze via ${displayTool(is.tool)}`})})]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Outcome"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[Nl==="achieved"||Nl==="mostly_achieved"?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(CircleHelp,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold capitalize",children:(Nl==null?void 0:Nl.replace(/_/g," "))??"Not analyzed"})]})]})}),jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Activity"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-blue-500"}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-lg font-semibold",children:[nl.messages," messages",nl.partial&&" (loaded)"]})]}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[nl.tools," tool calls · ",nl.total," events"]})]})}),jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Elapsed time"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold",children:Ql==null?"In progress":Ql<60?`${Ql}m`:`${Math.floor(Ql/60)}h ${Ql%60}m`})]})]})}),jsxRuntimeExports.jsx(Card,{className:Ml>0?"border-amber-500/30 bg-amber-500/5":"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Friction"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:`h-4 w-4 ${Ml?"text-amber-500":"text-muted-foreground"}`}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold",children:ol?`${Ml} signal${Ml===1?"":"s"}`:"Unknown"})]})]})})]}),(jl||hl)&&jsxRuntimeExports.jsx(Card,{className:"border-primary/20 bg-primary/[0.03]",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-5",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Session goal"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-base font-medium",children:jl??hl}),jl&&hl&&jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:hl})]})}),Ma&&Ma.status!=="completed"&&jsxRuntimeExports.jsx(Card,{className:"bg-card border-border border-l-2 border-l-primary",children:jsxRuntimeExports.jsx(CardContent,{className:"pt-4 pb-4",children:jsxRuntimeExports.jsx("div",{className:"flex items-center gap-3",children:Ma.status==="failed"?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 text-destructive"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-destructive",children:"Analysis failed"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Ma.error})]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-primary"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium",children:[Ma.status==="pending"&&"Waiting for worker...",Ma.status==="claimed"&&"Worker picked up job...",Ma.status==="running"&&"Analyzing session..."]}),!!((Iu=Ma.progress)!=null&&Iu.step)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:[String(Ma.progress.step).replace(/_/g," "),!!Ma.progress.tool&&` via ${displayTool(String(Ma.progress.tool))}`]})]})]})})})}),ol&&Al?jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs(CardTitle,{className:"font-mono text-lg flex items-center gap-2",children:["Analysis",Nl&&jsxRuntimeExports.jsx(Badge,{variant:Nl==="achieved"||Nl==="mostly_achieved"?"default":Nl==="partially_achieved"?"secondary":"destructive",className:"font-mono",children:Nl.replace(/_/g," ")}),zl&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:zl.replace(/_/g," ")}),ql&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["via ",displayTool(ql)]})]}),eu]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[hl&&jsxRuntimeExports.jsx("p",{className:"text-sm",children:hl}),jl&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Goal"}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:jl})]}),Fl&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Primary Success"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-teal-600 dark:text-teal-400",children:Fl})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[Zl&&Object.keys(Zl).length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Goal Categories"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:Object.entries(Zl).filter(([,Bl])=>Bl>0).sort(([,Bl],[,ru])=>ru-Bl).map(([Bl,ru])=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono",children:[Bl.replace(/_/g," ")," ",ru>1?`(${ru})`:""]},Bl))})]}),Dl&&Object.values(Dl).some(Bl=>Bl>0)&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Friction Points"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:Object.entries(Dl).filter(([,Bl])=>Bl>0).sort(([,Bl],[,ru])=>ru-Bl).map(([Bl,ru])=>jsxRuntimeExports.jsxs(Badge,{variant:"destructive",className:"text-xs font-mono",children:[Bl.replace(/_/g," ")," (",ru,")"]},Bl))}),Il&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:Il})]})]})]})]}):ol&&jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs(CardTitle,{className:"font-mono text-lg flex items-center gap-2",children:["Analysis",pl!=null&&jsxRuntimeExports.jsxs(Badge,{variant:pl>=80?"default":pl>=50?"secondary":"destructive",className:"font-mono",children:[pl,"% adherence"]})]}),eu]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Tl}),ul&&ul.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:"Suggestions"}),ul.map((Bl,ru)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded p-3 mb-2 bg-background",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:Bl.rationale}),jsxRuntimeExports.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Current"}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono p-2 bg-card rounded",children:Bl.currentContent})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-primary mb-1",children:"Suggested"}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono p-2 bg-card rounded border-primary/20 border",children:Bl.suggestedContent})]})]})]},ru))]})]})]}),jsxRuntimeExports.jsxs(TooltipProvider,{children:[(dl.length>0||fl.length>0)&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[dl.length>0&&jsxRuntimeExports.jsx(ContextBlock,{instructions:dl}),fl.length>0&&fl.map(Bl=>jsxRuntimeExports.jsx(InstructionCard,{instruction:Bl},Bl.instructionId))]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[jsxRuntimeExports.jsxs("h3",{className:"text-sm font-medium flex items-center gap-1.5",children:["Timeline",jsxRuntimeExports.jsx(InfoTip,{content:"Conversation turns between you and the AI, including tool calls, thinking, and responses. Proxy snapshots show the exact context sent to the LLM for each turn."})]}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1 ml-auto",children:Ou.map(Bl=>jsxRuntimeExports.jsx(Badge,{asChild:!0,className:"py-1",variant:Ga===Bl.key?"default":"outline",children:jsxRuntimeExports.jsx("button",{type:"button",className:"cursor-pointer",onClick:()=>Va(Bl.key),children:Bl.label})},Bl.key))}),((Ha==null?void 0:Ha.length)??0)>0&&jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono shrink-0",children:[Ha.length," snapshots"]})]}),Ga==="turns"&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono",children:"Layout"}),[{key:"default",label:"Inline"},{key:"split",label:"Side panel"},{key:"capped",label:"Capped + summary"}].map(Bl=>jsxRuntimeExports.jsx(Badge,{asChild:!0,className:"py-1",variant:Ya===Bl.key?"default":"outline",children:jsxRuntimeExports.jsx("button",{type:"button",className:"cursor-pointer",onClick:()=>{el(Bl.key);const ru=new URLSearchParams($);Bl.key==="default"?ru.delete("layout"):ru.set("layout",Bl.key),ts(ru,{replace:!0})},children:Bl.label})},Bl.key))]}),ja?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:10}).map((Bl,ru)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-16 w-full"},ru))}):Ga==="turns"?jsxRuntimeExports.jsxs("div",{children:[cl.length===0&&((Ha==null?void 0:Ha.length)??0)===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(FileText,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No activity captured"}),jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Use ",jsxRuntimeExports.jsx("code",{className:"font-mono text-xs bg-secondary px-1 py-0.5 rounded",children:"rulemetric proxy start"})," to capture LLM context, or install hooks for event capture"]})]}):cl.length===0?jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground py-8 text-center",children:["No conversation turns — ",(Ha==null?void 0:Ha.length)??0," proxy snapshots captured."]}):(()=>{var Mu,lc;const Bl=((lc=(Mu=is==null?void 0:is.eventCounts)==null?void 0:Mu.byType)==null?void 0:lc.user_message)??cl.length,ru=[...cl].map((Tu,Eu)=>({turn:Tu,chronoIdx:Eu})).reverse();if(Ya==="split")return jsxRuntimeExports.jsx("div",{className:"space-y-2",children:ru.map(({turn:Tu,chronoIdx:Eu},Ua)=>{var yl;const ll=Ha==null?void 0:Ha[Eu];return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_360px] gap-6 border-t border-border/40 first:border-t-0",children:[jsxRuntimeExports.jsx(TurnContainer,{turn:Tu,index:Ua,totalTurns:Bl,snapshot:ll,hideSnapshot:!0}),jsxRuntimeExports.jsx("div",{className:"hidden lg:block pt-6",children:ll?jsxRuntimeExports.jsx("div",{className:"sticky top-4",children:jsxRuntimeExports.jsx(InlineTurnSnapshot,{snapshot:ll})}):jsxRuntimeExports.jsx("div",{className:"sticky top-4 text-xs text-muted-foreground/60 font-mono pt-2",children:"No snapshot for this turn"})})]},((yl=Tu.userMessage)==null?void 0:yl.id)??`turn-${Eu}`)})});if(Ya==="capped"){const Tu=(Ha??[]).reduce((Ua,ll)=>Ua+(ll.estimatedTokens??0),0),Eu=nl.tools;return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px] gap-8",children:[jsxRuntimeExports.jsx("div",{className:"max-w-3xl",children:ru.map(({turn:Ua,chronoIdx:ll},yl)=>{var $l;return jsxRuntimeExports.jsx(TurnContainer,{turn:Ua,index:yl,totalTurns:Bl,snapshot:Ha==null?void 0:Ha[ll]},(($l=Ua.userMessage)==null?void 0:$l.id)??`turn-${ll}`)})}),jsxRuntimeExports.jsx("aside",{className:"hidden xl:block",children:jsxRuntimeExports.jsxs("div",{className:"sticky top-4 space-y-3 border border-border rounded-lg p-4 bg-card",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Session Summary"}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Turns"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Bl})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Tool calls"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Eu})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Snapshots"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:(Ha==null?void 0:Ha.length)??0})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"~Total tokens"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Tu.toLocaleString()})]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border/40 pt-3",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Per-turn"}),jsxRuntimeExports.jsx("div",{className:"space-y-1 max-h-96 overflow-y-auto pr-1",children:ru.map(({turn:Ua,chronoIdx:ll},yl)=>{var bl,_l;const $l=Ha==null?void 0:Ha[ll],kl=Bl-yl,Za=Ua.events.filter(Ol=>Ol.eventType==="tool_call").length,al=eventUsage(Ua.assistantResponse)??((bl=$l==null?void 0:$l.metadata)==null?void 0:bl.usage),El=al==null?void 0:al.output_tokens;return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-mono",children:[jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60 w-10",children:["T",kl]}),Za>0&&jsxRuntimeExports.jsxs("span",{className:"text-amber-500",children:[Za,"t"]}),El!=null&&El>0&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[formatTokenCount(El),"tk"]}),($l==null?void 0:$l.estimatedTokens)!=null&&jsxRuntimeExports.jsxs("span",{className:"text-cyan-500/80 ml-auto",children:[formatTokenCount($l.estimatedTokens)," ctx"]})]},((_l=Ua.userMessage)==null?void 0:_l.id)??`meta-${ll}`)})})]})]})})]})}return ru.map(({turn:Tu,chronoIdx:Eu},Ua)=>{var ll;return jsxRuntimeExports.jsx(TurnContainer,{turn:Tu,index:Ua,totalTurns:Bl,snapshot:Ha==null?void 0:Ha[Eu]},((ll=Tu.userMessage)==null?void 0:ll.id)??`turn-${Eu}`)})})(),Na&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-6 pb-2",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Aa(),disabled:Oa,className:"cursor-pointer",children:Oa?"Loading...":"Load more events"})})]}):rl.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No events match the current filter."}):jsxRuntimeExports.jsxs("div",{children:[rl.map(Bl=>jsxRuntimeExports.jsx("div",{children:renderEvent(Bl)},Bl.id)),Na&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-6 pb-2",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Aa(),disabled:Oa,className:"cursor-pointer",children:Oa?"Loading...":"Load more events"})})]})]})]}),yu&&jsxRuntimeExports.jsx(ResumeBar,{sessionId:is.id,session:is,externalSessionId:is.externalSessionId,launchProjectPath:is.primaryCheckoutPath??is.projectPath??"/tmp",resumePrompt:qa,setResumePrompt:Fa,resumeMutation:La})]})}function ResumeBar({sessionId:es,session:$,externalSessionId:ts,launchProjectPath:is,resumePrompt:cs,setResumePrompt:Qr,resumeMutation:ja}){const{data:Na}=useSessionTerminalTarget(es),Aa=useSendMessage$1(es),{data:Oa}=useLaunchJobs(),Ia=(Na==null?void 0:Na.target)??null,La=(Na==null?void 0:Na.capabilities)??{liveSend:!1,fallbackResume:!0,tmuxAvailable:!1,workerOnline:!1},Ba=(()=>{const ol=!!(Ia&&Ia.status==="active");return!La.workerOnline&&ol?"worker_offline":ol&&La.liveSend?"live_ready":Ia&&Ia.status!=="active"?"target_missing":La.tmuxAvailable?"launch_ready":"tmux_missing"})(),Ma=Aa.isPending?"sending":Aa.isError?"send_failed":Aa.isSuccess?"sent":Ba,qa=Ba==="live_ready"&&(Ma==="live_ready"||Ma==="sending"||Ma==="sent"),Fa=qa?"Send to live Claude session… (Enter submits, Shift+Enter for newline)":"Resume this session… (Enter submits, Shift+Enter for newline)",Ha=(()=>{switch(Ma){case"live_ready":return"Send to live Claude";case"launch_ready":return"Resume in Terminal";case"tmux_missing":return"Resume in Terminal";case"target_missing":return"Start new live session";case"worker_offline":return"Worker offline";case"sending":return qa?"Sending…":"Resuming…";case"sent":return qa?"Sent":"Resumed";case"send_failed":return"Retry"}})(),Ka=Ma==="worker_offline"||Ma==="sending"||ja.isPending,Ga=Aa.data,Va=(Ga==null?void 0:Ga.delivery)==="live"?Ga.target.target:null,Ja=(Ia==null?void 0:Ia.attachCommand)??(Ia!=null&&Ia.target?`tmux attach -t ${Ia.target}`:null),Ya=(Oa??[]).find(ol=>{var pl;return((pl=ol.config)==null?void 0:pl.resumeSessionId)===ts}),el=Ya==null?void 0:Ya.status,tl=!!(Ya!=null&&Ya.completedAt)&&Date.now()-new Date(Ya.completedAt).getTime()<3e4,rl=(()=>{var ol;return Ma==="send_failed"?{dot:"bg-red-500",label:Aa.error instanceof Error?Aa.error.message:"Send failed"}:Ma==="sent"&&qa&&Va?{dot:"bg-teal-500",label:`Sent to ${Va}`}:el==="pending"||el==="claimed"?{dot:"bg-amber-500 animate-pulse",label:"Queued — waiting for worker"}:el==="running"?{dot:"bg-teal-500 animate-pulse",label:(ol=Ya==null?void 0:Ya.result)!=null&&ol.pid?`Running (PID ${Ya.result.pid})`:"Running"}:el==="failed"?{dot:"bg-red-500",label:(Ya==null?void 0:Ya.error)??"Failed"}:el==="completed"&&tl?{dot:"bg-teal-500",label:"Resumed — Claude is now active"}:null})(),cl=La.workerOnline?"":" Worker offline — job will queue and run when the worker connects.",dl=(()=>{switch(Ba){case"worker_offline":return"Start worker: `rulemetric service install` or `rulemetric evals agent`";case"tmux_missing":return"Install tmux to enable live send."+cl;case"target_missing":return"The previous tmux session ended. Starting a new one will spawn a fresh terminal."+cl;case"launch_ready":return"Live send needs a tmux target. Fallback will spawn a new terminal."+cl;default:return null}})(),fl=ol=>{ts&&ja.mutate({tool:"claude_code",projectPath:is,mode:"interactive",resumeSessionId:ts,...ol?{prompt:ol}:{}},{onSuccess:()=>{ue$1(ol?"Resume request sent":"Resume request sent (no prompt)"),Qr("")},onError:pl=>ue$1.error(pl instanceof Error?pl.message:"Failed to resume")})},nl=()=>{if(Ka)return;const ol=cs.trim();if(!ol){if(Ba==="live_ready"){ue$1.error("Type a message to send");return}if(!ts)return;fl("");return}if(Ba==="live_ready"){Aa.mutate({message:ol,delivery:"live",submit:!0},{onSuccess:()=>Qr("")});return}ts&&fl(ol)};return jsxRuntimeExports.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 border-t border-border bg-background shadow-[0_-4px_20px_rgba(0,0,0,0.15)]",children:[rl&&jsxRuntimeExports.jsx("div",{className:"border-b border-border/60 bg-secondary/40",children:jsxRuntimeExports.jsxs("div",{className:"max-w-screen-xl mx-auto px-6 py-1.5 sm:px-8 flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:`h-2 w-2 rounded-full ${rl.dot}`}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:rl.label}),Ja&&Ma==="sent"&&qa&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/70 font-mono ml-2",children:["· ",Ja]})]})}),jsxRuntimeExports.jsxs("div",{className:"max-w-screen-xl mx-auto px-6 py-3 sm:px-8 space-y-2",children:[jsxRuntimeExports.jsx(SessionTargetSummary,{target:Ia,capabilities:La,session:$}),dl&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:dl}),jsxRuntimeExports.jsxs("form",{onSubmit:ol=>{ol.preventDefault(),nl()},className:"flex items-end gap-2",children:[jsxRuntimeExports.jsx("textarea",{value:cs,onChange:ol=>Qr(ol.target.value),onKeyDown:ol=>{var pl;ol.key==="Enter"&&!ol.shiftKey&&!ol.nativeEvent.isComposing&&(ol.preventDefault(),(pl=ol.currentTarget.form)==null||pl.requestSubmit())},placeholder:Fa,rows:2,className:"flex-1 resize-none rounded-md border border-input bg-card px-3 py-2 text-sm font-mono ring-offset-background placeholder:text-muted-foreground/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",disabled:Ka}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ka,className:"cursor-pointer self-end",children:Ha})]})]})]})}function useProjects(es={}){const $=new URLSearchParams;es.limit&&$.set("limit",String(es.limit)),es.offset&&$.set("offset",String(es.offset));const ts=$.toString();return useQuery({queryKey:["projects",es],queryFn:()=>apiGet(`/api/projects${ts?`?${ts}`:""}`),refetchInterval:POLL.ACTIVE})}function useProject(es){return useQuery({queryKey:["projects",es],queryFn:()=>apiGet(`/api/projects/${es}`),enabled:!!es,refetchInterval:POLL.ACTIVE})}function Select({...es}){return jsxRuntimeExports.jsx(Root2$1,{"data-slot":"select",...es})}function SelectValue({...es}){return jsxRuntimeExports.jsx(Value,{"data-slot":"select-value",...es})}function SelectTrigger({className:es,size:$="default",children:ts,...is}){return jsxRuntimeExports.jsxs(Trigger$3,{"data-slot":"select-trigger","data-size":$,className:cn$1("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",es),...is,children:[ts,jsxRuntimeExports.jsx(Icon,{asChild:!0,children:jsxRuntimeExports.jsx(ChevronDown,{className:"size-4 opacity-50"})})]})}function SelectContent({className:es,children:$,position:ts="item-aligned",align:is="center",...cs}){return jsxRuntimeExports.jsx(Portal$2,{children:jsxRuntimeExports.jsxs(Content2$2,{"data-slot":"select-content",className:cn$1("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",ts==="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",es),position:ts,align:is,...cs,children:[jsxRuntimeExports.jsx(SelectScrollUpButton,{}),jsxRuntimeExports.jsx(Viewport,{className:cn$1("p-1",ts==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:$}),jsxRuntimeExports.jsx(SelectScrollDownButton,{})]})})}function SelectItem({className:es,children:$,...ts}){return jsxRuntimeExports.jsxs(Item,{"data-slot":"select-item",className:cn$1("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",es),...ts,children:[jsxRuntimeExports.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:jsxRuntimeExports.jsx(ItemIndicator,{children:jsxRuntimeExports.jsx(Check,{className:"size-4"})})}),jsxRuntimeExports.jsx(ItemText,{children:$})]})}function SelectScrollUpButton({className:es,...$}){return jsxRuntimeExports.jsx(ScrollUpButton,{"data-slot":"select-scroll-up-button",className:cn$1("flex cursor-default items-center justify-center py-1",es),...$,children:jsxRuntimeExports.jsx(ChevronUp,{className:"size-4"})})}function SelectScrollDownButton({className:es,...$}){return jsxRuntimeExports.jsx(ScrollDownButton,{"data-slot":"select-scroll-down-button",className:cn$1("flex cursor-default items-center justify-center py-1",es),...$,children:jsxRuntimeExports.jsx(ChevronDown,{className:"size-4"})})}function Textarea({className:es,...$}){return jsxRuntimeExports.jsx("textarea",{"data-slot":"textarea",className:cn$1("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",es),...$})}function sanitizeTmuxName(es){return`rm-${es.trim().replace(/[^A-Za-z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"session"}`}function previewTmuxTarget(es){return sanitizeTmuxName("claude-auto")}function LaunchSessionDialog({open:es,onOpenChange:$,initialProjectPath:ts}){const is=useNavigate(),{data:cs}=useAvailableLaunchers(),Qr=useCreateLaunchJob(),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(ts??""),[Ia,La]=reactExports.useState(""),[Ba,Ma]=reactExports.useState(""),[qa,Fa]=reactExports.useState("interactive");reactExports.useEffect(()=>{es&&Oa(Ja=>Ja||(ts??""))},[es,ts]);const Ha=()=>{Na(""),Oa(ts??""),La(""),Ma(""),Fa("interactive")},Ka=reactExports.useMemo(()=>previewTmuxTarget(),[]),Ga=Ja=>{Ja.preventDefault(),!(!ja||!Aa)&&Qr.mutate({tool:ja,projectPath:Aa,prompt:Ia||void 0,model:Ba||void 0,mode:qa},{onSuccess:Ya=>{var cl;const el=Ya.result,tl=(cl=el==null?void 0:el.terminalTarget)==null?void 0:cl.target,rl=(el==null?void 0:el.terminalTarget)&&el.terminalTarget.live===!1;ue$1(qa==="headless"?"Starting headless Claude Code job":tl?`Starting Claude Code in tmux target ${tl}`:rl?"Starting Claude Code in Terminal fallback":`Starting Claude Code in tmux target ${Ka}`),Ya.noLiveWorker&&ue$1.error("No worker online — start `rulemetric evals agent` to process this launch"),Ya.sessionId?is(`/sessions/${Ya.sessionId}`):is("/sessions"),Ha(),$(!1)},onError:Ya=>{ue$1.error(Ya instanceof Error?Ya.message:"Failed to create launch job")}})},Va=!!(ja&&Aa);return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-md",children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{children:"Launch Session"})}),jsxRuntimeExports.jsxs("form",{onSubmit:Ga,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"tool",children:"Tool"}),jsxRuntimeExports.jsxs(Select,{value:ja,onValueChange:Na,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"tool",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select a tool"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs==null?void 0:cs.map(Ja=>jsxRuntimeExports.jsx(SelectItem,{value:Ja.tool,children:Ja.tool.replace(/_/g," ")},Ja.tool))})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"projectPath",children:"Project Path"}),jsxRuntimeExports.jsx(Input,{id:"projectPath",value:Aa,onChange:Ja=>Oa(Ja.target.value),placeholder:"/path/to/project",required:!0})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"prompt",children:"Prompt"}),jsxRuntimeExports.jsx(Textarea,{id:"prompt",value:Ia,onChange:Ja=>La(Ja.target.value),placeholder:"Optional prompt for the session",rows:3})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"model",children:"Model"}),jsxRuntimeExports.jsx(Input,{id:"model",value:Ba,onChange:Ja=>Ma(Ja.target.value),placeholder:"Optional model override"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"mode",children:"Mode"}),jsxRuntimeExports.jsxs(Select,{value:qa,onValueChange:Ja=>Fa(Ja),children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"mode",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"interactive",children:"Interactive"}),jsxRuntimeExports.jsx(SelectItem,{value:"headless",children:"Headless"})]})]})]}),Va&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-3 text-xs font-mono space-y-1",children:[jsxRuntimeExports.jsx("div",{className:"text-muted-foreground uppercase tracking-wide text-[10px] mb-1",children:"Launch summary"}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Tool"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:ja.replace(/_/g," ")})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Mode"}),jsxRuntimeExports.jsx("span",{children:qa})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Project path"}),jsxRuntimeExports.jsx("span",{className:"truncate",title:Aa,children:Aa})]}),Ia&&jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Prompt"}),jsxRuntimeExports.jsx("span",{className:"truncate max-w-[16rem]",title:Ia,children:Ia})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Expected target"}),jsxRuntimeExports.jsx("span",{className:"truncate",title:Ka,children:Ka})]}),qa==="interactive"&&jsxRuntimeExports.jsx("div",{className:"pt-1 text-[10px] text-amber-600",children:"Live send requires tmux on the worker host."})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",onClick:()=>$(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:!ja||!Aa||Qr.isPending,children:Qr.isPending?"Launching...":"Launch"})]})]})]})})}function ProjectCard$1({p:es,onClick:$,onLaunch:ts}){return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",onClick:$,children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0 pb-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-base font-semibold truncate",children:es.name}),es.gitRemoteUrl&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1 mt-1",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:es.gitRemoteUrl})]}),es.primaryCheckoutPath&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1 mt-0.5",children:[jsxRuntimeExports.jsx(Folder,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:es.primaryCheckoutPath})]})]}),jsxRuntimeExports.jsx("div",{className:"flex flex-col items-end gap-1 shrink-0 ml-3",children:es.activeSessionCount>0?jsxRuntimeExports.jsxs(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:[es.activeSessionCount," active"]}):jsxRuntimeExports.jsx(Badge,{variant:"outline",children:"idle"})})]}),jsxRuntimeExports.jsxs(CardContent,{className:"pt-0 pb-4 text-xs text-muted-foreground font-mono flex items-center justify-between",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," session",es.sessionCount===1?"":"s"," total"]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsxs("span",{children:["last activity ",formatRelativeTime(es.lastActivityAt,{fallback:"never"})]}),es.primaryCheckoutPath&&jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"outline",className:"h-7 px-2 text-[11px] cursor-pointer",onClick:is=>{is.stopPropagation(),ts(es.primaryCheckoutPath)},title:`Launch a new session in ${es.primaryCheckoutPath}`,children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3 w-3 mr-1"}),"Launch"]})]})]})]})}function ProjectsListPage(){const es=useNavigate(),{data:$,isLoading:ts,isError:is}=useProjects({limit:100}),[cs,Qr]=reactExports.useState("cards"),[ja,Na]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState(void 0),Ia=Ba=>{Oa(Ba),Na(!0)};let La;return ts?La=jsxRuntimeExports.jsxs("div",{className:"grid gap-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"})]}):is?La=jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-destructive font-mono",children:"Failed to load projects."}):!$||$.projects.length===0?La=jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Layers,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No projects yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm mt-1",children:"Projects appear after your first captured session in this org."})]}):cs==="cards"?La=jsxRuntimeExports.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:$.projects.map(Ba=>jsxRuntimeExports.jsx(ProjectCard$1,{p:Ba,onClick:()=>es(`/projects/${Ba.id}`),onLaunch:Ma=>Ia(Ma)},Ba.id))}):La=jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{children:"Project"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Active"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Total"}),jsxRuntimeExports.jsx(TableHead,{className:"w-40 text-right",children:"Last activity"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsx(TableBody,{children:$.projects.map(Ba=>jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>es(`/projects/${Ba.id}`),children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("div",{className:"font-mono text-sm font-semibold truncate",children:Ba.name}),Ba.gitRemoteUrl&&jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground font-mono truncate",children:Ba.gitRemoteUrl})]})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:Ba.activeSessionCount>0?jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:Ba.activeSessionCount}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono text-sm",children:"—"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right font-mono text-sm",children:Ba.sessionCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:formatRelativeTime(Ba.lastActivityAt,{fallback:"never"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",onClick:Ma=>Ma.stopPropagation(),children:Ba.primaryCheckoutPath?jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"outline",className:"h-7 px-2 text-[11px] cursor-pointer",onClick:()=>Ia(Ba.primaryCheckoutPath),title:`Launch a new session in ${Ba.primaryCheckoutPath}`,children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3 w-3 mr-1"}),"Launch"]}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})})]},Ba.id))})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Projects"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"All projects in your active org. Click one to see its sessions."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",className:"h-8 cursor-pointer",onClick:()=>Ia(void 0),children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3.5 w-3.5 mr-1.5"}),"Launch session"]}),jsxRuntimeExports.jsxs("div",{role:"group","aria-label":"View mode",className:"inline-flex items-center rounded-md border border-border bg-card p-0.5",children:[jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:cs==="cards"?"secondary":"ghost","aria-pressed":cs==="cards",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>Qr("cards"),children:"Cards"}),jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:cs==="list"?"secondary":"ghost","aria-pressed":cs==="list",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>Qr("list"),children:"List"})]})]})]}),La,jsxRuntimeExports.jsx(LaunchSessionDialog,{open:ja,onOpenChange:Na,initialProjectPath:Aa})]})}function useRuns(es={}){const $=new URLSearchParams;es.limit&&$.set("limit",String(es.limit)),es.offset&&$.set("offset",String(es.offset)),es.projectId&&$.set("projectId",es.projectId);const ts=$.toString();return useQuery({queryKey:["runs","list",es],queryFn:()=>apiGet(`/api/runs${ts?`?${ts}`:""}`),enabled:es.projectId===void 0||!!es.projectId,refetchInterval:POLL.ACTIVE})}function useRunsEnabled(){return"false"==="1"}function sessionGoal(es){var ts;const $=(ts=es.analysis)==null?void 0:ts.goalSummary;return $?{text:$,isFallback:!1}:es.firstUserPrompt?{text:es.firstUserPrompt,isFallback:!0}:{text:"(no goal yet)",isFallback:!0}}function isActive(es){if(es.endedAt)return!1;const $=new Date(es.lastActivityAt??es.startedAt).getTime();return Date.now()-$<1800*1e3}function duration$1(es){const ts=new Date(es.endedAt??es.lastActivityAt??es.startedAt).getTime()-new Date(es.startedAt).getTime();if(!Number.isFinite(ts)||ts<0)return"—";const is=Math.floor(ts/6e4);return is<1?"<1m":is<60?`${is}m`:`${Math.floor(is/60)}h ${is%60}m`}function SessionCard({s:es,emphasized:$,onOpen:ts}){const is=sessionGoal(es);return jsxRuntimeExports.jsx(Card,{className:`cursor-pointer transition-colors hover:bg-secondary/30 ${$?"border-teal-500/40 shadow-[0_0_12px_-4px_rgba(16,185,129,0.35)]":""}`,onClick:ts,children:jsxRuntimeExports.jsxs(CardContent,{className:"py-3 flex flex-col gap-2 h-full",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground font-mono flex-wrap",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:captureToolKey(es.tool),className:"h-4 w-4 shrink-0"}),jsxRuntimeExports.jsx("span",{children:displayTool(es.tool)}),es.gitBranch&&jsxRuntimeExports.jsxs("span",{children:["· ",es.gitBranch]}),jsxRuntimeExports.jsxs("span",{children:["· ",formatRelativeTime(es.lastActivityAt??es.startedAt)]}),isActive(es)&&jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30 text-[10px]",children:"active"})]}),jsxRuntimeExports.jsx("p",{className:`text-sm line-clamp-2 ${is.isFallback?"italic text-muted-foreground":"text-foreground"}`,children:is.text}),es.lastMessagePreview&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground line-clamp-2 font-mono",children:["↳ ",es.lastMessagePreview]}),jsxRuntimeExports.jsxs("div",{className:"mt-auto pt-1 text-[11px] text-muted-foreground font-mono",children:[es.eventCount," events · ",duration$1(es)]})]})})}function ProjectDetailPage(){const{id:es}=useParams(),$=useNavigate(),ts=useProject(es),is=useSessions({projectId:es,hideEmpty:!1,limit:200}),cs=useRunsEnabled();useRuns({projectId:""});const[Qr,ja]=reactExports.useState("cards"),[Na,Aa]=reactExports.useState(!1);if(ts.isLoading)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"})]});if(ts.isError||!ts.data)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/projects",className:"text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"h-3 w-3"})," Projects"]}),jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-destructive font-mono",children:"Project not found."})]});const Oa=ts.data,Ia=is.data??[],La=null,Ba=Ia;let Ma;if(is.isLoading)Ma=jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});else if(Ia.length===0)Ma=jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground font-mono text-sm",children:"No sessions yet for this project."});else if(Qr==="cards"){const qa=Ba.filter(isActive),Fa=Ba.filter(Ha=>!isActive(Ha));Ma=jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[qa.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"relative flex h-2 w-2",children:[jsxRuntimeExports.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-teal-500 opacity-60"}),jsxRuntimeExports.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-teal-500"})]}),jsxRuntimeExports.jsxs("h4",{className:"text-sm font-mono font-semibold text-teal-600",children:["Active now · ",qa.length]})]}),jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:qa.map(Ha=>jsxRuntimeExports.jsx(SessionCard,{s:Ha,emphasized:!0,onOpen:()=>$(`/sessions/${Ha.id}`)},Ha.id))})]}),Fa.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[qa.length>0&&jsxRuntimeExports.jsx("h4",{className:"text-sm font-mono font-semibold text-muted-foreground",children:"Earlier"}),jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:Fa.map(Ha=>jsxRuntimeExports.jsx(SessionCard,{s:Ha,onOpen:()=>$(`/sessions/${Ha.id}`)},Ha.id))})]})]})}else Ma=jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{className:"w-40",children:"Tool"}),jsxRuntimeExports.jsx(TableHead,{className:"w-40",children:"Branch"}),jsxRuntimeExports.jsx(TableHead,{children:"Goal"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24",children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Last activity"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ba.map(qa=>{const Fa=sessionGoal(qa);return jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>$(`/sessions/${qa.id}`),children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:captureToolKey(qa.tool),className:"h-4 w-4 text-muted-foreground shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm truncate",children:displayTool(qa.tool)})]})}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-sm text-muted-foreground",children:qa.gitBranch??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"max-w-md",children:jsxRuntimeExports.jsx("p",{className:`text-sm line-clamp-2 ${Fa.isFallback?"italic text-muted-foreground":"text-foreground"}`,children:Fa.text})}),jsxRuntimeExports.jsx(TableCell,{children:isActive(qa)?jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:"active"}):qa.endedAt?jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs font-mono",children:"ended"}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs font-mono",children:"idle"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:formatRelativeTime(qa.lastActivityAt??qa.startedAt)})]},qa.id)})})]})});return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs(Link,{to:"/projects",className:"text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"h-3 w-3"})," Projects"]}),jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight truncate",children:Oa.name}),Oa.description&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Oa.description}),jsxRuntimeExports.jsxs("div",{className:"mt-2 space-y-1",children:[Oa.gitRemoteUrl&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:Oa.gitRemoteUrl})]}),Oa.primaryCheckoutPath&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(Folder,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:Oa.primaryCheckoutPath})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"text-right shrink-0 space-y-1.5 flex flex-col items-end",children:[cs,Oa.activeSessionCount>0&&jsxRuntimeExports.jsxs(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:[Oa.activeSessionCount," active"]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:[Oa.sessionCount," total"]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:["last ",formatRelativeTime(Oa.lastActivityAt)]})]})]})})}),La,jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-mono font-semibold",children:"Sessions"}),jsxRuntimeExports.jsxs("div",{role:"group","aria-label":"View mode",className:"inline-flex items-center rounded-md border border-border bg-card p-0.5",children:[jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:Qr==="cards"?"secondary":"ghost","aria-pressed":Qr==="cards",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>ja("cards"),children:"Cards"}),jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:Qr==="list"?"secondary":"ghost","aria-pressed":Qr==="list",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>ja("list"),children:"List"})]})]}),Ma,cs]})}function useEvalTargets(es){return useQuery({queryKey:["eval-targets",es],queryFn:()=>apiGet("/api/eval-targets")})}function useEvalTarget(es){return useQuery({queryKey:["eval-targets",es],queryFn:()=>apiGet(`/api/eval-targets/${es}`),enabled:!!es})}function useEvals(es){return useQuery({queryKey:["eval-targets",es,"evals"],queryFn:()=>apiGet(`/api/eval-targets/${es}/evals`),enabled:!!es})}function useEvalRuns(es,$){return useQuery({queryKey:["eval-targets",es,"runs",$],queryFn:()=>apiGet(`/api/eval-targets/${es}/runs`),enabled:!!es})}function useBenchmarks(es){return useQuery({queryKey:["eval-targets",es,"benchmarks"],queryFn:()=>apiGet(`/api/eval-targets/${es}/benchmarks`),enabled:!!es})}function useEvalComparisons(es){return useQuery({queryKey:["eval-targets",es,"comparisons"],queryFn:()=>apiGet(`/api/eval-targets/${es}/comparisons`),enabled:!!es})}function useEvalComparison(es,$=!0){return useQuery({queryKey:["eval-comparisons",es],queryFn:()=>apiGet(`/api/eval-comparisons/${es}`),enabled:!!es&&$})}function useGradeAnnotations(es){return useQuery({queryKey:["eval-targets",es,"annotations"],queryFn:()=>apiGet(`/api/eval-targets/${es}/annotations?limit=500`),enabled:!!es})}function useAnnotateGrade(es){const $=useQueryClient();return useMutation({mutationFn:({runId:ts,expectationIndex:is,verdict:cs,flag:Qr,note:ja})=>apiPut(`/api/eval-runs/${ts}/annotations/${is}`,{verdict:cs,...Qr!==void 0?{flag:Qr}:{},...ja!==void 0?{note:ja}:{}}),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"annotations"]}),$.invalidateQueries({queryKey:["eval-targets",es,"judge-calibration"]})}})}function useRemoveGradeAnnotation(es){const $=useQueryClient();return useMutation({mutationFn:({runId:ts,expectationIndex:is})=>apiDelete(`/api/eval-runs/${ts}/annotations/${is}`),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"annotations"]}),$.invalidateQueries({queryKey:["eval-targets",es,"judge-calibration"]})}})}function useJudgeDisagreements(es){return useQuery({queryKey:["eval-targets",es,"judge-disagreements"],queryFn:()=>apiGet(`/api/eval-targets/${es}/judge-reviews/disagreements`),enabled:!!es})}function useResolveJudgeReview(es){const $=useQueryClient();return useMutation({mutationFn:({id:ts,resolution:is})=>apiPatch(`/api/judge-reviews/${ts}/resolve`,{resolution:is}),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"judge-disagreements"]})}})}function useJudgeCalibration(es){return useQuery({queryKey:["eval-targets",es,"judge-calibration"],queryFn:()=>apiGet(`/api/eval-targets/${es}/judge-calibration`),enabled:!!es})}function useAnnotationQueue(es){return useQuery({queryKey:["eval-targets",es,"annotation-queue"],queryFn:()=>apiGet(`/api/eval-targets/${es}/annotation-queue`),enabled:!!es})}function EvalTargetsListPage(){const es=useNavigate(),{data:$,isLoading:ts}=useEvalTargets();return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Eval Targets"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Manage eval targets and view benchmark results"})]}),ts?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 w-full"},cs))}):$!=null&&$.length?jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{children:"Name"}),jsxRuntimeExports.jsx(TableHead,{children:"Type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Version"}),jsxRuntimeExports.jsx(TableHead,{children:"Description"}),jsxRuntimeExports.jsx(TableHead,{children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:$.map(is=>jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>es(`/eval-targets/${is.id}`),children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-sm font-medium",children:is.name}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono",children:is.type})}),jsxRuntimeExports.jsxs(TableCell,{className:"text-right font-mono text-sm",children:["v",is.version]}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground max-w-64 truncate",children:is.description||"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground",children:new Date(is.updatedAt).toLocaleDateString()})]},is.id))})]})}):jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No eval targets yet"}),jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Create eval targets via the CLI with"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric eval-targets create"})]})]})]})}function usePromotions(es){return useQuery({queryKey:["eval-targets",es,"promotions"],queryFn:()=>apiGet(`/api/eval-targets/${es}/promotions?limit=50`),enabled:!!es})}function useEvalJobs(es){return useQuery({queryKey:["eval-jobs",es],queryFn:()=>apiGet(`/api/eval-targets/${es}/jobs`),enabled:!!es})}function useCreateEvalJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/eval-jobs",$),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-jobs",$.evalTargetId]})}})}function useCancelEvalJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/eval-jobs/${$}/cancel`,{}),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-jobs",$.evalTargetId]})}})}function useRealtimeEvalJobs(es,$){const ts=useQueryClient(),[is,cs]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!es)return;const Qr=`user_id=eq.${es}`,ja=supabase.channel(`eval-jobs-${$??"all"}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"eval_jobs",filter:Qr},Na=>{const Aa=Na.new;$&&Aa.evalTargetId!==$||(cs(Aa),ts.invalidateQueries({queryKey:["eval-jobs",Aa.evalTargetId]}))}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"eval_jobs",filter:Qr},Na=>{const Aa=Na.new;$&&Aa.evalTargetId!==$||(Aa.status==="completed"||Aa.status==="failed"||Aa.status==="cancelled"?(cs(null),ts.invalidateQueries({queryKey:["eval-runs",Aa.evalTargetId]}),ts.invalidateQueries({queryKey:["eval-jobs",Aa.evalTargetId]})):cs(Aa))}).subscribe();return()=>{supabase.removeChannel(ja)}},[es,$,ts]),is}function useEvalConversation(es){return useQuery({queryKey:["eval-conversation",es],queryFn:()=>apiGet(`/api/eval-targets/${es}/conversations`),enabled:!!es})}function useCreateConversation(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/eval-targets/${$}/conversations`,{}),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-conversation",$.evalTargetId]})}})}function useSendMessage(){const es=useQueryClient();return useMutation({mutationFn:({conversationId:$,content:ts})=>apiPost(`/api/eval-conversations/${$}/messages`,{content:ts}),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["eval-conversation-messages",ts.conversationId]})}})}function useConversationMessages(es,$=2e3){return useQuery({queryKey:["eval-conversation-messages",es],queryFn:()=>apiGet(`/api/eval-conversations/${es}/messages`),enabled:!!es,refetchInterval:$})}function useApplyProposal(){const es=useQueryClient(),$=useNavigate();return useMutation({mutationFn:({conversationId:ts,messageId:is})=>apiPost(`/api/eval-conversations/${ts}/apply-proposal`,{messageId:is}),onSuccess:ts=>{es.invalidateQueries({queryKey:["eval-targets"]}),es.invalidateQueries({queryKey:["eval-conversation"]}),es.invalidateQueries({queryKey:["eval-conversation-messages"]}),$(`/eval-targets/${ts.newTarget.id}`)}})}function ChatPanel({targetId:es}){const{data:$}=useEvalConversation(es),ts=useCreateConversation(),is=useSendMessage(),cs=useApplyProposal(),Qr=$==null?void 0:$.id,{data:ja}=useConversationMessages(Qr,2e3),[Na,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(!1),[La,Ba]=reactExports.useState(!1),Ma=reactExports.useRef(null);reactExports.useEffect(()=>{var Va;(Va=Ma.current)==null||Va.scrollIntoView({behavior:"smooth"})},[ja==null?void 0:ja.length]);const qa=reactExports.useCallback(async Va=>{if(!(!Va.trim()||Oa)){Ia(!0);try{let Ja=Qr;Ja||(Ja=(await ts.mutateAsync(es)).id);const Ya=await is.mutateAsync({conversationId:Ja,content:Va.trim()});Ba(Ya.noLiveWorker),Aa("")}finally{Ia(!1)}}},[Qr,ts,is,es,Oa]),Fa=async()=>{await qa(Na)},Ha=Va=>{Va.key==="Enter"&&!Va.shiftKey&&(Va.preventDefault(),Fa())},Ka=Va=>{Qr&&cs.mutate({conversationId:Qr,messageId:Va})},Ga=ja??($==null?void 0:$.messages)??[];return jsxRuntimeExports.jsxs("div",{className:"flex flex-col h-[600px]",children:[jsxRuntimeExports.jsxs("div",{className:"flex-1 overflow-y-auto space-y-3 p-4",children:[Ga.length===0&&jsxRuntimeExports.jsxs("div",{className:"text-center text-muted-foreground text-sm py-12 space-y-3",children:[jsxRuntimeExports.jsx("p",{children:"Start by running evals or generating test cases."}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 justify-center",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:Oa,onClick:()=>qa("Generate test cases for this instruction"),children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-3 w-3 mr-1"}),"Generate Test Cases"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:Oa,onClick:()=>qa("Run the evals"),children:[jsxRuntimeExports.jsx(Play,{className:"h-3 w-3 mr-1"}),"Run Evals"]})]})]}),Ga.map((Va,Ja)=>Va.type==="status"&&Ga.slice(Ja+1).some(Ya=>Ya.type==="results"||Ya.type==="proposal"||Ya.type==="generated"||Ya.role==="user")?null:jsxRuntimeExports.jsx(MessageBubble,{message:Va,onApply:Ka,applyingProposal:cs.isPending,isLastStatus:Va.type==="status"},Va.id)),jsxRuntimeExports.jsx("div",{ref:Ma})]}),La&&jsxRuntimeExports.jsxs("div",{className:"border-t border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-500",children:["No CLI worker is listening — your message is queued but nothing will answer it. Start one with ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals agent"}),"."]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-3 flex gap-2",children:[jsxRuntimeExports.jsx("textarea",{value:Na,onChange:Va=>Aa(Va.target.value),onKeyDown:Ha,placeholder:"Type a message... (e.g. 'run evals', 'this output is missing X')",className:"flex-1 bg-muted rounded-lg px-3 py-2 text-sm resize-none min-h-[40px] max-h-[120px] focus:outline-none focus:ring-1 focus:ring-primary",rows:1,disabled:Oa}),jsxRuntimeExports.jsx(Button,{size:"icon",onClick:Fa,disabled:Oa||!Na.trim(),className:"shrink-0",children:Oa?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}):jsxRuntimeExports.jsx(Send,{className:"h-4 w-4"})})]})]})}function MessageBubble({message:es,onApply:$,applyingProposal:ts,isLastStatus:is}){if(es.role==="user")return jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx("div",{className:"bg-primary text-primary-foreground rounded-lg px-3 py-2 max-w-[80%] text-sm",children:es.content})});switch(es.type){case"status":return jsxRuntimeExports.jsx(StatusMessage,{content:es.content,isActive:!!is});case"results":return jsxRuntimeExports.jsx(ResultsMessage,{content:es.content,data:es.data});case"proposal":return jsxRuntimeExports.jsx(ProposalMessage,{content:es.content,data:es.data,messageId:es.id,onApply:$,applying:ts});case"applied":return jsxRuntimeExports.jsx(AppliedMessage,{content:es.content});case"generated":return jsxRuntimeExports.jsx(GeneratedMessage,{content:es.content,data:es.data});default:return jsxRuntimeExports.jsx("div",{className:"flex justify-start",children:jsxRuntimeExports.jsx("div",{className:"bg-card border border-border rounded-lg px-3 py-2 max-w-[80%] text-sm",children:es.content})})}}function StatusMessage({content:es,isActive:$}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground px-3 py-1",children:[$?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}):jsxRuntimeExports.jsx(CircleCheck,{className:"h-3 w-3 text-muted-foreground/50"}),es]})}function ResultsMessage({content:es,data:$}){const[ts,is]=reactExports.useState(null);if(!$)return jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:es});const{summary:cs,results:Qr}=$,ja=cs.passRate>=.8?"text-teal-500":cs.passRate>=.5?"text-yellow-500":"text-red-500";return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsxs("span",{className:`font-mono text-lg font-bold ${ja}`,children:[cs.passed,"/",cs.total]}),jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["evals passed (",Math.round(cs.passRate*100),"%)"]})]}),jsxRuntimeExports.jsx("div",{className:"space-y-1",children:Qr.map((Na,Aa)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(ts===Aa?null:Aa),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-left hover:bg-secondary/30",children:[ts===Aa?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),Na.passed?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(CircleX,{className:"h-4 w-4 text-red-500"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:Na.evalName})]}),ts===Aa&&jsxRuntimeExports.jsxs("div",{className:"px-3 pb-3 space-y-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Output:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 overflow-x-auto max-h-40 whitespace-pre-wrap",children:Na.output})]}),Na.evidence&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Evidence:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 overflow-x-auto max-h-32 whitespace-pre-wrap",children:Na.evidence})]})]})]},Aa))})]})}function ProposalMessage({content:es,data:$,messageId:ts,onApply:is,applying:cs}){const[Qr,ja]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-primary/30 rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:es}),($==null?void 0:$.suggestions)&&$.suggestions.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("button",{onClick:()=>ja(!Qr),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),$.suggestions.length," suggested change",$.suggestions.length>1?"s":""]}),Qr&&jsxRuntimeExports.jsx("div",{className:"space-y-2",children:$.suggestions.map((Na,Aa)=>jsxRuntimeExports.jsxs("div",{className:"bg-muted rounded p-3 text-xs space-y-1",children:[jsxRuntimeExports.jsx("div",{className:"font-mono font-medium text-primary",children:Na.section}),Na.current&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-red-400 font-medium",children:"- "}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:Na.current})]}),Na.proposed&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-teal-400 font-medium",children:"+ "}),jsxRuntimeExports.jsx("span",{children:Na.proposed})]}),jsxRuntimeExports.jsx("div",{className:"text-muted-foreground italic",children:Na.reasoning})]},Aa))})]}),jsxRuntimeExports.jsx("div",{className:"flex gap-2",children:jsxRuntimeExports.jsxs(Button,{size:"sm",onClick:()=>is(ts),disabled:cs,children:[cs?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin mr-1"}):null,"Apply Changes"]})})]})}function AppliedMessage({content:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-teal-500 px-3 py-1",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4"}),es]})}function GeneratedMessage({content:es,data:$}){const[ts,is]=reactExports.useState(null);return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:es}),($==null?void 0:$.cases)&&jsxRuntimeExports.jsx("div",{className:"space-y-1",children:$.cases.map((cs,Qr)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(ts===Qr?null:Qr),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-left hover:bg-secondary/30",children:[ts===Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:cs.name})]}),ts===Qr&&jsxRuntimeExports.jsxs("div",{className:"px-3 pb-3 space-y-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Prompt:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 whitespace-pre-wrap",children:cs.prompt})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Expectations:"}),jsxRuntimeExports.jsx("div",{className:"mt-1 space-y-1",children:cs.expectations.map((ja,Na)=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-normal",children:ja},Na))})]})]})]},Qr))})]})}const MIN_QUOTE_LEN=12,MIN_CODE_LEN=4,SHORT_CANDIDATE_LEN=20;function extractEvidenceQuotes(es){const $=[],ts=is=>{const cs=is==null?void 0:is.trim();cs&&$.push(cs)};for(const is of[/"([^"]+)"/g,/“([^”]+)”/g,/'([^']+)'/g,/‘([^’]+)’/g])for(const cs of es.matchAll(is))cs[1].length>=MIN_QUOTE_LEN&&ts(cs[1]);for(const is of es.matchAll(/`([^`]+)`/g))is[1].length>=MIN_CODE_LEN&&ts(is[1]);return es.trim().length>=SHORT_CANDIDATE_LEN&&ts(es),[...new Set($)]}function findEvidenceRanges(es,$){if(!es||!$)return[];const ts=[];for(const cs of extractEvidenceQuotes($))for(const[Qr,ja]of[[es,cs],[es.toLowerCase(),cs.toLowerCase()]]){let Na=0,Aa=!1;for(;;){const Oa=Qr.indexOf(ja,Na);if(Oa===-1||(ts.push([Oa,Oa+ja.length]),Aa=!0,cs.length<SHORT_CANDIDATE_LEN))break;Na=Oa+ja.length}if(Aa)break}ts.sort((cs,Qr)=>cs[0]-Qr[0]||cs[1]-Qr[1]);const is=[];for(const[cs,Qr]of ts){const ja=is[is.length-1];ja&&cs<=ja[1]?ja[1]=Math.max(ja[1],Qr):is.push([cs,Qr])}return is}function segmentByRanges(es,$){if($.length===0)return[{text:es,highlighted:!1}];const ts=[];let is=0;for(const[cs,Qr]of $)cs>is&&ts.push({text:es.slice(is,cs),highlighted:!1}),ts.push({text:es.slice(cs,Qr),highlighted:!0}),is=Qr;return is<es.length&&ts.push({text:es.slice(is),highlighted:!1}),ts}function SecondOpinions({flags:es,actions:$}){const ts=reactExports.useMemo(()=>{const Ka=new Map;for(const Ga of es){const Va=`${Ga.evalRunId}:${Ga.expectationIndex}`;Ka.set(Va,[...Ka.get(Va)??[],Ga])}return[...Ka.entries()].map(([Ga,Va])=>({key:Ga,rows:Va,first:Va[0],humanVerdict:Va[0].humanPassed===Va[0].judgePassed?"approve":"reject",consensus:new Set(Va.map(Ja=>Ja.reviewerEngine)).size>1})).sort((Ga,Va)=>Number(Va.consensus)-Number(Ga.consensus))},[es]),[is,cs]=reactExports.useState(new Set),[Qr,ja]=reactExports.useState(null),[Na,Aa]=reactExports.useState(!1),Oa=ts.length>0&&ts.every(Ka=>is.has(Ka.key)),Ia=()=>cs(Oa?new Set:new Set(ts.map(Ka=>Ka.key))),La=Ka=>cs(Ga=>{const Va=new Set(Ga);return Va.has(Ka)?Va.delete(Ka):Va.add(Ka),Va}),Ba=async(Ka,Ga,Va)=>{Aa(!0);let Ja=0,Ya=0;for(const el of Va)try{await Ga(el),Ja+=1}catch{Ya+=1}Aa(!1),cs(new Set),Ya===0?ue$1.success(`${Ka} ${Ja} label${Ja===1?"":"s"}`):ue$1.error(`${Ka} ${Ja}, ${Ya} failed — the rest are still flagged`)},Ma=Ka=>$.resolve({id:Ka.first.id,resolution:"kept"}),qa=async Ka=>{await $.annotate({runId:Ka.first.evalRunId,expectationIndex:Ka.first.expectationIndex,verdict:Ka.humanVerdict==="approve"?"reject":"approve"}),await $.resolve({id:Ka.first.id,resolution:"relabeled"})},Fa=async Ka=>{await $.removeAnnotation({runId:Ka.first.evalRunId,expectationIndex:Ka.first.expectationIndex}),await $.resolve({id:Ka.first.id,resolution:"relabeled"})};if(ts.length===0)return null;const Ha=ts.filter(Ka=>is.has(Ka.key));return jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-b border-border px-3 py-2",children:[jsxRuntimeExports.jsxs("label",{className:"flex cursor-pointer items-center gap-2",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:Oa,onChange:Ia,className:"h-3.5 w-3.5 accent-teal-500","aria-label":"Select all flags"}),jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:["Second opinions",jsxRuntimeExports.jsxs("span",{className:"ml-1.5 text-muted-foreground font-normal",children:[ts.length," label",ts.length===1?"":"s"," flagged"]})]})]}),Ha.length>0?jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Kept",Ma,Ha),children:["Keep ",Ha.length," label",Ha.length===1?"":"s"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Flipped",qa,Ha),children:["Flip ",Ha.length]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",disabled:Na,onClick:()=>Ba("Removed",Fa,Ha),children:["Remove ",Ha.length," & requeue"]})]}):jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"A second model disagrees with these labels — keep yours, or flip it if the reviewer caught a judge error."})]}),jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:ts.map(Ka=>{const Ga=Ka.first,Va=Qr===Ka.key;return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:cn$1("flex items-center gap-2 px-3 py-1.5 text-sm",is.has(Ka.key)&&"bg-primary/[0.04]"),children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:is.has(Ka.key),onChange:()=>La(Ka.key),className:"h-3.5 w-3.5 shrink-0 accent-teal-500","aria-label":`Select ${Ga.expectationText}`}),jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ja(Va?null:Ka.key),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[Va?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[13px]",children:Ga.expectationText}),jsxRuntimeExports.jsxs("span",{className:"hidden shrink-0 font-mono text-[11px] text-muted-foreground sm:inline",children:[Ga.evalName??"case"," #",Ga.runNumber]}),Ka.consensus&&jsxRuntimeExports.jsx("span",{className:"shrink-0 rounded bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-500",children:"2 vendors"}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px]",children:["You: ",Ka.humanVerdict==="approve"?"right":"wrong"]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 rounded bg-red-500/10 px-1.5 py-0.5 text-[10px] text-red-500",children:[Ka.rows.length," reviewer",Ka.rows.length===1?"":"s"," disagree"]})]}),jsxRuntimeExports.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Kept",Ma,[Ka]),children:"Keep"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-red-500 hover:text-red-400",disabled:Na,onClick:()=>Ba("Flipped",qa,[Ka]),children:"Flip"})]})]}),Va&&jsxRuntimeExports.jsxs("div",{className:"space-y-2 border-t border-border/50 bg-muted/20 px-9 py-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[jsxRuntimeExports.jsxs("span",{className:"rounded bg-muted px-1.5 py-0.5",children:["Judge: ",Ga.judgePassed?"PASS":"FAIL"]}),jsxRuntimeExports.jsxs("span",{className:"rounded bg-muted px-1.5 py-0.5",children:["You: judge was ",Ka.humanVerdict==="approve"?"right":"wrong"]}),Ka.rows.map(Ja=>jsxRuntimeExports.jsxs("span",{className:"rounded bg-red-500/10 px-1.5 py-0.5 text-red-500",children:[Ja.reviewerModel,": ",Ja.reviewerPassed?"PASS":"FAIL"]},Ja.id)),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground",children:Ga.configuration})]}),Ga.outputExcerpt&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Agent output (excerpt)"}),jsxRuntimeExports.jsx("pre",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap rounded-md bg-muted p-2 text-xs",children:Ga.outputExcerpt})]})]})]},Ka.key)})})]})}function AnchorProgressCard({check:es,judge:$,pooling:ts}){const is=Math.min(100,Math.round(es.nAnchors/es.pilotTarget*100));return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium flex items-center gap-1.5",children:["Anchor set",jsxRuntimeExports.jsx(InfoTip,{term:"anchorSet"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[($==null?void 0:$.currentModel)&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(InfoTip,{term:"judge",children:"judge"}),": ",$.currentModel]}),es.adequate?jsxRuntimeExports.jsx(Badge,{className:"font-mono text-xs",children:"adequate"}):jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:"not yet adequate"}),jsxRuntimeExports.jsx(InfoTip,{term:"adequate"})]})]}),$!=null&&$.staleAnchors>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:[$.staleAnchors," label",$.staleAnchors===1?"":"s"," from an older judge model no longer count toward this judge's calibration — the queue below only serves runs graded by the current judge."]}),jsxRuntimeExports.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:jsxRuntimeExports.jsx("div",{className:"bg-primary rounded-full h-2 transition-all duration-300",style:{width:`${is}%`}})}),ts&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:ts.engaged?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["rectifier: ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"pooled"})," from"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.poolTargets})," same-judge targets /"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.poolAnchors})," anchors (λ=",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.withLambda.toFixed(2)}),Math.abs(ts.withLambda-ts.withoutLambda)>.01&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" / ",ts.withoutLambda.toFixed(2)]}),")"]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["rectifier: ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"target-specific"}),ts.withReason?` — ${ts.withReason}`:""]})}),(ts==null?void 0:ts.engaged)&&ts.assumedExchangeability&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Pool spans ",ts.poolTargets," of the 3 targets needed to MEASURE between-target variance — until then the judge is assumed to behave the same across targets rather than shown to. No calibrated verdict rests on that assumption."]}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[es.nAnchors," / ",es.pilotTarget]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(InfoTip,{term:"humanLabeledRuns",children:"human-labeled runs"})," (with"," ",es.nAnchorsWith," · without ",es.nAnchorsWithout,")",es.mde!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · ",jsxRuntimeExports.jsx(InfoTip,{term:"mde",children:"MDE"})," ±",(es.mde*100).toFixed(0),"pp vs ±",(es.targetEffect*100).toFixed(0),"pp target"]})]})]}),es.adequate?jsxRuntimeExports.jsx("p",{className:"text-xs text-teal-500",children:"Pilot target, cohort minimums, and target detectable effect all met — corrected estimates are publishable at this precision."}):jsxRuntimeExports.jsx("ul",{className:"text-xs text-muted-foreground space-y-0.5",children:es.reasons.map((cs,Qr)=>jsxRuntimeExports.jsxs("li",{children:["— ",cs]},Qr))})]})}function CaseDiscriminationCard({data:es}){const $=cs=>`${(cs*100).toFixed(0)}%`,ts=es.nonDiscriminating+es.unpaired,is=es.total>0&&ts/es.total>=.5;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium flex items-center gap-1.5",children:["Case discrimination",jsxRuntimeExports.jsx(InfoTip,{term:"discrimination"})]}),is?jsxRuntimeExports.jsxs(Badge,{variant:"destructive",className:"font-mono text-xs",children:[ts,"/",es.total," measure nothing"]}):jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"font-mono text-xs",children:[es.discriminating,"/",es.total," discriminate"]})]}),is&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-500",children:"Most cases don't separate with vs without, so the effect can't be resolved by adding runs — the variance is structural. Cull or replace the flagged cases before labeling."}),jsxRuntimeExports.jsxs("ul",{className:"text-xs space-y-1",children:[es.cases.map(cs=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:cs.discriminating?"text-foreground":"text-muted-foreground line-through",children:cs.name}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-muted-foreground whitespace-nowrap",children:[$(cs.withPassRate)," vs ",$(cs.withoutPassRate),cs.discriminating?jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[" · ",jsxRuntimeExports.jsxs(InfoTip,{term:"separation",children:["Δ",$(cs.separation)]})]}):jsxRuntimeExports.jsxs("span",{className:"text-amber-500",children:[" · ",jsxRuntimeExports.jsx(InfoTip,{term:"flat",children:"flat"})]})]})]},cs.name)),es.unpaired>0&&jsxRuntimeExports.jsxs("li",{className:"text-muted-foreground",children:["+ ",es.unpaired," case",es.unpaired===1?"":"s"," with no baseline cohort (can't be diagnosed — every baseline run missing or failed)"]})]})]})}function JudgeCalibrationCard({data:es}){const{anchors:$,calibration:ts,judge:is}=es,cs=Qr=>`${(Qr*100).toFixed(0)}%`;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono font-medium",children:"Judge calibration"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[(is==null?void 0:is.currentModel)&&`judge ${is.currentModel} · `,$.llmAnchors," human label",$.llmAnchors===1?"":"s",$.flagged>0&&` · ${$.flagged} flagged`]})]}),is!=null&&(is.staleAnchors>0||is.staleRuns>0)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Judge model changed — ",is.staleRuns," graded run",is.staleRuns===1?"":"s"," and ",is.staleAnchors," label",is.staleAnchors===1?"":"s"," from older judges are excluded here. Re-run evals and re-label in the Review tab to rebuild the anchor set under the current judge."]}),$.llmAnchors===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No human labels yet. Work through the Review tab (approve/reject each judge grade) — labels measure the judge's bias and correct the pass-rate estimates below (PPI)."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$.agreementRate!=null&&jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Judge/human agreement:"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:cs($.agreementRate)}),$.agreementCi&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:[" ","[",cs($.agreementCi.lower),"–",cs($.agreementCi.upper),"]"]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["on ",$.llmAnchors," reviewed assertion",$.llmAnchors===1?"":"s"]})]}),ts&&(ts.sufficient?jsxRuntimeExports.jsxs("div",{className:"text-sm space-y-1",children:[jsxRuntimeExports.jsxs("p",{children:["Corrected pass rates:"," ",jsxRuntimeExports.jsxs("span",{className:"font-mono",children:["with ",cs(ts.with.estimate)," · without"," ",cs(ts.without.estimate)]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(judge-only said ",cs(ts.with.naive)," ·"," ",cs(ts.without.naive),")"]})]}),jsxRuntimeExports.jsxs("p",{children:["Corrected delta:"," ",jsxRuntimeExports.jsxs("span",{className:`font-mono ${ts.significant?ts.delta>=0?"text-teal-500":"text-red-500":""}`,children:[ts.delta>=0?"+":"",cs(ts.delta)]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["95% CI ",cs(ts.ci.lower)," to ",cs(ts.ci.upper),ts.significant?"":" — not significant"," (unpaired, judge-bias-corrected)"]})]})]}):jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:[ts.insufficientReason??`need >= ${$.minAnchors} fully-reviewed runs per cohort for a corrected estimate`,". Fully-reviewed runs so far: ",$.labeledRuns.with," with ·"," ",$.labeledRuns.without," without."]})),es.powerCheck&&(es.powerCheck.adequate?jsxRuntimeExports.jsxs("p",{className:"text-xs text-teal-500",children:["Anchor set adequate — pilot target, cohort minimums, and ±",(es.powerCheck.targetEffect*100).toFixed(0),"pp detectable-effect target all met."]}):jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Anchor set not yet adequate (",es.powerCheck.nAnchors,"/",es.powerCheck.pilotTarget," pilot labels",es.powerCheck.mde!=null&&`, MDE ±${(es.powerCheck.mde*100).toFixed(0)}pp vs ±${(es.powerCheck.targetEffect*100).toFixed(0)}pp target`,") — treat corrected numbers as provisional; grow it in the Review tab."]}))]})]})}function CopyButton({text:es,what:$}){const{copy:ts}=useCopyToClipboard();return jsxRuntimeExports.jsx("button",{type:"button",onClick:async()=>await ts(es)?ue$1.success(`Copied ${$}`):ue$1.error("Copy failed — clipboard unavailable"),title:`Copy ${$}`,className:"rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground",children:jsxRuntimeExports.jsx(Copy,{className:"h-3.5 w-3.5"})})}function Kbd({children:es,className:$}){return jsxRuntimeExports.jsx("kbd",{className:cn$1("inline-flex items-center rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium text-muted-foreground",$),children:es})}function ReviewerAgreementCard({reviewers:es}){const $=is=>`${(is*100).toFixed(0)}%`,ts=is=>is==null?"—":is.toFixed(2);return jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsx("div",{className:"border-b border-border px-3 py-2",children:jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:["Second-opinion agreement",jsxRuntimeExports.jsx("span",{className:"ml-1.5 font-normal text-muted-foreground",children:"vs your current labels"})]})}),jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.filter(is=>is.pairs>0).map(is=>{const cs=is.kappa!=null&&is.snapshotKappa!=null&&Math.abs(is.kappa-is.snapshotKappa)>=.005;return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 px-3 py-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-[13px] text-foreground",children:is.models.join(", ")}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[is.pairs," assertion",is.pairs===1?"":"s",is.orphaned>0&&` (+${is.orphaned} requeued)`]}),is.agreementRate!=null&&jsxRuntimeExports.jsxs("span",{children:["matches you ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:$(is.agreementRate)})]}),jsxRuntimeExports.jsxs("span",{children:["κ ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts(is.kappa)}),cs&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" ","(was ",ts(is.snapshotKappa)," before your corrections)"]})]}),is.judgeAgreementRate!=null&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["judge matches you ",$(is.judgeAgreementRate)]}),is.suggestedAnchorWeight!=null&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["anchor weight ",is.suggestedAnchorWeight.toFixed(2)]})]},is.engine)})})]})}function ReviewTab({targetId:es,queue:$,isFetching:ts,refetchQueue:is,annotations:cs,powerCheck:Qr,judge:ja,caseDiscrimination:Na,pooling:Aa,reviewers:Oa,targetContent:Ia,targetType:La}){var Gl,cu;const[Ba,Ma]=reactExports.useState(0),[qa,Fa]=reactExports.useState(!1),Ha=reactExports.useRef(!1);reactExports.useEffect(()=>{Aa!=null&&Aa.engaged&&!Ha.current&&(Ha.current=!0,Fa(!0))},[Aa==null?void 0:Aa.engaged]);const[Ka,Ga]=reactExports.useState(!1),[Va,Ja]=reactExports.useState({}),Ya=reactExports.useRef([]),el=useJudgeDisagreements(es),tl=useResolveJudgeReview(es),[rl,cl]=reactExports.useState({}),dl=useAnnotateGrade(es),fl=useRemoveGradeAnnotation(es),nl=new Map(cs.map(Al=>[`${Al.evalRunId}:${Al.expectationIndex}`,Al])),ol=(Al,Ml)=>{var xu,fu;const Ql=`${Al.id}:${Ml}`;if(Ql in rl)return rl[Ql];const eu=nl.get(Ql);return eu?eu.verdict:((fu=(xu=Al.expectations[Ml])==null?void 0:xu.annotation)==null?void 0:fu.verdict)??null},pl=(Al,Ml,Ql,eu)=>{const xu=`${Al}:${Ml}`;eu===Ql?(cl(fu=>{const Ou={...fu};return delete Ou[xu],Ou}),fl.mutate({runId:Al,expectationIndex:Ml},{onError:()=>ue$1.error("Couldn't remove the label — it may still be recorded. Retry in a moment.")})):(cl(fu=>({...fu,[xu]:Ql})),Ya.current.push({runId:Al,expectationIndex:Ml}),dl.mutate({runId:Al,expectationIndex:Ml,verdict:Ql},{onError:()=>{cl(fu=>{const Ou={...fu};return delete Ou[xu],Ou}),ue$1.error("Label didn't save — check your connection and mark it again.")}}))},Tl=$==null?void 0:$.runs[Ba],ul=(Tl==null?void 0:Tl.expectations.filter(Al=>Al.method==="llm"&&!Al.errored))??[],hl=Tl?ul.filter(Al=>ol(Tl,Al.index)!=null).length:0,jl=Tl!=null&&ul.length>0&&hl===ul.length,Nl=Tl?((Gl=ul.find(Al=>ol(Tl,Al.index)==null))==null?void 0:Gl.index)??null:null,[zl,Zl]=reactExports.useState(null);reactExports.useEffect(()=>{Zl(null),Ga(!1)},[Tl==null?void 0:Tl.id]);const Dl=zl??Nl,Il=reactExports.useRef(null),Fl=reactExports.useRef(null),ql=reactExports.useMemo(()=>{const Al=Tl==null?void 0:Tl.expectations.find(Ql=>Ql.method==="llm"&&Ql.index===Dl);if(!Al||!(Tl!=null&&Tl.output))return{segments:null,count:0};const Ml=findEvidenceRanges(Tl.output,Al.evidence);return Ml.length===0?{segments:null,count:0}:{segments:segmentByRanges(Tl.output,Ml),count:Ml.length}},[Tl,Dl]);reactExports.useEffect(()=>{const Al=Il.current,Ml=Fl.current;if(!Al||!Ml)return;const Ql=Ml.getBoundingClientRect().top-Al.getBoundingClientRect().top;Al.scrollTo({top:Al.scrollTop+Ql-48,behavior:"smooth"})},[Dl,Tl==null?void 0:Tl.id,ql.count]),reactExports.useEffect(()=>{const Al=Ml=>{if(Ml.metaKey||Ml.ctrlKey||Ml.altKey)return;const Ql=Ml.target;if(Ql&&(Ql.tagName==="INPUT"||Ql.tagName==="TEXTAREA"||Ql.isContentEditable)||!Tl)return;const eu=Ml.key.toLowerCase();if((eu==="1"||eu==="a")&&Nl!=null)Ml.preventDefault(),pl(Tl.id,Nl,"approve",null);else if((eu==="2"||eu==="d")&&Nl!=null)Ml.preventDefault(),pl(Tl.id,Nl,"reject",null);else if((Ml.key==="Enter"||eu==="n")&&jl)Ml.preventDefault(),Ma(xu=>xu+1);else if(eu==="s")Ml.preventDefault(),Ma(xu=>xu+1);else if(eu==="u"){const xu=Ya.current.pop();if(xu){Ml.preventDefault();const fu=`${xu.runId}:${xu.expectationIndex}`;cl(Ou=>{const yu={...Ou};return delete yu[fu],yu}),fl.mutate(xu,{onError:()=>ue$1.error("Couldn't undo — the label may still be recorded.")})}}else Ml.key==="ArrowRight"&&$&&Ba<$.runs.length-1?(Ml.preventDefault(),Ma(xu=>xu+1)):Ml.key==="ArrowLeft"&&Ba>0&&(Ml.preventDefault(),Ma(xu=>xu-1))};return window.addEventListener("keydown",Al),()=>window.removeEventListener("keydown",Al)},[Tl,Nl,jl,Ba,$]);const nu=Al=>{const Ml=Al.expectations.filter(eu=>eu.method==="llm");if(Ml.length===0)return"done";const Ql=Ml.filter(eu=>ol(Al,eu.index)!=null).length;return Ql===Ml.length?"done":Ql>0?"partial":"todo"};return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[$&&$.remaining>0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-primary/40 bg-primary/[0.06] px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Review the judge's grade — not the output."}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[13px] text-muted-foreground",children:["For each assertion below, decide whether the AI judge got the pass/fail right — mark"," ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"Judge was right"})," if it did, or"," ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"Judge was wrong"})," if it didn't. Each mark adds one"," ",jsxRuntimeExports.jsx(InfoTip,{term:"humanLabeledRuns",children:"human anchor"}),Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ","(",jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[Qr.nAnchors,"/",Qr.pilotTarget]}),")"]})," ","toward calibrating this judge — so a real verdict can be shown."]}),jsxRuntimeExports.jsxs("p",{className:"mt-2 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-muted-foreground",children:["Keyboard: ",jsxRuntimeExports.jsx(Kbd,{children:"1"})," judge was right ",jsxRuntimeExports.jsx(Kbd,{children:"2"})," judge was wrong",jsxRuntimeExports.jsx(Kbd,{children:"U"})," undo last ",jsxRuntimeExports.jsx(Kbd,{children:"Enter"})," next run ",jsxRuntimeExports.jsx(Kbd,{children:"S"})," skip ",jsxRuntimeExports.jsx(Kbd,{children:"←"}),jsxRuntimeExports.jsx(Kbd,{children:"→"})," switch run"]})]}),cs.length>=10&&cs.every(Al=>Al.verdict==="approve")&&(((cu=el.data)==null?void 0:cu.length)??0)===0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/[0.06] px-4 py-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium text-amber-500",children:["All ",cs.length," labels agree with the judge"]}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[13px] text-muted-foreground",children:["A label set with zero rejects can't detect judge bias — don't hunt for rejects, but if the judge looks wrong, say so. To surface likely judge errors worth a second look, run"," ",jsxRuntimeExports.jsxs("span",{className:"font-mono text-foreground",children:["rulemetric evals validate-judge ",es]})," ","— assertions where a second model disagrees with the judge are the best candidates."]})]}),el.data&&el.data.length>0&&jsxRuntimeExports.jsx(SecondOpinions,{flags:el.data,actions:{annotate:Al=>dl.mutateAsync(Al),removeAnnotation:Al=>fl.mutateAsync(Al),resolve:Al=>tl.mutateAsync(Al)}}),Oa&&Oa.some(Al=>Al.pairs>0)&&jsxRuntimeExports.jsx(ReviewerAgreementCard,{reviewers:Oa}),Qr?jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Fa(Al=>!Al),className:"flex w-full items-center gap-3 rounded-lg px-4 py-2.5 text-left transition-colors hover:bg-muted/40",children:[qa?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[Qr.nAnchors,"/",Qr.pilotTarget," labeled"]}),jsxRuntimeExports.jsxs("span",{className:"truncate text-xs text-muted-foreground",children:[$?`${$.remaining} to review`:"",Qr.mde!=null&&` · MDE ±${(Qr.mde*100).toFixed(0)}pp`,Na&&Na.total>0&&` · ${Na.discriminating}/${Na.total} cases discriminate`,Aa&&(Aa.engaged?jsxRuntimeExports.jsx("span",{className:"text-teal-500",children:` · pooled ✓ (${Aa.poolTargets} targets / ${Aa.poolAnchors} anchors)`}):" · rectifier: target-specific")]})]}),jsxRuntimeExports.jsx("div",{className:"mt-1.5 h-1.5 w-full rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-primary transition-all",style:{width:`${Math.min(100,Math.round(Qr.nAnchors/Qr.pilotTarget*100))}%`}})})]})]}),qa&&jsxRuntimeExports.jsxs("div",{className:"space-y-4 border-t border-border p-4",children:[jsxRuntimeExports.jsx(AnchorProgressCard,{check:Qr,judge:ja,pooling:Aa}),Na&&Na.total>0&&jsxRuntimeExports.jsx(CaseDiscriminationCard,{data:Na})]})]}):Na&&Na.total>0&&jsxRuntimeExports.jsx(CaseDiscriminationCard,{data:Na}),$?$.remaining===0?jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"All caught up — every LLM-judged assertion of this target is reviewed."}):Tl?jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-3 border-b border-border",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",title:Tl.configuration==="with_target"?"This run executed WITH the content under test in the agent's context":"Baseline arm — this run executed WITHOUT the content under test",children:Tl.configuration==="with_target"?"with instruction":"baseline · no instruction"}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 break-words font-mono text-sm",children:[Tl.evalName," · run #",Tl.runNumber]})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[jsxRuntimeExports.jsx("span",{className:"mr-1 text-xs text-muted-foreground",children:"batch"}),$.runs.map((Al,Ml)=>{const Ql=nu(Al);return jsxRuntimeExports.jsx("button",{onClick:()=>Ma(Ml),title:`${Al.evalName} · ${Al.configuration}${Ql==="done"?" · reviewed":Ql==="partial"?" · partially reviewed":""}`,className:cn$1("h-6 min-w-6 rounded border px-1 font-mono text-[11px] transition-colors",Ql==="done"?"bg-teal-500/10 text-teal-500":Ql==="partial"?"bg-amber-500/10 text-amber-500":"text-muted-foreground hover:text-foreground",Ml===Ba?"border-primary/70":"border-border"),children:Ql==="done"?"✓":Ml+1},Al.id)})]})]}),jsxRuntimeExports.jsxs("div",{className:"p-4 grid gap-4 xl:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-3 xl:sticky xl:top-4 xl:self-start",children:[jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border","data-testid":"review-input-panel",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-3 py-1.5",children:[jsxRuntimeExports.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Input — what the agent was asked"}),jsxRuntimeExports.jsx(CopyButton,{text:Tl.prompt,what:"prompt"})]}),jsxRuntimeExports.jsx("p",{className:"max-h-44 overflow-y-auto whitespace-pre-wrap p-3 text-sm",children:Tl.prompt})]}),Tl.configuration==="with_target"&&Ia&&jsxRuntimeExports.jsxs("details",{className:"rounded-md border border-border","data-testid":"review-target-panel",children:[jsxRuntimeExports.jsxs("summary",{className:"cursor-pointer rounded-md bg-muted/40 px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground transition-colors hover:text-foreground",children:["Also in context — the ",La," under test"]}),jsxRuntimeExports.jsx("pre",{className:"max-h-60 overflow-y-auto whitespace-pre-wrap border-t border-border/60 p-3 text-xs",children:Ia})]}),!Tl.output&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-dashed border-border px-3 py-2.5 text-xs text-muted-foreground",children:"No output was captured for this run — the judge graded an empty transcript. Treat its passes with suspicion."}),Tl.output&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border","data-testid":"review-output-panel",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-3 py-1.5",children:[jsxRuntimeExports.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:["Output — what the judge graded",Tl.outputTruncated?" (first 20k chars)":""]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-0.5",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>Ga(Al=>!Al),className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground/70 transition-colors hover:text-foreground",children:Ka?"Collapse":"Show all"}),jsxRuntimeExports.jsx(CopyButton,{text:Tl.output,what:"output"})]})]}),jsxRuntimeExports.jsx("pre",{ref:Il,className:cn$1("text-xs p-3 overflow-x-auto overflow-y-auto whitespace-pre-wrap rounded-b-md bg-muted/30",Ka?"max-h-none":"max-h-[26rem]"),children:ql.segments?ql.segments.map((Al,Ml)=>{if(!Al.highlighted)return jsxRuntimeExports.jsx("span",{children:Al.text},Ml);const Ql=ql.segments.findIndex(eu=>eu.highlighted)===Ml;return jsxRuntimeExports.jsx("mark",{ref:Ql?Fl:void 0,className:"bg-teal-500/25 text-inherit rounded-sm",children:Al.text},Ml)}):Tl.output})]})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Judge grades — did the judge get each one right?"}),jsxRuntimeExports.jsx(InfoTip,{content:"You're checking the AI JUDGE, not re-grading the output. For each assertion, decide whether the judge's pass/fail verdict was correct: approve if the judge got it right, reject if it got it wrong. Each click is one human anchor that calibrates how much to trust the judge."})]}),Tl.expectations.map(Al=>{const Ml=Al.method==="llm"&&!Al.errored,Ql=Ml?ol(Tl,Al.index):null,eu=Ml&&Al.index===Nl,xu=Ml&&Al.index===Dl;return jsxRuntimeExports.jsxs("div",{onMouseEnter:Ml?()=>Zl(Al.index):void 0,onMouseLeave:Ml?()=>Zl(null):void 0,className:cn$1("rounded-md border p-3 transition-colors",eu?"border-primary/60 bg-primary/[0.04]":"border-border"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2.5",children:[Al.errored?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mt-0.5 shrink-0 text-[10px] text-muted-foreground",title:"The grader crashed or the assertion definition is broken — no verdict exists to review. Re-run grading.",children:"grader errored"}):Ml?jsxRuntimeExports.jsxs("span",{className:cn$1("mt-0.5 shrink-0 rounded px-1.5 py-0.5 font-mono text-[10px] font-medium",Al.passed?"bg-teal-500/10 text-teal-500":"bg-red-500/10 text-red-500"),children:["Judge: ",Al.passed?"PASS":"FAIL"]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"mt-0.5 shrink-0 text-[10px]",children:["auto ",Al.passed?"✓":"✗"]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"font-mono text-sm",children:Al.text}),Al.evidence&&jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{className:"font-medium text-muted-foreground/70",children:["Judge's evidence:"," "]}),Al.evidence]}),xu&&(ql.count>0?jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[11px] text-teal-500",children:[ql.count," cited span",ql.count===1?"":"s"," highlighted in the output above"]}):jsxRuntimeExports.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground/70",children:"evidence isn't quoted verbatim — nothing to highlight"}))]})]}),Ml&&jsxRuntimeExports.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-2 pl-0.5",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>pl(Tl.id,Al.index,"approve",Ql),disabled:dl.isPending||fl.isPending,className:cn$1("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition-colors",Ql==="approve"?"border-teal-500/60 bg-teal-500/10 text-teal-500":"border-border text-muted-foreground hover:border-teal-500/40 hover:text-teal-500"),children:[jsxRuntimeExports.jsx(ThumbsUp,{className:"h-3.5 w-3.5"})," Judge was right",eu&&jsxRuntimeExports.jsx(Kbd,{children:"1"})]}),jsxRuntimeExports.jsxs("button",{onClick:()=>pl(Tl.id,Al.index,"reject",Ql),disabled:dl.isPending||fl.isPending,className:cn$1("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition-colors",Ql==="reject"?"border-red-500/60 bg-red-500/10 text-red-500":"border-border text-muted-foreground hover:border-red-500/40 hover:text-red-500"),children:[jsxRuntimeExports.jsx(ThumbsDown,{className:"h-3.5 w-3.5"})," Judge was wrong",eu&&jsxRuntimeExports.jsx(Kbd,{children:"2"})]}),Ql&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"✓ recorded"})]}),Ml&&Ql==="reject"&&(()=>{var Bl;const fu=`${Tl.id}:${Al.index}`,Ou=((Bl=nl.get(fu))==null?void 0:Bl.note)??"",yu=Va[fu]??Ou,ic=yu!==Ou,Iu=()=>dl.mutate({runId:Tl.id,expectationIndex:Al.index,verdict:"reject",note:yu.trim()||null},{onError:()=>ue$1.error("Note didn't save — try again.")});return jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2 pl-0.5",children:[jsxRuntimeExports.jsx("input",{type:"text",value:yu,maxLength:2e3,onChange:ru=>Ja(Mu=>({...Mu,[fu]:ru.target.value})),onKeyDown:ru=>{ru.key==="Enter"&&ic&&(ru.preventDefault(),Iu())},placeholder:"Why was the judge wrong? (optional — saved with the label)",className:"h-7 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-xs placeholder:text-muted-foreground/60 focus:border-primary/50 focus:outline-none"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",disabled:!ic||dl.isPending,onClick:Iu,children:Ou&&!ic?"Saved":"Save note"})]})})()]},Al.index)})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-border p-3",children:[jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 basis-48 text-xs text-muted-foreground",children:[hl,"/",ul.length," assertions reviewed",jl?jsxRuntimeExports.jsx("span",{className:"text-teal-500",children:" · this run now counts toward the pilot"}):ul.length>1?jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/70",children:[" ","· label all ",ul.length," for this run to count toward the pilot"]}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[!jl&&ul.length>1&&jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:dl.isPending,onClick:()=>{for(const Al of ul)ol(Tl,Al.index)==null&&pl(Tl.id,Al.index,"approve",null)},children:["Mark all ",ul.length," right"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:jl?"default":"ghost",onClick:()=>Ma(Ba+1),children:[jl?"Next run":"Skip run",jsxRuntimeExports.jsx(Kbd,{className:"ml-1.5 border-transparent bg-transparent",children:jl?"↵":"S"}),jsxRuntimeExports.jsx(ChevronRight,{className:"ml-0.5 h-3 w-3"})]})]})]})]}):jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-6 text-center space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Batch reviewed — ",$.remaining," run",$.remaining===1?"":"s"," still need",$.remaining===1?"s":""," review."]}),jsxRuntimeExports.jsxs(Button,{size:"sm",disabled:ts,onClick:()=>{Ma(0),is()},children:[ts&&jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 mr-1.5 animate-spin"}),"Load next batch"]})]}):jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"})]})}const FINISHED_FILTERS=["all","evolution","decided","skipped","failed"],FinishedFilterSchema=enumType(FINISHED_FILTERS),PAGE_SIZES=[20,50,100],JobOutcomeSchema=enumType(["ok","skipped","decided","failed"]),PendingKindSchema=objectType({kind:stringType(),count:numberType(),oldestMinutes:numberType()}).strict(),WorkerVerdictSchema=objectType({severity:enumType(["ok","warn","fail"]),headline:stringType(),hints:arrayType(stringType()),stuck:arrayType(PendingKindSchema),unclaimable:arrayType(PendingKindSchema),engineBlocked:arrayType(PendingKindSchema)}).strict(),WorkerSchema=objectType({present:booleanType(),active:booleanType(),ageSeconds:numberType().nullable(),clientName:stringType().nullable(),clientVersion:stringType().nullable(),lastHeartbeat:stringType().nullable()}).strict(),ReviewGateTargetSchema=objectType({id:stringType(),name:stringType(),awaitingReview:numberType(),humanLabeled:numberType(),humanLabeledWith:numberType(),humanLabeledWithout:numberType(),pilotTarget:numberType()}).strict(),ReviewGateSchema=objectType({blocking:booleanType(),totalAwaitingReview:numberType(),targets:arrayType(ReviewGateTargetSchema)}).strict(),RunningJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),claimedAt:stringType().nullable(),elapsedSeconds:numberType().nullable(),leaseHealthy:booleanType()}).strict(),QueuedJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),createdAt:stringType(),waitedSeconds:numberType(),attempts:numberType()}).strict(),FinishedJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),finishedAt:stringType().nullable(),durationSeconds:numberType().nullable(),outcome:JobOutcomeSchema,reason:stringType().nullable(),detail:stringType().nullable()}).strict(),LoopProposalSchema=objectType({id:stringType(),evalTargetId:stringType().nullable(),targetName:stringType().nullable(),createdAt:stringType(),decision:stringType(),applied:booleanType(),effectClass:stringType(),proposalSource:stringType()}).strict(),LoopChangesSchema=objectType({decisions:numberType(),applied:numberType(),byDecision:objectType({promote:numberType(),revert:numberType(),refuse:numberType()}).strict(),readyToApply:numberType(),readyToApplyTargetId:stringType().nullable(),readyToApplyPromotionId:stringType().nullable(),lastAppliedAt:stringType().nullable(),lastDecidedAt:stringType().nullable(),suggestionsProposed:numberType(),suggestionsAccepted:numberType(),suggestionsPending:numberType(),lastAcceptedAt:stringType().nullable(),landedTotal:numberType(),window:objectType({hours:numberType(),landed:numberType(),decisions:numberType(),promotionsApplied:numberType(),adoptionApplied:numberType(),suggestionsSurfaced:numberType(),suggestionsAccepted:numberType(),suggestionsDeclined:numberType()}).strict()}).strict(),DeliveryProjectSchema=objectType({projectId:stringType(),name:stringType().nullable(),canonicalPath:stringType().nullable(),canonicalLastSeenAt:stringType().nullable(),stale:booleanType(),lastActivityAt:stringType().nullable(),lastAnalysedAt:stringType().nullable(),suggestionsPending:numberType(),suggestionsAccepted:numberType(),lastAcceptedAt:stringType().nullable()}).strict(),RecommendationApplicationSchema=objectType({id:stringType(),instructionId:stringType(),title:stringType(),artifact:stringType(),harness:stringType(),targetPath:stringType(),projectPath:stringType(),status:stringType(),applyMode:stringType(),verdictDetail:stringType().nullable(),updatedAt:stringType()}).strict(),PromotionPathProjectSchema=objectType({projectId:stringType(),trials:objectType({running:numberType(),orphaned:numberType(),eligible:numberType(),maxConcurrent:numberType(),maxPerRun:numberType(),blocked:enumType(["none","concurrency","per-run","no-candidates"])}).strict(),autoAccept:objectType({enabled:booleanType(),usedInWindow:numberType(),maxPerWindow:numberType(),maxPerRun:numberType(),windowDays:numberType(),eligible:numberType(),windowResetsAt:stringType().nullable()}).strict()}).strict(),LoopSummarySchema=objectType({worker:WorkerSchema,verdict:WorkerVerdictSchema,reviewGate:ReviewGateSchema,running:arrayType(RunningJobSchema),queued:arrayType(QueuedJobSchema),failedInWindow:numberType(),proposals:arrayType(LoopProposalSchema),proposalTotal:numberType(),changes:LoopChangesSchema,counts:objectType({experimentsRunning:numberType(),suggestions:recordType(stringType(),numberType())}).strict(),windowHours:numberType()}).strict(),LoopDiagnosticsSchema=objectType({recent:arrayType(FinishedJobSchema),recentTotal:numberType(),filterCounts:objectType({all:numberType(),evolution:numberType(),decided:numberType(),skipped:numberType(),failed:numberType()}).strict(),insights:objectType({entries:numberType(),distinct:numberType(),repeated:numberType(),dismissed:numberType(),maxTimesGenerated:numberType(),lastSeenAt:stringType().nullable()}).strict(),delivery:objectType({projects:arrayType(DeliveryProjectSchema),total:numberType(),staleCount:numberType()}).strict(),promotionPaths:objectType({projects:arrayType(PromotionPathProjectSchema)}).strict(),adoption:objectType({available:booleanType(),counts:recordType(stringType(),numberType()),applications:arrayType(RecommendationApplicationSchema)}).strict(),windowHours:numberType(),limit:numberType(),filter:FinishedFilterSchema}).strict();LoopSummarySchema.merge(LoopDiagnosticsSchema).strict();Object.keys(LoopSummarySchema.shape);Object.keys(LoopDiagnosticsSchema.shape);const loopQueryKeys={summary:es=>["loop","summary",es.hours,es.limit],diagnostics:es=>["loop","diagnostics",es.hours,es.limit,es.filter]};function summaryPollInterval(es){var ts,is;return(((ts=es==null?void 0:es.running)==null?void 0:ts.length)??0)>0||(((is=es==null?void 0:es.queued)==null?void 0:is.length)??0)>0?POLL.LIVE:POLL.HEARTBEAT}function assertLoopPayload(es,$){const ts=es==="summary"?["running","queued","proposals"]:["recent"],is=$;if(!(typeof is=="object"&&is!==null&&ts.every(Qr=>Array.isArray(is[Qr]))&&(es==="summary"?typeof is.changes=="object"&&is.changes!==null&&typeof is.worker=="object":typeof is.filterCounts=="object"&&is.filterCounts!==null))){const Qr=typeof $=="string"?`${$.slice(0,40).replace(/\s+/g," ")}…`:typeof $;throw new Error(`/api/loop/${es} returned something that is not a loop ${es} (got ${Qr}). An API that predates this page answers with the SPA fallback — is the API you are talking to current?`)}return $}function diagnosticsQuery(es){return{enabled:es.open,refetchInterval:es.open?POLL.HEARTBEAT:!1}}function diagnosticsPanelState(es){return es.open?es.hasData?"ready":es.isError?"error":"loading":"closed"}function headlineInputs(es){return{workerPresent:es.worker.present,leaseUnhealthy:es.running.some($=>!$.leaseHealthy),readyToApply:es.changes.readyToApply,failedRecently:es.failedInWindow,running:es.running.length,queued:es.queued.length,engineBlocked:(es.verdict.engineBlocked??[]).reduce(($,ts)=>$+ts.count,0)}}function useProvenanceImpact(){return useQuery({queryKey:["provenance-impact"],queryFn:()=>apiGet("/api/insights/provenance-impact"),refetchInterval:POLL.SLOW})}function usePromotionDetail(es,$){return useQuery({queryKey:["promotion",es],queryFn:()=>apiGet(`/api/promotions/${es}`),enabled:$&&!!es,staleTime:5*6e4})}function useApplyPromotion(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/promotions/${$}/apply`,{}),onSuccess:()=>{es.invalidateQueries({queryKey:["loop"]}),es.invalidateQueries({queryKey:["promotion"]})}})}function useRunLoopNow(){const es=useQueryClient();return useMutation({mutationFn:()=>apiPost("/api/loop/run-now",{}),onSuccess:()=>{es.invalidateQueries({queryKey:["loop"]})}})}function useLoopSummary(es){const $=new URLSearchParams({hours:String(es.hours),limit:String(es.limit)});return useQuery({queryKey:loopQueryKeys.summary(es),queryFn:async()=>assertLoopPayload("summary",await apiGet(`/api/loop/summary?${$.toString()}`)),placeholderData:ts=>ts,refetchInterval:ts=>summaryPollInterval(ts.state.data)})}function useLoopDiagnostics(es,$){const ts=new URLSearchParams({hours:String(es.hours),limit:String(es.limit),filter:es.filter}),is=diagnosticsQuery($);return useQuery({queryKey:loopQueryKeys.diagnostics(es),queryFn:async()=>assertLoopPayload("diagnostics",await apiGet(`/api/loop/diagnostics?${ts.toString()}`)),enabled:is.enabled,placeholderData:cs=>cs,refetchInterval:is.refetchInterval})}const MAX_LINES=4e3,toLines=es=>es===""?[]:es.split(`
|
|
143
|
+
`);function lineDiff(es,$){const ts=toLines(es),is=toLines($);if(ts.length>MAX_LINES||is.length>MAX_LINES)return[...ts.map((Aa,Oa)=>({op:"remove",text:Aa,oldLine:Oa+1,newLine:null})),...is.map((Aa,Oa)=>({op:"add",text:Aa,oldLine:null,newLine:Oa+1}))];const cs=Array.from({length:ts.length+1},()=>new Array(is.length+1).fill(0));for(let Aa=ts.length-1;Aa>=0;Aa--)for(let Oa=is.length-1;Oa>=0;Oa--)cs[Aa][Oa]=ts[Aa]===is[Oa]?cs[Aa+1][Oa+1]+1:Math.max(cs[Aa+1][Oa],cs[Aa][Oa+1]);const Qr=[];let ja=0,Na=0;for(;ja<ts.length&&Na<is.length;)ts[ja]===is[Na]?(Qr.push({op:"same",text:ts[ja],oldLine:ja+1,newLine:Na+1}),ja++,Na++):cs[ja+1][Na]>=cs[ja][Na+1]?(Qr.push({op:"remove",text:ts[ja],oldLine:ja+1,newLine:null}),ja++):(Qr.push({op:"add",text:is[Na],oldLine:null,newLine:Na+1}),Na++);for(;ja<ts.length;)Qr.push({op:"remove",text:ts[ja],oldLine:++ja,newLine:null});for(;Na<is.length;)Qr.push({op:"add",text:is[Na],oldLine:null,newLine:++Na});return Qr}function toHunks(es,$=3){const ts=new Set;es.forEach((Na,Aa)=>{if(Na.op!=="same")for(let Oa=Math.max(0,Aa-$);Oa<=Math.min(es.length-1,Aa+$);Oa++)ts.add(Oa)});const is=[];let cs=[],Qr=0,ja=0;return es.forEach((Na,Aa)=>{ts.has(Aa)?(cs.length===0&&(Qr=ja,ja=0),cs.push(Na)):(cs.length>0&&(is.push({lines:cs,skippedBefore:Qr}),cs=[]),ja++)}),cs.length>0&&is.push({lines:cs,skippedBefore:Qr}),is}function diffStat(es){let $=0,ts=0;for(const is of es)is.op==="add"?$++:is.op==="remove"&&ts++;return{added:$,removed:ts}}function EvidenceJson({label:es,value:$}){return Object.keys($).length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-foreground",children:es}),jsxRuntimeExports.jsx("pre",{className:"mt-1 overflow-x-auto rounded border border-border bg-background/60 p-2 text-xs text-muted-foreground",children:JSON.stringify($,null,2)})]})}function PromotionDetailPanel({promotionId:es,open:$,allowApply:ts=!1,testId:is}){const{data:cs,isLoading:Qr,isError:ja}=usePromotionDetail(es,$),Na=useApplyPromotion();if(!$)return null;const Aa=cs?lineDiff(cs.fromContent,cs.toContent):[],Oa=cs?toHunks(Aa):[],Ia=diffStat(Aa);return jsxRuntimeExports.jsxs("div",{className:"reveal min-w-0 border-t border-border bg-muted/10 px-3 py-3","data-testid":is??`proposal-detail-${es}`,children:[Qr&&jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),ja&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90",children:"Could not load this proposed change."}),cs&&jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"grid gap-3 text-sm md:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Decision rationale"}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-foreground",children:cs.rationale||"No final rationale was recorded."})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Proposal rationale"}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-foreground",children:cs.proposalRationale||"No proposal rationale was recorded."})]})]}),cs.refusals.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-amber-400",children:"Refusal reasons"}),jsxRuntimeExports.jsx("ul",{className:"list-disc space-y-1 pt-1 pl-5 text-sm text-foreground",children:cs.refusals.map((La,Ba)=>jsxRuntimeExports.jsx("li",{children:La},Ba))})]}),cs.touchedSections.length>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"font-medium text-foreground",children:"Touched sections:"})," ",cs.touchedSections.join(" · ")]}),jsxRuntimeExports.jsxs("div",{className:"grid min-w-0 gap-3 md:grid-cols-2",children:[jsxRuntimeExports.jsx(EvidenceJson,{label:"Verdict evidence",value:cs.verdict}),jsxRuntimeExports.jsx(EvidenceJson,{label:"Decision gates",value:cs.gates})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"pb-1 font-mono text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{className:"text-teal-400",children:["+",Ia.added]})," ",jsxRuntimeExports.jsxs("span",{className:"text-amber-400",children:["−",Ia.removed]})," lines"]}),jsxRuntimeExports.jsx("div",{className:"max-h-96 max-w-full overflow-auto rounded border border-border bg-background/50","data-testid":"promotion-diff",children:jsxRuntimeExports.jsx("div",{className:"w-max min-w-full font-mono text-xs leading-relaxed",children:Oa.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{children:[La.skippedBefore>0&&jsxRuntimeExports.jsxs("div",{className:"bg-muted/30 px-2 py-0.5 text-muted-foreground",children:["… ",La.skippedBefore," unchanged line",La.skippedBefore===1?"":"s"]}),La.lines.map((Ma,qa)=>jsxRuntimeExports.jsxs("div",{className:cn$1("px-2",Ma.op==="add"&&"bg-teal-400/10 text-teal-300",Ma.op==="remove"&&"bg-amber-400/10 text-amber-300",Ma.op==="same"&&"text-muted-foreground"),children:[jsxRuntimeExports.jsx("span",{className:"select-none pr-2 opacity-50",children:Ma.op==="add"?"+":Ma.op==="remove"?"−":" "}),Ma.text||" "]},qa))]},Ba))})})]}),ts&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:Na.isPending||Na.isSuccess,onClick:()=>Na.mutate(es),className:cn$1("rounded border px-3 py-1 text-xs transition-colors duration-150",Na.isSuccess?"border-teal-400/40 text-teal-400":"cursor-pointer border-teal-400/40 text-teal-400 hover:bg-teal-400/10",Na.isPending&&"opacity-60"),"data-testid":"apply-promotion",children:Na.isSuccess?"Applied":Na.isPending?"Applying…":"Apply this change"}),Na.isError&&jsxRuntimeExports.jsx("span",{className:"text-xs text-amber-400/90","data-testid":"apply-error",children:Na.error instanceof Error?Na.error.message:"Could not apply this change."})]})]})]})}function PromotionsTab({promotions:es,isLoading:$}){const[ts,is]=reactExports.useState(null);return $?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading promotions…"}):es.length===0?jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-border px-4 py-3",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No evolution decisions yet. The nightly loop records one row here per measured proposal — promote, revert, or refuse."})}):jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-border divide-y divide-border",children:es.map(cs=>{const Qr=ts===cs.id;return jsxRuntimeExports.jsxs("div",{"data-testid":"promotion-row",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(Qr?null:cs.id),"aria-expanded":Qr,"aria-controls":`proposal-detail-${cs.id}`,className:"flex min-h-11 w-full cursor-pointer items-start justify-between gap-4 px-4 py-3 text-left hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring","data-testid":`promotion-toggle-${cs.id}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"font-mono text-sm",children:[cs.decision," · ",cs.effectClass," · ",new Date(cs.createdAt).toLocaleDateString()]}),jsxRuntimeExports.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["via ",cs.proposalSource]}),cs.rationale&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:cs.rationale})]})]}),jsxRuntimeExports.jsx("span",{className:cn$1("shrink-0 rounded border px-2 py-0.5 text-xs",cs.applied?"border-teal-400/40 text-teal-400":"border-muted-foreground/40 text-muted-foreground"),children:cs.applied?"applied":"not applied"})]}),jsxRuntimeExports.jsx(PromotionDetailPanel,{promotionId:cs.id,open:Qr})]},cs.id)})})}function ActiveJobCard({job:es}){const $=es.progress,ts=$.total>0?Math.round($.completed/$.total*100):0;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 bg-secondary/20 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-primary"}),jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:[es.status==="pending"&&"Waiting for CLI worker to pick up job...",es.status==="claimed"&&`Claimed by ${es.claimedBy}. Starting...`,es.status==="running"&&($.message||"Running...")]})]}),$.total>0&&jsxRuntimeExports.jsxs("span",{className:"text-sm font-mono text-muted-foreground",children:[$.completed,"/",$.total," (",ts,"%)"]})]}),$.total>0&&jsxRuntimeExports.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:jsxRuntimeExports.jsx("div",{className:"bg-primary rounded-full h-2 transition-all duration-300",style:{width:`${ts}%`}})}),$.current&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-mono truncate",children:$.current})]})}function BackgroundMeasurement({targetId:es}){var Na,Aa,Oa,Ia;const $=useQueryClient(),ts=["eval-targets",es,"background"],is=useQuery({queryKey:ts,queryFn:()=>apiGet(`/api/eval-targets/${es}/background`),refetchInterval:15e3}),cs=useMutation({mutationFn:La=>apiPatch(`/api/eval-targets/${es}/background`,{enabled:La}),onSuccess:()=>{$.invalidateQueries({queryKey:ts})}}),Qr=is.data,ja=is.error??cs.error;return jsxRuntimeExports.jsxs("section",{"aria-label":"Background measurement",className:"rounded-lg border border-border p-4 space-y-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[jsxRuntimeExports.jsxs("h3",{className:"font-medium",children:["Background measurement",Qr?` · ${Qr.enabled?"On":"Off"}`:""]}),Qr&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",disabled:cs.isPending||!Qr.enabled&&Qr.blockers.length>0,onClick:()=>cs.mutate(!Qr.enabled),children:cs.isPending?"Saving…":Qr.enabled?"Pause nightly trials":"Enable nightly trials"})]}),ja&&jsxRuntimeExports.jsx("p",{role:"alert",className:"break-words text-destructive",children:ja.message}),!Qr&&!ja&&jsxRuntimeExports.jsx("p",{role:"status",children:"Loading schedule…"}),Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:[Qr.schedule,"; up to ",Qr.maxRuns/2," paired cases per night, rotating through ",Qr.liveCases," cases until sufficient evidence. Uses your local worker and subscription quota. Does not rewrite files."]}),jsxRuntimeExports.jsxs("p",{className:"break-words",children:["Actor: ",Qr.measurement?`${Qr.measurement.engine} · ${Qr.measurement.model??"CLI default"}`:"Existing worker defaults","; grader: ",Qr.judge.engine," · ",Qr.judge.model??"default",". ",jsxRuntimeExports.jsx(Link,{className:"underline",to:"/settings",children:"Measurement settings"})]}),!Qr.ready&&jsxRuntimeExports.jsx("p",{role:"status",className:"text-amber-500",children:"Waiting for a compatible worker. Start or upgrade your local worker; installed engines do not guarantee account credits."}),Qr.blockers.map(La=>jsxRuntimeExports.jsx("p",{className:"text-amber-500",children:La},La)),Qr.latest?jsxRuntimeExports.jsxs("p",{className:"break-words","data-testid":"background-last-result",children:["Last batch: ",Qr.latest.status," · ",new Date(Qr.latest.createdAt).toLocaleString(),((Na=Qr.latest.result)==null?void 0:Na.ranRuns)!=null&&` · ${Qr.latest.result.ranRuns} completed, ${Qr.latest.result.failedRuns??0} failed`,` — ${Qr.latest.error??((Aa=Qr.latest.result)==null?void 0:Aa.failures)??((Oa=Qr.latest.result)==null?void 0:Oa.reason)??((Ia=Qr.latest.result)==null?void 0:Ia.skipped)??"Waiting for results"}`]}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"No background batch yet. Results appear in Runs and Review below."}),!Qr.enabled&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No new nightly batches will start. A batch already executing may finish."})]})]})}const label=es=>typeof es=="string"&&es?es:"Not recorded",number=es=>typeof es=="number"&&Number.isFinite(es)&&es>=0?es:null;function RunEvidence({run:es}){const $=number(es.outputs.costUsd),ts=number(es.timing.total_tokens);return jsxRuntimeExports.jsxs("div",{className:"space-y-2 text-xs","data-testid":"run-evidence",children:[jsxRuntimeExports.jsxs("dl",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2 [&_dd]:break-words [&_dt]:text-muted-foreground",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Harness / provider"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.outputs.engine)," / ",label(es.outputs.provider)]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Resolved model"}),jsxRuntimeExports.jsx("dd",{children:label(es.outputs.model)})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Tokens"}),jsxRuntimeExports.jsx("dd",{children:ts===null?"Not recorded":ts.toLocaleString()})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Estimated API-equivalent cost"}),jsxRuntimeExports.jsx("dd",{children:$===null?"Unavailable — not zero":`$${$.toFixed(5)}`})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Methodology / delivery"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.outputs.methodology)," / ",label(es.outputs.delivery)]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Judge"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.grading.judge_engine)," / ",label(es.grading.judge_model)]})]})]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Compare revisions within the same harness, provider, model and methodology. Dollar estimates are not subscription charges or proven savings."}),es.outputs.isolated===!1&&jsxRuntimeExports.jsx("p",{className:"text-amber-500",children:"No repository workspace was available for this run."}),Array.isArray(es.outputs.leakedFiles)&&es.outputs.leakedFiles.length>0&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-destructive",children:"Contaminated workspace: instruction files survived baseline isolation."}),typeof es.outputs.error=="string"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"break-words text-destructive",children:es.outputs.error})]})}const TAB_KEYS=["chat","evals","runs","review","benchmarks","comparisons","promotions"],RUNS_PAGE_LIMIT=50,COMPARISONS_PAGE_LIMIT=50;function EvalTargetDetailPage(){const{id:es}=useParams(),[$,ts]=useTabParam(TAB_KEYS,"chat"),{data:is,isLoading:cs}=useEvalTarget(es),{data:Qr,isLoading:ja}=useEvals(es),{data:Na,isLoading:Aa}=useEvalRuns(es),{data:Oa,isLoading:Ia}=useBenchmarks(es),{data:La,isLoading:Ba}=useEvalComparisons(es),{data:Ma}=useGradeAnnotations(es),{data:qa}=useJudgeCalibration(es),{data:Fa,isFetching:Ha,refetch:Ka}=useAnnotationQueue(es),{data:Ga,isLoading:Va}=usePromotions(es),{data:Ja}=useJudgeDisagreements(es),{user:Ya}=useAuth(),{data:el}=useEvalJobs(es),tl=useCreateEvalJob(),rl=useCancelEvalJob(),cl=useRealtimeEvalJobs(Ya==null?void 0:Ya.id,es),{isConnected:dl,workerCount:fl}=useWorkerStatus("cli-worker"),nl=cl??(el==null?void 0:el.find(hl=>["pending","claimed","running"].includes(hl.status)))??null,ol=!!nl&&["pending","claimed","running"].includes(nl.status),pl=(el==null?void 0:el[0])??null,Tl=!ol&&(pl==null?void 0:pl.status)==="failed"?pl:null;if(cs)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-96"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]});if(!is)return jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Eval target not found."});const ul=[{key:"chat",label:"Chat"},{key:"evals",label:"Evals",count:Qr==null?void 0:Qr.length},{key:"runs",label:"Runs",count:Na&&Na.length>=RUNS_PAGE_LIMIT?`${RUNS_PAGE_LIMIT}+`:Na==null?void 0:Na.length},{key:"review",label:"Review",count:Fa==null?void 0:Fa.remaining},{key:"benchmarks",label:"Benchmarks",count:Oa==null?void 0:Oa.length},{key:"comparisons",label:"Comparisons",count:La&&La.length>=COMPARISONS_PAGE_LIMIT?`${COMPARISONS_PAGE_LIMIT}+`:La==null?void 0:La.length},{key:"promotions",label:"Promotions",count:Ga==null?void 0:Ga.total}];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/eval-targets",children:jsxRuntimeExports.jsx(ArrowLeft,{className:"h-4 w-4"})})}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-64",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight break-words",children:is.name}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground break-words",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"mr-2 font-mono",children:is.type}),"v",is.version,is.description&&` — ${is.description}`]})]}),jsxRuntimeExports.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("div",{className:`h-2 w-2 rounded-full ${dl?"bg-teal-500":"bg-red-500"}`}),dl?`${fl} worker${fl>1?"s":""} online`:"No workers"]}),ol?jsxRuntimeExports.jsxs(Button,{variant:"destructive",size:"sm",onClick:()=>nl&&rl.mutate(nl.id),disabled:rl.isPending,children:[jsxRuntimeExports.jsx(Square,{className:"h-3 w-3 mr-1.5"}),"Cancel Run"]}):jsxRuntimeExports.jsxs(Button,{size:"sm",onClick:()=>es&&tl.mutate({evalTargetId:es}),disabled:tl.isPending||!(Qr!=null&&Qr.length)||!dl,title:dl?Qr!=null&&Qr.length?void 0:"Add eval cases first — none defined for this target":"Start a CLI worker: rulemetric evals agent",children:[jsxRuntimeExports.jsx(Play,{className:"h-3 w-3 mr-1.5"}),"Run Evals"]})]})]}),jsxRuntimeExports.jsx(BackgroundMeasurement,{targetId:is.id}),!ol&&Qr&&Qr.length===0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-amber-500 font-medium",children:"No eval cases defined"}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Add cases via CLI: ",jsxRuntimeExports.jsxs("code",{className:"bg-muted px-1 py-0.5 rounded text-[11px]",children:["rulemetric evals create ",es,' --name "..." --prompt "..." -e "..."']})]})]}),nl&&["pending","claimed","running"].includes(nl.status)&&jsxRuntimeExports.jsx(ActiveJobCard,{job:nl}),Tl&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-red-500/30 bg-red-500/5 px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-red-500 font-medium",children:"Last run failed"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono break-words",children:Tl.error??"No error recorded for this job."})]}),$!=="review"&&(((Fa==null?void 0:Fa.remaining)??0)>0||((Ja==null?void 0:Ja.length)??0)>0)&&jsxRuntimeExports.jsx("button",{type:"button","data-testid":"review-callout",onClick:()=>ts("review"),className:"group w-full rounded-lg border border-primary/40 bg-primary/[0.06] px-4 py-3 text-left transition-colors hover:bg-primary/[0.1]",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium",children:[((Fa==null?void 0:Fa.remaining)??0)>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fa.remaining," run",Fa.remaining===1?"":"s"," await your review"]}),((Fa==null?void 0:Fa.remaining)??0)>0&&((Ja==null?void 0:Ja.length)??0)>0&&" · ",((Ja==null?void 0:Ja.length)??0)>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Ja.length," label",Ja.length===1?"":"s"," flagged by a second opinion"]})]}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-[13px] text-muted-foreground",children:"For each run you'll see the prompt, the agent's output, and the judge's pass/fail on every assertion — you mark whether the judge got it right. A few minutes of labels calibrate the judge so its verdicts can be trusted."})]}),jsxRuntimeExports.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-sm font-medium text-primary",children:["Start reviewing",jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})}),jsxRuntimeExports.jsx("div",{className:"flex gap-1 border-b border-border overflow-x-auto",children:ul.map(hl=>jsxRuntimeExports.jsxs("button",{onClick:()=>ts(hl.key),className:`shrink-0 whitespace-nowrap px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${$===hl.key?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,children:[hl.label,hl.count!=null&&jsxRuntimeExports.jsxs("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",hl.count,")"]})]},hl.key))}),$==="evals"&&jsxRuntimeExports.jsx(EvalsTab,{evalCases:Qr??[],isLoading:ja}),$==="runs"&&jsxRuntimeExports.jsx(RunsTab,{targetId:es,runs:Na??[],isLoading:Aa,annotations:Ma??[]}),$==="review"&&jsxRuntimeExports.jsx(ReviewTab,{targetId:es,queue:Fa,isFetching:Ha,refetchQueue:Ka,annotations:Ma??[],powerCheck:qa==null?void 0:qa.powerCheck,judge:qa==null?void 0:qa.judge,caseDiscrimination:qa==null?void 0:qa.caseDiscrimination,pooling:qa==null?void 0:qa.pooling,reviewers:qa==null?void 0:qa.reviewers,targetContent:is.content??null,targetType:is.type}),$==="benchmarks"&&jsxRuntimeExports.jsx(BenchmarksTab,{benchmarks:Oa??[],isLoading:Ia,judgeCalibration:qa}),$==="comparisons"&&jsxRuntimeExports.jsx(ComparisonsTab,{comparisons:La??[],isLoading:Ba}),$==="promotions"&&jsxRuntimeExports.jsx(PromotionsTab,{promotions:(Ga==null?void 0:Ga.promotions)??[],isLoading:Va}),$==="chat"&&es&&jsxRuntimeExports.jsx(ChatPanel,{targetId:es})]})}function EvalsTab({evalCases:es,isLoading:$}){return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.map(ts=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono font-medium",children:ts.name}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:ts.prompt}),ts.expectations.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:ts.expectations.map((is,cs)=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:is},cs))})]},ts.id))}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"No evals defined yet."})}function RunsTab({targetId:es,runs:$,isLoading:ts,annotations:is}){const[cs,Qr]=reactExports.useState(null),ja=useAnnotateGrade(es),Na=useRemoveGradeAnnotation(es),Aa=new Map(is.map(Ia=>[`${Ia.evalRunId}:${Ia.expectationIndex}`,Ia])),Oa=(Ia,La,Ba)=>{const Ma=Aa.get(`${Ia}:${La}`);(Ma==null?void 0:Ma.verdict)===Ba?Na.mutate({runId:Ia,expectationIndex:La}):ja.mutate({runId:Ia,expectationIndex:La,verdict:Ba})};return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):$.length?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[$.length>=RUNS_PAGE_LIMIT&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing the ",RUNS_PAGE_LIMIT," most recent runs — older runs are not loaded."]}),$.map(Ia=>{var Ma,qa,Fa,Ha,Ka;const La=cs===Ia.id,Ba=(qa=(Ma=Ia.grading)==null?void 0:Ma.summary)==null?void 0:qa.pass_rate;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>Qr(La?null:Ia.id),className:"w-full flex flex-wrap items-center justify-between gap-2 p-3 text-left hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[La?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:Ia.status==="completed"?"default":"destructive",className:"font-mono text-xs",children:Ia.status}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm",children:[Ia.configuration," · run #",Ia.runNumber," · iter ",Ia.iteration]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[Ba!=null&&jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[(Ba*100).toFixed(0),"% pass"]}),((Fa=Ia.timing)==null?void 0:Fa.duration_ms)&&jsxRuntimeExports.jsxs("span",{children:[(Ia.timing.duration_ms/1e3).toFixed(1),"s"]}),jsxRuntimeExports.jsx("span",{children:new Date(Ia.createdAt).toLocaleDateString()})]})]}),La&&jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-4 space-y-3",children:[jsxRuntimeExports.jsx(RunEvidence,{run:Ia}),((Ha=Ia.grading)==null?void 0:Ha.expectations)&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Expectations"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"— review each grade: your labels calibrate the judge"})]}),Ia.grading.expectations.map((Ga,Va)=>{const Ja=Aa.get(`${Ia.id}:${Va}`);return jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 text-sm group",children:[Ga.passed?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500 mt-0.5 shrink-0"}):jsxRuntimeExports.jsx(CircleX,{className:"h-4 w-4 text-red-500 mt-0.5 shrink-0"}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:Ga.text}),Ga.method==="deterministic"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"ml-1.5 text-[10px] align-middle",children:"deterministic"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-xs",children:Ga.evidence})]}),Ga.method!=="deterministic"&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[jsxRuntimeExports.jsx("button",{onClick:()=>Oa(Ia.id,Va,"approve"),disabled:ja.isPending||Na.isPending,title:"Judge graded this correctly",className:`p-1 rounded transition-colors ${(Ja==null?void 0:Ja.verdict)==="approve"?"text-teal-500 bg-teal-500/10":"text-muted-foreground/50 hover:text-teal-500"}`,children:jsxRuntimeExports.jsx(ThumbsUp,{className:"h-3.5 w-3.5"})}),jsxRuntimeExports.jsx("button",{onClick:()=>Oa(Ia.id,Va,"reject"),disabled:ja.isPending||Na.isPending,title:"Judge got this grade wrong",className:`p-1 rounded transition-colors ${(Ja==null?void 0:Ja.verdict)==="reject"?"text-red-500 bg-red-500/10":"text-muted-foreground/50 hover:text-red-500"}`,children:jsxRuntimeExports.jsx(ThumbsDown,{className:"h-3.5 w-3.5"})})]})]},Va)})]}),!!((Ka=Ia.outputs)!=null&&Ka.transcript)&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Output"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto max-h-48",children:String(Ia.outputs.transcript)})]})]})]},Ia.id)})]}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"No runs yet. Execute evals via the CLI."})}function BenchmarksTab({benchmarks:es,isLoading:$,judgeCalibration:ts}){return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[ts&&jsxRuntimeExports.jsx(JudgeCalibrationCard,{data:ts}),es.map(is=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium",children:["Iteration ",is.iteration]}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground",children:new Date(is.createdAt).toLocaleDateString()})]}),Object.entries(is.runSummary).map(([cs,Qr])=>cs==="delta"?jsxRuntimeExports.jsxs("div",{className:"bg-muted/50 rounded-md p-3",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Delta (with - without target)"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-4 text-sm font-mono",children:Object.entries(Qr).map(([ja,Na])=>jsxRuntimeExports.jsxs("span",{children:[ja,": ",Na]},ja))}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Mean difference only — no significance test. At the default 1 run per eval this is a single-run difference and is not statistically meaningful."})]},cs):jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:cs}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Object.entries(Qr).map(([ja,Na])=>{const Aa=Na;return jsxRuntimeExports.jsxs("div",{className:"bg-muted/30 rounded-md p-2 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:ja}),jsxRuntimeExports.jsxs("div",{className:"font-mono",children:[Aa.mean.toFixed(3),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["±",Aa.stddev.toFixed(3)]})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["[",Aa.min.toFixed(3),", ",Aa.max.toFixed(3),"]"]})]},ja)})})]},cs)),is.notes.length>0&&jsxRuntimeExports.jsx("div",{className:"text-sm space-y-1",children:is.notes.map((cs,Qr)=>jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:["— ",cs]},Qr))})]},is.id))]}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[ts&&jsxRuntimeExports.jsx(JudgeCalibrationCard,{data:ts}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["No benchmarks yet. Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals benchmark"})," ","to create one."]})]})}function ComparisonsTab({comparisons:es,isLoading:$}){const[ts,is]=reactExports.useState(null);return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[es.length>=COMPARISONS_PAGE_LIMIT&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing the ",COMPARISONS_PAGE_LIMIT," most recent comparisons — older ones are not loaded."]}),es.map(cs=>{var Aa,Oa;const Qr=ts===cs.id,ja=Ia=>Ia===cs.targetAId?`${cs.targetAName} v${cs.targetAVersion}`:Ia===cs.targetBId?`${cs.targetBName} v${cs.targetBVersion}`:null,Na=cs.status==="parse_failed"?"unparseable":ja(cs.winnerTargetId)??"TIE";return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(Qr?null:cs.id),className:"w-full flex items-center justify-between p-3 text-left hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:cs.status==="parse_failed"?"destructive":cs.winnerTargetId?"default":"secondary",className:"font-mono text-xs",children:Na}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm",children:[cs.targetAName," v",cs.targetAVersion," vs ",cs.targetBName," v",cs.targetBVersion]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[cs.model&&jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:cs.model}),jsxRuntimeExports.jsx("span",{children:new Date(cs.createdAt).toLocaleDateString()})]})]}),Qr&&jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-4 space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Judged blind",cs.isSwapped?" (labels swapped)":""," — winners shown unblinded."]}),cs.status==="parse_failed"?jsxRuntimeExports.jsx(ComparisonRawOutput,{id:cs.id}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cs.overall.reasoning&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Overall"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:cs.overall.reasoning})]}),(Aa=cs.overall.strengthsWinner)!=null&&Aa.length||(Oa=cs.overall.weaknessesLoser)!=null&&Oa.length?jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"font-medium mb-1",children:"Winner strengths"}),jsxRuntimeExports.jsx("ul",{className:"text-muted-foreground list-disc list-inside space-y-0.5",children:(cs.overall.strengthsWinner??[]).map((Ia,La)=>jsxRuntimeExports.jsx("li",{children:Ia},La))})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"font-medium mb-1",children:"Loser weaknesses"}),jsxRuntimeExports.jsx("ul",{className:"text-muted-foreground list-disc list-inside space-y-0.5",children:(cs.overall.weaknessesLoser??[]).map((Ia,La)=>jsxRuntimeExports.jsx("li",{children:Ia},La))})]})]}):null,cs.perEval.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Per eval"}),cs.perEval.map((Ia,La)=>jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[jsxRuntimeExports.jsx(Badge,{variant:Ia.winnerTargetId?"default":"secondary",className:"font-mono text-xs shrink-0",children:ja(Ia.winnerTargetId)??"TIE"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:Ia.evalName}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-xs",children:Ia.reasoning})]})]},La))]})]})]})]},cs.id)})]}):jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["No comparisons yet. Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals compare <target-a> <target-b>"})," ","to create one."]})}function ComparisonRawOutput({id:es}){const{data:$,isLoading:ts}=useEvalComparison(es);return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-16 w-full"}):jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Judge output (not parseable as a structured verdict)"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto max-h-48 whitespace-pre-wrap",children:($==null?void 0:$.rawOutput)??"No raw output recorded."})]})}function PublicDocsShell({children:es}){return jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx("nav",{className:"sticky top-0 z-50 border-b border-border bg-background/80 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl flex items-center justify-between px-4 h-14",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-semibold",children:"RuleMetric"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",className:"cursor-pointer",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/login",children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/signup",children:"Get Started"})})]})]})}),jsxRuntimeExports.jsx("main",{className:"mx-auto max-w-6xl px-4 py-8",children:es})]})}function DocsRoute(){const{session:es,loading:$}=useAuth();return $?jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 w-64",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-1/2"})]})}):es?jsxRuntimeExports.jsx(RootLayout,{children:jsxRuntimeExports.jsx(DocsPage,{})}):jsxRuntimeExports.jsx(PublicDocsShell,{children:jsxRuntimeExports.jsx(DocsPage,{})})}function useHarnessReleases(es,$=50){const ts=new URLSearchParams;return ts.set("harness",es),ts.set("limit",String($)),useQuery({queryKey:["harness-releases",es,$],queryFn:()=>apiGet(`/api/harness-releases?${ts}`)})}function useSyncHarnessReleases(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/harness-releases/sync",{harness:$}),onSuccess:()=>es.invalidateQueries({queryKey:["harness-releases"]})})}function AnalysisFreshnessBanner({freshness:es,totalAnalyzed:$}){if(!es||$===0)return null;const{with_timestamp:ts,pre_instrumentation:is,stale_30d:cs,oldest_analyzed_at:Qr}=es,ja=$>0?Math.round(is/$*100):0,Na=ts>0?Math.round(cs/ts*100):0;if(is===0&&cs===0)return null;const Aa=ja>=25||Na>=50?"warn":"info",Oa=Aa==="warn"?"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300":"border-border bg-muted/40 text-muted-foreground";return jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-2 rounded-md border px-3 py-2 text-xs ${Oa}`,children:[Aa==="warn"?jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 shrink-0 mt-0.5"}):jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 shrink-0 mt-0.5"}),jsxRuntimeExports.jsxs("div",{className:"flex-1 font-mono space-y-0.5",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:Aa==="warn"?"Some inputs to these stats are stale or untimestamped":"Input freshness"}),jsxRuntimeExports.jsxs("p",{children:[is>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is," of ",$," analyzed sessions (",ja,"%) predate timestamp tracking. Re-analyze them to participate in freshness checks."]}),is>0&&cs>0&&" ",cs>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cs," of ",ts," timestamped analyses (",Na,"%) are over 30 days old",Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ","(oldest: ",new Date(Qr).toLocaleDateString(),")"]}),"."]})]})]})]})}function jobStepLabel(es){const $=es.progress;return $!=null&&$.step&&($!=null&&$.current)&&($!=null&&$.total)?`${$.step} (${$.current}/${$.total})`:$!=null&&$.step?$.step:es.status==="claimed"?"starting...":es.status==="pending"?"queued":es.status}function JobStatusIcon({status:es}){switch(es){case"completed":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"});case"running":case"claimed":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3.5 w-3.5 text-blue-500 animate-spin shrink-0"});case"failed":return jsxRuntimeExports.jsx(CircleX,{className:"h-3.5 w-3.5 text-red-500 shrink-0"});case"pending":default:return jsxRuntimeExports.jsx(CircleDashed,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})}}function JobTracker({jobs:es}){if(es.length===0)return null;const $=es.filter(La=>La.status==="completed").length,ts=es.filter(La=>La.status==="failed").length,is=es.filter(La=>La.status==="running"||La.status==="claimed").length,cs=es.filter(La=>La.status==="pending").length,Qr=es.length,ja=$+ts,Na=ja===Qr,Aa=$/Qr*100,Oa=ts/Qr*100,Ia=is/Qr*100;return jsxRuntimeExports.jsx(Card,{className:Na?"border-teal-500/30 bg-teal-500/5":"border-blue-500/30 bg-blue-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-4 pb-4 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[Na?jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-blue-500"}),jsxRuntimeExports.jsx("p",{className:"min-w-0 break-words text-sm font-medium",children:Na?Qr===1?"Recommendations ready":`All ${Qr} projects done`:Qr===1?`Generating recommendations — ${jobStepLabel(es[0])}`:`Generating recommendations — ${ja}/${Qr} complete`})]}),Qr>1&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground font-mono",children:[$>0&&jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[$," done"]}),is>0&&jsxRuntimeExports.jsxs("span",{className:"text-blue-500",children:[is," running"]}),cs>0&&jsxRuntimeExports.jsxs("span",{children:[cs," queued"]}),ts>0&&jsxRuntimeExports.jsxs("span",{className:"text-red-500",children:[ts," failed"]})]})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden flex",children:Qr===1?(()=>{const La=es[0],Ba=La.progress,Ma=Ba!=null&&Ba.current&&(Ba!=null&&Ba.total)?Ba.current/Ba.total*100:0;return La.status==="completed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500",style:{width:"100%"}}):La.status==="failed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500",style:{width:"100%"}}):jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Math.max(Ma,5)}%`}})})():jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Aa>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500 transition-all duration-500",style:{width:`${Aa}%`}}),Oa>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500 transition-all duration-500",style:{width:`${Oa}%`}}),Ia>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Ia}%`}})]})}),Qr>1&&jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-x-6 gap-y-1",children:es.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2 py-0.5 text-xs",children:[jsxRuntimeExports.jsx(JobStatusIcon,{status:La.status}),jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono",children:La.projectPath??"global"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:La.status==="running"||La.status==="claimed"?jobStepLabel(La):La.status==="failed"?"error":La.status==="completed"?"done":"queued"})]},La.id))})]})})}function ProjectJobBadge({job:es}){return es.status==="completed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"mr-1 h-2.5 w-2.5"})," done"]}):es.status==="failed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleX,{className:"mr-1 h-2.5 w-2.5"})," failed"]}):es.status==="running"||es.status==="claimed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-blue-500/10 text-blue-500 border-blue-500/20 font-mono",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-2.5 w-2.5 animate-spin"})," ",jobStepLabel(es)]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleDashed,{className:"mr-1 h-2.5 w-2.5"})," queued"]})}function WorkerOfflineBanner(){const{workers:es,isLoading:$}=useWorkerStatus("cli-worker");if($)return null;const ts=es.slice().sort((Qr,ja)=>new Date(ja.lastHeartbeat).getTime()-new Date(Qr.lastHeartbeat).getTime())[0];if((ts==null?void 0:ts.status)==="active")return null;const cs=ts?`${Math.round((Date.now()-new Date(ts.lastHeartbeat).getTime())/1e3)}s ago`:"never";return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm",children:[jsxRuntimeExports.jsx("div",{className:"font-medium text-amber-500 mb-1",children:"Worker offline"}),jsxRuntimeExports.jsxs("div",{className:"text-muted-foreground",children:["No cli-worker has heartbeat'd within the last 60s (last seen: ",cs,"). Insights jobs will queue but won't run until the worker is healthy. Restart with"," ",jsxRuntimeExports.jsx("code",{className:"font-mono text-xs bg-secondary px-1 py-0.5 rounded",children:"launchctl kickstart -k gui/$UID/com.rulemetric.worker"}),"."]})]})}function formatCompact(es){return new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(es)}function parseTimestamp(es){if(!es)return null;const $=es.replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),ts=new Date($);return Number.isNaN(ts.getTime())?null:ts}function formatSessionRange(es,$){const ts=parseTimestamp(es),is=parseTimestamp($),cs={month:"short",day:"numeric",year:"numeric"};if(ts&&is){const ja=ts.getFullYear()===is.getFullYear();return`${ts.toLocaleDateString(void 0,ja?{month:"short",day:"numeric"}:cs)} – ${is.toLocaleDateString(void 0,cs)}`}const Qr=ts??is;return Qr?Qr.toLocaleDateString(void 0,cs):null}function outcomeScore(es){const $=(es.achieved??0)+(es.mostly_achieved??0),ts=Object.values(es).reduce((is,cs)=>is+cs,0);return ts?Math.round($/ts*100):null}function InsightsOverview({computed:es}){var Na;const $=outcomeScore(es.outcomes??{}),ts=es.total_sessions?Math.round(es.sessions_with_analysis/es.total_sessions*100):0,is=Object.entries(es.friction??{}).sort((Aa,Oa)=>Oa[1]-Aa[1])[0],cs=Object.entries(es.tool_counts??{}).sort((Aa,Oa)=>Oa[1]-Aa[1]).slice(0,5),Qr=((Na=cs[0])==null?void 0:Na[1])??1,ja=[{label:"Successful outcomes",value:$==null?"—":`${$}%`,detail:`${es.sessions_with_analysis} analyzed`,icon:CircleCheck},{label:"Estimated spend",value:`$${(es.estimated_cost_usd??0).toFixed(2)}`,detail:`${formatCompact(es.total_input_tokens+es.total_output_tokens)} tokens`,icon:DollarSign},{label:"Tool errors",value:es.total_tool_errors.toLocaleString(),detail:`${es.total_interruptions} interruptions`,icon:TriangleAlert},{label:"Code changed",value:`+${formatCompact(es.total_lines_added)}`,detail:`${formatCompact(es.total_lines_removed)} removed · ${es.git_commits} commits`,icon:TrendingUp}];return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:ja.map(({label:Aa,value:Oa,detail:Ia,icon:La})=>jsxRuntimeExports.jsx(Card,{className:"min-w-0",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium uppercase tracking-wide",children:Aa}),jsxRuntimeExports.jsx(La,{className:"h-4 w-4"})]}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-2xl font-mono font-semibold",children:Oa}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Ia})]})},Aa))}),es.truncated&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[jsxRuntimeExports.jsxs(Card,{className:"min-w-0 lg:col-span-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"What is slowing work down?"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[Object.entries(es.friction??{}).sort((Aa,Oa)=>Oa[1]-Aa[1]).slice(0,5).map(([Aa,Oa])=>{const Ia=Math.max(1,Object.values(es.friction).reduce((La,Ba)=>La+Ba,0));return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"mb-1 flex min-w-0 justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words",children:Aa.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"shrink-0 font-mono text-muted-foreground",children:Oa})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-amber-500",style:{width:`${Math.max(4,Oa/Ia*100)}%`}})})]},Aa)}),!is&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction has been detected in analyzed sessions."})]})]}),jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base flex items-center gap-2",children:[jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"})," Most-used tools"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:cs.map(([Aa,Oa])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:Aa}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-20 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${Oa/Qr*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"w-10 text-right font-mono text-xs text-muted-foreground",children:Oa})]},Aa))})]})]}),ts<80&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Analysis coverage is ",ts,"%. Outcome and friction metrics reflect ",es.sessions_with_analysis," of ",es.total_sessions," sessions."]})]})}function ProjectCard({project:es,hasReport:$,activeJob:ts,onClick:is}){const cs=formatSessionRange(es.firstSession,es.lastSession);return jsxRuntimeExports.jsxs(Card,{className:"min-w-0 cursor-pointer hover:border-primary/50 transition-colors",...activatable(is),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"min-w-0 break-words text-base font-mono",children:es.name}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:shrink-0",children:[ts?jsxRuntimeExports.jsx(ProjectJobBadge,{job:ts}):$?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs bg-teal-500/10 text-teal-500 border-teal-500/20",children:"Recommendations"}):null,jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs",children:[es.enrichedCount," enriched"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," sessions"]}),es.analyzedCount>0&&jsxRuntimeExports.jsxs("span",{children:[es.analyzedCount," analyzed"]})]}),cs&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:cs})]})]})}function ReleaseCategorySection({label:es,items:$,colorClass:ts}){const[is,cs]=reactExports.useState(!1);return $.length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(!is),className:"flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors w-full text-left cursor-pointer",children:[is?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 shrink-0"}),jsxRuntimeExports.jsx("span",{className:ts,children:es}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",$.length,")"]})]}),is&&jsxRuntimeExports.jsx("ul",{className:"mt-1.5 ml-5 space-y-1",children:$.map((Qr,ja)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground leading-relaxed",children:Qr},ja))})]})}function ReleaseCard({release:es}){var ja,Na,Aa;const $=es.categories??{features:[],fixes:[],security:[]},ts=((ja=$.features)==null?void 0:ja.length)??0,is=((Na=$.fixes)==null?void 0:Na.length)??0,cs=((Aa=$.security)==null?void 0:Aa.length)??0,Qr=new Date(es.publishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono",children:es.version}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:Qr})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[ts>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20",children:[ts," feature",ts!==1?"s":""]}),is>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20",children:[is," fix",is!==1?"es":""]}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20",children:[cs," security"]})]})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Features",items:$.features??[],colorClass:"text-teal-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Fixes",items:$.fixes??[],colorClass:"text-amber-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Security",items:$.security??[],colorClass:"text-red-500"}),es.url&&jsxRuntimeExports.jsx("div",{className:"pt-1 flex justify-end",children:jsxRuntimeExports.jsxs("a",{href:es.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["View release ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})})]})]})}function HarnessUpdatesTab(){const{data:es,isLoading:$}=useHarnessReleases("claude_code"),ts=useSyncHarnessReleases();return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-mono font-semibold",children:"Claude Code Releases"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Changelog from the Claude Code GitHub repository"})]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>ts.mutate("claude_code"),disabled:ts.isPending,className:"cursor-pointer",children:[ts.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-3.5 w-3.5"}),"Sync"]})]}),ts.isSuccess&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Synced ",ts.data.synced," new release",ts.data.synced!==1?"s":""," (",ts.data.total," total checked)"]}),$?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(4)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-32"},cs))}):!es||es.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(Package,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No releases synced yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Click Sync to fetch the latest releases from GitHub."})]})]})})}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.map(is=>jsxRuntimeExports.jsx(ReleaseCard,{release:is},is.id))})]})}function InsightsListPage(){const[es,$]=useTabParam(["overview","harness-updates"],"overview"),ts=useNavigate(),{data:is,isLoading:cs}=useComputedInsights(),{data:Qr}=useInsightsProjects(),ja=useRegenerateAllInsights(),Na=useActiveInsightsJobs(),{data:Aa}=useInsightsJobs(void 0,500),Oa=(Aa??[]).filter(Fa=>Fa.status!=="cancelled"),Ia=(()=>{if(Oa.length<2)return[];const Fa=[...Oa].sort((Ka,Ga)=>new Date(Ka.createdAt).getTime()-new Date(Ga.createdAt).getTime());let Ha=[];for(let Ka=0;Ka<Fa.length;Ka++){const Ga=new Date(Fa[Ka].createdAt).getTime(),Va=Fa.filter(Ja=>new Date(Ja.createdAt).getTime()-Ga<12e4&&new Date(Ja.createdAt).getTime()>=Ga);Va.length>Ha.length&&(Ha=Va)}return Ha.length<2?[]:Ha})(),La=Ia.length>1,Ba=new Map;for(const Fa of Ia)Fa.projectPath&&!Ba.has(Fa.projectPath)&&Ba.set(Fa.projectPath,Fa);const Ma=new Set(Oa.filter(Fa=>Fa.status==="completed"&&Fa.projectPath).map(Fa=>Fa.projectPath)),qa=Fa=>{if(Fa.errors.length>0&&ue$1.error(`${Fa.errors.length} project${Fa.errors.length===1?"":"s"} failed to enqueue`,{description:`${Fa.errors[0].projectPath}: ${Fa.errors[0].error}`}),Fa.created>0){ue$1.success(`Started ${Fa.created} regeneration job${Fa.created===1?"":"s"}`,Fa.noLiveWorker?{description:"No live worker — start `rulemetric evals agent` to run them."}:void 0);return}const Ha=Fa.skipped.filter(Ga=>Ga.reason==="fresh").length,Ka=Fa.skipped.length-Ha;Ha>0?ue$1(Ka>0?`${Ha} project${Ha===1?"":"s"} fresh (<4h), ${Ka} skipped`:`All ${Ha} project${Ha===1?" is":"s are"} fresh (regenerated <4h ago)`,{action:{label:"Force regenerate",onClick:()=>ja.mutate({force:!0},{onSuccess:qa,onError:Ga=>ue$1.error("Couldn't start the regeneration",{description:Ga instanceof Error?Ga.message:"Please try again."})})}}):Ka>0?ue$1(`${Ka} project${Ka===1?"":"s"} skipped (no checkout or too few sessions)`):Fa.errors.length===0&&ue$1("No projects eligible for regeneration")};return cs?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Fa,Ha)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-28"},Ha))})]}):!is||is.total_sessions===0?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No sessions captured yet"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground max-w-md mx-auto mt-2",children:["Run ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric hooks install"})," in a project to start capturing Claude Code sessions. Insights will appear automatically after your next session."]})]})]})})})}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]}):jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-6",children:[jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2 sm:shrink-0",children:jsxRuntimeExports.jsx(Button,{onClick:()=>ja.mutate(void 0,{onSuccess:qa,onError:Fa=>ue$1.error("Couldn't start the regeneration",{description:Fa instanceof Error?Fa.message:"Please try again."})}),disabled:ja.isPending||Na.length>0,className:"w-full cursor-pointer sm:w-auto",children:Na.length>0?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating (",Na.length," remaining)..."]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4"}),"Regenerate All"]})})})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:[La&&jsxRuntimeExports.jsx(JobTracker,{jobs:Ia}),(is==null?void 0:is.analysis_freshness)&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:is.analysis_freshness,totalAnalyzed:is.sessions_with_analysis}),jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsx(InsightsOverview,{computed:is}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts("/insights/computed"),className:"text-sm font-medium text-primary hover:underline cursor-pointer",children:"Explore detailed trends and recommendations →"}),Qr&&Qr.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-mono font-semibold text-muted-foreground pt-2",children:"By Project"}),Qr.filter(Fa=>Fa.sessionCount>=3).map(Fa=>{const Ha=Ma.has(Fa.projectPath),Ka=Ba.get(Fa.projectPath),Ga=Fa.projectId??void 0,Va=Ga?`/insights/computed?projectPath=${encodeURIComponent(Fa.projectPath)}&projectId=${encodeURIComponent(Ga)}`:`/insights/computed?projectPath=${encodeURIComponent(Fa.projectPath)}`;return jsxRuntimeExports.jsx(ProjectCard,{project:Fa,hasReport:Ha,activeJob:Ka,onClick:()=>ts(Va)},Ga??Fa.projectPath)})]})]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]})}function verdictState(es){return es.sufficient?es.significant?"significant":"no-effect":(es.strataDroppedForTimeSeparation??0)>0?"no-comparable-cohort":"insufficient"}function VerdictBadge({verdict:es}){const $=`95% CI ${(es.ci.lower*100).toFixed(0)}–${(es.ci.upper*100).toFixed(0)}%`,ts=`n=${es.nWith}`,is=es.strata!=null?` · within ${es.strata} project${es.strata===1?"":"s"}`:"",cs=es.confounded?` · observational${is}`:"",Qr=verdictState(es);if(Qr==="no-comparable-cohort"){const Oa=es.strataDroppedForTimeSeparation;return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`No comparable cohort. ${Oa} project-month${Oa===1?"":"s"} held both exposed and unexposed sessions, but they're separated in time — this treatment's sessions all ran later than the ones without it, so any difference is a calendar difference, not an effect. More sessions won't resolve it; a randomised holdout would.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-amber-400 border-amber-400/40",children:"no comparable cohort"})})}if(Qr==="insufficient")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Not enough sessions to measure this yet, so no number is shown (rather than a fabricated one).${es.insufficientReason?` ${es.insufficientReason}`:""}`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"insufficient data"})});if(Qr==="no-effect")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`The with-vs-without difference isn't statistically distinguishable from zero, so we report no effect rather than noise. ${$}, ${ts}${cs}.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"no measured effect"})});const ja=es.delta>0,Na=`${ja?"+":""}${(es.delta*100).toFixed(0)}%`,Aa=es.pValue!=null?`, p=${es.pValue.toFixed(3)}`:"";return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Sessions with this ${ja?"did measurably BETTER":"did measurably WORSE"} than sessions without it, and the difference is statistically significant. ${$}, ${ts}${Aa}${cs}. Observational — a correlation from real sessions, not a controlled experiment.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono shrink-0",ja?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),children:[Na," outcome"]})})}function SessionsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[Object.keys(es.projects).length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Projects (",Object.keys(es.projects).length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.projects})})]}),es.session_summaries.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Sessions with Analysis (",es.session_summaries.length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:es.session_summaries.map($=>{const ts=$.id.length===36&&$.id.includes("-"),is=jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-3 rounded-lg border border-border bg-background p-3 ${ts?"hover:border-primary/50 cursor-pointer":""}`,children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs shrink-0",children:$.date}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-sm truncate",children:$.summary||$.goal||"No summary"}),$.goal&&$.summary&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:$.goal}),"outcome"in $&&$.outcome&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mt-1 text-[10px]",children:friendlyLabel($.outcome)})]})]});return ts?jsxRuntimeExports.jsx(Link,{to:`/sessions/${$.id}`,children:is},$.id):jsxRuntimeExports.jsx("div",{children:is},$.id)})})})]})]})}function RecEntryControls({item:es,projectPath:$}){const ts=useDismissRecommendation();return es.id?jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-1 shrink-0",children:[(es.timesGenerated??1)>1&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground",title:`This exact advice has been generated by ${es.timesGenerated} separate insights runs. Dismissing it stops the repetition for 90 days.`,"data-testid":"rec-seen-count",children:["seen ×",es.timesGenerated]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-6 w-6 p-0 text-muted-foreground",title:"Dismiss — hidden for 90 days",disabled:ts.isPending,"data-testid":"rec-dismiss",onClick:()=>ts.mutate({contentHash:es.id,projectPath:$},{onError:is=>ue$1.error(is.message)}),children:jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})})]}):null}function RecommendationsTab({rec:es,projectPath:$,autoAddAvailable:ts}){var ja,Na,Aa,Oa,Ia,La;const is=useAutoAddSuggestion(),[cs,Qr]=reactExports.useState(new Set);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[es.at_a_glance&&jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30 bg-amber-500/5",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-4 w-4 text-amber-500"}),"At a Glance"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Object.entries(es.at_a_glance).map(([Ba,Ma])=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1",children:Ba.replace(/_/g," ")}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:Ma})]},Ba))})]}),((ja=es.what_works)==null?void 0:ja.impressive_workflows)&&es.what_works.impressive_workflows.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Impressive Things You Did"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.what_works.impressive_workflows.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.description})]},Ma))})]}),((Na=es.friction_analysis)==null?void 0:Na.categories)&&es.friction_analysis.categories.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-amber-500"}),"Where Things Go Wrong"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.friction_analysis.categories.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.category}),jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.description}),Ba.examples.length>0&&jsxRuntimeExports.jsx("ul",{className:"mt-2 space-y-1",children:Ba.examples.map((qa,Fa)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground pl-3 border-l-2 border-border",children:qa},Fa))})]},Ba.id??Ma))})]}),((Aa=es.suggestions)==null?void 0:Aa.features_to_try)&&es.suggestions.features_to_try.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 text-blue-500"}),"Features to Try"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.features_to_try.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.feature}),Ba.example_code&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.example_code}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.example_code})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.why_for_you}),Ba.example_code&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.example_code})]},Ma))})]}),((Oa=es.suggestions)==null?void 0:Oa.claude_md_additions)&&es.suggestions.claude_md_additions.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Suggested CLAUDE.md Additions"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.claude_md_additions.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-muted px-2 py-1 rounded flex-1 overflow-x-auto",children:Ba.addition}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.addition}),$&&ts&&jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",disabled:cs.has(Ma)||is.isPending,onClick:qa=>{qa.stopPropagation(),is.mutate({projectPath:$,addition:Ba.addition,why:Ba.why},{onSuccess:Fa=>{(Fa.success||Fa.reason==="already_present")&&Qr(Ha=>new Set(Ha).add(Ma))},onError:Fa=>{const Ha=Fa instanceof ApiError&&(Fa.code==="not_local_mode"||Fa.statusCode===501);ue$1.error(Ha?"Add to CLAUDE.md only works when the API runs on your machine (local mode) — use the copy button instead.":Fa instanceof Error?Fa.message:"Failed to update CLAUDE.md")}})},children:is.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}):cs.has(Ma)?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3 text-teal-500"}):jsxRuntimeExports.jsx(Upload,{className:"h-3 w-3"})})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:Ba.why}),cs.has(Ma)&&jsxRuntimeExports.jsx("p",{className:"text-xs text-teal-500 mt-1",children:"Added to CLAUDE.md"})]},Ma))})]}),((Ia=es.suggestions)==null?void 0:Ia.usage_patterns)&&es.suggestions.usage_patterns.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-cyan-500"}),"Usage Patterns"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.usage_patterns.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[Ba.copyable_prompt&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.copyable_prompt})]}),jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.suggestion}),Ba.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.copyable_prompt})]},Ba.id??Ma))})]}),((La=es.on_the_horizon)==null?void 0:La.opportunities)&&es.on_the_horizon.opportunities.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-4 w-4 text-pink-500"}),"On the Horizon"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.on_the_horizon.opportunities.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),Ba.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.whats_possible}),Ba.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.copyable_prompt})]},Ma))})]}),es.fun_ending&&jsxRuntimeExports.jsx(Card,{className:"border-pink-500/20 bg-pink-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:es.fun_ending.headline}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:es.fun_ending.detail})]})})]})}function ScorePair({label:es,withVal:$,withoutVal:ts,delta:is,unit:cs,inverted:Qr}){const ja=Oa=>Oa!=null?`${Oa}${cs}`:"—",Na=is!=null&&is!==0?(Qr?is<0:is>0)?"text-teal-500":"text-red-500":"text-muted-foreground",Aa=is!=null&&is>0?"+":"";return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:ja($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"vs"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:ja(ts)})]}),is!=null&&is!==0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:`text-[10px] mt-1 ${Na} ${(Qr?is<0:is>0)?"bg-teal-500/10 border-teal-500/20":"bg-red-500/10 border-red-500/20"}`,children:[Aa,is,cs]})]})}function SegmentLine({title:es,noun:$,segments:ts}){if(!ts||ts.length===0)return null;const is=ts.filter(Qr=>Qr.verdict.sufficient),cs=ts.length-is.length;return is.length===0&&cs===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[10px] text-muted-foreground mr-0.5",children:es}),is.map(Qr=>{const ja=Qr.verdict,Na=ja.delta>0,Aa=ja.significant?`${Na?"+":""}${(ja.delta*100).toFixed(0)}%`:"no effect",Oa=ja.significant?Na?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40":"text-muted-foreground",Ia=`95% CI ${(ja.ci.lower*100).toFixed(0)}–${(ja.ci.upper*100).toFixed(0)}%, n=${ja.nWith} exposed / ${ja.nWithout} unexposed (observational)`;return jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono",Oa),title:Ia,children:[Qr.label," ",Aa]},Qr.label)}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground",title:`Not enough exposed + unexposed sessions within a project to measure ${cs===1?`this ${$}`:`these ${$}s`} yet.`,children:[cs," ",$,cs===1?"":"s",": insufficient"]})]})}function SegmentBreakdown({impact:es}){const $=(es.segments??[]).map(is=>({label:is.model,verdict:is.verdict})),ts=(es.harnessSegments??[]).map(is=>({label:is.harness,verdict:is.verdict}));return $.length===0&&ts.length===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-3 pt-3 border-t",children:[jsxRuntimeExports.jsx(SegmentLine,{title:"By model:",noun:"model",segments:$}),jsxRuntimeExports.jsx(SegmentLine,{title:"By harness:",noun:"harness",segments:ts})]})}function RandomisedBadges({randomised:es}){const $=ts=>ts.split("/").filter(Boolean).pop()??ts;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[es.verdicts.map(ts=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`RANDOMISED verdict on ${ts.projectPath}: sessions were assigned to receive or not receive this instruction, and the ${ts.decision==="always"?"receiving":"withheld"} arm did measurably ${ts.decision==="always"?"better":"better without it"}. ${(ts.delta>0?"+":"")+(ts.delta*100).toFixed(0)}pp, 95% CI ${(ts.ciLower*100).toFixed(0)} to ${(ts.ciUpper*100).toFixed(0)}pp, n=${ts.nTreated}/${ts.nControl}. This supersedes the observational estimate for that project — assignment, not correlation.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:ts.decision==="always"?"text-[10px] font-mono shrink-0 text-teal-400 border-teal-400/40":"text-[10px] font-mono shrink-0 text-red-400 border-red-400/40","data-testid":"randomised-verdict-badge",children:["randomised · ",ts.delta>0?"+":"",(ts.delta*100).toFixed(0),"pp on ",$(ts.projectPath)]})},ts.projectPath)),es.experiments.map(ts=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Under randomised measurement on ${ts.projectPath} right now — injected to some sessions and withheld from the rest until the arms decide.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground","data-testid":"randomised-running-badge",children:["measuring · ",$(ts.projectPath)]})},ts.id))]})}function ImpactCard({impact:es,linkedSessions:$,source:ts}){const is=es.with,cs=es.without,Qr=es.comparison;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono truncate",children:es.instructionName}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[jsxRuntimeExports.jsx(ProvenanceBadge,{source:ts}),es.autoAdded&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-teal-400 border-teal-400/40",title:`Auto-added from a recommendation${es.autoAdded.count>1?` ×${es.autoAdded.count}`:""}`+(es.autoAdded.lastAssignedAt?` (last ${new Date(es.autoAdded.lastAssignedAt).toLocaleDateString()})`:"")+" — the verdict beside this is whether it helped.",children:["auto-added",es.autoAdded.count>1?` ×${es.autoAdded.count}`:""]}),es.randomised&&jsxRuntimeExports.jsx(RandomisedBadges,{randomised:es.randomised}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict}),$!=null&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:[$," sessions"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-xs",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:"Sessions"}),jsxRuntimeExports.jsxs("p",{className:"font-mono",children:[is.sessionCount," with / ",cs.sessionCount," without"]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground mt-0.5",children:[is.enrichedCount," / ",cs.enrichedCount," enriched"]})]}),jsxRuntimeExports.jsx(ScorePair,{label:"Outcome Score",withVal:is.avgOutcomeScore,withoutVal:cs.avgOutcomeScore,delta:Qr.outcomeScoreDelta,unit:""}),jsxRuntimeExports.jsx(ScorePair,{label:"Tool Errors",withVal:is.avgToolErrors,withoutVal:cs.avgToolErrors,delta:Qr.toolErrorsDelta,unit:"",inverted:!0}),jsxRuntimeExports.jsx(ScorePair,{label:"Avg Duration",withVal:is.avgDurationMinutes,withoutVal:cs.avgDurationMinutes,delta:Qr.durationDelta,unit:"m",inverted:!0})]}),jsxRuntimeExports.jsx(SegmentBreakdown,{impact:es})]})]})}function InstructionImpactLoader({instructionId:es,linkedSessions:$,source:ts}){const{data:is,isLoading:cs}=useInstructionImpact(es);return cs?jsxRuntimeExports.jsx(Skeleton,{className:"h-24"}):!is||is.with.sessionCount===0&&is.without.sessionCount===0?null:jsxRuntimeExports.jsx(ImpactCard,{impact:is,linkedSessions:$,source:ts})}function GroomingCard(){const{data:es,isLoading:$}=useGroomCandidates(),ts=useArchiveInstruction(),is=useRestoreInstruction(),[cs,Qr]=reactExports.useState(new Set);if($||!es)return null;if(!es.captureHealthy)return jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Grooming paused"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:es.reason})})]});const ja=es.harmful??[],Na=es.bloated??[],Aa=es.candidates.length+ja.length;if(Aa===0&&Na.length===0)return null;const Oa=La=>jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-6 text-[10px] shrink-0",disabled:cs.has(La)||ts.isPending,onClick:()=>ts.mutate(La,{onSuccess:()=>{Qr(Ba=>new Set(Ba).add(La)),ue$1.success("Archived",{description:"Soft delete — this can be restored.",action:{label:"Undo",onClick:()=>is.mutate(La,{onSuccess:()=>{Qr(Ba=>{const Ma=new Set(Ba);return Ma.delete(La),Ma}),ue$1.success("Restored")},onError:()=>ue$1.error("Restore failed")})}})},onError:()=>ue$1.error("Archive failed")}),children:cs.has(La)?"Archived":"Archive"}),Ia=es.safetyGuarded+(es.harmfulSafetyGuarded??0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm",children:["Instructions worth a second look (",Aa+Na.length,")"]}),Ia>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Safety / destructive-guardrail rules are never proposed for retirement, however rarely they fire or however they score.",children:[Ia," safety rule",Ia===1?"":"s"," protected"]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Your own instructions worth a second look. Archiving is reversible; safety rules are never listed here."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Na.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-amber-400/90 mb-0.5",children:"Expensive, no measurable effect"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Enough exposure to detect an effect and none was found — so these are candidates to SHORTEN, not to retire. Neutral means undetected, not worthless; the rule may carry something the outcome score cannot see. No archive button here on purpose."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:Na.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:La.verdict}),La.containsSafetyLanguage&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-400 shrink-0",title:"Contains destructive-command or credential guardrail language. Shown anyway — a trim changes nothing on its own — but preserve those lines when shortening.",children:"has guardrails"})]}),jsxRuntimeExports.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Estimated from content length (chars/4), not a tokenizer count.",children:["~",La.estimatedTokens.toLocaleString()," tok/session"]})]},La.id))})]}),ja.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-red-400/90 mb-0.5",children:"Measurably worse outcomes"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Present in sessions that scored significantly lower. Correlational, not proven cause — the rule may just ride along with harder tasks — so review before retiring; the verdict beside each shows the effect."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:ja.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:La.verdict})]}),Oa(La.id)]},La.id))})]}),es.candidates.length>0&&jsxRuntimeExports.jsxs("div",{children:[ja.length>0&&jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-muted-foreground mb-1.5",children:"No recent use"}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-80 overflow-y-auto",children:es.candidates.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] shrink-0 text-muted-foreground",children:La.reason})]}),Oa(La.id)]},La.id))})]})]})]})}function InstructionsTab({projectFilter:es}){const{data:$,isLoading:ts}=useLinkedInstructions(es);return ts?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(3)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},cs))}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(GroomingCard,{}),!$||$.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No instructions linked to sessions yet. Instructions are auto-captured from context snapshots — the session-end hook snapshots your on-disk CLAUDE.md files, and the proxy additionally captures runtime-rendered prompts and skills."})})}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Instructions linked to sessions, ranked by usage. Comparing sessions with vs. without each instruction."}),$.map(is=>jsxRuntimeExports.jsx(InstructionImpactLoader,{instructionId:is.id,linkedSessions:is.linkedSessions,source:is.source},is.id))]})]})}function InsightsDetailPage(){const{id:es}=useParams(),[$]=useSearchParams(),ts=es==="computed",is=ts?$.get("projectPath")??$.get("project")??void 0:void 0,cs=ts?$.get("projectId")??void 0:void 0,[Qr,ja]=reactExports.useState(""),{data:Na,recommendations:Aa,isLoading:Oa,fullProjectPath:Ia,title:La,subtitle:Ba,lastCompletedJob:Ma,activeJobs:qa,createJob:Fa}=useProjectInsights(es,is,cs,Qr||void 0),[Ha,Ka]=useTabParam(["overview","tools","quality","sessions","instructions","recommendations"],"overview");if(Oa)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48"}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((Ya,el)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},el))})]});if(!Na)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Report not found."})]});const Ga=ts?Na.tools_used??{}:{},Va=Object.keys(Ga).sort((Ya,el)=>(Ga[el]??0)-(Ga[Ya]??0)),Ja=Na.autoAddAvailable!==!1;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:La}),ts&&(Va.length>1||Qr)&&jsxRuntimeExports.jsxs("select",{value:Qr,onChange:Ya=>ja(Ya.target.value),className:"h-8 rounded-md border border-input bg-background px-2 text-xs font-mono cursor-pointer focus:outline-none focus:ring-1 focus:ring-ring",children:[jsxRuntimeExports.jsx("option",{value:"",children:"All Tools"}),Va.map(Ya=>jsxRuntimeExports.jsxs("option",{value:Ya,children:[displayTool(Ya)," (",Ga[Ya],")"]},Ya)),Qr&&!Va.includes(Qr)&&jsxRuntimeExports.jsx("option",{value:Qr,children:displayTool(Qr)})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Ba}),ts&&Va.length>0&&!Qr&&jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:Va.map(Ya=>jsxRuntimeExports.jsx(Badge,{asChild:!0,variant:"outline",children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ja(Ya),className:"text-[10px] font-mono cursor-pointer hover:bg-primary/10",children:[displayTool(Ya),": ",Ga[Ya]]})},Ya))})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[Ma&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Last generated ",new Date(Ma.completedAt).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>Fa.mutate(Ia??is,{onSuccess:Ya=>{Ya.noLiveWorker?ue$1.warning("Queued, but no worker is listening",{description:"Start one with `rulemetric evals agent` (or `rulemetric service install --worker-only`) and it will pick this up."}):ue$1.success("Generating recommendations…")},onError:Ya=>ue$1.error("Couldn't start the run",{description:Ya instanceof Error?Ya.message:"Please try again."})}),disabled:Fa.isPending||qa.length>0,variant:"outline",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),qa.length>0?`Generating — ${jobStepLabel(qa[0])}`:Aa?"Refresh Recommendations":"Generate Recommendations"]})]})]}),ts&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:Na.analysis_freshness,totalAnalyzed:Na.sessions_with_analysis??0}),jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),qa.length>0&&jsxRuntimeExports.jsx(JobTracker,{jobs:qa}),jsxRuntimeExports.jsxs(Tabs,{value:Ha,onValueChange:Ka,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"mr-2 h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"tools",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"Tools"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"quality",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"mr-2 h-4 w-4"}),"Quality"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"sessions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"mr-2 h-4 w-4"}),"Sessions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"instructions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"mr-2 h-4 w-4"}),"Instructions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"recommendations",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),"Recommendations"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"mt-6",children:jsxRuntimeExports.jsx(OverviewTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"tools",className:"mt-6",children:jsxRuntimeExports.jsx(ToolsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"quality",className:"mt-6",children:jsxRuntimeExports.jsx(QualityTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"sessions",className:"mt-6",children:jsxRuntimeExports.jsx(SessionsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"instructions",className:"mt-6",children:jsxRuntimeExports.jsx(InstructionsTab,{projectFilter:is})}),jsxRuntimeExports.jsx(TabsContent,{value:"recommendations",className:"mt-6",children:Aa?jsxRuntimeExports.jsx(RecommendationsTab,{rec:Aa,projectPath:Ia,autoAddAvailable:Ja}):jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:qa.length>0?`Generating recommendations — ${jobStepLabel(qa[0])}`:'No recommendations yet. Use "Generate Recommendations" above to analyze this project’s sessions.'})})})})]})]})}const MEMORY_PAGE_SIZE=50;function useMemories(es="active",$="",ts="all"){return useInfiniteQuery({queryKey:["memories",{status:es,search:$,kind:ts}],initialPageParam:0,queryFn:({pageParam:is})=>{const cs=new URLSearchParams({status:es,limit:String(MEMORY_PAGE_SIZE),offset:String(is)});return $&&cs.set("search",$),ts&&ts!=="all"&&cs.set("kind",ts),apiGet(`/api/memories?${cs.toString()}`).then(Qr=>Qr.memories)},getNextPageParam:(is,cs)=>is.length<MEMORY_PAGE_SIZE?void 0:cs.length*MEMORY_PAGE_SIZE})}function useMemory(es){return useQuery({queryKey:["memories",es],queryFn:()=>apiGet(`/api/memories/${es}`),enabled:!!es})}function useMemoryImpact(es){return useQuery({queryKey:["insights","memory-impact",es],queryFn:()=>apiGet(`/api/insights/memory-impact?memoryId=${es}`),enabled:!!es})}function useMemoryExperiments(es){return useQuery({queryKey:["memories",es,"experiments"],queryFn:()=>apiGet(`/api/memories/${es}/experiments`),enabled:!!es,select:$=>$.experiments,refetchInterval:$=>{var is;return(((is=$.state.data)==null?void 0:is.experiments)??[]).some(cs=>cs.status==="pending"||cs.status==="running")?5e3:!1}})}function useCreateExperiment(es){const $=useQueryClient();return useMutation({mutationFn:ts=>apiPost(`/api/memories/${es}/experiments`,ts),onSuccess:()=>$.invalidateQueries({queryKey:["memories",es,"experiments"]})})}function useCreateMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/memories",$),onSuccess:()=>es.invalidateQueries({queryKey:["memories"]})})}function useUpdateMemory(){const es=useQueryClient();return useMutation({mutationFn:({id:$,...ts})=>apiPatch(`/api/memories/${$}`,ts),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts.id]})}})}function useArchiveMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/memories/${$}`),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts]})}})}const KINDS=["fact","decision","correction","convention"];function MemoryFormDialog({open:es,onOpenChange:$,memory:ts}){const is=!!ts,cs=useCreateMemory(),Qr=useUpdateMemory(),[ja,Na]=reactExports.useState("fact"),[Aa,Oa]=reactExports.useState(""),[Ia,La]=reactExports.useState("");reactExports.useEffect(()=>{es&&(Na((ts==null?void 0:ts.kind)??"fact"),Oa((ts==null?void 0:ts.title)??""),La((ts==null?void 0:ts.body)??""))},[es,ts==null?void 0:ts.id]);const Ba=cs.isPending||Qr.isPending,Ma=Aa.trim().length>0&&Ia.trim().length>0&&!Ba,qa=()=>{if(!Ma)return;const Fa=Ka=>()=>{ue$1.success(`Memory ${Ka}`),$(!1)},Ha=Ka=>ue$1.error(Ka instanceof Error?Ka.message:"Something went wrong");is?Qr.mutate({id:ts.id,kind:ja,title:Aa.trim(),body:Ia.trim()},{onSuccess:Fa("updated"),onError:Ha}):cs.mutate({kind:ja,title:Aa.trim(),body:Ia.trim()},{onSuccess:Fa("created"),onError:Ha})};return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:is?"Edit memory":"New memory"}),jsxRuntimeExports.jsx(DialogDescription,{children:"A durable note the session-start hook injects into future sessions as context. Its measured effect is tracked automatically."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Kind"}),jsxRuntimeExports.jsxs(Select,{value:ja,onValueChange:Fa=>Na(Fa),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsx(SelectContent,{children:KINDS.map(Fa=>jsxRuntimeExports.jsx(SelectItem,{value:Fa,className:"capitalize",children:Fa},Fa))})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Title"}),jsxRuntimeExports.jsx(Input,{value:Aa,onChange:Fa=>Oa(Fa.target.value),placeholder:"Short, memorable summary",maxLength:300})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:Fa=>La(Fa.target.value),placeholder:"The fact / decision / correction / convention to remember.",rows:5})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:qa,disabled:!Ma,className:"cursor-pointer",children:Ba?"Saving…":is?"Save changes":"Create"})]})]})})}const kindColors={fact:"bg-blue-500/15 text-blue-400 border-blue-500/30",decision:"bg-primary/15 text-primary border-primary/30",correction:"bg-red-500/15 text-red-400 border-red-500/30",convention:"bg-pink-500/15 text-pink-400 border-pink-500/30"};function useDebouncedValue(es,$){const[ts,is]=reactExports.useState(es);return reactExports.useEffect(()=>{const cs=setTimeout(()=>is(es),$);return()=>clearTimeout(cs)},[es,$]),ts}function MemoryList(){const[es,$]=reactExports.useState("active"),[ts,is]=reactExports.useState(""),[cs,Qr]=reactExports.useState("all"),[ja,Na]=reactExports.useState(!1),Aa=useNavigate(),Oa=useDebouncedValue(ts.trim(),300),{data:Ia,isLoading:La,error:Ba,hasNextPage:Ma,fetchNextPage:qa,isFetchingNextPage:Fa}=useMemories(es,Oa,cs),Ha=reactExports.useMemo(()=>(Ia==null?void 0:Ia.pages.flat())??[],[Ia]),Ka=Oa!==""||cs!=="all";if(Ba)return jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load memories: ",Ba.message]});const Ga=es!=="active";return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative min-w-40 flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search memories...",value:ts,onChange:Va=>is(Va.target.value),className:"pl-9 bg-background border-border"})]}),jsxRuntimeExports.jsxs(Select,{value:cs,onValueChange:Qr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-36 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All kinds"}),jsxRuntimeExports.jsx(SelectItem,{value:"fact",children:"Fact"}),jsxRuntimeExports.jsx(SelectItem,{value:"decision",children:"Decision"}),jsxRuntimeExports.jsx(SelectItem,{value:"correction",children:"Correction"}),jsxRuntimeExports.jsx(SelectItem,{value:"convention",children:"Convention"})]})]}),jsxRuntimeExports.jsxs(Select,{value:es,onValueChange:Va=>$(Va),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-32 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"active",children:"Active"}),jsxRuntimeExports.jsx(SelectItem,{value:"archived",children:"Archived"}),jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All"})]})]}),jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New"]})]}),La?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((Va,Ja)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 rounded-lg"},Ja))}):Ha.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12",children:[jsxRuntimeExports.jsx(Brain,{className:"mx-auto h-8 w-8 text-muted-foreground/40 mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-4",children:Ka?"No memories match your filters.":"No memories yet. Create one, or let the distiller extract them from your sessions."}),!Ka&&jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create memory"]})]}):jsxRuntimeExports.jsx("div",{className:"bg-card border border-border rounded-lg",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-transparent",children:[jsxRuntimeExports.jsx(TableHead,{children:"Title"}),jsxRuntimeExports.jsx(TableHead,{children:"Kind"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden md:table-cell",children:"Scope"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden lg:table-cell",children:"Source"}),Ga&&jsxRuntimeExports.jsx(TableHead,{children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ha.map(Va=>jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-secondary/50 transition-colors duration-200 cursor-pointer",onClick:()=>Aa(`/memories/${Va.id}`),children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium max-w-md truncate",children:Va.title}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[Va.kind]}`,children:Va.kind})}),jsxRuntimeExports.jsx(TableCell,{className:"hidden md:table-cell text-xs text-muted-foreground",children:Va.projectId?"Project":"Global"}),jsxRuntimeExports.jsx(TableCell,{className:"hidden lg:table-cell text-xs text-muted-foreground",children:Va.source}),Ga&&jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs capitalize text-muted-foreground",children:Va.status})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-xs text-muted-foreground",children:formatDistanceToNow(Va.updatedAt)})]},Va.id))})]})}),Ma&&jsxRuntimeExports.jsx("div",{className:"flex justify-center",children:jsxRuntimeExports.jsx(Button,{variant:"outline",className:"cursor-pointer",disabled:Fa,onClick:()=>qa(),children:Fa?"Loading…":"Load more"})}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:ja,onOpenChange:Na})]})}function MemoriesListPage(){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Memories"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Durable project facts your agent recalls — injected at session start, and measured for whether they actually help."})]}),jsxRuntimeExports.jsx(MemoryList,{})]})}function ExperimentRow({exp:es}){var $,ts,is;return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-mono truncate",title:es.taskPrompt,children:es.taskPrompt}),jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:["v",es.memoryVersion," · ",es.engine," · ",es.trials," trials · ",formatDistanceToNow(es.createdAt)]}),es.status==="failed"&&es.error&&jsxRuntimeExports.jsx("p",{className:"text-[10px] text-red-400 mt-0.5",title:es.error,children:es.error}),es.result&&jsxRuntimeExports.jsxs("details",{className:"mt-2 text-xs",children:[jsxRuntimeExports.jsxs("summary",{className:"cursor-pointer",children:["Trial evidence · ",es.result.completedTrials,"/",es.trials," usable pairs"]}),jsxRuntimeExports.jsxs("p",{className:"break-words mt-2",children:[es.result.engine," · ",es.result.model??"Model not recorded",es.result.judge&&` · configured grader ${es.result.judge.engine} ${es.result.judge.model??"(default)"}`]}),es.result.actualJudge&&jsxRuntimeExports.jsx("p",{className:"break-words",children:es.result.actualJudge.engine?`Actual grader: ${es.result.actualJudge.engine} · ${es.result.actualJudge.model??"model not recorded"}`:"Deterministic assertions · no model grader used"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"With memory / without memory. Dollar values are API-equivalent estimates, not subscription charges."}),jsxRuntimeExports.jsx("ol",{className:"space-y-1 mt-2",children:($=es.result.pairs)==null?void 0:$.map((cs,Qr)=>{var ja,Na,Aa,Oa;return jsxRuntimeExports.jsxs("li",{className:"break-words",children:["Pair ",Qr+1,": score ",cs.withScore,"/",cs.withoutScore,"; tokens ",cs.withTokens??"?","/",cs.withoutTokens??"?",";"," ","seconds ",((ja=cs.withLatency)==null?void 0:ja.toFixed(1))??"?","/",((Na=cs.withoutLatency)==null?void 0:Na.toFixed(1))??"?",";"," ","estimated $ ",((Aa=cs.withCostUsd)==null?void 0:Aa.toFixed(5))??"unknown","/",((Oa=cs.withoutCostUsd)==null?void 0:Oa.toFixed(5))??"unknown"]},Qr)})}),(ts=es.result.excluded)==null?void 0:ts.map(cs=>jsxRuntimeExports.jsxs("p",{className:"break-words text-amber-500",children:["Excluded trial ",cs.trial,": ",cs.reason]},cs.trial))]})]}),jsxRuntimeExports.jsx("div",{className:"shrink-0",children:es.status==="completed"&&((is=es.result)!=null&&is.verdict)?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["n=",es.result.completedTrials]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.result.verdict})]}):es.status==="failed"||es.status==="completed"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] text-red-400 border-red-400/40",children:es.status==="failed"?"failed":"no usable verdict"}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] text-muted-foreground gap-1",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),es.status==="running"?"running":"queued"]})})]})}function MemoryExperiments({memoryId:es}){const{data:$,isLoading:ts}=useMemoryExperiments(es),is=useCreateExperiment(es),[cs,Qr]=reactExports.useState(!1),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),[Ia,La]=reactExports.useState(10),[Ba,Ma]=reactExports.useState("claude"),[qa,Fa]=reactExports.useState(""),[Ha,Ka]=reactExports.useState("claude"),[Ga,Va]=reactExports.useState("");function Ja(){const Ya=Aa.split(`
|
|
144
|
+
`).map(el=>el.trim()).filter(Boolean);if(!ja.trim()||Ya.length===0){ue$1.error("A task prompt and at least one expectation are required.");return}is.mutate({taskPrompt:ja.trim(),expectations:Ya,trials:Ia,engine:Ba,graderEngine:Ha,...Ga.trim()?{graderModel:Ga.trim()}:{},...qa.trim()?{model:qa.trim()}:{}},{onSuccess:el=>{ue$1.success(el.noLiveWorker?"Queued — start `rulemetric evals agent` on your laptop to run it":"Controlled A/B started — the causal verdict appears when it finishes"),Na(""),Oa(""),Qr(!1)},onError:el=>ue$1.error(`Failed: ${el.message}`)})}return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-3.5 w-3.5"})," Controlled A/B"]}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs",onClick:()=>Qr(Ya=>!Ya),children:cs?"Cancel":"Run A/B"})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["The gold-standard causal test: the same task run with vs without this memory injected, graded and paired. Unlike the observational effect above, this holds the task and harness constant — so its delta isn't confounded. Each trial runs the selected harness on your laptop (needs"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"rulemetric evals agent"}),"). Ten trials is a minimum, not a guarantee of a conclusive result."]}),cs&&jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-md border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-task",className:"text-xs",children:"Task prompt"}),jsxRuntimeExports.jsx(Textarea,{id:"ab-task",value:ja,onChange:Ya=>Na(Ya.target.value),placeholder:"e.g. Add a new dependency to this project.",className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-exp",className:"text-xs",children:"Expectations (one per line)"}),jsxRuntimeExports.jsx(Textarea,{id:"ab-exp",value:Aa,onChange:Ya=>Oa(Ya.target.value),placeholder:`Uses pnpm, not npm
|
|
145
|
+
Runs the install command`,className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap items-end justify-between gap-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-end gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-engine",className:"text-xs",children:"Harness"}),jsxRuntimeExports.jsxs(Select,{value:Ba,onValueChange:Ya=>Ma(Ya),children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"ab-engine",size:"sm",className:"w-28 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"claude",children:"Claude"}),jsxRuntimeExports.jsx(SelectItem,{value:"codex",children:"Codex"}),jsxRuntimeExports.jsx(SelectItem,{value:"pi",children:"Pi"})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-trials",className:"text-xs",children:"Trials"}),jsxRuntimeExports.jsx(Input,{id:"ab-trials",type:"number",min:1,max:50,value:Ia,onChange:Ya=>La(Math.max(1,Math.min(50,Number(Ya.target.value)||1))),className:"text-xs h-8 w-20"})]})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-model",className:"text-xs",children:"Trial model pin"}),jsxRuntimeExports.jsx(Input,{id:"ab-model",value:qa,onChange:Ya=>Fa(Ya.target.value),placeholder:Ba==="pi"?"openai-codex/gpt-5.4-mini":Ba==="codex"?"Required Codex model":"Optional Claude model"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Both arms use this model. The independent grader below must also be available on the worker."})]}),jsxRuntimeExports.jsxs("details",{className:"text-xs space-y-2",children:[jsxRuntimeExports.jsxs("summary",{className:"cursor-pointer",children:["Grader: ",Ha," · ",Ga||"default"]}),jsxRuntimeExports.jsx(Label,{htmlFor:"ab-grader",children:"Grader harness"}),jsxRuntimeExports.jsxs("select",{id:"ab-grader",className:"w-full rounded border bg-background p-2",value:Ha,onChange:Ya=>{Ka(Ya.target.value),Va("")},children:[jsxRuntimeExports.jsx("option",{value:"claude",children:"Claude"}),jsxRuntimeExports.jsx("option",{value:"codex",children:"Codex / OpenAI"})]}),jsxRuntimeExports.jsx(Label,{htmlFor:"ab-grader-model",children:"Grader model pin"}),jsxRuntimeExports.jsx(Input,{id:"ab-grader-model",value:Ga,onChange:Ya=>Va(Ya.target.value),placeholder:Ha==="codex"?"Required Codex model":"Optional Claude model"})]}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:is.isPending||Ha==="codex"&&!Ga.trim()||Ba==="codex"&&!qa.trim()||Ba==="pi"&&!/^[^\s/:]+\/[^\s/]+$/.test(qa.trim()),onClick:Ja,children:is.isPending?"Starting…":"Run experiment"})]}),ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-12"}):!$||$.length===0?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No controlled experiments yet. Run one to get an unconfounded causal delta."}):jsxRuntimeExports.jsxs("div",{children:[$.length>=20&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Showing the 20 most recent experiments."}),$.map(Ya=>jsxRuntimeExports.jsx(ExperimentRow,{exp:Ya},Ya.id))]})]})]})}function formatTokens(es){return es==null?"—":es>=1e6?`${(es/1e6).toFixed(1)}M`:es>=1e3?`${(es/1e3).toFixed(0)}K`:String(es)}function Cohort({label:es,value:$}){return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:$})]})}function MemoryImpactCard({impact:es}){const $=es.with,ts=es.without,is=es.comparison,cs=$.avgOutcomeScore!=null&&ts.avgOutcomeScore!=null?`${$.avgOutcomeScore} vs ${ts.avgOutcomeScore}${is.outcomeScoreDelta!=null?` (${is.outcomeScoreDelta>0?"+":""}${is.outcomeScoreDelta})`:""}`:"—",Qr=$.avgTotalTokens!=null&&ts.avgTotalTokens!=null?`${formatTokens($.avgTotalTokens)} vs ${formatTokens(ts.avgTotalTokens)}`:"—";return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Measured effect"}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-xs",children:[jsxRuntimeExports.jsx(Cohort,{label:"Sessions",value:`${$.sessionCount} with / ${ts.sessionCount} without`}),jsxRuntimeExports.jsx(Cohort,{label:"Outcome score",value:cs}),jsxRuntimeExports.jsx(Cohort,{label:"Avg tokens/session",value:Qr})]}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mt-3",children:"Observational — sessions exposed to this memory vs not, compared within each project. Not a controlled experiment; cost is estimated."})]})]})}function VersionHistoryCard({versions:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Effect by version"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[es.map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:["v",$.version]}),$.isCurrent&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] py-0 text-muted-foreground",children:"current"}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[$.with.sessionCount," session",$.with.sessionCount===1?"":"s"]})]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:$.verdict})]},$.version)),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground pt-1",children:"Each edit bumps the version and re-opens measurement, so a version is scored only on the sessions that actually saw it."})]})]})}function MemoryImpactLoader({memoryId:es}){const{data:$,isLoading:ts}=useMemoryImpact(es);return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-28"}):!$||$.with.sessionCount===0&&$.without.sessionCount===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No measured effect yet. Once this memory is injected into sessions (via the session-start hook) and those sessions are analyzed, its verdict appears here."})})}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(MemoryImpactCard,{impact:$}),$.versions.length>1&&jsxRuntimeExports.jsx(VersionHistoryCard,{versions:$.versions})]})}function MemoryDetail({id:es}){const{data:$,isLoading:ts,error:is}=useMemory(es),cs=useArchiveMemory(),Qr=useUpdateMemory(),[ja,Na]=reactExports.useState(!1);if(ts)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40"})]});if(is||!$)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/memories",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Memory not found."})]});const Aa=$.status==="archived";return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/memories",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Pencil,{className:"mr-1.5 h-3.5 w-3.5"})," Edit"]}),Aa?jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer",disabled:Qr.isPending,onClick:()=>Qr.mutate({id:$.id,status:"active"},{onSuccess:()=>ue$1.success("Memory restored"),onError:()=>ue$1.error("Restore failed")}),children:[jsxRuntimeExports.jsx(RotateCcw,{className:"mr-1.5 h-3.5 w-3.5"})," Restore"]}):jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer text-red-400 hover:text-red-400",disabled:cs.isPending,onClick:()=>cs.mutate($.id,{onSuccess:()=>ue$1.success("Memory archived (reversible)"),onError:()=>ue$1.error("Archive failed")}),children:[jsxRuntimeExports.jsx(Archive,{className:"mr-1.5 h-3.5 w-3.5"})," Archive"]})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[$.kind]??""}`,children:$.kind}),Aa&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-muted-foreground",children:"archived"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["v",$.version," · ",$.source," · ",$.projectId?"project-scoped":"global"]})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight mt-2",children:$.title})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Content"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",children:$.body})})]}),jsxRuntimeExports.jsx(MemoryImpactLoader,{memoryId:$.id}),jsxRuntimeExports.jsx(MemoryExperiments,{memoryId:$.id}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:ja,onOpenChange:Na,memory:$})]})}function MemoryDetailPage(){const{id:es}=useParams();return es?jsxRuntimeExports.jsx(MemoryDetail,{id:es}):null}const CATEGORY_LABELS={workflow:"Workflow",language:"Language",framework:"Framework",tool:"Tool",security:"Security",testing:"Testing",architecture:"Architecture",devops:"DevOps",documentation:"Documentation",performance:"Performance",other:"Other"};function CopyInstallButton({skill:es}){const{copied:$,copy:ts}=useCopyToClipboard(),is=`rulemetric skills install ${es.id}`;return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5",onClick:cs=>{cs.stopPropagation(),ts(is)},title:is,children:[$?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),$?"Copied!":"Install"]})}function SkillCard({skill:es,onSelect:$}){return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",onClick:()=>$(es),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono leading-tight",children:es.name}),jsxRuntimeExports.jsx(CopyInstallButton,{skill:es})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:es.description}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] font-mono",children:CATEGORY_LABELS[es.category]??es.category}),es.tools.slice(0,3).map(ts=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono",children:displayTool(ts)},ts)),es.tools.length>3&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:["+",es.tools.length-3]})]}),es.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:es.tags.slice(0,4).map(ts=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono",children:["#",ts]},ts))})]})]})}function SkillDetailDialog({skill:es,open:$,onClose:ts}){var Oa;const{copied:is,copy:cs}=useCopyToClipboard(),{data:Qr,isLoading:ja}=useSkill($?es==null?void 0:es.id:void 0);if(!es)return null;const Na=Qr??es,Aa=`rulemetric skills install ${Na.id}`;return jsxRuntimeExports.jsx(Dialog,{open:$,onOpenChange:Ia=>!Ia&&ts(),children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-[95vw] max-h-[90vh] overflow-y-auto",children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{className:"font-mono",children:Na.name})}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Na.description}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:CATEGORY_LABELS[Na.category]??Na.category}),Na.tools.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:displayTool(Ia)},Ia))]}),(((Oa=Na.languages)==null?void 0:Oa.length)??0)>0&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"Languages:"}),Na.languages.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-mono",children:Ia},Ia))]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium font-mono",children:"Install"}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[Na.content&&jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-primary/30 text-primary hover:bg-primary/10",onClick:()=>{const Ia=new Blob([Na.content],{type:"text/markdown"}),La=URL.createObjectURL(Ia),Ba=document.createElement("a");Ba.href=La,Ba.download=`${Na.id}.md`,Ba.click(),URL.revokeObjectURL(La)},children:[jsxRuntimeExports.jsx(Download,{className:"h-3 w-3"}),"Download"]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5",onClick:()=>{cs(Aa)},children:[is?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),is?"Copied!":"Copy CLI"]})]})]}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-[#0B1120] text-muted-foreground rounded p-2 overflow-x-auto",children:Aa})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-xs font-medium font-mono mb-2",children:"Content"}),ja&&!Na.content?jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}):Na.content?jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-[#0B1120] text-muted-foreground rounded p-3 overflow-x-auto whitespace-pre-wrap max-h-[55vh]",children:Na.content}):jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No content available."})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:["Source:"," ",jsxRuntimeExports.jsxs("a",{href:Na.source.url,target:"_blank",rel:"noopener noreferrer",className:"underline inline-flex items-center gap-1",children:[Na.source.repo,jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})]}),Na.source.license&&jsxRuntimeExports.jsx("span",{children:Na.source.license})]})]})]})})}const PAGE_SIZE$1=60;function SkillsListPage(){const{data:es,isLoading:$}=useSkillsRegistry(),[ts,is]=reactExports.useState(""),[cs,Qr]=reactExports.useState(null),[ja,Na]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(null),[Ia,La]=reactExports.useState(PAGE_SIZE$1),Ba=(es==null?void 0:es.skills)??[],Ma=reactExports.useMemo(()=>[...new Set(Ba.map(Ga=>Ga.category))].sort(),[Ba]),qa=reactExports.useMemo(()=>[...new Set(Ba.flatMap(Ga=>Ga.tools))].sort(),[Ba]),Fa=reactExports.useMemo(()=>{let Ga=Ba;if(ts){const Va=ts.toLowerCase();Ga=Ga.filter(Ja=>Ja.name.toLowerCase().includes(Va)||Ja.description.toLowerCase().includes(Va)||Ja.tags.some(Ya=>Ya.toLowerCase().includes(Va))||Ja.id.toLowerCase().includes(Va))}return cs&&(Ga=Ga.filter(Va=>Va.category===cs)),ja&&(Ga=Ga.filter(Va=>Va.tools.includes(ja)||Va.tools.includes("universal"))),Ga.sort((Va,Ja)=>{var tl,rl;const Ya=((tl=Va.popularity)==null?void 0:tl.stars)??0,el=((rl=Ja.popularity)==null?void 0:rl.stars)??0;return Ya!==el?el-Ya:Va.name.localeCompare(Ja.name)}),Ga},[Ba,ts,cs,ja]);reactExports.useEffect(()=>{La(PAGE_SIZE$1)},[ts,cs,ja]);const Ha=Fa.slice(0,Ia),Ka=Fa.length>Ia;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Skills Registry"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Browse and install community-contributed skills for your AI coding tools"})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search skills...",value:ts,onChange:Ga=>is(Ga.target.value),className:"pl-9 font-mono"})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 flex-wrap",children:[cs&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Qr(null),children:[CATEGORY_LABELS[cs]??cs,jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]}),ja&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Na(null),children:[displayTool(ja),jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]})]})]}),!cs&&!ja&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground mr-1 self-center",children:"Category:"}),Ma.map(Ga=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Qr(Ga),children:CATEGORY_LABELS[Ga]??Ga},Ga))]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground mr-1 self-center",children:"Tool:"}),qa.map(Ga=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Na(Ga),children:displayTool(Ga)},Ga))]})]}),$?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Ga,Va)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40"},Va))}):Fa.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Ba.length===0?"No skills in registry":"No matching skills"}),Ba.length===0&&jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric skills update"})," ","to fetch the registry"]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono",children:["Showing ",Ha.length," of ",Fa.length," skill",Fa.length!==1?"s":"",ts||cs||ja?" matching filters":""]}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ha.map(Ga=>jsxRuntimeExports.jsx(SkillCard,{skill:Ga,onSelect:Oa},Ga.id))}),Ka&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-2",children:jsxRuntimeExports.jsxs(Button,{variant:"outline",className:"cursor-pointer font-mono",onClick:()=>La(Ga=>Ga+PAGE_SIZE$1),children:["Load ",Math.min(PAGE_SIZE$1,Fa.length-Ia)," more"]})})]}),jsxRuntimeExports.jsx(SkillDetailDialog,{skill:Aa,open:!!Aa,onClose:()=>Oa(null)})]})}function relativeDate(es){if(!es)return"recently";const $=new Date(es).getTime();if(Number.isNaN($))return"recently";const ts=Math.floor((Date.now()-$)/864e5);return ts<1?"today":ts===1?"yesterday":ts<30?`${ts}d ago`:ts<365?`${Math.floor(ts/30)}mo ago`:`${Math.floor(ts/365)}y ago`}function formatStars(es){return es>=1e3?`${(es/1e3).toFixed(1)}k`:String(es)}function PublicCatalogPage(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(es);reactExports.useEffect(()=>{const La=setTimeout(()=>is(es),250);return()=>clearTimeout(La)},[es]);const{data:cs,isLoading:Qr,isFetchingNextPage:ja,fetchNextPage:Na,hasNextPage:Aa,error:Oa}=usePublicCatalog(ts||void 0),Ia=reactExports.useMemo(()=>(cs==null?void 0:cs.pages.flat())??[],[cs]);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[jsxRuntimeExports.jsx(Globe,{className:"h-6 w-6"}),"Public Catalog"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Community-maintained skills and instructions, browsable here for reference."})]}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search public catalog...",value:es,onChange:La=>$(La.target.value),className:"pl-9"})]}),Oa?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load public catalog: ",Oa.message]}):Qr?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((La,Ba)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40 rounded-lg"},Ba))}):Ia.length===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:ts?`No public skills match "${ts}".`:"No public skills available yet. The registry syncs daily."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ia.map(La=>jsxRuntimeExports.jsx(Link,{to:`/catalog/public/${La.id}`,className:"block",children:jsxRuntimeExports.jsxs(Card,{className:"flex flex-col h-full hover:border-primary/50 hover:bg-muted/30 transition-colors cursor-pointer",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:La.name}),La.description&&jsxRuntimeExports.jsx(CardDescription,{className:"line-clamp-3",children:La.description})]}),jsxRuntimeExports.jsxs(CardContent,{className:"mt-auto space-y-2",children:[La.tags&&La.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:La.tags.slice(0,5).map(Ba=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:Ba},Ba))}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{title:La.sourceUpdatedAt??La.updatedAt,children:["Updated ",relativeDate(La.sourceUpdatedAt??La.updatedAt)]}),typeof La.popularityScore=="number"&&La.popularityScore>0&&jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-1",title:"GitHub stars on the source repo",children:[jsxRuntimeExports.jsx(Star,{className:"h-3 w-3 fill-current"}),formatStars(La.popularityScore)]})]})]})]})},La.id))}),Aa&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-4",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Na(),disabled:ja,className:"cursor-pointer",children:ja?"Loading…":`Load more (showing ${Ia.length})`})}),!Aa&&Ia.length>0&&jsxRuntimeExports.jsxs("div",{className:"text-center text-xs text-muted-foreground pt-2",children:[Ia.length," skill",Ia.length===1?"":"s"," loaded"]})]})]})}function PublicSkillDetailPage(){var cs,Qr;const{id:es}=useParams(),{data:$,isLoading:ts,error:is}=useQuery({queryKey:["instruction",es],queryFn:()=>apiGet(`/api/instructions/${es}`),enabled:!!es});return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/catalog/public",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to Public Catalog"]})}),is?jsxRuntimeExports.jsxs("div",{className:"text-destructive",children:["Failed to load: ",is.message]}):ts||!$?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-1/2"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Globe,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:$.scope}),((cs=$.frontmatter)==null?void 0:cs.category)&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:$.frontmatter.category})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:$.name}),$.description&&jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:$.description})]}),$.tags&&$.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:$.tags.map(ja=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:ja},ja))}),((Qr=$.frontmatter)==null?void 0:Qr.source)&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Source"})}),jsxRuntimeExports.jsxs(CardContent,{className:"text-sm space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"font-mono text-xs text-muted-foreground",children:[$.frontmatter.source.repo,$.frontmatter.source.path&&` / ${$.frontmatter.source.path}`]}),$.frontmatter.source.url&&jsxRuntimeExports.jsxs("a",{href:$.frontmatter.source.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:["View on GitHub ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]}),$.frontmatter.source.license&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["License: ",$.frontmatter.source.license]})]})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Content"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("pre",{className:"whitespace-pre-wrap break-words text-xs font-mono bg-muted/40 rounded p-3 max-h-[60vh] overflow-y-auto",children:$.content})})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Version ",$.version," · updated ",new Date($.updatedAt).toLocaleString()]})]})]})}const scopeColors={public:"bg-teal-500/15 text-teal-400 border-teal-500/30",org:"bg-blue-500/15 text-blue-400 border-blue-500/30",team:"bg-primary/15 text-primary border-primary/30",personal:"bg-muted text-muted-foreground border-border"};function SuggestionRow({suggestion:es,projectPath:$,verdict:ts,experiment:is,evidence:cs}){var Ja;const Qr=useLogSuggestionEvent(),ja=usePromoteFromPublic(),Na=useArchiveInstruction(),Aa=useRestoreInstruction(),Oa=useNominateExperiment(),Ia=es.kind??"add",[La,Ba]=reactExports.useState(!1),Ma=useInstructionDetail(es.instructionId,La),qa=Qr.isPending||ja.isPending||Na.isPending||Oa.isPending;function Fa(Ya){Oa.mutate({instructionId:es.instructionId,projectPath:$,source:Ya},{onSuccess:()=>ue$1(`Under measurement: ${es.name}`,{description:"Injected to half your sessions on this project; the verdict decides."}),onError:el=>ue$1.error(`Could not start the trial: ${el.message}`)})}async function Ha(){try{await Na.mutateAsync(es.instructionId),await Qr.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Retired: ${es.name}`,{description:"Archived — soft delete, restorable.",action:{label:"Undo",onClick:()=>Aa.mutate(es.instructionId,{onSuccess:()=>ue$1.success("Restored"),onError:()=>ue$1.error("Restore failed")})}})}catch(Ya){ue$1.error(`Failed: ${Ya.message}`)}}async function Ka(){try{await Qr.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Noted: ${es.name}`,{description:"Nothing changed — shorten it yourself and the next cycle re-measures it."})}catch(Ya){ue$1.error(`Failed: ${Ya.message}`)}}async function Ga(){try{es.instructionScope==="public"&&await ja.mutateAsync({sourceInstructionId:es.instructionId,targetScope:"personal"}),await Qr.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Accepted: ${es.name}`)}catch(Ya){ue$1.error(`Failed: ${Ya.message}`)}}async function Va(){try{await Qr.mutateAsync({suggestionId:es.id,eventType:"dismissed",projectPath:$}),ue$1(`Dismissed: ${es.name}`)}catch(Ya){ue$1.error(`Failed: ${Ya.message}`)}}return jsxRuntimeExports.jsxs("div",{"data-testid":"suggestion-row","data-suggestion-id":es.id,"data-kind":Ia,className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-2 py-3 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{...activatable(()=>Ba(Ya=>!Ya)),"aria-expanded":La,"data-testid":"suggestion-row-toggle",className:"flex-1 min-w-0 basis-56 space-y-1 cursor-pointer rounded-md -mx-1 px-1 hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":!0,className:cn$1("h-4 w-4 shrink-0 text-muted-foreground transition-transform",La&&"rotate-90")}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:scopeColors[es.instructionScope]??scopeColors.personal,children:es.instructionScope}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words font-medium",children:es.name}),Ia!=="add"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:Ia==="remove"?"text-xs border-red-500/40 text-red-400":"text-xs border-amber-500/40 text-amber-400",children:Ia==="remove"?"retire":"trim"}),es.estimatedTokens!=null&&es.estimatedTokens>0&&Ia!=="add"&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"font-mono text-xs text-muted-foreground",title:"Estimated from content length (chars/4), not a tokenizer count.",children:["~",es.estimatedTokens.toLocaleString()," tok/session"]}),jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:es.score.toFixed(2)}),es.isStale&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:"stale"}),(ts==null?void 0:ts.sufficient)&&jsxRuntimeExports.jsx(VerdictBadge,{verdict:ts}),is&&jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"This instruction is under randomised measurement on this project: injected to some sessions and withheld from the rest, until the arms decide. It is not being pitched while the question is being answered.",children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-teal-400 border-teal-400/40","data-testid":"under-measurement-badge",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"mr-1 h-3 w-3"}),"under measurement",is.source==="trial"?" · trial":is.source==="borrow"?" · borrowed":""]})}),(cs??[]).map(Ya=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Measured on ${Ya.projectPath}: ${Ya.decision==="always"?"helped":"hurt"} (${Number(Ya.delta)>0?"+":""}${(Number(Ya.delta)*100).toFixed(0)}pp, 95% CI ${(Number(Ya.ciLower)*100).toFixed(0)} to ${(Number(Ya.ciUpper)*100).toFixed(0)}pp, n=${Ya.nTreated}/${Ya.nControl}). That evidence was earned THERE — it does not transfer here; it argues for measuring here.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:Ya.decision==="always"?"text-[10px] font-mono text-teal-400 border-teal-400/40":"text-[10px] font-mono text-red-400 border-red-400/40","data-testid":"cross-project-evidence",children:[Number(Ya.delta)>0?"+":"",(Number(Ya.delta)*100).toFixed(0),"pp elsewhere"]})},Ya.projectPath))]}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason}),es.description&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.description}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Generated ",formatDistanceToNow(es.generatedAt)]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 shrink-0",children:[Ia==="add"&&!is&&jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"cursor-pointer",onClick:()=>Fa(((cs==null?void 0:cs.length)??0)>0?"borrow":"trial"),disabled:qa,"data-testid":"trial-button",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-4 w-4 mr-1"}),((cs==null?void 0:cs.length)??0)>0?"Test here":"Trial"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"cursor-pointer",onClick:Ia==="remove"?Ha:Ia==="trim"?Ka:Ga,disabled:qa,children:[jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 mr-1"}),Ia==="remove"?"Retire":Ia==="trim"?"Noted":"Accept"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"cursor-pointer",onClick:Va,disabled:qa,children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 mr-1"}),"Dismiss"]})]}),La&&jsxRuntimeExports.jsx("div",{className:"basis-full","data-testid":"suggestion-detail",children:Ma.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-16","data-testid":"suggestion-detail-loading"}):Ma.isError?jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-400/90","data-testid":"suggestion-detail-error",children:["Could not load this instruction's body: ",Ma.error.message]}):(Ja=Ma.data)!=null&&Ja.content?jsxRuntimeExports.jsx("pre",{"data-testid":"suggestion-detail-content",className:"whitespace-pre-wrap break-words rounded-md border border-border bg-secondary/20 p-3 font-mono text-xs",children:Ma.data.content}):Ma.data?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"suggestion-detail-empty",children:"This instruction stores no body — it is tracked by reference, so there is nothing to preview here."}):null})]})}function AdoptedRow({row:es,projectPath:$}){var Ka;const ts=useArchiveInstruction(),is=useQueryClient(),[cs,Qr]=reactExports.useState(!1),[ja,Na]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState(null),Ia=useInstructionDetail(es.instructionId,cs),La=es.promotedToInstructionId??es.instructionId,Ba=es.archived||ja,Ma=`rulemetric instructions retract ${La}`;async function qa(){Oa(null);try{await ts.mutateAsync(La),Na(!0),is.invalidateQueries({queryKey:["instruction-suggestions","adopted",$]}),ue$1(`Archived: ${es.name}`,{description:"RuleMetric stops injecting it. Run the command shown to remove it from the file."})}catch(Ga){Oa(Ga.message)}}async function Fa(){try{await navigator.clipboard.writeText(Ma),ue$1.success("Copied")}catch{ue$1.error("Could not copy — select the command and copy it by hand.")}}const Ha=new Date(es.acceptedAt);return jsxRuntimeExports.jsxs("div",{"data-testid":"adopted-row","data-suggestion-id":es.id,"data-actor":es.actor,className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-2 py-3 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{...activatable(()=>Qr(Ga=>!Ga)),"aria-expanded":cs,"data-testid":"adopted-row-toggle",className:"flex-1 min-w-0 basis-56 space-y-1 cursor-pointer rounded-md -mx-1 px-1 hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":!0,className:cn$1("h-4 w-4 shrink-0 text-muted-foreground transition-transform",cs&&"rotate-90")}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words font-medium",children:es.name}),es.actor==="auto"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs border-amber-500/40 text-amber-400",title:"Accepted by the auto-accept cron (score ≥ your threshold) with nobody watching.",children:[jsxRuntimeExports.jsx(Bot,{"aria-hidden":!0,className:"mr-1 h-3 w-3"}),"Automatic"]}):es.actor==="human"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs border-teal-500/40 text-teal-400",children:[jsxRuntimeExports.jsx(User,{"aria-hidden":!0,className:"mr-1 h-3 w-3"}),"You accepted"]}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground",title:"No acceptance event was recorded for this row, so who accepted it is not known.",children:"Actor unknown"}),es.kind!=="add"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:es.kind==="remove"?"retired":"trim noted"}),jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:es.score.toFixed(2)}),Ba&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground","data-testid":"adopted-archived",children:"archived"})]}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground","data-testid":"adopted-reason",children:["Adopted because: ",es.reason]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"adopted-when",children:jsxRuntimeExports.jsxs("time",{dateTime:es.acceptedAt,title:Ha.toLocaleString(),children:["Adopted ",formatDistanceToNow(es.acceptedAt)]})})]}),jsxRuntimeExports.jsx("div",{className:"flex gap-2 shrink-0",children:!Ba&&jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"cursor-pointer",onClick:qa,disabled:ts.isPending,"data-testid":"adopted-retract",children:[jsxRuntimeExports.jsx(Undo2,{className:"h-4 w-4 mr-1"}),ts.isPending?"Archiving…":"Retract"]})}),Aa&&jsxRuntimeExports.jsxs("p",{className:"basis-full text-xs text-amber-400/90","data-testid":"retract-error",children:["Could not archive: ",Aa]}),Ba&&jsxRuntimeExports.jsxs("div",{className:"basis-full rounded-md border border-border bg-secondary/20 p-3 space-y-2","data-testid":"retract-panel",children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground","data-testid":"retract-note",children:["Archived — RuleMetric no longer injects this instruction. The block is still in your instruction file on disk; this removes it (dry-run first, add ",jsxRuntimeExports.jsx("code",{children:"--apply"})," to write):"]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("code",{className:"flex-1 min-w-0 break-all font-mono text-xs","data-testid":"retract-command",children:Ma}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"cursor-pointer shrink-0",onClick:Fa,"aria-label":"Copy command",children:jsxRuntimeExports.jsx(Copy,{className:"h-4 w-4"})})]})]}),cs&&jsxRuntimeExports.jsx("div",{className:"basis-full","data-testid":"suggestion-detail",children:Ia.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-16","data-testid":"suggestion-detail-loading"}):Ia.isError?jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-400/90","data-testid":"suggestion-detail-error",children:["Could not load this instruction's body: ",Ia.error.message]}):(Ka=Ia.data)!=null&&Ka.content?jsxRuntimeExports.jsx("pre",{"data-testid":"suggestion-detail-content",className:"whitespace-pre-wrap break-words rounded-md border border-border bg-secondary/20 p-3 font-mono text-xs",children:Ia.data.content}):Ia.data?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"suggestion-detail-empty",children:"This instruction stores no body — it is tracked by reference, so there is nothing to preview here."}):null})]})}function AdoptedDisclosure({projectPath:es}){var ja,Na,Aa;const[$,ts]=reactExports.useState(!1),is=useAdoptedSuggestions(es),cs=(Na=(ja=is.data)==null?void 0:ja.pages[0])==null?void 0:Na.counts,Qr=((Aa=is.data)==null?void 0:Aa.pages.flatMap(Oa=>Oa.adopted))??[];return is.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-64 mt-4","data-testid":"adopted-loading"}):is.isError?jsxRuntimeExports.jsxs("p",{className:"mt-4 text-xs text-amber-400/90","data-testid":"adopted-error",children:["Could not load what was adopted here: ",is.error.message]}):cs?jsxRuntimeExports.jsxs("div",{className:"mt-4 border-t border-border pt-3","data-testid":"adopted-section",children:[jsxRuntimeExports.jsxs("div",{...activatable(()=>ts(Oa=>!Oa)),"aria-expanded":$,"data-testid":"adopted-toggle",className:"flex items-center gap-2 text-sm cursor-pointer rounded-md -mx-1 px-1 py-1 hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":!0,className:cn$1("h-4 w-4 shrink-0 text-muted-foreground transition-transform",$&&"rotate-90")}),jsxRuntimeExports.jsxs("span",{children:["Adopted into this project · ",cs.total,cs.total>0&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" (",cs.byActor.auto," automatic)"]})]}),jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"Suggestions that were written into this project's instruction file. Automatic ones were accepted by the auto-accept cron with nobody watching — read the evidence line on each and retract anything that is not true of your project.",children:jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground underline decoration-dotted",children:"what is this?"})})]}),$&&jsxRuntimeExports.jsxs("div",{"data-testid":"adopted-list",children:[cs.total===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"Nothing has been adopted into this project yet."}):Qr.map(Oa=>jsxRuntimeExports.jsx(AdoptedRow,{row:Oa,projectPath:es},Oa.id)),is.hasNextPage&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"cursor-pointer mt-2",onClick:()=>is.fetchNextPage(),disabled:is.isFetchingNextPage,"data-testid":"adopted-load-more",children:is.isFetchingNextPage?"Loading…":`Load more (${cs.total-Qr.length} remaining)`})]})]}):null}function SuggestionsListPage(){const es=useProjectPaths(),$=es.data??[],ts=useSuggestionsForProjects($),is=es.isLoading,cs=ts.some(Oa=>Oa.isLoading),Qr=ts.map((Oa,Ia)=>{var La,Ba,Ma;return{projectPath:$[Ia],suggestions:((La=Oa.data)==null?void 0:La.suggestions)??[],experiments:(Ba=Oa.data)==null?void 0:Ba.experiments,crossProject:(Ma=Oa.data)==null?void 0:Ma.crossProject,isLoading:Oa.isLoading}}).filter(Oa=>Oa.projectPath),ja=Qr.reduce((Oa,Ia)=>Oa+Ia.suggestions.length,0),Na=Qr.flatMap(Oa=>Oa.suggestions.map(Ia=>Ia.instructionId)),{data:Aa}=useSuggestionImpacts(Na);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-6 w-6"}),"Suggestions"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Precomputed instruction suggestions for your recent projects. Updated daily at 04:30."})]}),is?jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Array.from({length:3}).map((Oa,Ia)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40 rounded-lg"},Ia))}):Qr.length===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No recent projects found. Run a session through Claude Code or Cursor to populate this view."}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[!cs&&ja===0&&jsxRuntimeExports.jsx("div",{className:"text-center py-6 text-muted-foreground","data-testid":"no-open-suggestions",children:"No open suggestions. The cron runs daily at 04:30 and scores your recent projects against your library."}),Qr.map(Oa=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono truncate",children:Oa.projectPath})}),jsxRuntimeExports.jsxs(CardContent,{children:[Oa.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}):Oa.suggestions.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No suggestions for this project."}):jsxRuntimeExports.jsx("div",{children:Oa.suggestions.map(Ia=>{var La,Ba;return jsxRuntimeExports.jsx(SuggestionRow,{suggestion:Ia,projectPath:Oa.projectPath,verdict:Aa==null?void 0:Aa[Ia.instructionId],experiment:(La=Oa.experiments)==null?void 0:La[Ia.instructionId],evidence:(Ba=Oa.crossProject)==null?void 0:Ba[Ia.instructionId]},Ia.id)})}),jsxRuntimeExports.jsx(AdoptedDisclosure,{projectPath:Oa.projectPath})]})]},Oa.projectPath))]})]})}function useInstructionExperiments(es=50){return useQuery({queryKey:["instruction-experiments",es],queryFn:()=>apiGet(`/api/instruction-experiments?limit=${es}`)})}const LIMIT=50,pp=es=>`${es>0?"+":""}${(es*100).toFixed(0)}pp`;function VerdictHeadline({verdict:es}){if(es.resolution==="resolved"&&es.delta!=null&&es.ci!=null){const $=es.delta>0;return jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-resolved",children:[jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("font-mono text-sm",$?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),"data-testid":"verdict-delta",children:[pp(es.delta)," outcome"]}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sessions that received this instruction scored measurably"," ",$?"better":"worse"," than the sessions it was withheld from."]}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground","data-testid":"verdict-ci",children:["95% CI ",pp(es.ci.lower)," to ",pp(es.ci.upper)," · n=",es.measured.treated," ","treated / ",es.measured.control," control"]})]})}return es.contentChanged?jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-edited",children:[jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"The instruction was edited while the experiment ran, so the arms measured different texts and no verdict transfers to the new content. The experiment stopped; the instruction re-enters testing as new content.",children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-sm text-amber-400 border-amber-400/40",children:"edited mid-test"})}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason})]}):es.randomisationSuspect?jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-suspect",children:[jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"The two arms ran at different times. Randomisation interleaves them by construction, so this is evidence the assignment itself broke — an experiment created mid-stream, a re-salted experiment, or a backfilled arm. More sessions will not resolve it.",children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-sm text-amber-400 border-amber-400/40",children:"randomisation suspect"})}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason})]}):es.resolution==="insufficient"?jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-insufficient",children:[jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"Not enough graded sessions on one or both arms yet, so no number is shown rather than a fabricated one. This one resolves itself: keep running sessions on this project.",children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-sm text-muted-foreground",children:"insufficient data"})}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-inconclusive",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-sm text-muted-foreground",children:"no measured effect"}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason})]})}function ArmCounts({verdict:es}){const $=es.assigned.treated+es.assigned.control,ts=es.measured.treated+es.measured.control,is=$-ts,cs=({label:Qr,arm:ja})=>jsxRuntimeExports.jsxs("div",{className:"contents",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:Qr}),jsxRuntimeExports.jsx("span",{className:"text-right font-mono","data-testid":`assigned-${ja}`,children:es.assigned[ja]}),jsxRuntimeExports.jsx("span",{className:"text-right font-mono","data-testid":`measured-${ja}`,children:es.measured[ja]})]});return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto] gap-x-6 gap-y-1 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"arm"}),jsxRuntimeExports.jsx("span",{className:"text-right text-xs uppercase tracking-wide text-muted-foreground",children:jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"Sessions bucketed into this arm before anything was injected.",children:jsxRuntimeExports.jsx("span",{className:"cursor-help border-b border-dotted border-muted-foreground/50",children:"assigned"})})}),jsxRuntimeExports.jsx("span",{className:"text-right text-xs uppercase tracking-wide text-muted-foreground",children:jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"Assigned sessions that came back with a graded outcome. This is the verdict's real n.",children:jsxRuntimeExports.jsx("span",{className:"cursor-help border-b border-dotted border-muted-foreground/50",children:"measured"})})}),jsxRuntimeExports.jsx(cs,{label:"treated (shown)",arm:"treated"}),jsxRuntimeExports.jsx(cs,{label:"control (withheld)",arm:"control"})]}),is>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground","data-testid":"ungraded-note",children:[is," assigned session",is===1?"":"s"," ",is===1?"has":"have"," no graded outcome yet — counted as assigned, not toward the verdict."]})]})}function ExperimentCard({experiment:es}){return jsxRuntimeExports.jsxs(Card,{"data-testid":"experiment-card","data-experiment-id":es.id,children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"min-w-0 break-words text-base","data-testid":"experiment-name",children:es.instructionName}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:es.instructionSource}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("text-xs",es.status==="running"?"text-teal-400 border-teal-400/40":"text-muted-foreground"),children:es.status}),es.source!=="manual"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground","data-testid":"source-badge",children:es.source==="groom"?"nominated by grooming":es.source==="trial"?"trial":"borrowed evidence"}),es.stoppedReason==="trial_neutral"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground","data-testid":"stopped-reason-badge",children:"ended · no detectable effect"}),es.stoppedReason==="content_changed"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-amber-400 border-amber-400/40","data-testid":"stopped-reason-badge",children:"ended · content edited"}),es.graduation&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("font-mono text-xs",es.graduation.decision==="always"?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),"data-testid":"graduation-badge",children:["graduated · ",es.graduation.decision==="always"?"always inject":"never inject"]})]}),jsxRuntimeExports.jsx("p",{className:"min-w-0 break-all font-mono text-xs text-muted-foreground",children:es.projectPath})]}),jsxRuntimeExports.jsx(CardContent,{className:"grid gap-6 md:grid-cols-2",children:es.verdict?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(VerdictHeadline,{verdict:es.verdict}),jsxRuntimeExports.jsx(ArmCounts,{verdict:es.verdict})]}):jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"This experiment is no longer readable — it was removed while the page was open."})})]})}function ExperimentsListPage(){const{data:es,isLoading:$,isError:ts,error:is}=useInstructionExperiments(LIMIT),cs=(es==null?void 0:es.experiments)??[],Qr=(es==null?void 0:es.total)??0;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"flex items-center gap-2 text-2xl font-bold tracking-tight",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-6 w-6"}),"Experiments"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Instructions being withheld from half your sessions, so the difference they make is measured rather than assumed."})]}),$?jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((ja,Na)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-48 rounded-lg"},Na))}):ts?jsxRuntimeExports.jsxs("div",{className:"py-12 text-center text-muted-foreground","data-testid":"experiments-error",children:["Could not load experiments: ",is.message]}):cs.length===0?jsxRuntimeExports.jsx("div",{className:"py-12 text-center text-muted-foreground","data-testid":"experiments-empty",children:"No instructions are under test. An instruction enters the loop when it is nominated for measurement — until then, nothing is being withheld from any session."}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[cs.map(ja=>jsxRuntimeExports.jsx(ExperimentCard,{experiment:ja},ja.id)),Qr>cs.length&&jsxRuntimeExports.jsxs("p",{className:"text-center text-xs text-muted-foreground","data-testid":"experiments-truncated",children:["Showing ",cs.length," of ",Qr,"."]})]})]})}function isNotable(es){return es.outcome==="decided"||es.outcome==="failed"?!0:typeof es.detail=="string"&&es.detail.trim().length>0}function partitionFinished(es){const $=[],ts=new Map;for(const cs of es){if(isNotable(cs)){$.push(cs);continue}const Qr=ts.get(cs.kind)??{kind:cs.kind,count:0,outcomes:{},totalSeconds:0,slowestSeconds:0};Qr.count+=1,Qr.outcomes[cs.outcome]=(Qr.outcomes[cs.outcome]??0)+1;const ja=cs.durationSeconds??0;Qr.totalSeconds+=ja,Qr.slowestSeconds=Math.max(Qr.slowestSeconds,ja),ts.set(cs.kind,Qr)}const is=[...ts.values()].sort((cs,Qr)=>Qr.count-cs.count);return{notable:$,routine:is,routineCount:is.reduce((cs,Qr)=>cs+Qr.count,0)}}function duration(es){return es==null?"—":es<60?`${es}s`:es<3600?`${Math.floor(es/60)}m ${es%60}s`:`${Math.floor(es/3600)}h ${Math.floor(es%3600/60)}m`}function shortDuration(es){return es==null?"—":es<60?`${Math.round(es)}s`:es<3600?`${Math.round(es/60)}m`:`${(es/3600).toFixed(1)}h`}function headlineState(es){const{workerPresent:$,leaseUnhealthy:ts,readyToApply:is,failedRecently:cs,running:Qr,queued:ja,engineBlocked:Na}=es;return ts?{tone:"critical",text:"A job is claimed but its lease has expired — the worker took work and stopped."}:$?Na>0?{tone:"critical",text:(Na===1?"1 job needs":`${Na} jobs need`)+" a local LLM engine (`claude` or `codex`) that the worker cannot find — they will finish empty, not fail."}:is>0?{tone:"action",text:`${is} measured edit${is===1?"":"s"} waiting for you to apply.`}:cs>0?{tone:"warn",text:`${cs} job${cs===1?"":"s"} failed in this window.`}:Qr>0||ja>0?{tone:"calm",text:`${Qr} running, ${ja} queued.`}:{tone:"calm",text:"Idle — nothing queued, nothing waiting on you."}:{tone:"critical",text:"No worker is connected, so nothing will run."}}function loopFunnel(es){const $=es.window??{hours:0,landed:es.applied+es.suggestionsAccepted,decisions:es.decisions,promotionsApplied:es.applied,suggestionsSurfaced:es.suggestionsProposed,suggestionsAccepted:es.suggestionsAccepted,suggestionsDeclined:0},ts=$.suggestionsAccepted+$.suggestionsDeclined,is=es.byDecision.promote;return{windowHours:$.hours,landed:$.landed,landedTotal:es.landedTotal??es.applied+es.suggestionsAccepted,surfaced:$.suggestionsSurfaced,accepted:$.suggestionsAccepted,declined:$.suggestionsDeclined,answered:ts,answeredRate:$.suggestionsSurfaced>0?ts/$.suggestionsSurfaced:null,pending:es.suggestionsPending??0,promotesApplied:es.applied,promotes:is,decisionsWithoutEdit:es.byDecision.revert+es.byDecision.refuse,lastLandedAt:[es.lastAppliedAt,es.lastAcceptedAt].filter(cs=>typeof cs=="string"&&cs.length>0).sort().at(-1)??null,neverActed:(es.landedTotal??es.applied+es.suggestionsAccepted)===0&&es.decisions+es.suggestionsProposed>0}}const FILTERS=[{key:"all",label:"All",testId:"filter-all"},{key:"evolution",label:"Evolution",testId:"filter-evolution"},{key:"decided",label:"Decisions",testId:"filter-decided"},{key:"skipped",label:"Skipped",testId:"filter-skipped"},{key:"failed",label:"Failed",testId:"filter-failed"}],HISTORY_RANGES=[{hours:24,label:"24h",testId:"range-24"},{hours:168,label:"7d",testId:"range-168"},{hours:720,label:"30d",testId:"range-720"}],GROUP="inline-flex flex-wrap items-center gap-0.5 self-start rounded-lg border border-border bg-card p-0.5",SEGMENT="inline-flex min-h-11 cursor-pointer items-center whitespace-nowrap rounded-md px-2.5 text-xs transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",SEGMENT_ACTIVE="bg-teal-400/10 font-medium text-teal-400",SEGMENT_IDLE="text-muted-foreground hover:bg-muted/60 hover:text-foreground";function LoopRangeControl({hours:es,onChange:$}){return jsxRuntimeExports.jsx("div",{className:GROUP,role:"group","aria-label":"History range","data-testid":"loop-controls",children:HISTORY_RANGES.map(ts=>jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>$({hours:ts.hours}),"aria-pressed":ts.hours===es,className:cn$1(SEGMENT,ts.hours===es?SEGMENT_ACTIVE:SEGMENT_IDLE),"data-testid":ts.testId,children:ts.label},ts.hours))})}function FinishedControls({counts:es,filter:$,limit:ts,onChange:is}){return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 font-normal",children:[jsxRuntimeExports.jsx("div",{className:GROUP,role:"group","aria-label":"Finished job filter",children:FILTERS.map(cs=>{const Qr=cs.key===$,ja=es[cs.key];return jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is({filter:cs.key}),"aria-pressed":Qr,className:cn$1(SEGMENT,Qr?SEGMENT_ACTIVE:SEGMENT_IDLE,!Qr&&ja===0&&"opacity-60"),"data-testid":cs.testId,children:[cs.label,jsxRuntimeExports.jsx("span",{className:"pl-1.5 tabular-nums opacity-70",children:ja})]},cs.key)})}),jsxRuntimeExports.jsxs("label",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Rows"}),jsxRuntimeExports.jsx("select",{value:ts,onChange:cs=>is({limit:Number(cs.target.value)}),className:cn$1("min-h-11 cursor-pointer rounded-lg border border-border bg-card px-2.5 text-xs","text-muted-foreground transition-colors duration-150 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),"data-testid":"limit-select",children:PAGE_SIZES.map(cs=>jsxRuntimeExports.jsxs("option",{value:cs,children:[cs," rows"]},cs))})]})]})}function Funnel({f:es}){const $=ts=>es.surfaced>0?ts/es.surfaced*100:0;return jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-1.5 gap-y-0.5 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"font-semibold tabular-nums text-foreground",children:es.surfaced}),jsxRuntimeExports.jsx("span",{children:"surfaced"}),jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("span",{className:"font-semibold tabular-nums text-foreground","data-testid":"funnel-answered",children:es.answered}),jsxRuntimeExports.jsx("span",{children:"answered"}),jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("span",{className:"font-semibold tabular-nums text-teal-400","data-testid":"changes-accepted",children:es.accepted}),jsxRuntimeExports.jsx("span",{children:"accepted"})]}),jsxRuntimeExports.jsxs("div",{className:"flex h-1.5 overflow-hidden rounded-full bg-border","aria-hidden":!0,children:[jsxRuntimeExports.jsx("div",{className:"bg-teal-400 transition-[width] duration-500 ease-out",style:{width:`${$(es.accepted)}%`}}),jsxRuntimeExports.jsx("div",{className:"bg-muted-foreground/50 transition-[width] duration-500 ease-out",style:{width:`${$(es.declined)}%`}})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"funnel-rate",children:es.answeredRate==null?"Nothing surfaced in this window.":`${Math.round(es.answeredRate*100)}% answered · ${es.declined} declined · ${es.pending} still open`})]})}function Chip({value:es,of:$,label:ts,good:is,testId:cs,ratioTestId:Qr,to:ja}){const Na=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:cn$1("font-semibold tabular-nums",is?"text-teal-400":"text-foreground"),"data-testid":cs,children:es}),$!=null&&jsxRuntimeExports.jsxs("span",{className:"tabular-nums text-muted-foreground",children:["/",$]})," ",jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:ts})]});return ja?jsxRuntimeExports.jsx(Link,{to:ja,className:"inline-block min-h-11 whitespace-nowrap leading-[2.75rem] transition-colors duration-150 hover:text-foreground","data-testid":Qr,children:Na}):jsxRuntimeExports.jsx("span",{className:"whitespace-nowrap","data-testid":Qr,children:Na})}function KpiStrip({status:es,insights:$}){const{changes:ts,counts:is}=es,cs=loopFunnel(ts),Qr=HISTORY_RANGES.find(ja=>ja.hours===cs.windowHours);return jsxRuntimeExports.jsx(Card,{className:cn$1(cs.neverActed&&"border-amber-400/40"),"data-testid":"changes-headline",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-0",children:[jsxRuntimeExports.jsxs("div",{className:"grid divide-y divide-border sm:grid-cols-[minmax(0,15.5rem)_minmax(0,1fr)] sm:divide-x sm:divide-y-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 px-4 py-3",children:[jsxRuntimeExports.jsxs("p",{className:"flex items-baseline gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:cn$1("text-4xl font-semibold tabular-nums",cs.landed>0?"text-teal-400":"text-muted-foreground"),"data-testid":"changes-landed",children:cs.landed}),Qr&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["in ",Qr.label]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"changes landed"}),jsxRuntimeExports.jsxs("p",{className:"pt-0.5 font-mono text-[11px] leading-snug text-muted-foreground/80","data-testid":"changes-landed-detail",children:[cs.landedTotal," all time",cs.lastLandedAt&&` · last ${cs.lastLandedAt.slice(0,10)}`]})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-2 px-4 py-3",children:[jsxRuntimeExports.jsx(Funnel,{f:cs}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 border-t border-border pt-1 text-xs",children:[jsxRuntimeExports.jsx(Chip,{value:cs.promotesApplied,of:cs.promotes||void 0,label:"promotes applied",good:cs.promotesApplied>0,testId:"changes-applied",ratioTestId:"changes-applied-ratio"}),jsxRuntimeExports.jsx(Chip,{value:is.experimentsRunning,label:"trials running",good:is.experimentsRunning>0,testId:"changes-trials",to:"/experiments"}),$&&jsxRuntimeExports.jsx(Chip,{value:$.repeated,of:$.distinct||void 0,label:"insights repeated",good:$.repeated>0,testId:"changes-insights"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-[11px] text-muted-foreground/80","data-testid":"changes-applied-detail",children:`${ts.byDecision.promote}P · ${ts.byDecision.revert}R · ${ts.byDecision.refuse}X`})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 border-t border-border px-4 py-1.5 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{"data-testid":"apply-scope-note",children:"“Applied” updates the stored instruction body, not the file on disk."}),jsxRuntimeExports.jsx(InfoTip,{content:'Deciding is not applying. A proposal can be measured, gated and recorded as "promote" and still never touch a file — that separation is deliberate (effectiveness.md §13). Applying updates `eval_targets.content`, which is what future eval runs measure against; the only code that writes an instruction FILE is retraction, and only for removals.'}),cs.neverActed&&jsxRuntimeExports.jsx("span",{className:"text-amber-400/90","data-testid":"never-acted",children:"· Measuring, not acting: nothing has ever been applied or accepted."})]})]})})}function windowLabel(es){return es%24===0&&es>=48?`${es/24}d`:`${es}h`}function RunningRow({job:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2","data-testid":"running-job",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4 shrink-0 text-teal-400"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono text-sm",children:es.kind}),!es.leaseHealthy&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"shrink-0 border-red-400/40 text-red-400",children:"lease expired"})]}),es.label&&jsxRuntimeExports.jsx("p",{className:"truncate text-sm text-muted-foreground",title:es.label,children:es.label})]}),jsxRuntimeExports.jsx("span",{className:"shrink-0 font-mono text-sm text-muted-foreground",children:duration(es.elapsedSeconds)})]})}function QueuedRow({job:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2","data-testid":"queued-job",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono text-sm",children:es.kind})]}),es.label&&jsxRuntimeExports.jsx("p",{className:"truncate text-sm text-muted-foreground",title:es.label,children:es.label})]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 font-mono text-sm text-muted-foreground",children:["waited ",duration(es.waitedSeconds)]})]})}const OUTCOME_ICON={ok:jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-teal-400"}),decided:jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-teal-400"}),skipped:jsxRuntimeExports.jsx(CircleMinus,{className:"h-4 w-4 shrink-0 text-amber-400"}),failed:jsxRuntimeExports.jsx(CircleX,{className:"h-4 w-4 shrink-0 text-red-400"})};function FinishedRow({job:es}){return jsxRuntimeExports.jsxs("div",{className:"py-2","data-testid":`finished-job-${es.outcome}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[OUTCOME_ICON[es.outcome],jsxRuntimeExports.jsx("span",{className:"truncate font-mono text-sm",children:es.kind}),es.outcome==="skipped"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"shrink-0 border-amber-400/40 text-amber-400",children:"skipped"}),es.outcome==="decided"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"shrink-0 border-teal-400/40 text-teal-400",children:es.reason})]}),jsxRuntimeExports.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:duration(es.durationSeconds)})]}),es.label&&jsxRuntimeExports.jsx("p",{className:"truncate pl-6 text-sm text-muted-foreground",title:es.label,children:es.label}),es.detail&&jsxRuntimeExports.jsx("p",{className:"whitespace-pre-wrap break-words pl-6 font-mono text-xs text-amber-400/90","data-testid":"finished-reason",children:es.detail})]})}function RoutineRow({group:es}){const $=es.outcomes.failed??0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5 text-xs","data-testid":"routine-group",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"truncate font-mono text-muted-foreground",children:es.kind}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 tabular-nums text-muted-foreground/70",children:["×",es.count]}),$>0&&jsxRuntimeExports.jsxs("span",{className:"shrink-0 text-amber-400/90","data-testid":"routine-failed",children:[$," failed"]})]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 tabular-nums text-muted-foreground/70",children:["slowest ",shortDuration(es.slowestSeconds)]})]})}function FinishedList({status:es,idle:$,workerPresent:ts,controls:is}){const[cs,Qr]=reactExports.useState(!1),{notable:ja,routine:Na,routineCount:Aa}=partitionFinished(es.recent);return jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"gap-2 pb-0",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"flex flex-wrap items-baseline gap-x-2 text-base",children:["Finished",jsxRuntimeExports.jsxs("span",{className:"text-xs font-normal text-muted-foreground","data-testid":"finished-window",children:["last ",windowLabel(es.windowHours),es.filter!=="all"&&` · ${es.filter}`,es.recentTotal>es.recent.length&&` · ${es.recent.length} of ${es.recentTotal}`]})]}),is]}),jsxRuntimeExports.jsx(CardContent,{className:"pt-0",children:es.recent.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground","data-testid":"nothing-finished",children:es.filter!=="all"&&es.filterCounts.all>0?`No ${es.filter} jobs in the last ${windowLabel(es.windowHours)} — ${es.filterCounts.all} finished overall.`:$&&!ts?"No worker connected, so nothing has run.":`No jobs finished in the last ${windowLabel(es.windowHours)}.`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ja.length>0?jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:ja.map(Oa=>jsxRuntimeExports.jsx(FinishedRow,{job:Oa},Oa.id))}):jsxRuntimeExports.jsx("p",{className:"py-1 text-sm text-muted-foreground","data-testid":"nothing-notable",children:"Nothing decided, failed or explained itself — just throughput."}),Aa>0&&jsxRuntimeExports.jsxs("div",{className:"mt-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Qr(Oa=>!Oa),className:"flex min-h-11 w-full cursor-pointer items-center justify-between gap-2 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-expanded":cs,"data-testid":"toggle-routine",children:[jsxRuntimeExports.jsxs("span",{children:[Aa," routine job",Aa===1?"":"s"," across ",Na.length," ","kind",Na.length===1?"":"s"]}),cs?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 shrink-0"})]}),cs&&jsxRuntimeExports.jsx("div",{className:"reveal divide-y divide-border pt-1",children:Na.map(Oa=>jsxRuntimeExports.jsx(RoutineRow,{group:Oa},Oa.kind))})]})]})})]})}function when(es){return es?new Date(es).toLocaleDateString():"never"}function DeliveryRow({project:es}){const $=es.canonicalPath;return jsxRuntimeExports.jsxs("div",{className:"py-2","data-testid":es.stale?"delivery-stale":"delivery-row",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"truncate text-sm",title:es.name??"",children:es.name??"(unnamed project)"}),jsxRuntimeExports.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground","data-testid":"delivery-path",children:$??"no checkout recorded — nothing can be written"})]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 text-right font-mono text-[11px] text-muted-foreground",children:[es.suggestionsAccepted," adopted"]})]}),jsxRuntimeExports.jsxs("p",{className:"pt-0.5 font-mono text-[11px] text-muted-foreground/80",children:["seen ",when(es.canonicalLastSeenAt)," · analysed ",when(es.lastAnalysedAt)," ·"," ",es.suggestionsPending," pending"]}),es.stale&&jsxRuntimeExports.jsxs("p",{className:"flex items-start gap-1.5 pt-1 text-xs text-amber-400/90","data-testid":"delivery-stale-note",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"mt-0.5 h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{children:"This project is active but its recorded checkout is not — edits written here land in a path nobody is working in."})]})]})}function DeliveryBlock({status:es}){const{projects:$,total:ts,staleCount:is}=es.delivery;return jsxRuntimeExports.jsxs(Card,{className:cn$1("gap-2",is>0&&"border-amber-400/40"),"data-testid":"delivery",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex flex-wrap items-baseline gap-x-2 text-base",children:["Where edits land",ts>$.length&&jsxRuntimeExports.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:[$.length," of ",ts," projects"]}),jsxRuntimeExports.jsx(InfoTip,{content:"Insights analyse a project at its canonical checkout path, and the auto-accept actuator writes the CLAUDE.md under that same path. If the path is stale, every stage still succeeds — it just succeeds somewhere nobody is working. Ranking is live-before-stale, then real checkout before worktree, then most recently seen."})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"pt-0",children:[is>0&&jsxRuntimeExports.jsxs("p",{className:"pb-2 text-xs text-amber-400/90","data-testid":"delivery-stale-summary",children:[is," of ",ts," project",ts===1?"":"s"," would be written to a checkout that has gone quiet."]}),$.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground","data-testid":"delivery-empty",children:"No project has recorded sessions yet, so there is nowhere to write."}):jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:$.map(cs=>jsxRuntimeExports.jsx(DeliveryRow,{project:cs},cs.projectId))})]})]})}function AdoptionBlock({status:es}){const[$,ts]=reactExports.useState("all"),[is,cs]=reactExports.useState("all"),[Qr,ja]=reactExports.useState("all"),Na=es.adoption??{available:!1,counts:{},applications:[]},Aa=reactExports.useMemo(()=>Na.applications.filter(Ia=>($==="all"||Ia.harness===$)&&(is==="all"||Ia.artifact===is)&&(Qr==="all"||Ia.status===Qr)),[Na.applications,$,is,Qr]),Oa=Ia=>[...new Set(Na.applications.map(La=>La[Ia]))].sort();return jsxRuntimeExports.jsxs(Card,{className:"gap-2","data-testid":"adoption-ledger",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center justify-between text-base",children:["Cross-harness adoption",jsxRuntimeExports.jsx(Link,{to:"/insights",className:"inline-flex min-h-11 items-center text-xs font-normal text-teal-400 transition-colors duration-150 hover:underline",children:"View insights"})]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Na.available?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-2",children:[["Harness",$,ts,Oa("harness")],["Artifact",is,cs,Oa("artifact")],["State",Qr,ja,Oa("status")]].map(([Ia,La,Ba,Ma])=>jsxRuntimeExports.jsxs("label",{className:"text-xs text-muted-foreground",children:[Ia," ",jsxRuntimeExports.jsxs("select",{value:La,onChange:qa=>Ba(qa.target.value),className:"rounded border border-border bg-background px-2 py-1 text-foreground",children:[jsxRuntimeExports.jsx("option",{value:"all",children:"all"}),Ma.map(qa=>jsxRuntimeExports.jsx("option",{value:qa,children:qa},qa))]})]},Ia))}),jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground",children:Object.entries(Na.counts).filter(([,Ia])=>Ia>0).map(([Ia,La])=>`${La} ${Ia}`).join(" · ")||"No applications yet"}),jsxRuntimeExports.jsxs("div",{className:"divide-y divide-border",children:[Aa.map(Ia=>jsxRuntimeExports.jsxs("details",{className:"py-2",children:[jsxRuntimeExports.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 truncate",children:Ia.title}),jsxRuntimeExports.jsxs("span",{className:"flex shrink-0 gap-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",children:Ia.harness}),jsxRuntimeExports.jsx(Badge,{variant:"outline",children:Ia.status})]})]}),jsxRuntimeExports.jsxs("div",{className:"pt-2 font-mono text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("p",{children:[Ia.artifact," · ",Ia.applyMode," apply"]}),jsxRuntimeExports.jsxs("p",{className:"break-all",children:[Ia.projectPath,"/",Ia.targetPath]}),Ia.verdictDetail&&jsxRuntimeExports.jsx("p",{className:"pt-1 font-sans",children:Ia.verdictDetail})]})]},Ia.id)),Aa.length===0&&jsxRuntimeExports.jsx("p",{className:"py-2 text-sm text-muted-foreground",children:"No applications match these filters."})]})]}):jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Adoption tracking is gated off until migration 00187 is applied."})})]})}function PromotionPathsBlock({status:es}){const $=es.promotionPaths??{projects:[]},ts=new Map(es.delivery.projects.map(cs=>[cs.projectId,cs.name])),is=$.projects.filter(cs=>cs.trials.running>0||cs.trials.orphaned>0||cs.trials.eligible>0||cs.autoAccept.usedInWindow>0||cs.autoAccept.eligible>0);return jsxRuntimeExports.jsxs(Card,{className:"gap-2","data-testid":"promotion-paths",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Promotion throughput"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground","data-testid":"paths-empty",children:"Nothing is being trialled or adopted anywhere — no eligible suggestions, no running experiments, no budget spent."}):is.map(cs=>jsxRuntimeExports.jsx(ProjectPaths,{paths:cs,name:ts.get(cs.projectId)??null},cs.projectId))})]})}function ProjectPaths({paths:es,name:$}){const{trials:ts,autoAccept:is}=es,cs=Math.max(0,is.maxPerWindow-is.usedInWindow);return jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"paths-project",children:[jsxRuntimeExports.jsx("p",{className:"truncate text-sm font-medium",children:$??es.projectId}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground","data-testid":"paths-trials",children:[ts.running,"/",ts.maxConcurrent," trial slots in use · ",ts.eligible," eligible waiting",ts.blocked==="concurrency"&&" · at capacity",ts.blocked==="no-candidates"&&ts.running===0&&" · nothing to trial"]}),ts.orphaned>0&&jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-amber-400/90","data-testid":"paths-orphaned",children:[ts.orphaned," running trial",ts.orphaned===1?"":"s"," aimed at a stale subpath — no sessions arrive there, so they will never conclude"]}),jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground","data-testid":"paths-auto-accept",children:is.enabled?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["auto-accept ",is.usedInWindow,"/",is.maxPerWindow," used this"," ",is.windowDays,"d window · ",is.eligible," above the bar",cs===0&&is.windowResetsAt&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · budget resets ",new Date(is.windowResetsAt).toLocaleDateString()]})]}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:"auto-accept is off for this project"})})]})}function ProvenanceBlock(){const{data:es}=useProvenanceImpact();return!es||es.groups.length===0?null:jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Does generated advice help?"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx("div",{className:"overflow-x-auto",children:jsxRuntimeExports.jsxs("table",{className:"w-full text-sm","data-testid":"provenance-table",children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsxs("tr",{className:"text-left text-xs uppercase tracking-wide text-muted-foreground",children:[jsxRuntimeExports.jsx("th",{className:"py-1 pr-4 font-normal",children:"Source"}),jsxRuntimeExports.jsx("th",{className:"py-1 pr-4 font-normal",children:"Rules"}),jsxRuntimeExports.jsx("th",{className:"py-1 pr-4 font-normal",children:"Sessions reached"}),jsxRuntimeExports.jsx("th",{className:"py-1 pr-4 font-normal",children:"Accepted"}),jsxRuntimeExports.jsx("th",{className:"py-1 font-normal",children:"Measured effect"})]})}),jsxRuntimeExports.jsx("tbody",{children:es.groups.map($=>jsxRuntimeExports.jsxs("tr",{className:"border-t border-border",children:[jsxRuntimeExports.jsx("td",{className:"py-1.5 pr-4 font-mono text-xs",children:$.provenance}),jsxRuntimeExports.jsx("td",{className:"py-1.5 pr-4",children:$.instructions}),jsxRuntimeExports.jsx("td",{className:"py-1.5 pr-4",children:$.exposedSessions}),jsxRuntimeExports.jsx("td",{className:"py-1.5 pr-4",children:$.accepted}),jsxRuntimeExports.jsx("td",{className:"py-1.5",children:$.evidenceClass==="randomised"&&$.meanDelta!=null?jsxRuntimeExports.jsxs("span",{className:cn$1("font-mono",$.meanDelta>0?"text-teal-400":"text-red-400"),children:[$.meanDelta>0?"+":"",($.meanDelta*100).toFixed(1),"pp",jsxRuntimeExports.jsxs("span",{className:"pl-1 text-xs text-muted-foreground",children:["(",$.randomisedVerdicts," verdict",$.randomisedVerdicts===1?"":"s",")"]})]}):jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"not yet measurable"})})]},$.provenance))})]})}),es.note&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90","data-testid":"provenance-note",children:es.note})]})]})}function InFlightCard({summary:es}){return es.running.length===0&&es.queued.length===0?null:jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center justify-between text-base",children:["In flight",jsxRuntimeExports.jsx(InfoTip,{content:"Jobs are claimed one at a time by your local worker, oldest first, and background crons are claimed last so they never starve user-visible work. A long wait here is usually queueing, not a failure."})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3 pt-0",children:[es.running.length>0&&jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.running.map($=>jsxRuntimeExports.jsx(RunningRow,{job:$},$.id))}),es.queued.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"pb-1 text-xs uppercase tracking-wide text-muted-foreground",children:["Queued (",es.queued.length,")"]}),jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.queued.map($=>jsxRuntimeExports.jsx(QueuedRow,{job:$},$.id))})]})]})]})}function InsightsMemory({insights:es,suggestions:$}){return jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Insights memory"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{"data-testid":"insights-memory",children:[jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:[es.entries," entries · ",es.distinct," distinct · ",es.repeated," repeated ·"," ",es.dismissed," dismissed · max seen ×",es.maxTimesGenerated]}),es.entries>0&&es.repeated===0&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-amber-400/90",children:"Nothing has repeated yet — identity is a verbatim content hash, so a paraphrase counts as a new ask."})]}),jsxRuntimeExports.jsxs("p",{className:"border-t border-border pt-2 text-xs text-muted-foreground",children:["suggestions:"," ",Object.entries($).map(([ts,is])=>`${is} ${ts}`).join(" · ")||"none"]})]})]})}function OperationalDetails({summary:es,query:$,onChange:ts,onDiagnostics:is}){const[cs,Qr]=reactExports.useState(!1),{data:ja,isError:Na,isPlaceholderData:Aa}=useLoopDiagnostics($,{open:cs}),Oa=diagnosticsPanelState({open:cs,hasData:ja!=null,isError:Na});reactExports.useEffect(()=>{is==null||is(ja)},[ja,is]);const Ia=es.running.length===0&&es.queued.length===0;return jsxRuntimeExports.jsxs("section",{"data-testid":"operational-details","aria-labelledby":"operational-details-toggle",children:[jsxRuntimeExports.jsxs("button",{id:"operational-details-toggle",type:"button",onClick:()=>Qr(La=>!La),"aria-expanded":cs,"aria-controls":"operational-details-body",className:"flex min-h-11 w-full cursor-pointer items-center gap-2 rounded-md border border-border bg-card px-3 text-left text-sm transition-colors duration-150 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":"operational-details-toggle",children:[cs?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Operational details"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"in-flight and finished jobs, where edits land, throughput, adoption"})]}),Oa!=="closed"&&jsxRuntimeExports.jsxs("div",{id:"operational-details-body",className:cn$1("reveal space-y-4 pt-4 transition-opacity duration-200",Aa&&"opacity-50"),"data-testid":"operational-details-body",children:[Oa==="loading"&&jsxRuntimeExports.jsxs("div",{className:"space-y-4","data-testid":"diagnostics-loading",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"})]}),Oa==="error"&&jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground","data-testid":"diagnostics-error",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 shrink-0 text-amber-400"}),"Could not load the operational details. The summary above is still live."]})}),Oa==="ready"&&ja&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Na&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90","data-testid":"diagnostics-stale",children:"The last refresh failed — showing the details as of the previous load."}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-4",children:[jsxRuntimeExports.jsx(InFlightCard,{summary:es}),jsxRuntimeExports.jsx(FinishedList,{status:ja,idle:Ia,workerPresent:es.worker.present,controls:jsxRuntimeExports.jsx(FinishedControls,{counts:ja.filterCounts,filter:$.filter,limit:$.limit,onChange:ts})}),jsxRuntimeExports.jsx(DeliveryBlock,{status:ja}),jsxRuntimeExports.jsx(PromotionPathsBlock,{status:ja})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-4",children:[jsxRuntimeExports.jsx(InsightsMemory,{insights:ja.insights,suggestions:es.counts.suggestions}),jsxRuntimeExports.jsx(AdoptionBlock,{status:ja}),jsxRuntimeExports.jsx(ProvenanceBlock,{})]})]})]})]})]})}function useLoopQuery(){const[es,$]=useSearchParams(),ts=(Na,Aa,Oa)=>Aa.includes(Na)?Na:Oa,is=Number(es.get("hours")),cs=Number(es.get("limit")),Qr={hours:HISTORY_RANGES.some(Na=>Na.hours===is)?is:24,limit:PAGE_SIZES.includes(cs)?cs:20,filter:ts(es.get("filter"),FINISHED_FILTERS,"all")};return{query:Qr,update:Na=>{const Aa={...Qr,...Na},Oa=new URLSearchParams;Aa.hours!==24&&Oa.set("hours",String(Aa.hours)),Aa.limit!==20&&Oa.set("limit",String(Aa.limit)),Aa.filter!=="all"&&Oa.set("filter",Aa.filter),$(Oa,{replace:!0})}}}function WorkerChip({status:es}){const{worker:$,verdict:ts}=es,is=$.present&&ts.severity!=="ok";return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2","data-testid":"worker-chip",children:[jsxRuntimeExports.jsx("span",{className:cn$1("inline-block h-2 w-2 rounded-full",$.present?$.active?"bg-teal-400":"bg-amber-400":"bg-muted-foreground")}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:$.present?$.active?"Worker running":"Worker stale":"No worker seen"}),$.clientName&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:[$.clientName," · ",$.clientVersion??"?",$.ageSeconds!=null&&` · ${duration($.ageSeconds)} ago`]}),is&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("min-w-0 whitespace-normal break-words text-left",ts.severity==="fail"?"border-red-400/40 text-red-400":"border-amber-400/40 text-amber-400"),children:ts.headline})]})}function PendingDiff({promotionId:es}){const[$,ts]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{className:"pt-2",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts(is=>!is),className:"inline-flex min-h-11 cursor-pointer items-center text-xs text-teal-400 transition-colors duration-150 hover:underline","data-testid":"toggle-pending-diff",children:$?"Hide the diff":"Show what it would change →"}),jsxRuntimeExports.jsx("div",{className:"pt-2",children:jsxRuntimeExports.jsx(PromotionDetailPanel,{promotionId:es,open:$,allowApply:!0,testId:"pending-diff"})})]})}function ReviewGateCallout({gate:es}){const $=(es==null?void 0:es.targets)??[];if(!(es!=null&&es.blocking)||$.length===0)return null;const ts=$[0];return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-amber-400/50 bg-amber-400/10 p-4","data-testid":"review-gate",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1",children:[jsxRuntimeExports.jsxs("p",{className:"text-base font-semibold text-amber-300","data-testid":"review-gate-headline",children:["The loop is waiting on you — ",es.totalAwaitingReview," run",es.totalAwaitingReview===1?"":"s"," need human review"]}),jsxRuntimeExports.jsx(Link,{to:`/eval-targets/${ts.id}?tab=review`,className:"inline-flex min-h-[36px] items-center rounded-md border border-amber-400/60 bg-amber-400/10 px-3 text-sm font-medium text-amber-200 transition-colors duration-150 hover:bg-amber-400/20","data-testid":"review-gate-action",children:"Review runs →"})]}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-sm text-muted-foreground",children:"Nothing else can do this step: an LLM labeling anchors to calibrate an LLM judge is circular. Until these are labeled the loop keeps measuring and keeps refusing to decide."}),jsxRuntimeExports.jsx("ul",{className:"pt-2 space-y-1",children:$.map(is=>jsxRuntimeExports.jsxs("li",{className:"text-sm","data-testid":"review-gate-target",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:is.name})," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["— ",is.awaitingReview," unreviewed, and"," ",jsxRuntimeExports.jsx("span",{className:"text-amber-300/90",children:"no human labels yet in this judge segment"}),"."]})]},is.id))})]})}function ReadyToApplyCallout({changes:es}){return es.readyToApply<=0?null:jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-teal-400/40 bg-teal-400/5 p-3","data-testid":"ready-to-apply",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-medium text-teal-400",children:[es.readyToApply," measured improvement",es.readyToApply===1?" is":"s are"," ","ready to apply"]})," ","— decided ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"promote"}),", never applied, and still measured against the file as it stands today."]}),es.readyToApplyPromotionId&&jsxRuntimeExports.jsx(PendingDiff,{promotionId:es.readyToApplyPromotionId})]})}function RunNowButton(){const es=useRunLoopNow();return jsxRuntimeExports.jsxs("div",{className:"text-right",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:es.isPending,onClick:()=>es.mutate(),className:cn$1("cursor-pointer rounded border border-teal-400/40 px-3 py-1.5 text-sm text-teal-400 transition-colors duration-150 hover:bg-teal-400/10",es.isPending&&"opacity-60"),"data-testid":"run-loop-now",children:es.isPending?"Queuing…":"Run cycle now"}),es.isSuccess&&jsxRuntimeExports.jsx("p",{className:"pt-1 font-mono text-xs text-muted-foreground","data-testid":"run-now-result",children:Object.entries(es.data).map(([$,ts])=>`${$}: ${String(ts).replace(/^regenerated: /,"")}`).join(" · ")}),es.isError&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-amber-400/90",children:"Could not queue the cycle."})]})}function StatusBanner({status:es}){const $=headlineState(headlineInputs(es));return jsxRuntimeExports.jsx("p",{className:cn$1("text-sm",$.tone==="critical"&&"text-red-400",$.tone==="action"&&"text-teal-400",$.tone==="warn"&&"text-amber-400/90",$.tone==="calm"&&"text-muted-foreground"),"data-testid":"loop-headline",children:$.text})}function LoopPage(){const{query:es,update:$}=useLoopQuery(),{data:ts,isLoading:is,isError:cs,isPlaceholderData:Qr}=useLoopSummary(es),[ja,Na]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(void 0);return is?jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"})]}):cs||!ts?jsxRuntimeExports.jsx("div",{className:"p-6",children:jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"flex items-center gap-2 py-6 text-muted-foreground",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"}),"Could not load loop status."]})})}):jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6","data-testid":"loop-page",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Loop"}),jsxRuntimeExports.jsx(RunNowButton,{})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pt-1",children:[jsxRuntimeExports.jsx(WorkerChip,{status:ts}),jsxRuntimeExports.jsx(StatusBanner,{status:ts})]})]}),jsxRuntimeExports.jsx(ReviewGateCallout,{gate:ts.reviewGate}),jsxRuntimeExports.jsx(LoopRangeControl,{hours:es.hours,onChange:$}),jsxRuntimeExports.jsxs("div",{className:cn$1("space-y-4 transition-opacity duration-200",Qr&&"opacity-50"),children:[jsxRuntimeExports.jsx(ReadyToApplyCallout,{changes:ts.changes}),jsxRuntimeExports.jsx(KpiStrip,{status:ts,insights:Aa==null?void 0:Aa.insights}),jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base",children:["Proposed changes",ts.proposalTotal>ts.proposals.length&&jsxRuntimeExports.jsxs("span",{className:"pl-2 font-normal text-muted-foreground",children:["showing ",ts.proposals.length," of ",ts.proposalTotal]})]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:ts.proposals.length>0?jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:ts.proposals.map(Ia=>{const La=ja===Ia.id;return jsxRuntimeExports.jsxs("div",{"data-testid":"proposal",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Na(La?null:Ia.id),"aria-expanded":La,"aria-controls":`proposal-detail-${Ia.id}`,className:"flex min-h-11 w-full cursor-pointer items-start justify-between gap-3 rounded-sm px-1 py-2 text-left transition-colors duration-150 hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":`proposal-toggle-${Ia.id}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[La?jsxRuntimeExports.jsx(ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"truncate text-sm",title:Ia.targetName??"",children:[Ia.targetName?Ia.targetName.split("/").pop():"(target deleted)",Ia.targetName&&jsxRuntimeExports.jsx("span",{className:"pl-1.5 text-xs text-muted-foreground",children:Ia.targetName.split("/").slice(-3,-1).join("/")})]}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:[Ia.decision," · ",Ia.effectClass," · via ",Ia.proposalSource," ·"," ",new Date(Ia.createdAt).toLocaleDateString()]})]})]}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("shrink-0",Ia.applied?"border-teal-400/40 text-teal-400":"border-muted-foreground/40 text-muted-foreground"),"data-testid":"proposal-applied",children:Ia.applied?"applied":"not applied"})]}),jsxRuntimeExports.jsx(PromotionDetailPanel,{promotionId:Ia.id,open:La})]},Ia.id)})}):jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No changes proposed yet."})})]}),jsxRuntimeExports.jsx(OperationalDetails,{summary:ts,query:es,onChange:$,onDiagnostics:Oa})]})]})}function ToggleSwitch({checked:es,label:$,onToggle:ts,disabled:is,danger:cs,testId:Qr,id:ja}){return jsxRuntimeExports.jsx("button",{type:"button",id:ja,role:"switch","aria-checked":es,"aria-label":$,disabled:is,onClick:ts,"data-testid":Qr,className:cn$1("relative flex h-11 w-11 shrink-0 items-center justify-center rounded-md",is?"cursor-not-allowed opacity-60":"cursor-pointer"),children:jsxRuntimeExports.jsx("span",{className:cn$1("relative block h-6 w-11 rounded-full border transition-colors",es?cs?"border-amber-400/60 bg-amber-400/30":"border-teal-400/60 bg-teal-400/30":"border-muted-foreground/40 bg-muted"),children:jsxRuntimeExports.jsx("span",{className:cn$1("absolute top-0.5 h-4 w-4 rounded-full transition-all",es?cn$1("left-6",cs?"bg-amber-400":"bg-teal-400"):"left-0.5 bg-muted-foreground")})})})}function useMeasurementSettings(){return useQuery({queryKey:["settings","measurement"],queryFn:()=>apiGet("/api/settings/measurement")})}function useHarborSettings(){return useQuery({queryKey:["settings","harbor"],queryFn:()=>apiGet("/api/settings/harbor")})}function useSetMeasurement(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPatch("/api/settings/measurement",$),onSuccess:()=>{es.invalidateQueries({queryKey:["settings"]})}})}function useSetHarbor(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPatch("/api/settings/harbor",{cadence:$}),onSuccess:()=>{es.invalidateQueries({queryKey:["settings","harbor"]})}})}function useAutoAcceptSettings(es){return useQuery({queryKey:["settings","auto-accept",null],queryFn:()=>apiGet("/api/settings/auto-accept")})}function useSetAutoAccept(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPatch("/api/settings/auto-accept",$),onSuccess:()=>{es.invalidateQueries({queryKey:["settings","auto-accept"]}),es.invalidateQueries({queryKey:["loop-status"]})}})}function useEvolutionTargets(){return useQuery({queryKey:["settings","evolution"],queryFn:()=>apiGet("/api/settings/evolution/targets")})}function useSetEvolution(){const es=useQueryClient();return useMutation({mutationFn:({evalTargetId:$,...ts})=>apiPatch(`/api/settings/evolution?evalTargetId=${encodeURIComponent($)}`,ts),onSuccess:()=>{es.invalidateQueries({queryKey:["settings","evolution"]}),es.invalidateQueries({queryKey:["loop-status"]})}})}function useEvolutionAccount(){return useQuery({queryKey:["settings","evolution-account"],queryFn:()=>apiGet("/api/settings/evolution-account")})}function useSetEvolutionAccount(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPatch("/api/settings/evolution-account",$),onSuccess:()=>{es.invalidateQueries({queryKey:["settings","evolution-account"]}),es.invalidateQueries({queryKey:["settings","evolution"]}),es.invalidateQueries({queryKey:["loop-status"]})}})}function Row({label:es,hint:$,htmlFor:ts,children:is}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-start gap-2","data-testid":"evolution-setting-row",children:[jsxRuntimeExports.jsxs("label",{htmlFor:ts,className:"min-w-0 cursor-pointer text-xs",children:[es,$&&jsxRuntimeExports.jsx("span",{className:"block text-[11px] text-muted-foreground",children:$})]}),is]})}function TargetRow({target:es,minPairs:$,maxPairs:ts,onPatch:is,pending:cs}){const{settings:Qr,name:ja}=es,Na=ja.split("/").pop()||ja,Aa=ja.slice(0,Math.max(0,ja.length-Na.length-1)),Oa=Ia=>`evolution-${Ia}-${es.evalTargetId}`;return jsxRuntimeExports.jsxs("div",{className:"space-y-3 rounded-md border border-border p-3","data-testid":"evolution-target",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"truncate font-mono text-sm",title:ja,children:Na}),Aa&&jsxRuntimeExports.jsx("p",{className:"truncate text-xs text-muted-foreground",title:ja,children:Aa}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground","data-testid":"evolution-summary",children:es.summary}),Qr.pausedBy==="account"&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-[11px] text-amber-400/90",children:"Held by the account-wide pause above — the per-target switch cannot clear it."})]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[jsxRuntimeExports.jsx(Row,{label:"Enrolled",hint:"measure this instruction",htmlFor:Oa("enabled"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("enabled"),checked:Qr.enabled,label:`Enrol ${Na} in evolution`,testId:"evolution-enabled",disabled:cs,onToggle:()=>is({enabled:!Qr.enabled})})}),jsxRuntimeExports.jsx(Row,{label:"May rewrite",hint:"act on a verdict, not just record it",htmlFor:Oa("apply"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("apply"),checked:Qr.apply,danger:!0,label:`Allow evolution to rewrite ${Na}`,testId:"evolution-apply",disabled:cs,onToggle:()=>is({apply:!Qr.apply})})}),jsxRuntimeExports.jsx(Row,{label:"Paused",hint:"stop spending, keep the opt-in",htmlFor:Oa("paused"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("paused"),checked:Qr.pausedBy==="target",label:`Pause evolution for ${Na}`,testId:"evolution-paused",disabled:cs||Qr.pausedBy==="account",onToggle:()=>is({paused:Qr.pausedBy!=="target"})})}),jsxRuntimeExports.jsx(Row,{label:"Skip auto-enrolment",hint:"never picked up by the rule",htmlFor:Oa("optout"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("optout"),checked:Qr.optOut,label:`Exclude ${Na} from automatic enrolment`,testId:"evolution-optout",disabled:cs,onToggle:()=>is({optOut:!Qr.optOut})})}),jsxRuntimeExports.jsx(Row,{label:"Pool across nights",hint:"one candidate, evidence accumulated",htmlFor:Oa("accumulate"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("accumulate"),checked:Qr.accumulate,label:`Accumulate evidence across nights for ${Na}`,testId:"evolution-accumulate",disabled:cs,onToggle:()=>is({accumulate:!Qr.accumulate})})})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-t border-border pt-3",children:[jsxRuntimeExports.jsx("label",{className:"text-xs",htmlFor:`pairs-${es.evalTargetId}`,children:"Evidence required"}),jsxRuntimeExports.jsx("input",{id:`pairs-${es.evalTargetId}`,type:"number",min:$,max:ts,defaultValue:Qr.pairs,disabled:cs,"data-testid":"evolution-pairs",onBlur:Ia=>{const La=Number(Ia.currentTarget.value);Number.isFinite(La)&&La!==Qr.pairs&&is({pairs:La})},className:"w-20 rounded border border-border bg-transparent px-2 py-1 text-xs"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["paired tasks before it may act (",$,"–",ts,"). Higher is stricter: more evidence and a tighter interval, at a bigger nightly bill."]})]})]})}function EvolutionCard(){const{data:es,isLoading:$}=useEvolutionTargets(),{data:ts}=useEvolutionAccount(),is=useSetEvolution(),cs=useSetEvolutionAccount(),Qr=(ts==null?void 0:ts.paused)??(es==null?void 0:es.accountPaused)??!1;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Instruction evolution"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:$||!es?jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-6 rounded-md border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:"Stop all instruction evolution"}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:"Account-wide. No instruction is measured or rewritten while this is on, whatever its own switches say. Turning it off restores exactly what was set before."})]}),jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr,danger:!0,label:"Pause instruction evolution for the whole account",testId:"evolution-account-pause",disabled:cs.isPending,onToggle:()=>cs.mutate({paused:!Qr})})]}),jsxRuntimeExports.jsx("p",{className:"text-sm","data-testid":"evolution-writable",children:Qr?jsxRuntimeExports.jsx("span",{className:"font-medium text-amber-400",children:"Evolution is paused for this account."}):es.writable===0?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:"No instruction may be rewritten automatically. The loop can still measure and record decisions."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("span",{className:"font-medium text-amber-400",children:[es.writable," instruction",es.writable===1?"":"s"]})," ","may be rewritten by the nightly loop without asking."]})}),es.targets.length===0?jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["None of your ",es.totalInstructionTargets," instructions are enrolled. Evolution measures a proposed edit against the current version and only acts on a controlled verdict."]}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.targets.map(ja=>jsxRuntimeExports.jsx(TargetRow,{target:ja,minPairs:es.limits.minPairs,maxPairs:es.limits.maxPairs,pending:is.isPending,onPatch:Na=>is.mutate({evalTargetId:ja.evalTargetId,...Na})},ja.evalTargetId))}),es.unconfigured>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:[es.unconfigured," other instruction",es.unconfigured===1?" is":"s are"," not configured for evolution and are left alone."]}),(is.isError||cs.isError)&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-2 text-xs text-amber-400/90",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3"}),"Could not save that. Try again."]})]})})]})}const selectClass="h-10 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline focus-visible:outline-2";function MeasurementForm({preference:es,onSave:$,pending:ts}){const is=reactExports.useId(),[cs,Qr]=reactExports.useState(es.engine??"legacy"),[ja,Na]=reactExports.useState(es.model??""),Aa=MeasurementPreferenceSchema.safeParse({engine:cs==="legacy"?null:cs,model:ja.trim()||null}),Oa=cs!==(es.engine??"legacy")||ja.trim()!==(es.model??"");return jsxRuntimeExports.jsxs("form",{className:"space-y-3",onSubmit:Ia=>{Ia.preventDefault(),Aa.success&&$(Aa.data)},children:[jsxRuntimeExports.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{htmlFor:`${is}-engine`,className:"text-sm",children:"Measurement engine"}),jsxRuntimeExports.jsxs("select",{id:`${is}-engine`,className:selectClass,value:cs,disabled:ts,onChange:Ia=>{Qr(Ia.target.value),Na("")},children:[jsxRuntimeExports.jsx("option",{value:"legacy",children:"Unset (existing worker defaults)"}),jsxRuntimeExports.jsx("option",{value:"claude",children:"Claude"}),jsxRuntimeExports.jsx("option",{value:"codex",children:"Codex"}),jsxRuntimeExports.jsx("option",{value:"pi",children:"Pi"})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{htmlFor:`${is}-model`,className:"text-sm",children:"Model pin"}),jsxRuntimeExports.jsx(Input,{id:`${is}-model`,value:ja,disabled:cs==="legacy"||ts,onChange:Ia=>Na(Ia.target.value),"aria-describedby":`${is}-help`,placeholder:cs==="codex"?"Your supported Codex model":"Optional for Claude"})]})]}),jsxRuntimeExports.jsx("p",{id:`${is}-help`,className:"text-xs text-muted-foreground",children:cs==="pi"?"Pi requires a provider/model pin, for example openai-codex/gpt-5.4-mini. Uses your installed Pi and its account. Harbor is not supported with Pi.":cs==="codex"?"Codex requires a model pin supported by your installed CLI and account.":"Unset preserves existing behavior. Claude without a pin uses its eval default and Haiku for Harbor."}),cs==="codex"&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Codex reports tokens, not measured dollars. Harbor reward tasks run as calibration; the dollar-cost-only locality task is unsupported."}),jsxRuntimeExports.jsx("p",{className:"max-w-prose text-xs text-muted-foreground",children:"Saving affects future opted-in jobs only, not queued or running work. It does not enable a schedule or grant permission to rewrite files."}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:!Aa.success||!Oa||ts,children:ts?"Saving…":"Save measurement engine"})]})}function HarborControls({data:es,pending:$,onSave:ts}){const is=reactExports.useId(),[cs,Qr]=reactExports.useState(es.cadence);return jsxRuntimeExports.jsxs("form",{className:"space-y-3 border-t pt-4",onSubmit:ja=>{ja.preventDefault(),ts(cs)},children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{htmlFor:is,className:"text-sm",children:"Harbor schedule"}),jsxRuntimeExports.jsx("select",{id:is,className:selectClass,value:cs,disabled:$,onChange:ja=>Qr(ja.target.value),children:es.options.map(ja=>jsxRuntimeExports.jsx("option",{value:ja.cadence,children:ja.label},ja.cadence))})]}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:es.summary}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:es.readiness.reported?es.readiness.ready?"A worker reports the required Harbor dependencies.":`Worker not ready: ${es.readiness.missing.join(", ")}.`:"No recent worker readiness report. Start or upgrade your local worker."}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Background runs need your local worker awake. Harbor also needs Docker running; this does not provide cloud execution."}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:$||cs===es.cadence||cs!=="off"&&!es.readiness.ready,children:$?"Saving…":"Save Harbor schedule"}),es.sweeps.length>0&&jsxRuntimeExports.jsx("ul",{className:"space-y-2 text-xs",children:es.sweeps.map(ja=>jsxRuntimeExports.jsxs("li",{className:"break-words",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:ja.task}),": ",ja.last?`${ja.last.decision??ja.last.status} — ${ja.last.reason??"No result yet"}`:"Not run yet"]},ja.task))})]})}function MeasurementCard(){var Qr,ja;const es=useMeasurementSettings(),$=useHarborSettings(),ts=useSetMeasurement(),is=useSetHarbor(),cs=es.error??$.error??ts.error??is.error;return jsxRuntimeExports.jsxs(Card,{"data-testid":"measurement-card",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Measurement and background runs"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[cs&&jsxRuntimeExports.jsx("p",{role:"alert",className:"break-words text-sm text-destructive",children:cs.message}),es.data?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(MeasurementForm,{preference:es.data.preference,onSave:Na=>ts.mutate(Na),pending:ts.isPending},JSON.stringify(es.data.preference)),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:(Qr=es.data.workers)!=null&&Qr.length?es.data.workers.map(Na=>`${Na.engines.join(", ")||"No engines reported"}; protocol ${Na.protocol??"unknown"}; seen ${Na.lastSeen}`).join(". "):"No recent measurement worker report."}),(es.data.graderBlockers??[]).map(Na=>jsxRuntimeExports.jsxs("p",{className:"break-words text-xs text-amber-500",children:[Na.name,": configured grader unavailable (",Na.engine,", ",Na.model,"). Install that engine on the selected worker, or deliberately reconfigure and recalibrate this target."]},Na.targetId))]}):!cs&&jsxRuntimeExports.jsx("p",{role:"status",children:"Loading measurement settings…"}),$.data&&jsxRuntimeExports.jsx(HarborControls,{data:$.data,pending:is.isPending,onSave:Na=>is.mutate(Na)},`${$.data.cadence}:${JSON.stringify((ja=es.data)==null?void 0:ja.preference)}`)]})]})}function SettingsPage(){const{data:es,isLoading:$}=useAutoAcceptSettings(),ts=useSetAutoAccept();return jsxRuntimeExports.jsxs("div",{className:"space-y-6 p-6","data-testid":"settings-page",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Settings"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"What RuleMetric is allowed to do on its own."})]}),jsxRuntimeExports.jsx(MeasurementCard,{}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Automatic adoption"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:$||!es?jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-6",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Let the nightly loop add high-confidence suggestions to your"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"CLAUDE.md"})," without asking."]}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:"On by default. Every rule it adds is a tagged block you can remove with one command, and it never removes or edits anything you wrote."})]}),jsxRuntimeExports.jsx(ToggleSwitch,{checked:es.effective,label:"Automatic adoption",disabled:ts.isPending,onToggle:()=>ts.mutate({enabled:!es.effective}),testId:"auto-accept-toggle"})]}),jsxRuntimeExports.jsxs("p",{className:"text-sm","data-testid":"auto-accept-state",children:["Currently"," ",jsxRuntimeExports.jsx("span",{className:es.effective?"font-medium text-teal-400":"font-medium",children:es.effective?"ON":"OFF"}),es.source==="project"&&" for this project"]}),jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"pb-2 text-xs uppercase tracking-wide text-muted-foreground",children:"What it may do"}),jsxRuntimeExports.jsxs("ul",{className:"space-y-1 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("li",{children:["• Only ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:es.limits.kind})," proposals — removals and trims always wait for you"]}),jsxRuntimeExports.jsxs("li",{children:["• Only above score ",es.limits.minScore,", which is already injected into every session"]}),jsxRuntimeExports.jsx("li",{children:"• Never text containing unfilled placeholders"}),jsxRuntimeExports.jsxs("li",{children:["• At most ",es.limits.maxPerRun," per night and ",es.limits.maxPerWindow," per"," ",es.limits.windowDays," days, per project"]})]})]}),ts.isError&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-2 text-xs text-amber-400/90",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3"}),"Could not save that. Try again."]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border pt-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("p",{children:"Also available from the CLI:"}),jsxRuntimeExports.jsxs("pre",{className:"overflow-x-auto pt-1 font-mono",children:["rulemetric suggestions auto --off",`
|
|
146
|
+
`,"rulemetric suggestions auto --off --project <project-id>",`
|
|
147
|
+
`,"rulemetric suggestions undo <instruction-id>"]})]})]})})]}),jsxRuntimeExports.jsx(EvolutionCard,{})]})}function tierFor(es){return es>=95?"red":es>=80?"orange":es>=60?"yellow":"green"}const TIER_COLOR={green:"stroke-teal-500",yellow:"stroke-yellow-500",orange:"stroke-orange-500",red:"stroke-red-500"},TIER_TEXT={green:"text-teal-600",yellow:"text-yellow-600",orange:"text-orange-600",red:"text-red-600"};function formatCountdown(es,$){const ts=es.getTime()-$.getTime();if(ts<=0)return"resetting now";const is=Math.floor(ts/6e4),cs=Math.floor(is/1440),Qr=Math.floor((is-cs*60*24)/60),ja=is-cs*60*24-Qr*60;return cs>0?`resets in ${cs}d ${Qr}h`:Qr>0?`resets in ${Qr}h ${ja}m`:`resets in ${ja}m`}function formatObservedAt(es,$){const ts=$.getTime()-es.getTime();if(ts<6e4)return{label:"live",fresh:!0};const is=Math.floor(ts/6e4);return is<60?{label:`synced ${is}m ago`,fresh:!1}:{label:`synced ${Math.floor(is/60)}h ago`,fresh:!1}}function Ring({pct:es,tier:$}){const is=2*Math.PI*30,Qr=Math.max(0,Math.min(100,es))/100*is;return jsxRuntimeExports.jsxs("svg",{width:80,height:80,viewBox:"0 0 80 80",className:"-rotate-90",children:[jsxRuntimeExports.jsx("circle",{cx:40,cy:40,r:30,strokeWidth:8,fill:"none",className:"stroke-muted"}),jsxRuntimeExports.jsx("circle",{cx:40,cy:40,r:30,strokeWidth:8,fill:"none",strokeLinecap:"round",strokeDasharray:`${Qr} ${is}`,className:cn$1("transition-all duration-500",TIER_COLOR[$])})]})}function LimitRing(es){const{label:$,usedPercentage:ts,resetsAt:is,observedAt:cs,inferredCap:Qr,unit:ja,confidenceBandPct:Na,capQualifier:Aa="inferred cap",providerReported:Oa=!1}=es,[Ia,La]=reactExports.useState(()=>new Date);reactExports.useEffect(()=>{const Ja=setInterval(()=>La(new Date),6e4);return()=>clearInterval(Ja)},[]);const Ba=assessLimitWindow({usedPercentage:ts,resetsAt:is,now:Ia}),Ma=Ba.kind==="current",qa=Ma?Ba.usedPercentage:0,Fa=tierFor(qa),Ha=Ma?qa>=100?{icon:Ban,text:"hit",color:"text-red-600"}:qa>=95?{icon:TriangleAlert,text:"imminent",color:"text-red-600"}:qa>=80?{icon:TriangleAlert,text:"approaching",color:"text-yellow-600"}:null:null,Ka=Ba.kind==="expired"?`window ended ${formatElapsed(Ba.endedMsAgo)} ago`:is?formatCountdown(new Date(is),Ia):"—",Ga=cs?formatObservedAt(new Date(cs),Ia):null,Va=Ma&&Qr!=null?Math.round(qa/100*Qr):null;return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4 rounded-lg border border-border bg-card p-4",children:[jsxRuntimeExports.jsx(Ring,{pct:qa,tier:Fa}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-semibold",children:$}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:cn$1("font-mono",Ma?TIER_TEXT[Fa]:"text-muted-foreground"),children:Ma?`${Math.round(qa)}%`:"—"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:Ka}),Ga?jsxRuntimeExports.jsx("span",{className:cn$1("text-xs",Ga.fresh?"text-teal-600":"text-muted-foreground"),children:Ga.fresh?"✓ live":Ga.label}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"? unknown"})]})]}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:Oa?jsxRuntimeExports.jsx("span",{className:"cursor-help font-mono",children:"Provider-reported quota window percentage"}):jsxRuntimeExports.jsxs("span",{className:"cursor-help font-mono",children:["≈"," ",Va??"?"," ","/ ",Qr??"?"," ",ja," (",Aa," · ±",Na,"%)"]})}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-xs",children:jsxRuntimeExports.jsx("p",{className:"text-xs",children:Oa?"Reported directly by the provider's rate-limit feed — the percentage is authoritative, not an estimate.":"Estimate based on Anthropic-published ranges. Actuals vary per user."})})]})}),Ha?jsxRuntimeExports.jsxs("span",{className:cn$1("flex items-center gap-1 font-mono",Ha.color),children:[jsxRuntimeExports.jsx(Ha.icon,{className:"h-3 w-3"}),Ha.text]}):null]}),Ba.kind==="never-observed"?jsxRuntimeExports.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:Oa?"no observation yet — run this tool through the proxy":"~ estimated · no observation yet"}):null,Ba.kind==="expired"?jsxRuntimeExports.jsxs("div",{className:"mt-1 text-xs text-muted-foreground",children:["last seen ",Math.round(Ba.lastPercentage),"% before this window closed · nothing observed since",Oa?" — run this tool through the proxy":""]}):null]})]})}const SOURCE_LABEL="Live usage · all tracked tools",COST_POLL_MS=3e4,RATE_LIMIT_RINGS=[{key:"five_hour",label:"5-hour window",unit:"msgs"},{key:"seven_day",label:"7-day (Sonnet tier)",unit:"hrs"},{key:"seven_day_opus",label:"7-day (Opus tier)",unit:"hrs"}],CODEX_RINGS=[{key:"five_hour",label:"Codex 5-hour window"},{key:"seven_day",label:"Codex 7-day window"}],PLAN_LABELS={max_20x:"Max-20x",max_5x:"Max-5x",pro:"Pro"};function planLabel(es){return PLAN_LABELS[es]??es}function startOfMonthIso(){const es=new Date;return new Date(es.getFullYear(),es.getMonth(),1).toISOString()}function UsagePage(){var el,tl,rl,cl,dl,fl,nl,ol,pl,Tl,ul,hl,jl,Nl,zl,Zl,Dl,Il,Fl,ql;const es=useCurrentLimits(),$=useCurrentLimits("codex"),ts=useInferredCaps(),is=startOfMonthIso(),cs=useComputedInsights(void 0,void 0,{since:is,refetchIntervalMs:COST_POLL_MS}),Qr=((el=es.data)==null?void 0:el.five_hour)??null,ja=((tl=es.data)==null?void 0:tl.seven_day)??null,Na=((rl=es.data)==null?void 0:rl.seven_day_opus)??null,Aa=((cl=$.data)==null?void 0:cl.five_hour)??null,Oa=((dl=$.data)==null?void 0:dl.seven_day)??null,Ia={five_hour:Aa,seven_day:Oa},La=!!(Aa||Oa),Ba=((fl=ts.data)==null?void 0:fl.five_hour_percent.inferred_cap)??null,Ma=((nl=ts.data)==null?void 0:nl.five_hour_percent.confidence_band_pct)??20,qa=((ol=ts.data)==null?void 0:ol.seven_day_percent.inferred_cap)??null,Fa=((pl=ts.data)==null?void 0:pl.seven_day_percent.confidence_band_pct)??20,Ha=((Tl=ts.data)==null?void 0:Tl.seven_day_opus_percent.inferred_cap)??null,Ka=((ul=ts.data)==null?void 0:ul.seven_day_opus_percent.confidence_band_pct)??20,Ga=ts.data?`${planLabel(ts.data.plan)}${ts.data.assumed?" est.":""}`:"inferred cap",Va=es.isLoading||ts.isLoading,Ja={five_hour:{obs:Qr,cap:Ba,band:Ma},seven_day:{obs:ja,cap:qa,band:Fa},seven_day_opus:{obs:Na,cap:Ha,band:Ka}},Ya=new Date(is).toLocaleString(void 0,{month:"long",year:"numeric"});return jsxRuntimeExports.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(Gauge,{className:"h-6 w-6 text-primary"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"font-mono text-xl font-semibold",children:"Usage"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:SOURCE_LABEL})]})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-4",children:[jsxRuntimeExports.jsx("h2",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:"Rate limits"}),Va?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"})]}):es.isError?jsxRuntimeExports.jsxs("div",{role:"status",className:"flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 flex-shrink-0"}),jsxRuntimeExports.jsxs("span",{children:["Couldn't load rate limits",es.error instanceof Error?`: ${es.error.message}`:"",". Retrying…"]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold",children:"Claude Code"}),RATE_LIMIT_RINGS.map(nu=>{var cu,Al,Ml;const Gl=Ja[nu.key];return jsxRuntimeExports.jsx(LimitRing,{label:nu.label,usedPercentage:((cu=Gl.obs)==null?void 0:cu.used_percentage)??null,resetsAt:((Al=Gl.obs)==null?void 0:Al.resets_at)??null,observedAt:((Ml=Gl.obs)==null?void 0:Ml.observed_at)??null,inferredCap:Gl.cap,unit:nu.unit,confidenceBandPct:Gl.band,capQualifier:Ga},nu.key)})]}),La?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold",children:"Codex"}),CODEX_RINGS.map(nu=>{const Gl=Ia[nu.key];return jsxRuntimeExports.jsx(LimitRing,{label:nu.label,usedPercentage:(Gl==null?void 0:Gl.used_percentage)??null,resetsAt:(Gl==null?void 0:Gl.resets_at)??null,observedAt:(Gl==null?void 0:Gl.observed_at)??null,inferredCap:null,unit:"",confidenceBandPct:0,providerReported:!0},nu.key)})]}):null]}),jsxRuntimeExports.jsxs("section",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("h2",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:["Estimated cost · ",Ya]}),cs.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CostBreakdownCard,{totalUsd:((hl=cs.data)==null?void 0:hl.estimated_cost_usd)??0,breakdown:(jl=cs.data)==null?void 0:jl.estimated_cost_breakdown,inputTokens:((Nl=cs.data)==null?void 0:Nl.total_input_tokens)??0,outputTokens:((zl=cs.data)==null?void 0:zl.total_output_tokens)??0,cacheReadTokens:((Zl=cs.data)==null?void 0:Zl.total_cache_read_tokens)??0,cacheWriteTokens:((Dl=cs.data)==null?void 0:Dl.total_cache_write_tokens)??0,byModel:(Il=cs.data)==null?void 0:Il.estimated_cost_by_model,byTool:(Fl=cs.data)==null?void 0:Fl.estimated_cost_by_tool}),(ql=cs.data)!=null&&ql.truncated?jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 flex-shrink-0"}),"Showing your 500 most recent sessions this month — older sessions in the window aren't counted, so this is a lower bound."]}):null]})]})]})}function AdminOverviewPage(){var Aa,Oa,Ia,La,Ba,Ma;const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQuery({queryKey:["org-detail",$],queryFn:()=>getOrg($),enabled:!!$}),is=useQuery({queryKey:["org-activity",$,"7d"],queryFn:()=>getOrgActivity($,"7d"),enabled:!!$}),cs=(Aa=ts.data)==null?void 0:Aa.members.length,Qr=(Oa=ts.data)==null?void 0:Oa.teams.length,ja=(Ia=is.data)==null?void 0:Ia.sessionCount,Na=((Ma=(Ba=(La=is.data)==null?void 0:La.topTools)==null?void 0:Ba[0])==null?void 0:Ma.tool)??null;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx(Building2,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"Organization admin"})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:(es==null?void 0:es.name)??"—"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx("code",{className:"text-xs",children:es==null?void 0:es.slug}),es&&jsxRuntimeExports.jsxs("span",{className:"ml-2 capitalize",children:["· you are ",es.role]})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/members",children:"Members"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/members/invitations",children:"Pending invites"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/settings",children:"Settings"})})]})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),label:"Members",value:cs,loading:ts.isLoading,error:!!ts.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Layers,{className:"h-4 w-4"}),label:"Teams",value:Qr,loading:ts.isLoading,error:!!ts.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:"Sessions (7d)",value:ja,loading:is.isLoading,error:!!is.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"}),label:"Top tool",value:Na??"—",loading:is.isLoading,error:!!is.error})]})]})}function StatCard$1({icon:es,label:$,value:ts,loading:is,error:cs}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[es,$]})}),jsxRuntimeExports.jsx(CardContent,{children:is?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}):cs?jsxRuntimeExports.jsx("span",{className:"text-sm text-destructive",children:"failed to load"}):jsxRuntimeExports.jsx("span",{className:"text-3xl font-mono font-semibold tabular-nums",children:ts??"—"})})]})}const NO_TEAM="__none";function InviteDialog({open:es,onOpenChange:$,orgSlug:ts}){const is=useQueryClient(),[cs,Qr]=reactExports.useState(""),[ja,Na]=reactExports.useState("member"),[Aa,Oa]=reactExports.useState(NO_TEAM),[Ia,La]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Qr(""),Na("member"),Oa(NO_TEAM),La(null))},[es]);const Ba=useQuery({queryKey:["org-teams",ts],queryFn:()=>listTeams(ts),enabled:es&&!!ts}),Ma=useMutation({mutationFn:Fa=>createInvitation(ts,Fa),onSuccess:Fa=>{Fa.emailSent?ue$1.success(`Invitation sent to ${Fa.email}`):ue$1.warning("Invite created, but the email could not be sent",{description:Fa.emailError?`${Fa.emailError} — share the invite link directly.`:"Share the invite link directly.",duration:3e4,action:{label:"Copy invite link",onClick:()=>{var Ha;(Ha=navigator.clipboard)==null||Ha.writeText(Fa.acceptUrl).then(()=>ue$1.success("Invite link copied")).catch(()=>ue$1.error("Couldn't copy — the link is in the invite row"))}}}),is.invalidateQueries({queryKey:["org-invitations",ts]}),$(!1)},onError:Fa=>{if(Fa instanceof ApiError){if(Fa.code==="INVITE_ALREADY_PENDING"){La("There's already a pending invitation for this email. Resend it from the Pending Invites page instead.");return}if(Fa.code==="INVALID_TEAM"){La("That team no longer exists in this organization. Refresh and try again.");return}ue$1.error(Fa.message);return}ue$1.error(Fa instanceof Error?Fa.message:"Failed to send invite")}});function qa(Fa){Fa.preventDefault(),La(null);const Ha=cs.trim();if(!Ha){La("Email is required.");return}if(!/^\S+@\S+\.\S+$/.test(Ha)){La("Enter a valid email address.");return}Ma.mutate({email:Ha,role:ja,...Aa!==NO_TEAM?{teamId:Aa}:{}})}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Invite a member"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Send an invitation email. The recipient gets a link that's valid for 7 days."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:qa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"invite-email",type:"email",autoComplete:"off",value:cs,onChange:Fa=>Qr(Fa.target.value),placeholder:"teammate@example.com",required:!0,disabled:Ma.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-role",children:"Role"}),jsxRuntimeExports.jsxs(Select,{value:ja,onValueChange:Fa=>Na(Fa),disabled:Ma.isPending,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"invite-role",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"Member"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"Admin"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Admins can invite, remove, and re-role other members. Members have read-only access to admin pages."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-team",children:"Team (optional)"}),jsxRuntimeExports.jsxs(Select,{value:Aa,onValueChange:Oa,disabled:Ma.isPending||Ba.isLoading,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"invite-team",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"No team"})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:NO_TEAM,children:"No team"}),(Ba.data??[]).map(Fa=>jsxRuntimeExports.jsx(SelectItem,{value:Fa.id,children:Fa.name},Fa.id))]})]}),Ba.error&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-destructive",children:["Couldn't load teams: ",Ba.error.message]})]}),Ia&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ia}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Ma.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ma.isPending,className:"cursor-pointer",children:Ma.isPending?"Sending…":"Send invitation"})]})]})]})})}function AdminMembersPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Qr,ja]=reactExports.useState(null),Na=useQuery({queryKey:["org-members",$],queryFn:()=>listMembers($),enabled:!!$}),Aa=useMutation({mutationFn:({userId:La,role:Ba})=>updateMemberRole($,La,Ba),onSuccess:()=>{ue$1.success("Role updated"),ts.invalidateQueries({queryKey:["org-members",$]}),ts.invalidateQueries({queryKey:["orgs"]})},onError:La=>{La instanceof ApiError&&La.code==="LAST_OWNER"?ue$1.error("Cannot demote the last owner."):ue$1.error(La instanceof Error?La.message:"Failed to update role"),ts.invalidateQueries({queryKey:["org-members",$]})}}),Oa=useMutation({mutationFn:La=>removeMember($,La),onSuccess:()=>{ue$1.success("Member removed"),ts.invalidateQueries({queryKey:["org-members",$]}),ts.invalidateQueries({queryKey:["orgs"]}),ja(null)},onError:La=>{La instanceof ApiError&&La.code==="LAST_OWNER"?ue$1.error("Cannot remove the last owner."):ue$1.error(La instanceof Error?La.message:"Failed to remove member")}}),Ia=Na.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Members"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Manage who has access to"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:(es==null?void 0:es.name)??"—"}),"."]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/members/invitations",children:[jsxRuntimeExports.jsx(Mail,{className:"mr-2 h-4 w-4"}),"Pending invites"]})}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Invite"]})]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load members: ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{className:"w-12"}),jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Display name"}),jsxRuntimeExports.jsx(TableHead,{children:"Role"}),jsxRuntimeExports.jsx(TableHead,{children:"Teams"}),jsxRuntimeExports.jsx(TableHead,{children:"Last active"}),jsxRuntimeExports.jsx(TableHead,{className:"w-12"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows$2,{}):Ia.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No members yet."})}):Ia.map(La=>{var Ba;return jsxRuntimeExports.jsx(MemberRow,{member:La,pending:Aa.isPending&&((Ba=Aa.variables)==null?void 0:Ba.userId)===La.userId,onRoleChange:Ma=>Aa.mutate({userId:La.userId,role:Ma}),onRemove:()=>ja(La)},La.userId)})})]})}),jsxRuntimeExports.jsx(InviteDialog,{open:is,onOpenChange:cs,orgSlug:$}),jsxRuntimeExports.jsx(RemoveMemberDialog$1,{member:Qr,onCancel:()=>ja(null),onConfirm:()=>Qr&&Oa.mutate(Qr.userId),pending:Oa.isPending})]})}function MemberRow({member:es,pending:$,onRoleChange:ts,onRemove:is}){const cs=reactExports.useMemo(()=>(es.email??es.displayName??"?").slice(0,1).toUpperCase(),[es.email,es.displayName]);return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Avatar,{size:"sm",children:jsxRuntimeExports.jsx(AvatarFallback,{children:cs})})}),jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:es.email??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:es.displayName??"—"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(Select,{value:es.role,onValueChange:Qr=>ts(Qr),disabled:$,children:[jsxRuntimeExports.jsx(SelectTrigger,{size:"sm",className:"w-32 capitalize",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"Owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"Admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"Member"})]})]})}),jsxRuntimeExports.jsx(TableCell,{children:es.teams.length===0?jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:"—"}):jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:es.teams.map(Qr=>jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-xs",children:Qr.name},Qr.id))})}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground text-sm",children:es.lastActiveAt?formatDistanceToNow(es.lastActiveAt):"never"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Member actions"})]})}),jsxRuntimeExports.jsx(DropdownMenuContent,{align:"end",children:jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:is,className:"text-destructive focus:text-destructive cursor-pointer",children:"Remove from organization"})})]})})]})}function SkeletonRows$2(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:4}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-6 rounded-full"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-32"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-8"})})]},$))})}function RemoveMemberDialog$1({member:es,onCancel:$,onConfirm:ts,pending:is}){return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:cs=>{cs||$()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Remove member?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[(es==null?void 0:es.email)??"This member"," will lose access to the organization. They can be re-invited later."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:$,disabled:is,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:ts,disabled:is,className:"cursor-pointer",children:is?"Removing…":"Remove"})]})]})})}function AdminInvitationsPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Qr,ja]=reactExports.useState(null),Na=useQuery({queryKey:["org-invitations",$],queryFn:()=>listInvitations($),enabled:!!$}),Aa=useMutation({mutationFn:La=>resendInvitation($,La),onSuccess:La=>{La.emailSent?ue$1.success(`Resent invitation to ${La.email}`):ue$1.warning("Invite link refreshed, but the email could not be sent",{description:La.emailError?`${La.emailError} — share the invite link directly.`:"Share the invite link directly.",duration:3e4,action:{label:"Copy invite link",onClick:()=>{var Ba;(Ba=navigator.clipboard)==null||Ba.writeText(La.acceptUrl).then(()=>ue$1.success("Invite link copied")).catch(()=>ue$1.error("Couldn't copy the invite link"))}}}),ts.invalidateQueries({queryKey:["org-invitations",$]})},onError:La=>ue$1.error(La instanceof Error?La.message:"Failed to resend invitation")}),Oa=useMutation({mutationFn:La=>revokeInvitation($,La),onSuccess:()=>{ue$1.success("Invitation revoked"),ts.invalidateQueries({queryKey:["org-invitations",$]}),ja(null)},onError:La=>ue$1.error(La instanceof Error?La.message:"Failed to revoke invitation")}),Ia=Na.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",size:"sm",className:"cursor-pointer mb-2 -ml-2 text-muted-foreground",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/members",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"}),"Back to members"]})}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Pending invitations"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"Sent but not yet accepted. Invitations expire 7 days after they're issued or last resent."})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Invite"]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load invitations:"," ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Role"}),jsxRuntimeExports.jsx(TableHead,{children:"Team"}),jsxRuntimeExports.jsx(TableHead,{children:"Invited by"}),jsxRuntimeExports.jsx(TableHead,{children:"Expires"}),jsxRuntimeExports.jsx(TableHead,{className:"w-48 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows$1,{}):Ia.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No pending invitations. Send one from the Members tab."})}):Ia.map(La=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:La.email}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize",children:La.role})}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:La.teamName??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:La.invitedByName??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground text-sm",children:formatDistanceToFuture(La.expiresAt)}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",disabled:Aa.isPending&&Aa.variables===La.id,onClick:()=>Aa.mutate(La.id),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-1 h-3 w-3"}),"Resend"]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>ja(La),className:"cursor-pointer text-destructive hover:text-destructive",children:[jsxRuntimeExports.jsx(Trash2,{className:"mr-1 h-3 w-3"}),"Revoke"]})]})})]},La.id))})]})}),jsxRuntimeExports.jsx(InviteDialog,{open:is,onOpenChange:cs,orgSlug:$}),jsxRuntimeExports.jsx(Dialog,{open:!!Qr,onOpenChange:La=>{La||ja(null)},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Revoke invitation?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[Qr!=null&&Qr.email?`${Qr.email} will no longer be able to accept this invitation.`:"This invitation will be revoked."," ","You can send a new one from the Members tab."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>ja(null),disabled:Oa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:()=>Qr&&Oa.mutate(Qr.id),disabled:Oa.isPending,className:"cursor-pointer",children:Oa.isPending?"Revoking…":"Revoke"})]})]})})]})}function SkeletonRows$1(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:3}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"})]})})]},$))})}const SLUG_REGEX$2=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function slugify$1(es){return es.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function AdminTeamsPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",[ts,is]=reactExports.useState(!1),[cs,Qr]=reactExports.useState(null),[ja,Na]=reactExports.useState(null),Aa=useQuery({queryKey:["org-teams",$],queryFn:()=>listTeams($),enabled:!!$}),Oa=Aa.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Teams"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Group members of"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:(es==null?void 0:es.name)??"—"})," ","to scope activity dashboards."]})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>is(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New team"]})]}),Aa.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load teams: ",Aa.error.message]}):Aa.isLoading?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Array.from({length:4}).map((Ia,La)=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20 mt-2"})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})})]},La))}):Oa.length===0?jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border border-dashed border-border py-16 text-center",children:[jsxRuntimeExports.jsx(Layers,{className:"h-10 w-10 text-muted-foreground mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"No teams yet."}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Create one to start grouping members."}),jsxRuntimeExports.jsxs(Button,{onClick:()=>is(!0),className:"cursor-pointer",variant:"outline",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create team"]})]}):jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Oa.map(Ia=>jsxRuntimeExports.jsx(TeamCard,{team:Ia,onRename:()=>Qr(Ia),onDelete:()=>Na(Ia)},Ia.id))}),jsxRuntimeExports.jsx(CreateTeamDialog,{open:ts,onOpenChange:is,orgSlug:$}),jsxRuntimeExports.jsx(RenameTeamDialog,{team:cs,orgSlug:$,onClose:()=>Qr(null)}),jsxRuntimeExports.jsx(DeleteTeamDialog,{team:ja,orgSlug:$,onClose:()=>Na(null)})]})}function TeamCard({team:es,onRename:$,onDelete:ts}){return jsxRuntimeExports.jsxs(Card,{className:"relative",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx(CardTitle,{className:"truncate",children:jsxRuntimeExports.jsx(Link,{to:`/admin/teams/${encodeURIComponent(es.slug)}`,className:"hover:underline",children:es.name})}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:jsxRuntimeExports.jsx("code",{children:es.slug})})]}),jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer -mr-2 -mt-1",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Team actions"})]})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",children:[jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:$,className:"cursor-pointer",children:"Rename"}),jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:ts,className:"text-destructive focus:text-destructive cursor-pointer",children:"Delete"})]})]})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),es.memberCount," ",es.memberCount===1?"member":"members"]})})]})}function CreateTeamDialog({open:es,onOpenChange:$,orgSlug:ts}){const is=useQueryClient(),[cs,Qr]=reactExports.useState(""),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(!1),[Ia,La]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Qr(""),Na(""),Oa(!1),La(null))},[es]);const Ba=useMutation({mutationFn:Fa=>createTeam(ts,Fa),onSuccess:()=>{ue$1.success("Team created"),is.invalidateQueries({queryKey:["org-teams",ts]}),is.invalidateQueries({queryKey:["org-detail",ts]}),$(!1)},onError:Fa=>{if(Fa instanceof ApiError&&Fa.code==="TEAM_SLUG_TAKEN"){La("That slug is already in use by another team.");return}if(Fa instanceof ApiError&&Fa.code==="VALIDATION_ERROR"){La("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Fa instanceof Error?Fa.message:"Failed to create team")}});function Ma(Fa){Qr(Fa),Aa||Na(slugify$1(Fa))}function qa(Fa){Fa.preventDefault(),La(null);const Ha=cs.trim(),Ka=ja.trim();if(!Ha){La("Name is required.");return}if(!SLUG_REGEX$2.test(Ka)){La("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Ba.mutate({name:Ha,slug:Ka})}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"New team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Teams group members of an organization for scoped activity views."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:qa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"team-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"team-name",value:cs,onChange:Fa=>Ma(Fa.target.value),placeholder:"Platform",required:!0,disabled:Ba.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"team-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"team-slug",value:ja,onChange:Fa=>{Na(Fa.target.value),Oa(!0)},placeholder:"platform",required:!0,disabled:Ba.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs."})]}),Ia&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ia}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Ba.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ba.isPending,className:"cursor-pointer",children:Ba.isPending?"Creating…":"Create team"})]})]})]})})}function RenameTeamDialog({team:es,orgSlug:$,onClose:ts}){const is=useQueryClient(),[cs,Qr]=reactExports.useState(""),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Qr(es.name),Na(es.slug),Oa(null))},[es]);const Ia=useMutation({mutationFn:({name:Ba,slug:Ma})=>updateTeam($,es.id,{name:Ba,slug:Ma}),onSuccess:()=>{ue$1.success("Team updated"),is.invalidateQueries({queryKey:["org-teams",$]}),is.invalidateQueries({queryKey:["org-detail",$]}),ts()},onError:Ba=>{if(Ba instanceof ApiError&&Ba.code==="TEAM_SLUG_TAKEN"){Oa("That slug is already in use by another team.");return}if(Ba instanceof ApiError&&Ba.code==="VALIDATION_ERROR"){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Ba instanceof Error?Ba.message:"Failed to update team")}});function La(Ba){Ba.preventDefault(),Oa(null);const Ma=cs.trim(),qa=ja.trim();if(!Ma){Oa("Name is required.");return}if(!SLUG_REGEX$2.test(qa)){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Ia.mutate({name:Ma,slug:qa})}return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Ba=>{Ba||ts()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Rename team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Change the team's display name and/or URL slug."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:La,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"rename-team-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"rename-team-name",value:cs,onChange:Ba=>Qr(Ba.target.value),required:!0,disabled:Ia.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"rename-team-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"rename-team-slug",value:ja,onChange:Ba=>Na(Ba.target.value),required:!0,disabled:Ia.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing the slug breaks any bookmarked links to this team."})]}),Aa&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Aa}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:ts,disabled:Ia.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ia.isPending,className:"cursor-pointer",children:Ia.isPending?"Saving…":"Save"})]})]})]})})}function DeleteTeamDialog({team:es,orgSlug:$,onClose:ts}){const is=useQueryClient(),cs=useMutation({mutationFn:()=>deleteTeam($,es.id),onSuccess:()=>{ue$1.success("Team deleted"),is.invalidateQueries({queryKey:["org-teams",$]}),is.invalidateQueries({queryKey:["org-detail",$]}),ts()},onError:Qr=>{ue$1.error(Qr instanceof Error?Qr.message:"Failed to delete team")}});return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Qr=>{Qr||ts()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Delete team?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[jsxRuntimeExports.jsx("strong",{children:es==null?void 0:es.name})," will be permanently deleted. Members will remain in the organization but will no longer be grouped under this team."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:ts,disabled:cs.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:()=>cs.mutate(),disabled:cs.isPending,className:"cursor-pointer",children:cs.isPending?"Deleting…":"Delete"})]})]})})}function TeamDetailPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",{teamSlug:ts=""}=useParams(),[is,cs]=useTabParam(["members","activity"],"members"),Qr=useQuery({queryKey:["org-teams",$],queryFn:()=>listTeams($),enabled:!!$}),ja=reactExports.useMemo(()=>{var Na;return((Na=Qr.data)==null?void 0:Na.find(Aa=>Aa.slug===ts))??null},[Qr.data,ts]);return Qr.isLoading?jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"})]}):Qr.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load team: ",Qr.error.message]}):ja?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-start justify-between gap-4",children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs(Link,{to:"/admin/teams",className:"text-xs text-muted-foreground hover:text-foreground inline-flex items-center",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-3 w-3"}),"All teams"]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:ja.name}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx("code",{className:"text-xs",children:ja.slug}),jsxRuntimeExports.jsxs("span",{className:"ml-2",children:["· ",ja.memberCount," ",ja.memberCount===1?"member":"members"]})]})]})}),jsxRuntimeExports.jsxs(Tabs,{value:is,onValueChange:cs,children:[jsxRuntimeExports.jsxs(TabsList,{variant:"line",children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"members",children:"Members"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"activity",children:"Activity"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"members",className:"pt-4",children:jsxRuntimeExports.jsx(MembersTab,{orgSlug:$,teamId:ja.id})}),jsxRuntimeExports.jsx(TabsContent,{value:"activity",className:"pt-4",children:jsxRuntimeExports.jsx(ActivityTab,{orgSlug:$,teamId:ja.id})})]})]}):jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border border-dashed border-border py-16 text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Team not found"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["No team with slug ",jsxRuntimeExports.jsx("code",{className:"text-xs",children:ts})," in this organization."]}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/teams",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to teams"]})})]})}function MembersTab({orgSlug:es,teamId:$}){const ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Qr,ja]=reactExports.useState(null),Na=useQuery({queryKey:["org-members",es],queryFn:()=>listMembers(es),enabled:!!es}),Aa=reactExports.useMemo(()=>(Na.data??[]).filter(La=>La.teams.some(Ba=>Ba.id===$)),[Na.data,$]),Oa=reactExports.useMemo(()=>(Na.data??[]).filter(La=>!La.teams.some(Ba=>Ba.id===$)),[Na.data,$]),Ia=useMutation({mutationFn:La=>removeTeamMember(es,$,La),onSuccess:()=>{ue$1.success("Member removed from team"),ts.invalidateQueries({queryKey:["org-members",es]}),ts.invalidateQueries({queryKey:["org-teams",es]}),ja(null)},onError:La=>{ue$1.error(La instanceof Error?La.message:"Failed to remove member")}});return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Members in this team. Adding a member here doesn't change their organization role — only the team grouping."}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Add member"]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load members: ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{className:"w-12"}),jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Display name"}),jsxRuntimeExports.jsx(TableHead,{children:"Org role"}),jsxRuntimeExports.jsx(TableHead,{className:"w-12"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows,{}):Aa.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No members in this team yet."})}):Aa.map(La=>jsxRuntimeExports.jsx(TeamMemberRow,{member:La,onRemove:()=>ja(La)},La.userId))})]})}),jsxRuntimeExports.jsx(AddMemberDialog,{open:is,onOpenChange:cs,orgSlug:es,teamId:$,addable:Oa,loading:Na.isLoading}),jsxRuntimeExports.jsx(RemoveMemberDialog,{member:Qr,onCancel:()=>ja(null),onConfirm:()=>Qr&&Ia.mutate(Qr.userId),pending:Ia.isPending})]})}function TeamMemberRow({member:es,onRemove:$}){const ts=reactExports.useMemo(()=>(es.email??es.displayName??"?").slice(0,1).toUpperCase(),[es.email,es.displayName]);return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Avatar,{size:"sm",children:jsxRuntimeExports.jsx(AvatarFallback,{children:ts})})}),jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:es.email??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:es.displayName??"—"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"capitalize",children:es.role})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Member actions"})]})}),jsxRuntimeExports.jsx(DropdownMenuContent,{align:"end",children:jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:$,className:"text-destructive focus:text-destructive cursor-pointer",children:"Remove from team"})})]})})]})}function SkeletonRows(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:3}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-6 rounded-full"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-8"})})]},$))})}const NO_USER="__none";function AddMemberDialog({open:es,onOpenChange:$,orgSlug:ts,teamId:is,addable:cs,loading:Qr}){const ja=useQueryClient(),[Na,Aa]=reactExports.useState(NO_USER),[Oa,Ia]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Aa(NO_USER),Ia(null))},[es]);const La=useMutation({mutationFn:Ma=>addTeamMember(ts,is,Ma),onSuccess:()=>{ue$1.success("Member added to team"),ja.invalidateQueries({queryKey:["org-members",ts]}),ja.invalidateQueries({queryKey:["org-teams",ts]}),$(!1)},onError:Ma=>{ue$1.error(Ma instanceof Error?Ma.message:"Failed to add member")}});function Ba(Ma){if(Ma.preventDefault(),Na===NO_USER){Ia("Pick a member to add.");return}La.mutate(Na)}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Add member to team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Pick an organization member to add. Only members not already on this team are listed."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Ba,className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"space-y-2",children:jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:Ma=>{Aa(Ma),Ia(null)},disabled:La.isPending||Qr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:Qr?"Loading…":"Select member"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs.length===0?jsxRuntimeExports.jsx(SelectItem,{value:NO_USER,disabled:!0,children:Qr?"Loading…":"All org members are on this team."}):cs.map(Ma=>jsxRuntimeExports.jsx(SelectItem,{value:Ma.userId,children:Ma.email??Ma.displayName??Ma.userId},Ma.userId))})]})}),Oa&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Oa}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:La.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:La.isPending||cs.length===0||Na===NO_USER,className:"cursor-pointer",children:La.isPending?"Adding…":"Add"})]})]})]})})}function RemoveMemberDialog({member:es,onCancel:$,onConfirm:ts,pending:is}){return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:cs=>{cs||$()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Remove from team?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[(es==null?void 0:es.email)??"This member"," will no longer be grouped under this team. They'll remain in the organization."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:$,disabled:is,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:ts,disabled:is,className:"cursor-pointer",children:is?"Removing…":"Remove"})]})]})})}function ActivityTab({orgSlug:es,teamId:$}){var ja,Na;const[ts,is]=reactExports.useState("7d"),cs=useQuery({queryKey:["team-activity",es,$,ts],queryFn:()=>getTeamActivity(es,$,ts),enabled:!!es&&!!$});if(cs.error)return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load activity: ",cs.error.message]});const Qr=cs.data;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center justify-end",children:jsxRuntimeExports.jsxs(Select,{value:ts,onValueChange:Aa=>is(Aa),children:[jsxRuntimeExports.jsx(SelectTrigger,{size:"sm",className:"w-32",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"7d",children:"Last 7 days"}),jsxRuntimeExports.jsx(SelectItem,{value:"30d",children:"Last 30 days"})]})]})}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:`Sessions (${ts})`,value:Qr==null?void 0:Qr.sessionCount,loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),label:"Active members",value:Qr==null?void 0:Qr.memberCount,loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"}),label:"Top tool",value:((Na=(ja=Qr==null?void 0:Qr.topTools)==null?void 0:ja[0])==null?void 0:Na.tool)??"—",loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:"Avg friction",value:Qr!=null&&Qr.frictionTrend&&Qr.frictionTrend.length>0?(Qr.frictionTrend.reduce((Aa,Oa)=>Aa+Oa.avgFriction,0)/Qr.frictionTrend.length).toFixed(2):"—",loading:cs.isLoading})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[jsxRuntimeExports.jsx(TopToolsCard,{data:Qr,loading:cs.isLoading}),jsxRuntimeExports.jsx(TopMembersCard,{data:Qr,loading:cs.isLoading}),jsxRuntimeExports.jsx(FrictionTrendCard,{data:Qr,loading:cs.isLoading}),jsxRuntimeExports.jsx(InstructionEffectivenessCard,{data:Qr,loading:cs.isLoading})]})]})}function StatCard({icon:es,label:$,value:ts,loading:is}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[es,$]})}),jsxRuntimeExports.jsx(CardContent,{children:is?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}):jsxRuntimeExports.jsx("span",{className:"text-3xl font-mono font-semibold tabular-nums",children:ts??"—"})})]})}function TopToolsCard({data:es,loading:$}){var cs;const ts=(es==null?void 0:es.topTools)??[],is=((cs=ts[0])==null?void 0:cs.count)??0;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Top tools"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(Qr=>jsxRuntimeExports.jsxs("li",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:Qr.tool}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:Qr.count})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-full rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${is>0?Qr.count/is*100:0}%`}})})]},Qr.tool))})})]})}function TopMembersCard({data:es,loading:$}){const ts=(es==null?void 0:es.topMembers)??[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Top members"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(is=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{className:"truncate font-medium",children:is.email??is.displayName??is.userId}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:is.count})]},is.userId))})})]})}function FrictionTrendCard({data:es,loading:$}){const ts=(es==null?void 0:es.frictionTrend)??[],is=ts.reduce((cs,Qr)=>Math.max(cs,Qr.avgFriction),0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Friction trend"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction data in this range."}):jsxRuntimeExports.jsx("ul",{className:"space-y-1.5",children:ts.map(cs=>jsxRuntimeExports.jsxs("li",{className:"space-y-0.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:cs.day}),jsxRuntimeExports.jsx("span",{className:"font-medium tabular-nums",children:cs.avgFriction.toFixed(2)})]}),jsxRuntimeExports.jsx("div",{className:"h-1 w-full rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${is>0?cs.avgFriction/is*100:0}%`}})})]},cs.day))})})]})}function InstructionEffectivenessCard({data:es,loading:$}){const ts=(es==null?void 0:es.instructionEffectiveness)??[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Instruction effectiveness"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No linked instructions in this range."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(is=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"truncate font-medium",children:is.name}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:is.source})]}),jsxRuntimeExports.jsx("span",{className:is.deltaPct==null?"text-muted-foreground tabular-nums":is.deltaPct>=0?"text-teal-600 dark:text-teal-500 tabular-nums":"text-destructive tabular-nums",children:is.deltaPct==null?"—":`${is.deltaPct>=0?"+":""}${is.deltaPct.toFixed(1)}%`})]},is.instructionId))})})]})}const SLUG_REGEX$1=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function AdminSettingsPage(){const{activeOrg:es}=useActiveOrg();if(!es)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"})]});const $=es.role==="owner";return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Settings"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Manage"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:es.name}),"'s name, slug, ownership, and lifecycle."]})]}),jsxRuntimeExports.jsx(GeneralSection,{orgName:es.name,orgSlug:es.slug}),$&&jsxRuntimeExports.jsx(TransferOwnershipSection,{orgSlug:es.slug}),$&&jsxRuntimeExports.jsx(DeleteOrgSection,{orgName:es.name,orgSlug:es.slug})]})}function Section({title:es,description:$,destructive:ts,children:is}){return jsxRuntimeExports.jsx(Card,{className:ts?"border-destructive/30":void 0,children:jsxRuntimeExports.jsx(CardContent,{className:"p-6",children:jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-[200px_1fr]",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("h3",{className:ts?"font-mono text-base font-semibold text-destructive":"font-mono text-base font-semibold",children:es}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:$})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:is})]})})})}function GeneralSection({orgName:es,orgSlug:$}){const ts=useQueryClient(),is=useNavigate(),[cs,Qr]=reactExports.useState(es),[ja,Na]=reactExports.useState($),[Aa,Oa]=reactExports.useState(null);reactExports.useEffect(()=>{Qr(es),Na($),Oa(null)},[es,$]);const Ia=useMutation({mutationFn:Ma=>updateOrg($,Ma),onSuccess:Ma=>{ue$1.success("Organization updated"),ts.invalidateQueries({queryKey:["profile"]}),ts.invalidateQueries({queryKey:["orgs"]}),ts.invalidateQueries({queryKey:["org-detail",$]}),Ma.slug!==$&&is("/admin/settings",{replace:!0})},onError:Ma=>{if(Ma instanceof ApiError&&Ma.code==="ORG_SLUG_TAKEN"){Oa("That slug is already taken by another organization.");return}if(Ma instanceof ApiError&&Ma.code==="VALIDATION_ERROR"){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Ma instanceof Error?Ma.message:"Failed to update organization")}});function La(Ma){Ma.preventDefault(),Oa(null);const qa=cs.trim(),Fa=ja.trim();if(!qa){Oa("Name is required.");return}if(!SLUG_REGEX$1.test(Fa)){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}const Ha={};qa!==es&&(Ha.name=qa),Fa!==$&&(Ha.slug=Fa),!(!Ha.name&&!Ha.slug)&&Ia.mutate(Ha)}const Ba=cs.trim()!==es||ja.trim()!==$;return jsxRuntimeExports.jsx(Section,{title:"General",description:"The display name and URL slug of this organization.",children:jsxRuntimeExports.jsxs("form",{onSubmit:La,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"org-name",value:cs,onChange:Ma=>Qr(Ma.target.value),required:!0,disabled:Ia.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"org-slug",value:ja,onChange:Ma=>Na(Ma.target.value),required:!0,disabled:Ia.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs and CLI commands. Changing the slug breaks any bookmarked links."})]}),Aa&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Aa}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ia.isPending||!Ba,className:"cursor-pointer",children:Ia.isPending?"Saving…":"Save"})})]})})}function TransferOwnershipSection({orgSlug:es}){const $=useQueryClient(),ts=useNavigate(),is=useQuery({queryKey:["org-members",es],queryFn:()=>listMembers(es),enabled:!!es}),cs=reactExports.useMemo(()=>(is.data??[]).filter(La=>La.role==="admin"),[is.data]),[Qr,ja]=reactExports.useState(null),[Na,Aa]=reactExports.useState(!1),Oa=useMutation({mutationFn:La=>transferOwnership(es,La),onSuccess:()=>{ue$1.success("Ownership transferred. You're now an admin."),$.invalidateQueries({queryKey:["org-members",es]}),$.invalidateQueries({queryKey:["orgs"]}),$.invalidateQueries({queryKey:["profile"]}),Aa(!1),ts("/admin/members")},onError:La=>{if(La instanceof ApiError&&La.code==="SAME_USER"){ue$1.error("You can't transfer ownership to yourself.");return}if(La instanceof ApiError&&La.code==="NOT_A_MEMBER"){ue$1.error("That user is no longer a member of this organization.");return}ue$1.error(La instanceof Error?La.message:"Failed to transfer ownership")}}),Ia=cs.find(La=>La.userId===Qr);return jsxRuntimeExports.jsxs(Section,{title:"Transfer ownership",description:"Promote another admin to owner. You will become an admin afterward.",children:[is.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"}):cs.length===0?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:["No other admins to transfer to. Promote a member to admin first on the"," ",jsxRuntimeExports.jsx("a",{href:"/admin/members",className:"underline",children:"Members"})," ","page."]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"transfer-target",children:"New owner"}),jsxRuntimeExports.jsxs(Select,{value:Qr??"",onValueChange:La=>ja(La),disabled:Oa.isPending,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"transfer-target",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select an admin…"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs.map(La=>jsxRuntimeExports.jsx(SelectItem,{value:La.userId,children:La.email??La.displayName??La.userId},La.userId))})]})]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsxs(Button,{type:"button",variant:"outline",disabled:!Qr||Oa.isPending,onClick:()=>Aa(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ArrowRightLeft,{className:"mr-2 h-4 w-4"}),"Transfer ownership"]})})]}),jsxRuntimeExports.jsx(Dialog,{open:Na,onOpenChange:Aa,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Transfer ownership?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[jsxRuntimeExports.jsx("strong",{children:(Ia==null?void 0:Ia.email)??(Ia==null?void 0:Ia.displayName)??"the selected user"})," ","will become the new owner of this organization. You'll keep admin access but lose the ability to delete the org or transfer ownership again."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>Aa(!1),disabled:Oa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",onClick:()=>Qr&&Oa.mutate(Qr),disabled:!Qr||Oa.isPending,className:"cursor-pointer",children:Oa.isPending?"Transferring…":"Transfer"})]})]})})]})}function DeleteOrgSection({orgName:es,orgSlug:$}){const ts=useQueryClient(),is=useSetActiveOrg(),cs=useNavigate(),[Qr,ja]=reactExports.useState(""),Na=Qr===$,Aa=useMutation({mutationFn:()=>deleteOrg($),onSuccess:async()=>{ue$1.success(`Deleted ${es}`);try{await is.mutateAsync(null)}catch{}ts.clear(),cs("/",{replace:!0})},onError:Oa=>{ue$1.error(Oa instanceof Error?Oa.message:"Failed to delete organization")}});return jsxRuntimeExports.jsxs(Section,{title:"Delete organization",description:"Permanently delete this organization, its teams, invitations, and member roles. Sessions are preserved (org_id is cleared).",destructive:!0,children:[jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-destructive",children:"This action cannot be undone."})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs(Label,{htmlFor:"delete-confirm",children:["Type ",jsxRuntimeExports.jsx("code",{className:"text-xs font-mono px-1 rounded bg-muted",children:$})," to confirm"]}),jsxRuntimeExports.jsx(Input,{id:"delete-confirm",value:Qr,onChange:Oa=>ja(Oa.target.value),autoComplete:"off",disabled:Aa.isPending})]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsxs(Button,{type:"button",variant:"destructive",disabled:!Na||Aa.isPending,onClick:()=>Aa.mutate(),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Trash2,{className:"mr-2 h-4 w-4"}),Aa.isPending?"Deleting…":"Delete organization"]})})]})}function useActiveLimits(){return useQuery({queryKey:["research","active-limits"],queryFn:()=>apiGet("/api/research/active-limits")})}function useObservations(es={}){const $=new URLSearchParams;es.provider&&$.set("provider",es.provider),es.plan&&$.set("plan",es.plan),es.limitType&&$.set("limit_type",es.limitType),es.limit!=null&&$.set("limit",String(es.limit)),es.offset!=null&&$.set("offset",String(es.offset));const ts=$.toString();return useQuery({queryKey:["research","observations",es],queryFn:()=>apiGet(`/api/research/observations${ts?`?${ts}`:""}`)})}function useDocChanges(es){return useQuery({queryKey:["research","doc-changes","default"],queryFn:()=>apiGet("/api/research/doc-changes")})}function useDisagreements(es=14){return useQuery({queryKey:["research","disagreements",es],queryFn:()=>apiGet(`/api/research/disagreements?since_days=${es}`)})}function useConfidenceHistory(es,$,ts,is=90){return useQuery({queryKey:["research","confidence-history",es,$,ts,is],queryFn:()=>{const Qr=new URLSearchParams({provider:es,plan:$,limit_type:ts,days:String(is)});return apiGet(`/api/research/confidence-history?${Qr}`)},enabled:!!es&&!!$&&!!ts})}function ConfidenceBar({value:es}){const $=Math.max(0,Math.min(1,es))*100,ts=es>=.9?"high":es>=.6?"mid":"low",is=ts==="high"?"bg-teal-500":ts==="mid"?"bg-amber-500":"bg-rose-500";return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-1.5 w-16 rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:`h-full ${is}`,style:{width:`${$}%`}})}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:[$.toFixed(0),"%"]})]})}function ConfidenceTrendSparkline({provider:es,plan:$,limitType:ts,width:is=80,height:cs=20}){const{data:Qr,isLoading:ja}=useConfidenceHistory(es,$,ts);if(ja)return jsxRuntimeExports.jsx("div",{className:"h-5 w-20 animate-pulse rounded bg-muted"});const Na=(Qr==null?void 0:Qr.items)??[];if(Na.length===0)return jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});if(Na.length===1)return jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:[(Na[0].confidence*100).toFixed(0),"%"]});const Aa=Na.map((Ma,qa)=>qa/(Na.length-1)*is),Oa=Na.map(Ma=>cs-Ma.confidence*cs),Ia=Aa.map((Ma,qa)=>`${qa===0?"M":"L"}${Ma.toFixed(1)},${Oa[qa].toFixed(1)}`).join(" "),La=Na[Na.length-1].confidence,Ba=La>=.9?"stroke-teal-500":La>=.6?"stroke-amber-500":"stroke-rose-500";return jsxRuntimeExports.jsx("svg",{width:is,height:cs,viewBox:`0 0 ${is} ${cs}`,className:"overflow-visible",role:"img","aria-label":`Confidence trend (${Na.length} points)`,children:jsxRuntimeExports.jsx("path",{d:Ia,fill:"none",className:Ba,strokeWidth:1.5,strokeLinejoin:"round"})})}function ActiveLimitsTable(){const{data:es,isLoading:$,error:ts}=useActiveLimits();if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load active limits."});const is=((es==null?void 0:es.items)??[]).slice().sort((cs,Qr)=>cs.provider!==Qr.provider?cs.provider.localeCompare(Qr.provider):cs.plan!==Qr.plan?cs.plan.localeCompare(Qr.plan):cs.limitType.localeCompare(Qr.limitType));return is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No active limits recorded yet."}):jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Provider"}),jsxRuntimeExports.jsx(TableHead,{children:"Plan"}),jsxRuntimeExports.jsx(TableHead,{children:"Limit type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Value"}),jsxRuntimeExports.jsx(TableHead,{children:"Unit"}),jsxRuntimeExports.jsx(TableHead,{children:"Confidence"}),jsxRuntimeExports.jsx(TableHead,{children:"Trend (90d)"}),jsxRuntimeExports.jsx(TableHead,{children:"Effective from"})]})}),jsxRuntimeExports.jsx(TableBody,{children:is.map(cs=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.provider}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.plan}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.limitType}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-right tabular-nums",children:Number(cs.value).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:cs.unit}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Number(cs.confidence)})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceTrendSparkline,{provider:cs.provider,plan:cs.plan,limitType:cs.limitType})}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs text-muted-foreground",children:new Date(cs.effectiveFrom).toLocaleString()})]},`${cs.provider}-${cs.plan}-${cs.limitType}-${cs.effectiveFrom}`))})]})}function RecentDocChanges(){const{data:es,isLoading:$,error:ts}=useDocChanges(),[is,cs]=reactExports.useState(null);if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load doc snapshots."});const ja=((es==null?void 0:es.items)??[]).slice().sort((Na,Aa)=>Na.changed!==Aa.changed?Na.changed?-1:1:new Date(Aa.latestFetchedAt).getTime()-new Date(Na.latestFetchedAt).getTime());return ja.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No doc snapshots in window."}):jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border rounded-md border border-border",children:ja.map(Na=>{const Aa=`${Na.provider}::${Na.docUrl}`,Oa=is===Aa;return jsxRuntimeExports.jsxs("li",{className:"px-3 py-2",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(Oa?null:Aa),className:"flex w-full items-center justify-between gap-3 text-left cursor-pointer",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:Na.provider}),Na.changed?jsxRuntimeExports.jsx(Badge,{variant:"default",className:"text-[10px]",children:"changed"}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px]",children:"stable"}),!Na.parseSuccess&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"text-[10px]",children:"parse-fail"})]}),jsxRuntimeExports.jsx("div",{className:"truncate font-mono text-xs text-muted-foreground",children:Na.docUrl})]}),jsxRuntimeExports.jsx("div",{className:"flex-shrink-0 font-mono text-xs text-muted-foreground tabular-nums",children:new Date(Na.latestFetchedAt).toLocaleString()})]}),Oa&&jsxRuntimeExports.jsx(DocSnapshotDetail,{group:Na})]},Aa)})})}function DocSnapshotDetail({group:es}){return jsxRuntimeExports.jsx("div",{className:"mt-2 ml-2 border-l-2 border-border pl-3 space-y-1",children:es.snapshots.slice(0,5).map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-mono text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:new Date($.fetchedAt).toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"truncate text-muted-foreground",children:$.contentHash.slice(0,12)}),!$.parseSuccess&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"text-[10px]",children:"parse-fail"})]},$.id))})}function SourceBadge({sourceType:es}){const $=LABELS[es]??es,ts=VARIANTS[es]??"outline";return jsxRuntimeExports.jsx(Badge,{variant:ts,className:"font-mono text-[10px] uppercase tracking-wide",children:$})}const LABELS={oauth_usage:"live",self_observed_429:"429",official_docs:"docs",self_observed_lower_bound:"lower",community:"community",llm_research:"llm"},VARIANTS={oauth_usage:"default",self_observed_429:"destructive",official_docs:"secondary",self_observed_lower_bound:"outline",community:"outline",llm_research:"outline"},PAGE_SIZE=50,ANY="__any";function ObservationsList(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(""),[cs,Qr]=reactExports.useState(""),[ja,Na]=reactExports.useState(0),Aa=useActiveLimits(),Oa=reactExports.useMemo(()=>{var Ga;const Fa=new Set,Ha=new Set,Ka=new Set;for(const Va of((Ga=Aa.data)==null?void 0:Ga.items)??[])Fa.add(Va.provider),Ha.add(Va.plan),Ka.add(Va.limitType);return{providers:Array.from(Fa).sort(),plans:Array.from(Ha).sort(),limitTypes:Array.from(Ka).sort()}},[Aa.data]),{data:Ia,isLoading:La,error:Ba}=useObservations({provider:es||void 0,plan:ts||void 0,limitType:cs||void 0,limit:PAGE_SIZE,offset:ja}),Ma=(Ia==null?void 0:Ia.total)??0,qa=(Ia==null?void 0:Ia.items)??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsx(FilterSelect,{label:"Provider",value:es,options:Oa.providers,onChange:Fa=>{$(Fa),Na(0)}}),jsxRuntimeExports.jsx(FilterSelect,{label:"Plan",value:ts,options:Oa.plans,onChange:Fa=>{is(Fa),Na(0)}}),jsxRuntimeExports.jsx(FilterSelect,{label:"Limit type",value:cs,options:Oa.limitTypes,onChange:Fa=>{Qr(Fa),Na(0)}}),jsxRuntimeExports.jsx("div",{className:"ml-auto font-mono text-xs text-muted-foreground tabular-nums",children:Ma>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ja+1,"–",Math.min(ja+PAGE_SIZE,Ma)," of ",Ma]})})]}),La?jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"}):Ba?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load observations."}):qa.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No observations match these filters."}):jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Observed at"}),jsxRuntimeExports.jsx(TableHead,{children:"Provider"}),jsxRuntimeExports.jsx(TableHead,{children:"Plan"}),jsxRuntimeExports.jsx(TableHead,{children:"Limit type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Value"}),jsxRuntimeExports.jsx(TableHead,{children:"Unit"}),jsxRuntimeExports.jsx(TableHead,{children:"Source"}),jsxRuntimeExports.jsx(TableHead,{children:"Confidence"})]})}),jsxRuntimeExports.jsx(TableBody,{children:qa.map(Fa=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs text-muted-foreground tabular-nums",children:new Date(Fa.observedAt).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Fa.provider}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Fa.plan}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Fa.limitType}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-right tabular-nums",children:Number(Fa.value).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:Fa.unit}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(SourceBadge,{sourceType:Fa.sourceType})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Number(Fa.confidence)})})]},Fa.id))})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:ja===0,onClick:()=>Na(Math.max(0,ja-PAGE_SIZE)),children:"Previous"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:ja+PAGE_SIZE>=Ma,onClick:()=>Na(ja+PAGE_SIZE),children:"Next"})]})]})}function FilterSelect({label:es,value:$,options:ts,onChange:is}){return jsxRuntimeExports.jsxs(Select,{value:$||ANY,onValueChange:cs=>is(cs===ANY?"":cs),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"h-8 w-[180px] text-xs",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:es})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsxs(SelectItem,{value:ANY,children:["All ",es.toLowerCase(),"s"]}),ts.map(cs=>jsxRuntimeExports.jsx(SelectItem,{value:cs,className:"font-mono text-xs",children:cs},cs))]})]})}function DisagreementView(){const{data:es,isLoading:$,error:ts}=useDisagreements();if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load disagreements."});const is=(es==null?void 0:es.items)??[];return is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No disagreements (>20% spread) detected in the last 14 days."}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:is.map(cs=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[cs.provider," / ",cs.plan," / ",cs.limitType]}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-destructive tabular-nums",children:["Δ ",cs.spreadPct.toFixed(1),"% (",cs.minValue.toLocaleString()," →"," ",cs.maxValue.toLocaleString(),")"]})]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border",children:cs.observations.map(Qr=>jsxRuntimeExports.jsxs("li",{className:"flex items-center gap-3 py-1.5 font-mono text-xs",children:[jsxRuntimeExports.jsx("span",{className:"w-40 text-muted-foreground tabular-nums",children:new Date(Qr.observedAt).toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"w-24 text-right tabular-nums",children:Qr.value.toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"w-16 text-muted-foreground",children:Qr.unit}),jsxRuntimeExports.jsx(SourceBadge,{sourceType:Qr.sourceType}),jsxRuntimeExports.jsx("div",{className:"ml-auto",children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Qr.confidence})})]},Qr.id))})})]},`${cs.provider}-${cs.plan}-${cs.limitType}`))})}function AdminResearchPage(){const[es,$]=useTabParam(["active","docs","observations","disagreements"],"active");return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx(Database,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"Usage research"})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:"Provider limits intelligence"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Fused view of provider rate-limits sourced from OAuth headers, 429 responses, official docs, and community signals."})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,className:"space-y-4",children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"active",children:"Active limits"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"docs",children:"Doc changes"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"observations",children:"Observations"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"disagreements",children:"Disagreements"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"active",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Active fused limits"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ActiveLimitsTable,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"docs",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Recent doc snapshots (7d)"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(RecentDocChanges,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"observations",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Raw observations"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ObservationsList,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"disagreements",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Source disagreements (14d, >20% spread)"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(DisagreementView,{})})]})})]})]})}function statusBadgeVariant(es){switch(es){case"draft":return{className:"bg-muted text-muted-foreground",label:"draft"};case"queued":return{className:"bg-blue-500/15 text-blue-700 dark:text-blue-300",label:"queued"};case"sending":return{className:"bg-blue-500/15 text-blue-700 dark:text-blue-300 animate-pulse",label:"sending"};case"sent":return{className:"bg-teal-500/15 text-teal-700 dark:text-teal-300",label:"sent"};case"failed":return{className:"bg-destructive/15 text-destructive",label:"failed"}}}function StatusBadge({status:es}){const{className:$,label:ts}=statusBadgeVariant(es);return jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("font-mono text-xs",$),children:ts})}function AdminAnnouncementsPage(){var Qr;const{profile:es,isLoading:$}=useActiveOrg(),[ts,is]=reactExports.useState(null),cs=useQuery({queryKey:["admin","announcements"],queryFn:()=>apiGet("/api/announcements"),refetchInterval:POLL.BACKGROUND,enabled:!!(es!=null&&es.isSuperadmin)});return reactExports.useEffect(()=>{var ja;!ts&&((ja=cs.data)!=null&&ja.announcements.length)&&is(cs.data.announcements[0].id)},[cs.data,ts]),$?jsxRuntimeExports.jsx("div",{className:"p-6",children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"})}):es!=null&&es.isSuperadmin?jsxRuntimeExports.jsxs("div",{className:"flex h-[calc(100vh-4rem)] flex-col",children:[jsxRuntimeExports.jsxs("header",{className:"border-b border-border p-6",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Announcements"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Superadmin · CHANGELOG-driven product announcement emails. Drafts are editable; sent ones are immutable."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden md:flex-row",children:[jsxRuntimeExports.jsx("aside",{className:"max-h-64 w-full shrink-0 overflow-y-auto border-b border-border md:max-h-none md:w-80 md:border-b-0 md:border-r",children:cs.isLoading?jsxRuntimeExports.jsxs("div",{className:"space-y-2 p-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-16"})]}):cs.error?jsxRuntimeExports.jsxs("p",{className:"p-4 text-sm text-destructive",children:["Failed to load: ",cs.error.message]}):(((Qr=cs.data)==null?void 0:Qr.announcements.length)??0)===0?jsxRuntimeExports.jsx("div",{className:"p-6 text-center",children:jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["No announcements yet. Add an entry to"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"CHANGELOG.md"}),", then run"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric crons run cron_check_changelog"})," ","if this release merits an announcement draft."]})}):jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border",children:cs.data.announcements.map(ja=>{const Na=ja.id===ts;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(ja.id),className:cn$1("flex w-full flex-col gap-1 px-4 py-3 text-left transition-colors","hover:bg-muted/50",Na&&"bg-secondary"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm font-medium",children:["v",ja.version]}),jsxRuntimeExports.jsx(StatusBadge,{status:ja.status})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:[ja.releaseDate,ja.status==="sent"&&ja.recipientCount!==null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · ",ja.recipientCount," recipients"]})]}),jsxRuntimeExports.jsx("div",{className:"line-clamp-2 text-sm",children:ja.subject})]})},ja.id)})})}),jsxRuntimeExports.jsx("main",{className:"flex-1 overflow-y-auto",children:ts?jsxRuntimeExports.jsx(AnnouncementDetailPane,{id:ts}):jsxRuntimeExports.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select an announcement to view details."})})]})]}):jsxRuntimeExports.jsx(Navigate,{to:"/admin",replace:!0})}function AnnouncementDetailPane({id:es}){var cl,dl;const $=useQueryClient(),ts=useQuery({queryKey:["admin","announcement",es],queryFn:()=>apiGet(`/api/announcements/${es}`),refetchInterval:fl=>{var ol;const nl=(ol=fl.state.data)==null?void 0:ol.status;return nl==="queued"||nl==="sending"?3e3:!1}}),is=useQuery({queryKey:["admin","announcement",es,"recipient-count"],queryFn:()=>apiGet(`/api/announcements/${es}/recipients/count`)}),[cs,Qr]=reactExports.useState(!1),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(!1),[Ia,La]=reactExports.useState(""),[Ba,Ma]=reactExports.useState("");reactExports.useEffect(()=>{Qr(!1),Oa(!1)},[es]);const qa=ts.data,Fa=(qa==null?void 0:qa.status)==="draft",Ha=()=>{$.invalidateQueries({queryKey:["admin","announcements"]}),$.invalidateQueries({queryKey:["admin","announcement",es]})},Ka=useMutation({mutationFn:fl=>apiPatch(`/api/announcements/${es}`,fl),onSuccess:()=>{ue$1.success("Saved"),Qr(!1),Oa(!1),Ha()},onError:fl=>{const nl=fl instanceof ApiError?fl.message:String(fl);ue$1.error(`Save failed: ${nl}`)}}),[Ga,Va]=reactExports.useState(!1),Ja=useMutation({mutationFn:()=>apiPost(`/api/announcements/${es}/send`,{}),onSuccess:fl=>{ue$1.success(fl.resumed?"Resuming send…":"Sending…"),Va(!1),Ha()},onError:fl=>{const nl=fl instanceof ApiError?fl.message:String(fl);ue$1.error(`Send failed: ${nl}`)}}),Ya=reactExports.useMemo(()=>!(qa!=null&&qa.sections)||typeof qa.sections!="object"?[]:Object.entries(qa.sections).map(([nl,ol])=>({key:nl,items:Array.isArray(ol)?ol.map(String):[String(ol)]})),[qa==null?void 0:qa.sections]);if(ts.isLoading)return jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-2/3"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]});if(ts.error||!qa)return jsxRuntimeExports.jsxs("p",{className:"p-6 text-sm text-destructive",children:["Failed to load announcement:"," ",((cl=ts.error)==null?void 0:cl.message)??"not found"]});const el=((dl=is.data)==null?void 0:dl.count)??null,tl=!Fa||el===0||Ja.isPending,rl=Fa?el===0?"No opted-in recipients":"":`Already ${qa.status} — cannot resend`;return jsxRuntimeExports.jsxs("div",{className:"space-y-6 p-6",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx(StatusBadge,{status:qa.status}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm text-muted-foreground",children:["v",qa.version]}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground",children:qa.releaseDate}),qa.sentAt&&jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["· Sent ",new Date(qa.sentAt).toLocaleString()]}),qa.recipientCount!==null&&qa.status==="sent"&&jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["· ",qa.recipientCount," recipients"]})]}),qa.deliveryCounts&&Object.keys(qa.deliveryCounts).length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap items-center gap-2",children:["sent","failed","skipped","pending"].filter(fl=>{var nl;return(((nl=qa.deliveryCounts)==null?void 0:nl[fl])??0)>0}).map(fl=>{var nl;return jsxRuntimeExports.jsxs(Badge,{variant:fl==="failed"?"destructive":"outline",className:"font-mono text-xs",children:[(nl=qa.deliveryCounts)==null?void 0:nl[fl]," ",fl]},fl)})}),cs?jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Input,{value:ja,onChange:fl=>Na(fl.target.value),autoFocus:!0,className:"text-lg"}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:!ja.trim()||Ka.isPending,onClick:()=>Ka.mutate({subject:ja.trim()}),children:Ka.isPending?"Saving…":"Save"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:()=>Qr(!1),children:"Cancel"})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:qa.subject}),Fa&&jsxRuntimeExports.jsx(Button,{size:"icon",variant:"ghost",onClick:()=>{Na(qa.subject),Qr(!0)},"aria-label":"Edit subject",children:jsxRuntimeExports.jsx(Pencil,{className:"h-4 w-4"})})]})]}),qa.error&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"})," Last error"]}),jsxRuntimeExports.jsx("pre",{className:"mt-2 whitespace-pre-wrap font-mono text-xs",children:qa.error})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 rounded-md border border-border bg-muted/30 p-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Recipients (opted in)"}),jsxRuntimeExports.jsx("div",{className:"font-mono text-3xl font-semibold",children:is.isLoading?"…":el??"?"}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Live count from ",jsxRuntimeExports.jsx("code",{children:"notification_preferences"})," — server-side aggregation, not a client filter."]})]}),jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("span",{tabIndex:tl?0:-1,children:jsxRuntimeExports.jsxs(Button,{size:"lg",disabled:tl,onClick:()=>Va(!0),children:[jsxRuntimeExports.jsx(Send,{className:"mr-2 h-4 w-4"}),"Send announcement"]})})}),rl&&jsxRuntimeExports.jsx(TooltipContent,{children:rl})]})})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"HTML preview"}),Fa&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:()=>{Aa||(La(qa.htmlBody),Ma(qa.textBody)),Oa(fl=>!fl)},children:Aa?"Close editor":"Edit body"})]}),jsxRuntimeExports.jsx("iframe",{sandbox:"allow-same-origin",srcDoc:qa.htmlBody,title:"Announcement HTML preview",className:"h-[480px] w-full rounded-md border border-border bg-white"})]}),Aa&&jsxRuntimeExports.jsxs("section",{className:"space-y-4 rounded-md border border-border p-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"html_body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:fl=>La(fl.target.value),rows:12,className:"font-mono text-xs"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"text_body"}),jsxRuntimeExports.jsx(Textarea,{value:Ba,onChange:fl=>Ma(fl.target.value),rows:8,className:"font-mono text-xs"})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",onClick:()=>Oa(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:Ka.isPending||Ia===qa.htmlBody&&Ba===qa.textBody,onClick:()=>Ka.mutate({htmlBody:Ia,textBody:Ba}),children:Ka.isPending?"Saving…":"Save body"})]})]}),jsxRuntimeExports.jsx(CollapsibleSection,{title:"Plain-text body",children:jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted/30 p-3 font-mono text-xs",children:qa.textBody})}),Ya.length>0&&jsxRuntimeExports.jsx(CollapsibleSection,{title:"Parsed sections",children:jsxRuntimeExports.jsx("div",{className:"space-y-3",children:Ya.map(({key:fl,items:nl})=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:fl}),jsxRuntimeExports.jsx("ul",{className:"ml-4 list-disc text-sm",children:nl.map((ol,pl)=>jsxRuntimeExports.jsx("li",{children:ol},pl))})]},fl))})}),jsxRuntimeExports.jsx(Dialog,{open:Ga,onOpenChange:Va,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Send announcement?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:["Send ",jsxRuntimeExports.jsxs("span",{className:"font-semibold",children:['"',qa.subject,'"']})," to"," ",jsxRuntimeExports.jsx("span",{className:"font-mono font-semibold",children:el??"?"})," ","recipients?"]})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"}),"This cannot be undone."]}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:"Recipients will receive an email within ~1 minute."})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Va(!1),disabled:Ja.isPending,children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:()=>Ja.mutate(),disabled:Ja.isPending,children:Ja.isPending?"Queuing…":"Send now"})]})]})})]})}function CollapsibleSection({title:es,children:$}){const[ts,is]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("section",{className:"rounded-md border border-border",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(cs=>!cs),className:"flex w-full items-center justify-between px-4 py-2 text-left text-sm font-medium hover:bg-muted/30",children:[jsxRuntimeExports.jsx("span",{children:es}),jsxRuntimeExports.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:ts?"−":"+"})]}),ts&&jsxRuntimeExports.jsx("div",{className:"border-t border-border p-4",children:$})]})}function listUsers(es={}){const $=new URLSearchParams;es.search&&$.set("search",es.search),es.limit!==void 0&&$.set("limit",String(es.limit)),es.offset!==void 0&&$.set("offset",String(es.offset));const ts=$.toString();return apiGet(`/api/superadmin/users${ts?`?${ts}`:""}`)}function getUserDetail(es){return apiGet(`/api/superadmin/users/${es}`)}function listAllOrgs(){return apiGet("/api/superadmin/orgs")}function assignUserToOrg(es,$){return apiPost(`/api/superadmin/users/${es}/assign`,$)}function removeUserFromOrg(es,$){return apiDelete(`/api/superadmin/users/${es}/orgs/${$}`)}function forceLogoutUser(es){return apiPost(`/api/superadmin/users/${es}/force-logout`,{})}function resetUserPassword(es){return apiPost(`/api/superadmin/users/${es}/reset-password`,{})}function setUserSuspended(es,$){return apiPatch(`/api/superadmin/users/${es}/suspend`,{suspended:$})}function deleteUser(es,$){return api(`/api/superadmin/users/${es}`,{method:"DELETE",body:{confirmEmail:$}})}function inviteUser(es){return apiPost("/api/superadmin/users/invite",es)}function SuperadminUsersPage(){var Ia,La,Ba,Ma;const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(""),[cs,Qr]=reactExports.useState(null),[ja,Na]=reactExports.useState(!1),Aa=qa=>{$(qa);const Fa=window.setTimeout(()=>is(qa),300);return()=>window.clearTimeout(Fa)},Oa=useQuery({queryKey:["superadmin","users",ts],queryFn:()=>listUsers({search:ts||void 0,limit:100})});return jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsxs("header",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Superadmin · Users"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Platform-level user directory. Click Manage to assign org membership, reset passwords, suspend, or delete."})]}),jsxRuntimeExports.jsx(Button,{onClick:()=>Na(!0),children:"Invite user"})]}),jsxRuntimeExports.jsxs("div",{className:"relative max-w-md",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{value:es,onChange:qa=>Aa(qa.target.value),placeholder:"Search by email…",className:"pl-9"})]}),Oa.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"}):Oa.error?jsxRuntimeExports.jsxs("p",{className:"text-sm text-destructive",children:["Failed to load: ",Oa.error.message]}):jsxRuntimeExports.jsxs("div",{className:"rounded-md border",children:[jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24 text-right",children:"Orgs"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Sessions"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Orphan org_id"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28",children:"Created"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsxs(TableBody,{children:[(Ia=Oa.data)==null?void 0:Ia.users.map(qa=>jsxRuntimeExports.jsx(UserRow,{user:qa,onManage:()=>Qr(qa.id)},qa.id)),((La=Oa.data)==null?void 0:La.users.length)===0&&jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No users."})})]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t p-2 text-xs text-muted-foreground text-right",children:["Showing ",(Ba=Oa.data)==null?void 0:Ba.users.length," of ",(Ma=Oa.data)==null?void 0:Ma.total," total"]})]}),cs&&jsxRuntimeExports.jsx(ManageUserSheet,{userId:cs,onClose:()=>Qr(null)}),jsxRuntimeExports.jsx(InviteUserDialog,{open:ja,onOpenChange:Na})]})}function InviteUserDialog({open:es,onOpenChange:$}){var La;const ts=useQueryClient(),[is,cs]=reactExports.useState(""),[Qr,ja]=reactExports.useState(""),[Na,Aa]=reactExports.useState("member"),Oa=useQuery({queryKey:["superadmin","all-orgs"],queryFn:listAllOrgs,enabled:es}),Ia=useMutation({mutationFn:()=>inviteUser({email:is,orgId:Qr||void 0,role:Qr?Na:void 0}),onSuccess:Ba=>{ue$1.success(`Invite sent to ${Ba.email}`+(Ba.assigned?` · pre-assigned as ${Ba.assigned.role}`:"")),ts.invalidateQueries({queryKey:["superadmin","users"]}),cs(""),ja(""),Aa("member"),$(!1)},onError:Ba=>{const Ma=Ba instanceof ApiError?Ba.message:String(Ba);ue$1.error(`Invite failed: ${Ma}`)}});return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Invite user"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Sends a Supabase invite email. Optionally pre-assign them to an org."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-3 py-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"invite-email",type:"email",value:is,onChange:Ba=>cs(Ba.target.value),placeholder:"user@example.com"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{children:"Pre-assign to org (optional)"}),jsxRuntimeExports.jsxs(Select,{value:Qr,onValueChange:ja,children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"None — invite only"})}),jsxRuntimeExports.jsx(SelectContent,{children:(((La=Oa.data)==null?void 0:La.orgs)??[]).map(Ba=>jsxRuntimeExports.jsx(SelectItem,{value:Ba.id,children:Ba.name},Ba.id))})]})]}),Qr&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{children:"Role"}),jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:Ba=>Aa(Ba),children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"member"})]})]})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{disabled:!is||Ia.isPending,onClick:()=>Ia.mutate(),children:Ia.isPending?"Sending…":"Send invite"})]})]})})}function UserRow({user:es,onManage:$}){return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-sm",children:es.email??"—"}),es.isSuperadmin&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:"superadmin"})]})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.orgCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.sessionCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.orphanSessionCount>0?jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"font-mono",children:es.orphanSessionCount}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"0"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:new Date(es.createdAt).toISOString().slice(0,10)}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:$,children:"Manage"})})]})}function ManageUserSheet({userId:es,onClose:$}){var fl;const ts=useQueryClient(),is=useQuery({queryKey:["superadmin","user",es],queryFn:()=>getUserDetail(es)}),cs=useQuery({queryKey:["superadmin","all-orgs"],queryFn:listAllOrgs}),[Qr,ja]=reactExports.useState(""),[Na,Aa]=reactExports.useState("member"),[Oa,Ia]=reactExports.useState(!0),La=()=>{ts.invalidateQueries({queryKey:["superadmin","users"]}),ts.invalidateQueries({queryKey:["superadmin","user",es]})},Ba=useMutation({mutationFn:()=>assignUserToOrg(es,{orgId:Qr,role:Na,claimSessions:Oa}),onSuccess:nl=>{ue$1.success(`Assigned as ${nl.role}`+(nl.claimed_sessions>0?` · claimed ${nl.claimed_sessions} orphan session${nl.claimed_sessions===1?"":"s"}`:"")),ja(""),La()},onError:nl=>{const ol=nl instanceof ApiError?nl.message:String(nl);ue$1.error(`Assign failed: ${ol}`)}}),Ma=useMutation({mutationFn:nl=>removeUserFromOrg(es,nl),onSuccess:()=>{ue$1.success("Removed from org"),La()},onError:nl=>{const ol=nl instanceof ApiError?nl.message:String(nl);ue$1.error(`Remove failed: ${ol}`)}}),qa=nl=>ol=>{const pl=ol instanceof ApiError?ol.message:String(ol);ue$1.error(`${nl} failed: ${pl}`)},Fa=useMutation({mutationFn:()=>forceLogoutUser(es),onSuccess:()=>ue$1.success("All sessions revoked"),onError:qa("Force logout")}),Ha=useMutation({mutationFn:()=>resetUserPassword(es),onSuccess:nl=>{nl.actionLink?(navigator.clipboard.writeText(nl.actionLink).catch(()=>{}),ue$1.success(`Recovery link copied for ${nl.email}`)):ue$1.success(`Recovery email sent to ${nl.email}`)},onError:qa("Reset password")}),Ka=useMutation({mutationFn:nl=>setUserSuspended(es,nl),onSuccess:nl=>{ue$1.success(nl.suspended?"User suspended":"User reinstated"),La()},onError:qa("Suspend")}),[Ga,Va]=reactExports.useState(!1),[Ja,Ya]=reactExports.useState(""),el=useMutation({mutationFn:()=>deleteUser(es,Ja),onSuccess:()=>{ue$1.success("User deleted"),Va(!1),Ya(""),ts.invalidateQueries({queryKey:["superadmin","users"]}),$()},onError:qa("Delete")}),tl=is.data,rl=((fl=cs.data)==null?void 0:fl.orgs)??[],cl=new Set((tl==null?void 0:tl.memberships.map(nl=>nl.orgId))??[]),dl=rl.filter(nl=>!cl.has(nl.id));return jsxRuntimeExports.jsxs(Sheet,{open:!0,onOpenChange:nl=>!nl&&$(),children:[jsxRuntimeExports.jsxs(SheetContent,{side:"right",className:"w-full sm:max-w-md overflow-y-auto",children:[jsxRuntimeExports.jsxs(SheetHeader,{children:[jsxRuntimeExports.jsx(SheetTitle,{className:"font-mono text-base",children:(tl==null?void 0:tl.user.email)??"Loading…"}),jsxRuntimeExports.jsx(SheetDescription,{children:tl?`${tl.sessionCounts.total} sessions, ${tl.sessionCounts.orphan} without an org`:""})]}),jsxRuntimeExports.jsxs("div",{className:"mt-6 space-y-6 px-1",children:[jsxRuntimeExports.jsxs("section",{children:[jsxRuntimeExports.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Current memberships"}),(tl==null?void 0:tl.memberships.length)===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Not a member of any org."}):jsxRuntimeExports.jsx("ul",{className:"space-y-1",children:tl==null?void 0:tl.memberships.map(nl=>jsxRuntimeExports.jsxs("li",{className:"flex items-center justify-between rounded-md border px-3 py-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"font-medium",children:nl.orgName}),jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground",children:nl.orgSlug})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",children:nl.role}),jsxRuntimeExports.jsx(Button,{size:"icon",variant:"ghost",disabled:Ma.isPending,onClick:()=>Ma.mutate(nl.orgId),"aria-label":"Remove from org",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})]},nl.orgId))})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-2 rounded-md border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"Account actions"}),(tl==null?void 0:tl.user.banned)&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",children:"Suspended"})]}),(tl==null?void 0:tl.user.lastSignInAt)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sign-in: ",new Date(tl.user.lastSignInAt).toLocaleString()]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Ha.isPending,onClick:()=>Ha.mutate(),children:Ha.isPending?"Generating…":"Reset password"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Fa.isPending,onClick:()=>Fa.mutate(),children:Fa.isPending?"Revoking…":"Force logout"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Ka.isPending,onClick:()=>Ka.mutate(!(tl!=null&&tl.user.banned)),children:Ka.isPending?"Updating…":tl!=null&&tl.user.banned?"Reinstate":"Suspend"}),jsxRuntimeExports.jsx(Button,{variant:"destructive",size:"sm",onClick:()=>Va(!0),children:"Delete user"})]})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-3 rounded-md border p-3",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"Add to org"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs(Select,{value:Qr,onValueChange:ja,children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Choose an org…"})}),jsxRuntimeExports.jsx(SelectContent,{children:dl.length===0?jsxRuntimeExports.jsx("div",{className:"p-2 text-sm text-muted-foreground",children:"No orgs available (already a member of all)."}):dl.map(nl=>jsxRuntimeExports.jsxs(SelectItem,{value:nl.id,children:[nl.name," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["(",nl.memberCount,")"]})]},nl.id))})]}),jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:nl=>Aa(nl),children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"member"})]})]}),jsxRuntimeExports.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:Oa,onChange:nl=>Ia(nl.target.checked),className:"h-4 w-4"}),"Claim ",(tl==null?void 0:tl.sessionCounts.orphan)??0," orphan session",(tl==null?void 0:tl.sessionCounts.orphan)===1?"":"s"," for this org"]}),jsxRuntimeExports.jsx(Button,{disabled:!Qr||Ba.isPending,onClick:()=>Ba.mutate(),className:"w-full",children:Ba.isPending?"Assigning…":"Assign"})]})]})]})]}),jsxRuntimeExports.jsx(Dialog,{open:Ga,onOpenChange:Va,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Delete user"}),jsxRuntimeExports.jsxs(DialogDescription,{children:["This permanently deletes the auth user and cascades all their sessions and memberships. Type"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:(tl==null?void 0:tl.user.email)??"—"})," to confirm."]})]}),jsxRuntimeExports.jsx(Input,{value:Ja,onChange:nl=>Ya(nl.target.value),placeholder:(tl==null?void 0:tl.user.email)??"",autoComplete:"off"}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Va(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{variant:"destructive",disabled:!(tl!=null&&tl.user.email)||Ja.toLowerCase()!==tl.user.email.toLowerCase()||el.isPending,onClick:()=>el.mutate(),children:el.isPending?"Deleting…":"Delete permanently"})]})]})})]})}function SuperAdminGuard({children:es}){const{profile:$,isLoading:ts}=useActiveOrg();return ts?jsxRuntimeExports.jsx("div",{className:"flex h-full items-center justify-center p-8",children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 w-64",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"})]})}):$!=null&&$.isSuperadmin?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:es??jsxRuntimeExports.jsx(Outlet,{})}):jsxRuntimeExports.jsx(Navigate,{to:"/dashboard",replace:!0})}const SLUG_REGEX=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function slugify(es){return es.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function NewOrgPage(){const es=useNavigate(),$=useSetActiveOrg(),[ts,is]=reactExports.useState(""),[cs,Qr]=reactExports.useState(""),[ja,Na]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState(null),[Ia,La]=reactExports.useState(null),Ba=useMutation({mutationFn:Ha=>createOrg(Ha),onSuccess:async Ha=>{try{await $.mutateAsync(Ha.id)}catch{}ue$1.success(`Created ${Ha.name}`),es("/admin",{replace:!0})},onError:Ha=>{if(Ha instanceof ApiError&&Ha.code==="ORG_SLUG_TAKEN"){const Ka=cs.replace(/-\d+$/,""),Ga=(()=>{const Ja=cs.match(/-(\d+)$/);return Ja?Number(Ja[1])+1:2})(),Va=`${Ka}-${Ga}`.slice(0,40);La(Va),Oa("That slug is already taken.");return}if(Ha instanceof ApiError&&Ha.code==="VALIDATION_ERROR"){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Ha instanceof Error?Ha.message:"Failed to create organization")}});function Ma(Ha){is(Ha),ja||Qr(slugify(Ha))}function qa(Ha){Ha.preventDefault(),Oa(null),La(null);const Ka=ts.trim(),Ga=cs.trim();if(!Ka){Oa("Name is required.");return}if(Ka.length>100){Oa("Name must be 100 characters or fewer.");return}if(!SLUG_REGEX.test(Ga)){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Ba.mutate({name:Ka,slug:Ga})}function Fa(){Ia&&(Qr(Ia),Na(!0),La(null),Oa(null))}return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-12 bg-background",children:jsxRuntimeExports.jsxs("div",{className:"w-full max-w-md space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer -ml-2",children:jsxRuntimeExports.jsxs(Link,{to:"/dashboard",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to dashboard"]})}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(Building2,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"New organization"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Create organization"}),jsxRuntimeExports.jsx(CardDescription,{children:"You'll be the owner. Your existing personal sessions stay where they are — only sessions captured after you switch to this org will be attributed to it."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("form",{onSubmit:qa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"org-name",value:ts,onChange:Ha=>Ma(Ha.target.value),placeholder:"Acme Inc.",required:!0,maxLength:100,disabled:Ba.isPending,autoFocus:!0})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"org-slug",value:cs,onChange:Ha=>{Qr(Ha.target.value),Na(!0)},placeholder:"acme",required:!0,disabled:Ba.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs and CLI commands."})]}),Aa&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive space-y-1",children:[jsxRuntimeExports.jsx("div",{children:Aa}),Ia&&jsxRuntimeExports.jsxs("div",{children:["Try"," ",jsxRuntimeExports.jsx("button",{type:"button",onClick:Fa,className:"font-mono underline cursor-pointer",children:Ia}),"?"]})]}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ba.isPending,className:"w-full cursor-pointer",children:Ba.isPending?"Creating…":"Create organization"})]})})]})]})})}function AcceptInvitationPage(){const{token:es}=useParams(),{session:$,loading:ts}=useAuth(),is=useNavigate(),cs=useSetActiveOrg(),Qr=useQuery({queryKey:["invitation-preview",es,($==null?void 0:$.user.id)??null],queryFn:()=>previewInvitation(es),enabled:!!es&&!ts,retry:!1}),[ja,Na]=reactExports.useState(!1),Aa=useMutation({mutationFn:()=>{var La;return acceptInvitation({token:es,acknowledgedSessionCount:((La=Qr.data)==null?void 0:La.sessionCount)??0})},onMutate:()=>{Na(!0)},onSuccess:async La=>{var Ba;try{await cs.mutateAsync(La.orgId)}catch{}ue$1.success(`Joined ${((Ba=Qr.data)==null?void 0:Ba.orgName)??"the organization"}`),is("/admin",{replace:!0})},onError:async La=>{if(Na(!1),La instanceof ApiError){if(La.code==="ALREADY_MEMBER"){ue$1.success("You're already a member. Taking you there now."),is("/admin",{replace:!0});return}if(La.code==="INVITE_EMAIL_MISMATCH"){ue$1.error("This invitation was sent to a different email address. Sign out and sign in with the correct email to accept.");return}if(La.code==="SESSION_COUNT_CHANGED"){await Qr.refetch(),ue$1.error("Your session count changed since you reviewed the consent notice. Please re-confirm.");return}if(La.code==="INVITE_GONE"||La.code==="INVITE_NOT_FOUND"){ue$1.error("This invitation is no longer valid.");return}}ue$1.error(La instanceof Error?La.message:"Failed to accept invitation")}}),Oa=Qr.error,Ia=Oa instanceof ApiError&&(Oa.code==="INVITE_GONE"||Oa.code==="INVITE_NOT_FOUND"||Oa.statusCode===410||Oa.statusCode===404);return reactExports.useEffect(()=>{Aa.isSuccess&&Na(!1)},[Aa.isSuccess]),jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-12 bg-background",children:jsxRuntimeExports.jsx("div",{className:"w-full max-w-md",children:es?ts||Qr.isLoading?jsxRuntimeExports.jsx(LoadingCard$1,{}):Ia?jsxRuntimeExports.jsx(GoneCard,{message:"This invitation is no longer valid. It may have been revoked, expired, or already accepted."}):Oa?jsxRuntimeExports.jsx(ErrorCard,{message:Oa.message}):Qr.data?jsxRuntimeExports.jsx(InvitationCard,{preview:Qr.data,token:es,isSignedIn:!!$,accepting:ja||Aa.isPending,onAccept:()=>Aa.mutate()}):jsxRuntimeExports.jsx(LoadingCard$1,{}):jsxRuntimeExports.jsx(GoneCard,{message:"Missing invitation token in URL."})})})}function LoadingCard$1(){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48 mt-2"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-full mt-2"})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"})]})]})}function GoneCard({message:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Invitation unavailable"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-xl font-mono",children:"This invitation is no longer valid"}),jsxRuntimeExports.jsx(CardDescription,{children:es})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"w-full cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/",children:"Back home"})})})]})}function ErrorCard({message:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Couldn't load invitation"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-xl font-mono",children:"Something went wrong"}),jsxRuntimeExports.jsx(CardDescription,{children:es})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"w-full cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/",children:"Back home"})})})]})}function InvitationCard({preview:es,token:$,isSignedIn:ts,accepting:is,onAccept:cs}){const Qr=`/invite/${encodeURIComponent($)}`;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(Building2,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"Organization invitation"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:es.orgName}),jsxRuntimeExports.jsx(CardDescription,{className:"space-y-2",children:jsxRuntimeExports.jsx("span",{className:"block",children:es.inviterName?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("strong",{children:es.inviterName})," invited you to join"," ",jsxRuntimeExports.jsx("strong",{children:es.orgName})," as"," ",jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize ml-1",children:es.role})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["You've been invited to join ",jsxRuntimeExports.jsx("strong",{children:es.orgName})," ","as"," ",jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize ml-1",children:es.role})]})})})]}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:ts?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ConsentNotice,{orgName:es.orgName,sessionCount:es.sessionCount}),jsxRuntimeExports.jsxs(Button,{type:"button",onClick:cs,disabled:is,className:"w-full cursor-pointer",children:[jsxRuntimeExports.jsx(UserCheck,{className:"mr-2 h-4 w-4"}),is?"Joining…":`Accept and join ${es.orgName}`]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border bg-muted/50 px-4 py-3 text-sm",children:"Sign in or sign up with the email this invitation was sent to, and we'll bring you back here to accept."}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"default",className:"flex-1 cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:`/login?next=${encodeURIComponent(Qr)}`,children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"flex-1 cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:`/signup?next=${encodeURIComponent(Qr)}`,children:"Sign up"})})]})]})})]})}function ConsentNotice({orgName:es,sessionCount:$}){return $===null?jsxRuntimeExports.jsx("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(ShieldAlert,{className:"h-4 w-4 mt-0.5 shrink-0"}),jsxRuntimeExports.jsx("div",{children:"You're signed in with a different email than this invitation was sent to. Sign out and sign in with the matching email to accept."})]})}):$===0?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/40 px-4 py-3 text-sm text-muted-foreground",children:["Accepting will give you ",es," access. You don't have any existing sessions, so nothing will be retroactively shared."]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border bg-muted/40 px-4 py-3 text-sm",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(ShieldAlert,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:["By accepting, all of your existing personal RuleMetric sessions"," (","at least"," ",jsxRuntimeExports.jsx("strong",{className:"font-mono tabular-nums",children:$}),$===1?" session":" sessions"," as of now",") will become visible to ",jsxRuntimeExports.jsx("strong",{children:es})," admins."]})]})})}const API_BASE="";async function fetchUnsubscribePreview(es){const $=await fetch(`${API_BASE}/api/unsubscribe/${encodeURIComponent(es)}`);if($.status===404){const ts=new Error("invalid_token");throw ts.statusCode=404,ts}if(!$.ok)throw new Error(`HTTP ${$.status}`);return await $.json()}async function postUnsubscribe(es){const $=await fetch(`${API_BASE}/api/unsubscribe/${encodeURIComponent(es)}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!$.ok){const ts=new Error(`HTTP ${$.status}`);throw ts.statusCode=$.status,ts}}function UnsubscribePage(){const{token:es}=useParams(),[$,ts]=reactExports.useState(!1),is=useQuery({queryKey:["unsubscribe-preview",es],queryFn:()=>fetchUnsubscribePreview(es),enabled:!!es,retry:!1}),cs=useMutation({mutationFn:()=>postUnsubscribe(es),onSuccess:()=>ts(!0)});return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4 py-12",children:jsxRuntimeExports.jsx("div",{className:"w-full max-w-md",children:es?is.isLoading?jsxRuntimeExports.jsx(LoadingCard,{}):is.error?jsxRuntimeExports.jsx(InvalidCard,{}):is.data?$?jsxRuntimeExports.jsx(UnsubscribedCard,{justConfirmed:!0}):is.data.alreadyUnsubscribed?jsxRuntimeExports.jsx(UnsubscribedCard,{}):jsxRuntimeExports.jsx(ConfirmCard,{onConfirm:()=>cs.mutate(),pending:cs.isPending,error:cs.error?"Failed to unsubscribe. Please try again.":null}):jsxRuntimeExports.jsx(LoadingCard,{}):jsxRuntimeExports.jsx(InvalidCard,{})})})}function LoadingCard(){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"}),jsxRuntimeExports.jsx(CardTitle,{className:"text-lg",children:"Loading…"})]})})})}function InvalidCard(){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Link invalid"})]}),jsxRuntimeExports.jsx(CardTitle,{children:"This unsubscribe link is invalid or expired"}),jsxRuntimeExports.jsx(CardDescription,{children:"The unsubscribe link you used isn't recognized. It may have been truncated by your email client, or the preference may have been reset."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Link,{to:"/",className:"text-sm text-primary underline",children:"Return to RuleMetric"})})]})}function ConfirmCard({onConfirm:es,pending:$,error:ts}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Bell,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"Product announcements"})]}),jsxRuntimeExports.jsx(CardTitle,{children:"Unsubscribe from RuleMetric product announcements?"}),jsxRuntimeExports.jsx(CardDescription,{children:"You won't receive product update emails from us anymore. You'll still receive transactional emails like sign-in links, invitations, and security alerts."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx(Button,{onClick:es,disabled:$,className:"w-full",variant:"destructive",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Unsubscribing…"]}):"Confirm unsubscribe"}),ts?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",role:"alert",children:ts}):null,jsxRuntimeExports.jsx(Link,{to:"/",className:"block text-center text-sm text-muted-foreground underline",children:"Cancel"})]})]})}function UnsubscribedCard({justConfirmed:es=!1}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-5 w-5 text-teal-500"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-teal-600",children:"Unsubscribed"})]}),jsxRuntimeExports.jsx(CardTitle,{children:es?"You've been unsubscribed":"You're already unsubscribed"}),jsxRuntimeExports.jsx(CardDescription,{children:es?"You'll still receive transactional emails (sign-in, invitations, security alerts).":"You're already off the product-announcements list. You'll still receive transactional emails (sign-in, invitations, security alerts)."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Link,{to:"/",className:"text-sm text-primary underline",children:"Return to RuleMetric"})})]})}function NotFoundPage(){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center gap-4",children:[jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold",children:"404"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),jsxRuntimeExports.jsx(Button,{asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/dashboard",children:"Go to Dashboard"})})]})}const queryClient=new QueryClient({defaultOptions:{queries:{staleTime:3e4,retry:1}}});function App(){const es=useRunsEnabled();return jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports.jsxs(AuthProvider,{children:[jsxRuntimeExports.jsx(BrowserRouter,{children:jsxRuntimeExports.jsx(PostHogProvider,{children:jsxRuntimeExports.jsxs(Routes,{children:[jsxRuntimeExports.jsx(Route,{path:"/",element:jsxRuntimeExports.jsx(LandingPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/agent-memory",element:jsxRuntimeExports.jsx(AgentMemoryPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/play/token-triage",element:jsxRuntimeExports.jsx(TokenTriagePage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instruction-audit",element:jsxRuntimeExports.jsx(InstructionAuditPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/login",element:jsxRuntimeExports.jsx(LoginPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/signup",element:jsxRuntimeExports.jsx(SignupPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/auth/confirm",element:jsxRuntimeExports.jsx(ConfirmPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/auth/extension",element:jsxRuntimeExports.jsx(ExtensionAuthPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/forgot-password",element:jsxRuntimeExports.jsx(ForgotPasswordPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/reset-password",element:jsxRuntimeExports.jsx(ResetPasswordPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/invite/:token",element:jsxRuntimeExports.jsx(AcceptInvitationPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/unsubscribe/:token",element:jsxRuntimeExports.jsx(UnsubscribePage,{})}),jsxRuntimeExports.jsx(Route,{path:"/docs",element:jsxRuntimeExports.jsx(DocsRoute,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(AuthGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/orgs/new",element:jsxRuntimeExports.jsx(NewOrgPage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(RootLayout,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/dashboard",element:jsxRuntimeExports.jsx(DashboardPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/connect",element:jsxRuntimeExports.jsx(ConnectPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/sessions",element:jsxRuntimeExports.jsx(SessionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/sessions/:id",element:jsxRuntimeExports.jsx(SessionDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/projects",element:jsxRuntimeExports.jsx(ProjectsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/projects/:id",element:jsxRuntimeExports.jsx(ProjectDetailPage,{})}),es,jsxRuntimeExports.jsx(Route,{path:"/eval-targets",element:jsxRuntimeExports.jsx(EvalTargetsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/eval-targets/:id",element:jsxRuntimeExports.jsx(EvalTargetDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/insights",element:jsxRuntimeExports.jsx(InsightsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/insights/:id",element:jsxRuntimeExports.jsx(InsightsDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/memories",element:jsxRuntimeExports.jsx(MemoriesListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/memories/:id",element:jsxRuntimeExports.jsx(MemoryDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/skills",element:jsxRuntimeExports.jsx(SkillsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/catalog/public",element:jsxRuntimeExports.jsx(PublicCatalogPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/catalog/public/:id",element:jsxRuntimeExports.jsx(PublicSkillDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/suggestions",element:jsxRuntimeExports.jsx(SuggestionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/experiments",element:jsxRuntimeExports.jsx(ExperimentsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/loop",element:jsxRuntimeExports.jsx(LoopPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/settings",element:jsxRuntimeExports.jsx(SettingsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/usage",element:jsxRuntimeExports.jsx(UsagePage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(SuperAdminGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/superadmin",element:jsxRuntimeExports.jsx(Navigate,{to:"/superadmin/users",replace:!0})}),jsxRuntimeExports.jsx(Route,{path:"/superadmin/users",element:jsxRuntimeExports.jsx(SuperadminUsersPage,{})})]}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(OrgAdminGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/admin",element:jsxRuntimeExports.jsx(AdminOverviewPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/members",element:jsxRuntimeExports.jsx(AdminMembersPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/members/invitations",element:jsxRuntimeExports.jsx(AdminInvitationsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/teams",element:jsxRuntimeExports.jsx(AdminTeamsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/teams/:teamSlug",element:jsxRuntimeExports.jsx(TeamDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/settings",element:jsxRuntimeExports.jsx(AdminSettingsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/research",element:jsxRuntimeExports.jsx(AdminResearchPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/announcements",element:jsxRuntimeExports.jsx(AdminAnnouncementsPage,{})})]})]})]}),jsxRuntimeExports.jsx(Route,{path:"*",element:jsxRuntimeExports.jsx(NotFoundPage,{})})]})})}),jsxRuntimeExports.jsx(Toaster,{})]})})})}"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js").catch(es=>{console.error("Service worker registration failed:",es)})});clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(App,{})}));
|