@suveren/gateway 0.6.1 → 0.6.2

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.
@@ -48,7 +48,7 @@ Error generating stack: `+o.message+`
48
48
  * @license MIT
49
49
  */var Ac="popstate";function $c(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function jh(e={}){function t(r,a){var d;let o=(d=a.state)==null?void 0:d.masked,{pathname:i,search:l,hash:c}=o||r.location;return fi("",{pathname:i,search:l,hash:c},a.state&&a.state.usr||null,a.state&&a.state.key||"default",o?{pathname:r.location.pathname,search:r.location.search,hash:r.location.hash}:void 0)}function n(r,a){return typeof a=="string"?a:ra(a)}return bh(t,n,null,e)}function ve(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function wt(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function kh(){return Math.random().toString(36).substring(2,10)}function Lc(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.unstable_mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function fi(e,t,n=null,r,a){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?mr(t):t,state:n,key:t&&t.key||r||kh(),unstable_mask:a}}function ra({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function mr(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function bh(e,t,n,r={}){let{window:a=document.defaultView,v5Compat:o=!1}=r,i=a.history,l="POP",c=null,d=f();d==null&&(d=0,i.replaceState({...i.state,idx:d},""));function f(){return(i.state||{idx:null}).idx}function g(){l="POP";let j=f(),h=j==null?null:j-d;d=j,c&&c({action:l,location:v.location,delta:h})}function p(j,h){l="PUSH";let m=$c(j)?j:fi(v.location,j,h);d=f()+1;let y=Lc(m,d),S=v.createHref(m.unstable_mask||m);try{i.pushState(y,"",S)}catch(b){if(b instanceof DOMException&&b.name==="DataCloneError")throw b;a.location.assign(S)}o&&c&&c({action:l,location:v.location,delta:1})}function x(j,h){l="REPLACE";let m=$c(j)?j:fi(v.location,j,h);d=f();let y=Lc(m,d),S=v.createHref(m.unstable_mask||m);i.replaceState(y,"",S),o&&c&&c({action:l,location:v.location,delta:0})}function w(j){return Ch(j)}let v={get action(){return l},get location(){return e(a,i)},listen(j){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(Ac,g),c=j,()=>{a.removeEventListener(Ac,g),c=null}},createHref(j){return t(a,j)},createURL:w,encodeLocation(j){let h=w(j);return{pathname:h.pathname,search:h.search,hash:h.hash}},push:p,replace:x,go(j){return i.go(j)}};return v}function Ch(e,t=!1){let n="http://localhost";typeof window<"u"&&(n=window.location.origin!=="null"?window.location.origin:window.location.href),ve(n,"No window.location.(origin|href) available to create URL");let r=typeof e=="string"?e:ra(e);return r=r.replace(/ $/,"%20"),!t&&r.startsWith("//")&&(r=n+r),new URL(r,n)}function mf(e,t,n="/"){return Nh(e,t,n,!1)}function Nh(e,t,n,r){let a=typeof t=="string"?mr(t):t,o=Gt(a.pathname||"/",n);if(o==null)return null;let i=pf(e);Eh(i);let l=null;for(let c=0;l==null&&c<i.length;++c){let d=Fh(o);l=Lh(i[c],d,r)}return l}function pf(e,t=[],n=[],r="",a=!1){let o=(i,l,c=a,d)=>{let f={relativePath:d===void 0?i.path||"":d,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};if(f.relativePath.startsWith("/")){if(!f.relativePath.startsWith(r)&&c)return;ve(f.relativePath.startsWith(r),`Absolute route path "${f.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),f.relativePath=f.relativePath.slice(r.length)}let g=Mt([r,f.relativePath]),p=n.concat(f);i.children&&i.children.length>0&&(ve(i.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${g}".`),pf(i.children,t,p,g,c)),!(i.path==null&&!i.index)&&t.push({path:g,score:Ah(g,i.index),routesMeta:p})};return e.forEach((i,l)=>{var c;if(i.path===""||!((c=i.path)!=null&&c.includes("?")))o(i,l);else for(let d of hf(i.path))o(i,l,!0,d)}),t}function hf(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),o=n.replace(/\?$/,"");if(r.length===0)return a?[o,""]:[o];let i=hf(r.join("/")),l=[];return l.push(...i.map(c=>c===""?o:[o,c].join("/"))),a&&l.push(...i),l.map(c=>e.startsWith("/")&&c===""?"/":c)}function Eh(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:$h(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}var Th=/^:[\w-]+$/,zh=3,Ih=2,Ph=1,Rh=10,_h=-2,Mc=e=>e==="*";function Ah(e,t){let n=e.split("/"),r=n.length;return n.some(Mc)&&(r+=_h),t&&(r+=Ih),n.filter(a=>!Mc(a)).reduce((a,o)=>a+(Th.test(o)?zh:o===""?Ph:Rh),r)}function $h(e,t){return e.length===t.length&&e.slice(0,-1).every((r,a)=>r===t[a])?e[e.length-1]-t[t.length-1]:0}function Lh(e,t,n=!1){let{routesMeta:r}=e,a={},o="/",i=[];for(let l=0;l<r.length;++l){let c=r[l],d=l===r.length-1,f=o==="/"?t:t.slice(o.length)||"/",g=gs({path:c.relativePath,caseSensitive:c.caseSensitive,end:d},f),p=c.route;if(!g&&d&&n&&!r[r.length-1].route.index&&(g=gs({path:c.relativePath,caseSensitive:c.caseSensitive,end:!1},f)),!g)return null;Object.assign(a,g.params),i.push({params:a,pathname:Mt([o,g.pathname]),pathnameBase:Uh(Mt([o,g.pathnameBase])),route:p}),g.pathnameBase!=="/"&&(o=Mt([o,g.pathnameBase]))}return i}function gs(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Mh(e.path,e.caseSensitive,e.end),a=t.match(n);if(!a)return null;let o=a[0],i=o.replace(/(.)\/+$/,"$1"),l=a.slice(1);return{params:r.reduce((d,{paramName:f,isOptional:g},p)=>{if(f==="*"){let w=l[p]||"";i=o.slice(0,o.length-w.length).replace(/(.)\/+$/,"$1")}const x=l[p];return g&&!x?d[f]=void 0:d[f]=(x||"").replace(/%2F/g,"/"),d},{}),pathname:o,pathnameBase:i,pattern:e}}function Mh(e,t=!1,n=!0){wt(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let r=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(i,l,c,d,f)=>{if(r.push({paramName:l,isOptional:c!=null}),c){let g=f.charAt(d+i.length);return g&&g!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return e.endsWith("*")?(r.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function Fh(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return wt(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Gt(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}var Oh=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function Bh(e,t="/"){let{pathname:n,search:r="",hash:a=""}=typeof e=="string"?mr(e):e,o;return n?(n=n.replace(/\/\/+/g,"/"),n.startsWith("/")?o=Fc(n.substring(1),"/"):o=Fc(n,t)):o=t,{pathname:o,search:Wh(r),hash:Hh(a)}}function Fc(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function fo(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function Dh(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function hl(e){let t=Dh(e);return t.map((n,r)=>r===t.length-1?n.pathname:n.pathnameBase)}function $s(e,t,n,r=!1){let a;typeof e=="string"?a=mr(e):(a={...e},ve(!a.pathname||!a.pathname.includes("?"),fo("?","pathname","search",a)),ve(!a.pathname||!a.pathname.includes("#"),fo("#","pathname","hash",a)),ve(!a.search||!a.search.includes("#"),fo("#","search","hash",a)));let o=e===""||a.pathname==="",i=o?"/":a.pathname,l;if(i==null)l=n;else{let g=t.length-1;if(!r&&i.startsWith("..")){let p=i.split("/");for(;p[0]==="..";)p.shift(),g-=1;a.pathname=p.join("/")}l=g>=0?t[g]:"/"}let c=Bh(a,l),d=i&&i!=="/"&&i.endsWith("/"),f=(o||i===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||f)&&(c.pathname+="/"),c}var Mt=e=>e.join("/").replace(/\/\/+/g,"/"),Uh=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Wh=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Hh=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e,Vh=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||"",this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function Kh(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function Gh(e){return e.map(t=>t.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var gf=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function yf(e,t){let n=e;if(typeof n!="string"||!Oh.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,a=!1;if(gf)try{let o=new URL(window.location.href),i=n.startsWith("//")?new URL(o.protocol+n):new URL(n),l=Gt(i.pathname,t);i.origin===o.origin&&l!=null?n=l+i.search+i.hash:a=!0}catch{wt(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:a,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var vf=["POST","PUT","PATCH","DELETE"];new Set(vf);var Yh=["GET",...vf];new Set(Yh);var pr=u.createContext(null);pr.displayName="DataRouter";var Ls=u.createContext(null);Ls.displayName="DataRouterState";var Qh=u.createContext(!1),xf=u.createContext({isTransitioning:!1});xf.displayName="ViewTransition";var Jh=u.createContext(new Map);Jh.displayName="Fetchers";var Xh=u.createContext(null);Xh.displayName="Await";var dt=u.createContext(null);dt.displayName="Navigation";var ca=u.createContext(null);ca.displayName="Location";var zt=u.createContext({outlet:null,matches:[],isDataRoute:!1});zt.displayName="Route";var gl=u.createContext(null);gl.displayName="RouteError";var wf="REACT_ROUTER_ERROR",qh="REDIRECT",Zh="ROUTE_ERROR_RESPONSE";function eg(e){if(e.startsWith(`${wf}:${qh}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.location=="string"&&typeof t.reloadDocument=="boolean"&&typeof t.replace=="boolean")return t}catch{}}function tg(e){if(e.startsWith(`${wf}:${Zh}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new Vh(t.status,t.statusText,t.data)}catch{}}function ng(e,{relative:t}={}){ve(hr(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:r}=u.useContext(dt),{hash:a,pathname:o,search:i}=ua(e,{relative:t}),l=o;return n!=="/"&&(l=o==="/"?n:Mt([n,o])),r.createHref({pathname:l,search:i,hash:a})}function hr(){return u.useContext(ca)!=null}function St(){return ve(hr(),"useLocation() may be used only in the context of a <Router> component."),u.useContext(ca).location}var Sf="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function jf(e){u.useContext(dt).static||u.useLayoutEffect(e)}function Qt(){let{isDataRoute:e}=u.useContext(zt);return e?yg():rg()}function rg(){ve(hr(),"useNavigate() may be used only in the context of a <Router> component.");let e=u.useContext(pr),{basename:t,navigator:n}=u.useContext(dt),{matches:r}=u.useContext(zt),{pathname:a}=St(),o=JSON.stringify(hl(r)),i=u.useRef(!1);return jf(()=>{i.current=!0}),u.useCallback((c,d={})=>{if(wt(i.current,Sf),!i.current)return;if(typeof c=="number"){n.go(c);return}let f=$s(c,JSON.parse(o),a,d.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:Mt([t,f.pathname])),(d.replace?n.replace:n.push)(f,d.state,d)},[t,n,o,a,e])}var ag=u.createContext(null);function sg(e){let t=u.useContext(zt).outlet;return u.useMemo(()=>t&&u.createElement(ag.Provider,{value:e},t),[t,e])}function ua(e,{relative:t}={}){let{matches:n}=u.useContext(zt),{pathname:r}=St(),a=JSON.stringify(hl(n));return u.useMemo(()=>$s(e,JSON.parse(a),r,t==="path"),[e,a,r,t])}function og(e,t){return kf(e,t)}function kf(e,t,n){var j;ve(hr(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:r}=u.useContext(dt),{matches:a}=u.useContext(zt),o=a[a.length-1],i=o?o.params:{},l=o?o.pathname:"/",c=o?o.pathnameBase:"/",d=o&&o.route;{let h=d&&d.path||"";Cf(l,!d||h.endsWith("*")||h.endsWith("*?"),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${l}" (under <Route path="${h}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
50
50
 
51
- Please change the parent <Route path="${h}"> to <Route path="${h==="/"?"*":`${h}/*`}">.`)}let f=St(),g;if(t){let h=typeof t=="string"?mr(t):t;ve(c==="/"||((j=h.pathname)==null?void 0:j.startsWith(c)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${h.pathname}" was given in the \`location\` prop.`),g=h}else g=f;let p=g.pathname||"/",x=p;if(c!=="/"){let h=c.replace(/^\//,"").split("/");x="/"+p.replace(/^\//,"").split("/").slice(h.length).join("/")}let w=mf(e,{pathname:x});wt(d||w!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),wt(w==null||w[w.length-1].route.element!==void 0||w[w.length-1].route.Component!==void 0||w[w.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let v=dg(w&&w.map(h=>Object.assign({},h,{params:Object.assign({},i,h.params),pathname:Mt([c,r.encodeLocation?r.encodeLocation(h.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:h.pathname]),pathnameBase:h.pathnameBase==="/"?c:Mt([c,r.encodeLocation?r.encodeLocation(h.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:h.pathnameBase])})),a,n);return t&&v?u.createElement(ca.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...g},navigationType:"POP"}},v):v}function ig(){let e=gg(),t=Kh(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",a={padding:"0.5rem",backgroundColor:r},o={padding:"2px 4px",backgroundColor:r},i=null;return console.error("Error handled by React Router default ErrorBoundary:",e),i=u.createElement(u.Fragment,null,u.createElement("p",null,"💿 Hey developer 👋"),u.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",u.createElement("code",{style:o},"ErrorBoundary")," or"," ",u.createElement("code",{style:o},"errorElement")," prop on your route.")),u.createElement(u.Fragment,null,u.createElement("h2",null,"Unexpected Application Error!"),u.createElement("h3",{style:{fontStyle:"italic"}},t),n?u.createElement("pre",{style:a},n):null,i)}var lg=u.createElement(ig,null),bf=class extends u.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=tg(e.digest);n&&(e=n)}let t=e!==void 0?u.createElement(zt.Provider,{value:this.props.routeContext},u.createElement(gl.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?u.createElement(cg,{error:e},t):t}};bf.contextType=Qh;var mo=new WeakMap;function cg({children:e,error:t}){let{basename:n}=u.useContext(dt);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=eg(t.digest);if(r){let a=mo.get(t);if(a)throw a;let o=yf(r.location,n);if(gf&&!mo.get(t))if(o.isExternal||r.reloadDocument)window.location.href=o.absoluteURL||o.to;else{const i=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(o.to,{replace:r.replace}));throw mo.set(t,i),i}return u.createElement("meta",{httpEquiv:"refresh",content:`0;url=${o.absoluteURL||o.to}`})}}return e}function ug({routeContext:e,match:t,children:n}){let r=u.useContext(pr);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),u.createElement(zt.Provider,{value:e},n)}function dg(e,t=[],n){let r=n==null?void 0:n.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let a=e,o=r==null?void 0:r.errors;if(o!=null){let f=a.findIndex(g=>g.route.id&&(o==null?void 0:o[g.route.id])!==void 0);ve(f>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),a=a.slice(0,Math.min(a.length,f+1))}let i=!1,l=-1;if(n&&r){i=r.renderFallback;for(let f=0;f<a.length;f++){let g=a[f];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(l=f),g.route.id){let{loaderData:p,errors:x}=r,w=g.route.loader&&!p.hasOwnProperty(g.route.id)&&(!x||x[g.route.id]===void 0);if(g.route.lazy||w){n.isStatic&&(i=!0),l>=0?a=a.slice(0,l+1):a=[a[0]];break}}}}let c=n==null?void 0:n.onError,d=r&&c?(f,g)=>{var p,x;c(f,{location:r.location,params:((x=(p=r.matches)==null?void 0:p[0])==null?void 0:x.params)??{},unstable_pattern:Gh(r.matches),errorInfo:g})}:void 0;return a.reduceRight((f,g,p)=>{let x,w=!1,v=null,j=null;r&&(x=o&&g.route.id?o[g.route.id]:void 0,v=g.route.errorElement||lg,i&&(l<0&&p===0?(Cf("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),w=!0,j=null):l===p&&(w=!0,j=g.route.hydrateFallbackElement||null)));let h=t.concat(a.slice(0,p+1)),m=()=>{let y;return x?y=v:w?y=j:g.route.Component?y=u.createElement(g.route.Component,null):g.route.element?y=g.route.element:y=f,u.createElement(ug,{match:g,routeContext:{outlet:f,matches:h,isDataRoute:r!=null},children:y})};return r&&(g.route.ErrorBoundary||g.route.errorElement||p===0)?u.createElement(bf,{location:r.location,revalidation:r.revalidation,component:v,error:x,children:m(),routeContext:{outlet:null,matches:h,isDataRoute:!0},onError:d}):m()},null)}function yl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function fg(e){let t=u.useContext(pr);return ve(t,yl(e)),t}function mg(e){let t=u.useContext(Ls);return ve(t,yl(e)),t}function pg(e){let t=u.useContext(zt);return ve(t,yl(e)),t}function vl(e){let t=pg(e),n=t.matches[t.matches.length-1];return ve(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function hg(){return vl("useRouteId")}function gg(){var r;let e=u.useContext(gl),t=mg("useRouteError"),n=vl("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function yg(){let{router:e}=fg("useNavigate"),t=vl("useNavigate"),n=u.useRef(!1);return jf(()=>{n.current=!0}),u.useCallback(async(a,o={})=>{wt(n.current,Sf),n.current&&(typeof a=="number"?await e.navigate(a):await e.navigate(a,{fromRouteId:t,...o}))},[e,t])}var Oc={};function Cf(e,t,n){!t&&!Oc[e]&&(Oc[e]=!0,wt(!1,n))}u.memo(vg);function vg({routes:e,future:t,state:n,isStatic:r,onError:a}){return kf(e,void 0,{state:n,isStatic:r,onError:a})}function Zt({to:e,replace:t,state:n,relative:r}){ve(hr(),"<Navigate> may be used only in the context of a <Router> component.");let{static:a}=u.useContext(dt);wt(!a,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:o}=u.useContext(zt),{pathname:i}=St(),l=Qt(),c=$s(e,hl(o),i,r==="path"),d=JSON.stringify(c);return u.useEffect(()=>{l(JSON.parse(d),{replace:t,state:n,relative:r})},[l,d,r,t,n]),null}function xg(e){return sg(e.context)}function Re(e){ve(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function wg({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:a,static:o=!1,unstable_useTransitions:i}){ve(!hr(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),c=u.useMemo(()=>({basename:l,navigator:a,static:o,unstable_useTransitions:i,future:{}}),[l,a,o,i]);typeof n=="string"&&(n=mr(n));let{pathname:d="/",search:f="",hash:g="",state:p=null,key:x="default",unstable_mask:w}=n,v=u.useMemo(()=>{let j=Gt(d,l);return j==null?null:{location:{pathname:j,search:f,hash:g,state:p,key:x,unstable_mask:w},navigationType:r}},[l,d,f,g,p,x,r,w]);return wt(v!=null,`<Router basename="${l}"> is not able to match the URL "${d}${f}${g}" because it does not start with the basename, so the <Router> won't render anything.`),v==null?null:u.createElement(dt.Provider,{value:c},u.createElement(ca.Provider,{children:t,value:v}))}function Sg({children:e,location:t}){return og(mi(e),t)}function mi(e,t=[]){let n=[];return u.Children.forEach(e,(r,a)=>{if(!u.isValidElement(r))return;let o=[...t,a];if(r.type===u.Fragment){n.push.apply(n,mi(r.props.children,o));return}ve(r.type===Re,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),ve(!r.props.index||!r.props.children,"An index route cannot have child routes.");let i={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(i.children=mi(r.props.children,o)),n.push(i)}),n}var Wa="get",Ha="application/x-www-form-urlencoded";function Ms(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function jg(e){return Ms(e)&&e.tagName.toLowerCase()==="button"}function kg(e){return Ms(e)&&e.tagName.toLowerCase()==="form"}function bg(e){return Ms(e)&&e.tagName.toLowerCase()==="input"}function Cg(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Ng(e,t){return e.button===0&&(!t||t==="_self")&&!Cg(e)}function pi(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function Eg(e,t){let n=pi(e);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(o=>{n.append(a,o)})}),n}var Ta=null;function Tg(){if(Ta===null)try{new FormData(document.createElement("form"),0),Ta=!1}catch{Ta=!0}return Ta}var zg=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function po(e){return e!=null&&!zg.has(e)?(wt(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Ha}"`),null):e}function Ig(e,t){let n,r,a,o,i;if(kg(e)){let l=e.getAttribute("action");r=l?Gt(l,t):null,n=e.getAttribute("method")||Wa,a=po(e.getAttribute("enctype"))||Ha,o=new FormData(e)}else if(jg(e)||bg(e)&&(e.type==="submit"||e.type==="image")){let l=e.form;if(l==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let c=e.getAttribute("formaction")||l.getAttribute("action");if(r=c?Gt(c,t):null,n=e.getAttribute("formmethod")||l.getAttribute("method")||Wa,a=po(e.getAttribute("formenctype"))||po(l.getAttribute("enctype"))||Ha,o=new FormData(l,e),!Tg()){let{name:d,type:f,value:g}=e;if(f==="image"){let p=d?`${d}.`:"";o.append(`${p}x`,"0"),o.append(`${p}y`,"0")}else d&&o.append(d,g)}}else{if(Ms(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=Wa,r=null,a=Ha,i=e}return o&&a==="text/plain"&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:o,body:i}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function xl(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Pg(e,t,n,r){let a=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n?a.pathname.endsWith("/")?a.pathname=`${a.pathname}_.${r}`:a.pathname=`${a.pathname}.${r}`:a.pathname==="/"?a.pathname=`_root.${r}`:t&&Gt(a.pathname,t)==="/"?a.pathname=`${t.replace(/\/$/,"")}/_root.${r}`:a.pathname=`${a.pathname.replace(/\/$/,"")}.${r}`,a}async function Rg(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function _g(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function Ag(e,t,n){let r=await Promise.all(e.map(async a=>{let o=t.routes[a.route.id];if(o){let i=await Rg(o,n);return i.links?i.links():[]}return[]}));return Fg(r.flat(1).filter(_g).filter(a=>a.rel==="stylesheet"||a.rel==="preload").map(a=>a.rel==="stylesheet"?{...a,rel:"prefetch",as:"style"}:{...a,rel:"prefetch"}))}function Bc(e,t,n,r,a,o){let i=(c,d)=>n[d]?c.route.id!==n[d].route.id:!0,l=(c,d)=>{var f;return n[d].pathname!==c.pathname||((f=n[d].route.path)==null?void 0:f.endsWith("*"))&&n[d].params["*"]!==c.params["*"]};return o==="assets"?t.filter((c,d)=>i(c,d)||l(c,d)):o==="data"?t.filter((c,d)=>{var g;let f=r.routes[c.route.id];if(!f||!f.hasLoader)return!1;if(i(c,d)||l(c,d))return!0;if(c.route.shouldRevalidate){let p=c.route.shouldRevalidate({currentUrl:new URL(a.pathname+a.search+a.hash,window.origin),currentParams:((g=n[0])==null?void 0:g.params)||{},nextUrl:new URL(e,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof p=="boolean")return p}return!0}):[]}function $g(e,t,{includeHydrateFallback:n}={}){return Lg(e.map(r=>{let a=t.routes[r.route.id];if(!a)return[];let o=[a.module];return a.clientActionModule&&(o=o.concat(a.clientActionModule)),a.clientLoaderModule&&(o=o.concat(a.clientLoaderModule)),n&&a.hydrateFallbackModule&&(o=o.concat(a.hydrateFallbackModule)),a.imports&&(o=o.concat(a.imports)),o}).flat(1))}function Lg(e){return[...new Set(e)]}function Mg(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Fg(e,t){let n=new Set;return new Set(t),e.reduce((r,a)=>{let o=JSON.stringify(Mg(a));return n.has(o)||(n.add(o),r.push({key:o,link:a})),r},[])}function Nf(){let e=u.useContext(pr);return xl(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function Og(){let e=u.useContext(Ls);return xl(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var wl=u.createContext(void 0);wl.displayName="FrameworkContext";function Ef(){let e=u.useContext(wl);return xl(e,"You must render this element inside a <HydratedRouter> element"),e}function Bg(e,t){let n=u.useContext(wl),[r,a]=u.useState(!1),[o,i]=u.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:f,onTouchStart:g}=t,p=u.useRef(null);u.useEffect(()=>{if(e==="render"&&i(!0),e==="viewport"){let v=h=>{h.forEach(m=>{i(m.isIntersecting)})},j=new IntersectionObserver(v,{threshold:.5});return p.current&&j.observe(p.current),()=>{j.disconnect()}}},[e]),u.useEffect(()=>{if(r){let v=setTimeout(()=>{i(!0)},100);return()=>{clearTimeout(v)}}},[r]);let x=()=>{a(!0)},w=()=>{a(!1),i(!1)};return n?e!=="intent"?[o,p,{}]:[o,p,{onFocus:br(l,x),onBlur:br(c,w),onMouseEnter:br(d,x),onMouseLeave:br(f,w),onTouchStart:br(g,x)}]:[!1,p,{}]}function br(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Dg({page:e,...t}){let{router:n}=Nf(),r=u.useMemo(()=>mf(n.routes,e,n.basename),[n.routes,e,n.basename]);return r?u.createElement(Wg,{page:e,matches:r,...t}):null}function Ug(e){let{manifest:t,routeModules:n}=Ef(),[r,a]=u.useState([]);return u.useEffect(()=>{let o=!1;return Ag(e,t,n).then(i=>{o||a(i)}),()=>{o=!0}},[e,t,n]),r}function Wg({page:e,matches:t,...n}){let r=St(),{future:a,manifest:o,routeModules:i}=Ef(),{basename:l}=Nf(),{loaderData:c,matches:d}=Og(),f=u.useMemo(()=>Bc(e,t,d,o,r,"data"),[e,t,d,o,r]),g=u.useMemo(()=>Bc(e,t,d,o,r,"assets"),[e,t,d,o,r]),p=u.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let v=new Set,j=!1;if(t.forEach(m=>{var S;let y=o.routes[m.route.id];!y||!y.hasLoader||(!f.some(b=>b.route.id===m.route.id)&&m.route.id in c&&((S=i[m.route.id])!=null&&S.shouldRevalidate)||y.hasClientLoader?j=!0:v.add(m.route.id))}),v.size===0)return[];let h=Pg(e,l,a.unstable_trailingSlashAwareDataRequests,"data");return j&&v.size>0&&h.searchParams.set("_routes",t.filter(m=>v.has(m.route.id)).map(m=>m.route.id).join(",")),[h.pathname+h.search]},[l,a.unstable_trailingSlashAwareDataRequests,c,r,o,f,t,e,i]),x=u.useMemo(()=>$g(g,o),[g,o]),w=Ug(g);return u.createElement(u.Fragment,null,p.map(v=>u.createElement("link",{key:v,rel:"prefetch",as:"fetch",href:v,...n})),x.map(v=>u.createElement("link",{key:v,rel:"modulepreload",href:v,...n})),w.map(({key:v,link:j})=>u.createElement("link",{key:v,nonce:n.nonce,...j,crossOrigin:j.crossOrigin??n.crossOrigin})))}function Hg(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var Vg=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Vg&&(window.__reactRouterVersion="7.13.1")}catch{}function Kg({basename:e,children:t,unstable_useTransitions:n,window:r}){let a=u.useRef();a.current==null&&(a.current=jh({window:r,v5Compat:!0}));let o=a.current,[i,l]=u.useState({action:o.action,location:o.location}),c=u.useCallback(d=>{n===!1?l(d):u.startTransition(()=>l(d))},[n]);return u.useLayoutEffect(()=>o.listen(c),[o,c]),u.createElement(wg,{basename:e,children:t,location:i.location,navigationType:i.action,navigator:o,unstable_useTransitions:n})}var Tf=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Ge=u.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:a,reloadDocument:o,replace:i,unstable_mask:l,state:c,target:d,to:f,preventScrollReset:g,viewTransition:p,unstable_defaultShouldRevalidate:x,...w},v){let{basename:j,navigator:h,unstable_useTransitions:m}=u.useContext(dt),y=typeof f=="string"&&Tf.test(f),S=yf(f,j);f=S.to;let b=ng(f,{relative:a}),T=St(),E=null;if(l){let N=$s(l,[],T.unstable_mask?T.unstable_mask.pathname:"/",!0);j!=="/"&&(N.pathname=N.pathname==="/"?j:Mt([j,N.pathname])),E=h.createHref(N)}let[P,k,z]=Bg(r,w),O=Qg(f,{replace:i,unstable_mask:l,state:c,target:d,preventScrollReset:g,relative:a,viewTransition:p,unstable_defaultShouldRevalidate:x,unstable_useTransitions:m});function K(N){t&&t(N),N.defaultPrevented||O(N)}let V=!(S.isExternal||o),U=u.createElement("a",{...w,...z,href:(V?E:void 0)||S.absoluteURL||b,onClick:V?K:t,ref:Hg(v,k),target:d,"data-discover":!y&&n==="render"?"true":void 0});return P&&!y?u.createElement(u.Fragment,null,U,u.createElement(Dg,{page:b})):U});Ge.displayName="Link";var Sl=u.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:a=!1,style:o,to:i,viewTransition:l,children:c,...d},f){let g=ua(i,{relative:d.relative}),p=St(),x=u.useContext(Ls),{navigator:w,basename:v}=u.useContext(dt),j=x!=null&&ey(g)&&l===!0,h=w.encodeLocation?w.encodeLocation(g).pathname:g.pathname,m=p.pathname,y=x&&x.navigation&&x.navigation.location?x.navigation.location.pathname:null;n||(m=m.toLowerCase(),y=y?y.toLowerCase():null,h=h.toLowerCase()),y&&v&&(y=Gt(y,v)||y);const S=h!=="/"&&h.endsWith("/")?h.length-1:h.length;let b=m===h||!a&&m.startsWith(h)&&m.charAt(S)==="/",T=y!=null&&(y===h||!a&&y.startsWith(h)&&y.charAt(h.length)==="/"),E={isActive:b,isPending:T,isTransitioning:j},P=b?t:void 0,k;typeof r=="function"?k=r(E):k=[r,b?"active":null,T?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let z=typeof o=="function"?o(E):o;return u.createElement(Ge,{...d,"aria-current":P,className:k,ref:f,style:z,to:i,viewTransition:l},typeof c=="function"?c(E):c)});Sl.displayName="NavLink";var Gg=u.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:a,state:o,method:i=Wa,action:l,onSubmit:c,relative:d,preventScrollReset:f,viewTransition:g,unstable_defaultShouldRevalidate:p,...x},w)=>{let{unstable_useTransitions:v}=u.useContext(dt),j=qg(),h=Zg(l,{relative:d}),m=i.toLowerCase()==="get"?"get":"post",y=typeof l=="string"&&Tf.test(l),S=b=>{if(c&&c(b),b.defaultPrevented)return;b.preventDefault();let T=b.nativeEvent.submitter,E=(T==null?void 0:T.getAttribute("formmethod"))||i,P=()=>j(T||b.currentTarget,{fetcherKey:t,method:E,navigate:n,replace:a,state:o,relative:d,preventScrollReset:f,viewTransition:g,unstable_defaultShouldRevalidate:p});v&&n!==!1?u.startTransition(()=>P()):P()};return u.createElement("form",{ref:w,method:m,action:h,onSubmit:r?c:S,...x,"data-discover":!y&&e==="render"?"true":void 0})});Gg.displayName="Form";function Yg(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function zf(e){let t=u.useContext(pr);return ve(t,Yg(e)),t}function Qg(e,{target:t,replace:n,unstable_mask:r,state:a,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c,unstable_useTransitions:d}={}){let f=Qt(),g=St(),p=ua(e,{relative:i});return u.useCallback(x=>{if(Ng(x,t)){x.preventDefault();let w=n!==void 0?n:ra(g)===ra(p),v=()=>f(e,{replace:w,unstable_mask:r,state:a,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c});d?u.startTransition(()=>v()):v()}},[g,f,p,n,r,a,t,e,o,i,l,c,d])}function If(e){wt(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=u.useRef(pi(e)),n=u.useRef(!1),r=St(),a=u.useMemo(()=>Eg(r.search,n.current?null:t.current),[r.search]),o=Qt(),i=u.useCallback((l,c)=>{const d=pi(typeof l=="function"?l(new URLSearchParams(a)):l);n.current=!0,o("?"+d,c)},[o,a]);return[a,i]}var Jg=0,Xg=()=>`__${String(++Jg)}__`;function qg(){let{router:e}=zf("useSubmit"),{basename:t}=u.useContext(dt),n=hg(),r=e.fetch,a=e.navigate;return u.useCallback(async(o,i={})=>{let{action:l,method:c,encType:d,formData:f,body:g}=Ig(o,t);if(i.navigate===!1){let p=i.fetcherKey||Xg();await r(p,n,i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:g,formMethod:i.method||c,formEncType:i.encType||d,flushSync:i.flushSync})}else await a(i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:g,formMethod:i.method||c,formEncType:i.encType||d,replace:i.replace,state:i.state,fromRouteId:n,flushSync:i.flushSync,viewTransition:i.viewTransition})},[r,a,t,n])}function Zg(e,{relative:t}={}){let{basename:n}=u.useContext(dt),r=u.useContext(zt);ve(r,"useFormAction must be used inside a RouteContext");let[a]=r.matches.slice(-1),o={...ua(e||".",{relative:t})},i=St();if(e==null){o.search=i.search;let l=new URLSearchParams(o.search),c=l.getAll("index");if(c.some(f=>f==="")){l.delete("index"),c.filter(g=>g).forEach(g=>l.append("index",g));let f=l.toString();o.search=f?`?${f}`:""}}return(!e||e===".")&&a.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(o.pathname=o.pathname==="/"?n:Mt([n,o.pathname])),ra(o)}function ey(e,{relative:t}={}){let n=u.useContext(xf);ve(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=zf("useViewTransitionState"),a=ua(e,{relative:t});if(!n.isTransitioning)return!1;let o=Gt(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=Gt(n.nextLocation.pathname,r)||n.nextLocation.pathname;return gs(a.pathname,i)!=null||gs(a.pathname,o)!=null}class Pf extends Error{constructor(n){super("different_account");Fs(this,"summary");this.name="DifferentAccountError",this.summary=n}}class ty{constructor(){Fs(this,"apiKey",null)}setApiKey(t){this.apiKey=t}clearApiKey(){this.apiKey=null}getApiKey(){return this.apiKey}async fetch(t,n){return globalThis.fetch(t,{...n,headers:{"Content-Type":"application/json",...this.apiKey?{"X-API-Key":this.apiKey}:{},...n==null?void 0:n.headers}})}async login(t,n={}){const r=await this.fetch("/auth/login",{method:"POST",headers:{"X-API-Key":t,"Content-Type":"application/json"},body:JSON.stringify({confirmWipe:n.confirmWipe===!0})});if(r.status===409){const o=await r.json().catch(()=>({}));if(o!=null&&o.wouldWipe)throw new Pf(o.summary??{credentialCount:0,serviceCount:0,credentialIds:[]})}if(!r.ok){const o=await r.json().catch(()=>({error:"Invalid API key"}));throw new Error(o.error||`Login failed: ${r.status}`)}return(await r.json()).user}async logout(){await this.fetch("/auth/logout",{method:"POST"})}async getGroups(){const t=await this.fetch("/api/groups");if(!t.ok)throw new Error(`Failed to fetch groups: ${t.status}`);const n=await t.json();return n.groups??n}async listProfiles(){const t=await this.fetch("/api/profiles");if(!t.ok)throw new Error(`Failed to fetch profiles: ${t.status}`);return(await t.json()).profiles}async getProfile(t){const n=await this.fetch(`/api/profiles/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch profile: ${n.status}`);return n.json()}async attest(t){const n=await this.fetch("/api/as/attest",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`Attest failed: ${n.status}`)}return n.json()}async getPending(t){const n=await this.fetch(`/api/attestations/pending?domain=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch pending: ${n.status}`);const r=await n.json();return r.pending??r}async getMyAttestations(t){const n=t?`?status=${encodeURIComponent(t)}`:"",r=await this.fetch(`/api/attestations/mine${n}`);if(!r.ok)throw new Error(`Failed to fetch attestations: ${r.status}`);return((await r.json()).attestations??[]).map(o=>{var i,l;return{authorization_id:o.authorization_id,profile_id:o.profileId,path:o.path,title:o.title??null,sp_status:o.status??null,frame:o.bounds??o.frame??{},required_domains:o.requiredDomains??[],attested_domains:o.attestedDomains??[],missing_domains:(o.requiredDomains??[]).filter(c=>!(o.attestedDomains??[]).includes(c)),deferred_commitment_domains:o.deferredCommitmentDomains??[],approvers_frozen:o.approversFrozen??[],above_cap:o.aboveCap??!1,created_at:o.createdAt?new Date(o.createdAt*1e3).toISOString():"",earliest_expiry:(i=o.attestations)!=null&&i.length?new Date(Math.min(...o.attestations.map(c=>c.expiresAt))*1e3).toISOString():null,remaining_seconds:(l=o.attestations)!=null&&l.length?Math.max(0,Math.min(...o.attestations.map(c=>c.expiresAt))-Math.floor(Date.now()/1e3)):null}})}async getDenials(t){const n=new URLSearchParams;t!=null&&t.since&&n.set("since",String(t.since)),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",a=await this.fetch(`/denials${r}`);if(!a.ok)throw new Error(`Failed to fetch denials: ${a.status}`);return a.json()}async getMyReceipts(t){const n=new URLSearchParams;t!=null&&t.date&&n.set("date",t.date),t!=null&&t.profile&&n.set("profile",t.profile),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!a.ok)throw new Error(`Failed to fetch receipts: ${a.status}`);return(await a.json()).receipts??[]}async revokeAttestation(t,n){const r=await this.fetch(`/api/authorizations/${encodeURIComponent(t)}/revoke`,{method:"POST",body:JSON.stringify({reason:n??"Revoked by user"})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to revoke"}));throw new Error(a.error||`Revoke failed: ${r.status}`)}}async getAttestations(t){const n=await this.fetch(`/api/attestations?authorization_id=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch attestations: ${n.status}`);return n.json()}async getGroupById(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch group: ${n.status}`);return n.json()}async createGroup(t){const n=await this.fetch("/api/groups",{method:"POST",body:JSON.stringify({name:t})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(o.error||`Create group failed: ${n.status}`)}const r=await n.json(),a=r.group||r;return{id:a.id,name:a.name,myDomains:a.myDomains||[],isAdmin:!0}}async joinGroup(t){const n=await this.fetch("/api/groups/join",{method:"POST",body:JSON.stringify({inviteCode:t})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(o.error||`Join group failed: ${n.status}`)}const r=await n.json(),a=r.group||r;return{id:a.id,name:a.name,myDomains:a.myDomains||[],isAdmin:a.isAdmin||!1}}async inviteToGroup(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/invite`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`Invite failed: ${n.status}`)}return n.json()}async getMyTeam(){const t=await this.fetch("/api/groups/me");if(!t.ok)return null;const n=await t.json();return n.group?{group:n.group,membership:n.membership}:null}async listUsers(){const t=await this.fetch("/api/users");return t.ok?(await t.json()).users??[]:[]}async setPubkey(t){const n=await this.fetch("/api/users/me/pubkey",{method:"PUT",body:JSON.stringify({pubkey:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to set pubkey"}));throw new Error(r.error||`setPubkey failed: ${n.status}`)}}async getPubkey(t){const n=await this.fetch(`/api/users/${encodeURIComponent(t)}/pubkey`);return n.status===404||!n.ok?null:(await n.json()).pubkey??null}async leaveTeam(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/leave`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to leave team"}));throw new Error(r.error||`Leave failed: ${n.status}`)}}async getVaultStatus(){const t=await this.fetch("/vault/status");if(!t.ok)throw new Error(`Failed to fetch vault status: ${t.status}`);return t.json()}async getCredential(t){const n=await this.fetch(`/vault/credentials/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to check credential: ${n.status}`);return n.json()}async setCredential(t,n){const r=await this.fetch(`/vault/credentials/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)});if(!r.ok)throw new Error(`Failed to save credential: ${r.status}`)}async testCredential(t){const n=await this.fetch(`/vault/test/${encodeURIComponent(t)}`,{method:"POST"});if(!n.ok)throw new Error(`Test failed: ${n.status}`);return n.json()}async aiAssist(t){const n=await this.fetch("/ai/assist",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI request failed"}))).error,disclaimer:"AI surfaces reality. You supply intent."}}async aiIntentReview(t){const n=await this.fetch("/ai/intent-review",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI request failed"}))).error}}async aiTest(t){const n=await this.fetch("/ai/test",{method:"POST",body:JSON.stringify(t??{})});if(!n.ok)throw new Error(`AI test failed: ${n.status}`);return n.json()}async aiModels(t){const n=await this.fetch("/ai/models",{method:"POST",body:JSON.stringify(t??{})});if(!n.ok)throw new Error(`Model list failed: ${n.status}`);return n.json()}async getMcpHealth(){const t=await this.fetch("/mcp/health");if(!t.ok)throw new Error(`MCP server unreachable: ${t.status}`);return t.json()}async getMcpIntegrations(){const t=await this.fetch("/mcp/integrations");if(!t.ok)throw new Error(`Failed to fetch integrations: ${t.status}`);return t.json()}async getOAuthHealth(t){try{const n=await this.fetch(`/auth/oauth/${encodeURIComponent(t)}/health`);return n.ok?await n.json():{status:"unverified"}}catch{return{status:"unverified"}}}async getIntegrationManifests(){const t=await this.fetch("/mcp/integrations/manifests");if(!t.ok)throw new Error(`Failed to fetch manifests: ${t.status}`);return t.json()}async discoverScopeField(t,n){const r=await this.fetch(`/integrations/${encodeURIComponent(t)}/discover/${encodeURIComponent(n)}`);if(!r.ok){const a=await r.json().catch(()=>({error:`Discovery failed: ${r.status}`}));throw new Error(a.error)}return r.json()}async activateIntegration(t){const n=await this.fetch(`/mcp/integrations/${encodeURIComponent(t)}/activate`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed"}));throw new Error(r.error||`Failed: ${n.status}`)}return n.json()}async removeMcpIntegration(t){const n=await this.fetch(`/mcp/integrations/${encodeURIComponent(t)}`,{method:"DELETE"});if(!n.ok)throw new Error(`Failed to remove integration: ${n.status}`)}async setReadPolicy(t,n){const r=await this.fetch(`/integrations/${encodeURIComponent(t)}/read-policy`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({readAgeDays:n})});if(!r.ok){const a=await r.json().catch(()=>({error:`HTTP ${r.status}`}));throw new Error(a.error)}}async getTeamProfileConfig(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`);if(r.status===404||!r.ok)return null;const a=await r.json();return(a==null?void 0:a.config)??null}async setTeamProfileConfig(t,n,r){const a=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify(r)});if(!a.ok){const o=await a.json().catch(()=>({error:"Failed to set profile config"}));throw new Error(o.error||`setTeamProfileConfig failed: ${a.status}`)}}async encryptIntent(t,n){const r=await this.fetch("/api/encrypt-intent",{method:"POST",body:JSON.stringify({intent:t,recipients:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Encryption failed"}));throw new Error(a.error||`encryptIntent failed: ${r.status}`)}return r.json()}async getApproversPubkeys(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}/approvers/pubkeys`);return r.ok?(await r.json()).approvers??[]:[]}async deleteTeamProfileConfig(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"DELETE"});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to delete profile config"}));throw new Error(a.error||`deleteTeamProfileConfig failed: ${r.status}`)}}async getProposals(t){const n=await this.fetch(`/api/proposals?domain=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch proposals: ${n.status}`);return(await n.json()).proposals??[]}async resolveProposal(t,n,r){const a=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/resolve`,{method:"POST",body:JSON.stringify({action:n,domain:r})});if(!a.ok){const o=await a.json().catch(()=>({error:"Failed"}));throw new Error(o.error||`Failed: ${a.status}`)}return a.json()}async getProposalsForApprover(){const t=await this.fetch("/api/proposals?approver=me");if(!t.ok)throw new Error(`Failed to fetch approver proposals: ${t.status}`);return(await t.json()).proposals??[]}async approveProposal(t){const n=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/approve`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed"}));throw new Error(r.error||`approveProposal failed: ${n.status}`)}return n.json()}async rejectProposal(t,n){const r=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({reason:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed"}));throw new Error(a.error||`rejectProposal failed: ${r.status}`)}return r.json()}async getAttestationIntent(t){const n=await this.fetch(`/api/authorizations/${encodeURIComponent(t)}/intent`);return n.status===404||n.status===403||!n.ok?null:n.json()}async decryptIntent(t){const n=await this.fetch("/api/decrypt-intent",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const a=await n.json().catch(()=>({error:"Decryption failed"}));throw new Error(a.error||`decryptIntent failed: ${n.status}`)}return(await n.json()).intent}async storeApprovedIntent(t,n){const r=await this.fetch("/api/approved-intents",{method:"POST",body:JSON.stringify({authorityId:t,intent:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed"}));throw new Error(a.error||`storeApprovedIntent failed: ${r.status}`)}}async listTeamAuthorizations(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/attestations`);if(!n.ok)throw new Error(`Failed to fetch team authorizations: ${n.status}`);return((await n.json()).items??[]).map(a=>{var l,c;const o=a.owner??{userId:""};return{authorization_id:a.authorization_id??a.authorizationId,profile_id:a.profileId??a.profile_id,path:a.path??"",title:a.title??null,sp_status:a.status??a.sp_status??null,frame:a.bounds??a.frame??{},required_domains:a.requiredDomains??a.required_domains??[],attested_domains:a.attestedDomains??a.attested_domains??[],missing_domains:(a.requiredDomains??a.required_domains??[]).filter(d=>!(a.attestedDomains??a.attested_domains??[]).includes(d)),deferred_commitment_domains:a.deferredCommitmentDomains??a.deferred_commitment_domains??[],approvers_frozen:a.approversFrozen??a.approvers_frozen??[],above_cap:a.aboveCap??a.above_cap??!1,created_at:a.createdAt?new Date(a.createdAt*1e3).toISOString():a.created_at??"",earliest_expiry:(l=a.attestations)!=null&&l.length?new Date(Math.min(...a.attestations.map(d=>d.expiresAt))*1e3).toISOString():null,remaining_seconds:(c=a.attestations)!=null&&c.length?Math.max(0,Math.min(...a.attestations.map(d=>d.expiresAt))-Math.floor(Date.now()/1e3)):null,owner:o}})}async listTeamReceipts(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts`);if(!n.ok)throw new Error(`Failed to fetch team receipts: ${n.status}`);return(await n.json()).receipts??[]}async getMyReceiptsPage(t){const n=new URLSearchParams;t!=null&&t.before&&n.set("before",t.before),t!=null&&t.profile&&n.set("profile",t.profile),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!a.ok)throw new Error(`Failed to fetch receipts: ${a.status}`);const o=await a.json();return{receipts:o.receipts??[],nextBefore:o.nextBefore??null}}async listTeamReceiptsPage(t,n){const r=new URLSearchParams;n!=null&&n.before&&r.set("before",n.before),n!=null&&n.profile&&r.set("profile",n.profile),n!=null&&n.limit&&r.set("limit",String(n.limit));const a=r.toString(),o=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts${a?"?"+a:""}`);if(!o.ok)throw new Error(`Failed to fetch team receipts: ${o.status}`);const i=await o.json();return{receipts:i.receipts??[],nextBefore:i.nextBefore??null}}async getThread(t){const n=t.sinceDays??7,r=t.status??"pending",a=t.domain||"owner",o=await this.getProposals(a);let i=[];if(r==="all"){const l=[],c=new Date;for(let f=0;f<n;f++){const g=new Date(c);g.setUTCDate(c.getUTCDate()-f),l.push(g.toISOString().slice(0,10))}i=(await Promise.all(l.map(f=>this.getMyReceipts({date:f,profile:t.profile})))).flat()}return{proposals:o,receipts:i}}async getAutostart(){const t=await this.fetch("/autostart");if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}async setAutostart(t){const n=await this.fetch("/autostart",{method:t?"POST":"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async getGateContent(t){const n=await this.fetch(`/gate-content?path=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch gate content: ${n.status}`);return(await n.json()).entry??null}async resyncGates(){const t=await this.fetch("/resync-gates",{method:"POST"});if(!t.ok)throw new Error(`Failed to resync gates: ${t.status}`)}async getEnrichedAuthorizations(){const t=await this.fetch("/active-authorizations");if(!t.ok)throw new Error(`Failed to fetch authorizations: ${t.status}`);return(await t.json()).authorizations??[]}async pushGateContent(t){const n=await this.fetch("/gate-content",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to push gate content"}));throw new Error(r.error||`Push gate content failed: ${n.status}`)}}async getAgentContext(){const t=await this.fetch("/agent-brief/context");if(!t.ok)throw new Error(`Failed to fetch agent context: ${t.status}`);return(await t.json()).content}async saveAgentContext(t){const n=await this.fetch("/agent-brief/context",{method:"PUT",body:JSON.stringify({content:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save agent context"}));throw new Error(r.error||`Save failed: ${n.status}`)}}async aiChat(t){const n=await this.fetch("/ai/chat",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI chat failed"}))).error||`Chat failed: ${n.status}`}}async getAIPrompts(){const t=await this.fetch("/ai-prompts");if(!t.ok)throw new Error(`Failed to load AI prompts: ${t.status}`);return t.json()}async setAIPrompt(t,n){const r=await this.fetch(`/ai-prompts/${t}`,{method:"PUT",body:JSON.stringify({value:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Save failed"}));throw new Error(a.error||`Save failed: ${r.status}`)}}}const A=new ty,Rf=u.createContext(null);function ny({children:e}){const[t,n]=u.useState(null),[r,a]=u.useState("personal"),[o,i]=u.useState(null),[l,c]=u.useState(""),[d,f]=u.useState(null),[g,p]=u.useState(null),[x,w]=u.useState(!1),[v,j]=u.useState(""),h=u.useRef(!1),m=u.useRef(null),y=u.useCallback(async()=>{if(h.current)try{const P=await A.getMyTeam();if(P){const{group:k,membership:z}=P;f(k),p(z),a("team"),i(k);const O=m.current??z.domains[0]??"owner";c(O)}else f(null),p(null),a("personal")}catch{}},[]);u.useEffect(()=>{const P=()=>{document.visibilityState==="visible"&&y()};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[y]);const S=u.useCallback(async(P,k={})=>{w(!0),j("");try{A.setApiKey(P),h.current=!0;const z=await A.login(P,k);n(z),m.current=z.id;const O=await A.getGroups(),K=O.find(V=>V.isPersonal)??O[0]??null;i(K),c("owner"),await y()}catch(z){throw A.clearApiKey(),h.current=!1,j(z instanceof Error?z.message:"Login failed"),z}finally{w(!1)}},[y]),b=u.useCallback(async()=>{await A.logout(),A.clearApiKey(),h.current=!1,m.current=null,n(null),i(null),c(""),f(null),p(null),a("personal"),j("")},[]),T=u.useCallback(()=>j(""),[]),E=u.useCallback((P,k)=>{i(P),c(k)},[]);return s.jsx(Rf.Provider,{value:{user:t,mode:r,group:o,domain:l,groupId:(o==null?void 0:o.id)??null,activeTeam:d,activeMembership:g,isLoading:x,error:v,login:S,logout:b,clearError:T,activeGroup:o,activeDomain:l,groups:o?[o]:[],setActiveContext:E,refreshGroups:y},children:e})}function $e(){const e=u.useContext(Rf);if(!e)throw new Error("useAuth must be used within AuthProvider");return e}const _f=u.createContext(null);function ry({children:e}){const{user:t}=$e(),n=u.useRef(null),[r,a]=u.useState(!1),o=u.useRef(new Map),i=u.useCallback((l,c)=>{const d=o.current;return d.has(l)||d.set(l,new Set),d.get(l).add(c),()=>{var f;(f=d.get(l))==null||f.delete(c)}},[]);return u.useEffect(()=>{if(!t){n.current&&(n.current.close(),n.current=null,a(!1));return}if(n.current)return;const l=A.getApiKey();if(!l)return;const c=new EventSource(`/events?key=${encodeURIComponent(l)}`);n.current=c,c.onopen=()=>a(!0),c.onerror=()=>a(!1);const d=["integration-changed","attestation-changed","proposal-added","proposal-resolved","team-membership-changed","action-approval-needed","action-resolved","proposal-approved","proposal-rejected"];for(const f of d)c.addEventListener(f,g=>{let p;try{p=JSON.parse(g.data)}catch{p=null}const x=o.current.get(f);if(x)for(const w of x)try{w(p)}catch(v){console.error(`[EventSource] handler for "${f}" threw:`,v)}});return()=>{c.close(),n.current=null,a(!1)}},[t]),s.jsx(_f.Provider,{value:{connected:r,addListener:i},children:e})}function xe(e,t){const n=u.useContext(_f);if(!n)return;const{addListener:r}=n;u.useEffect(()=>r(e,t),[e,t,r])}const Or="suveren-theme",Dc="hap-theme";function za(e){return e!=="system"?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}(function(){const t=localStorage.getItem(Dc);t!==null&&localStorage.getItem(Or)===null&&localStorage.setItem(Or,t),t!==null&&localStorage.removeItem(Dc)})();function Af(){const[e,t]=u.useState(()=>{const o=localStorage.getItem(Or);return o==="light"||o==="dark"?o:"system"}),[n,r]=u.useState(()=>za(e));u.useEffect(()=>{const o=document.documentElement,i=za(e);o.setAttribute("data-theme",i),e==="system"?localStorage.removeItem(Or):localStorage.setItem(Or,e),r(za(e))},[e]),u.useEffect(()=>{if(e!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r(za("system"));return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},[e]);const a=u.useCallback(()=>{t(o=>o==="system"?"light":o==="light"?"dark":"system")},[]);return{theme:e,effectiveTheme:n,toggle:a}}const ay=5*60*1e3,sy=2e3;function jl(){const[e,t]=u.useState(!1),[n,r]=u.useState("docker"),[a,o]=u.useState(""),[i,l]=u.useState(null),[c,d]=u.useState(!1),[f,g]=u.useState(!1),[p,x]=u.useState(!1),w=u.useRef(null);return u.useEffect(()=>{let v=!1;const j=(y=!1)=>{fetch(y?"/health?refresh=1":"/health").then(S=>S.json()).then(S=>{v||(S.installMethod&&r(S.installMethod),typeof S.latestVersion<"u"&&l(S.latestVersion),S.updateAvailable&&t(!0),S.version&&(o(S.version),w.current===null?w.current=S.version:S.version!==w.current&&S.version!=="dev"&&d(!0)))}).catch(()=>{})};j(!0);const h=setInterval(()=>j(!1),p?sy:ay),m=()=>{document.visibilityState==="visible"&&j(!1)};return document.addEventListener("visibilitychange",m),window.addEventListener("focus",m),()=>{v=!0,clearInterval(h),document.removeEventListener("visibilitychange",m),window.removeEventListener("focus",m)}},[p]),{updateAvailable:e&&!f,installMethod:n,version:a,latestVersion:i,serverRestarted:c,startFastPolling:()=>x(!0),dismiss:()=>g(!0)}}function oy(e){return e?e==="dev"?"dev":/^[0-9a-f]{40}$/i.test(e)?e.slice(0,7):e:""}const Uc={system:"◑",light:"☀",dark:"☾"};function iy(){const{mode:e,group:t,domain:n}=$e();return e==="personal"?s.jsx("span",{children:"personal"}):t?s.jsxs("span",{children:[t.name," / ",n]}):s.jsx("span",{children:n})}function kl({onMenuToggle:e}){const{user:t,logout:n}=$e(),{theme:r,toggle:a}=Af(),{version:o}=jl(),i=oy(o);return s.jsx("nav",{className:"top-nav",children:s.jsxs("div",{className:"top-nav-inner",children:[s.jsxs("div",{className:"logo-group",children:[s.jsx("span",{className:"logo",children:"Suveren"}),s.jsx("span",{className:"version-badge",children:"Local Gateway"})]}),s.jsx("div",{className:"nav-spacer"}),s.jsx("div",{className:"nav-actions nav-actions-desktop",children:t?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"user-chip",children:[s.jsx("strong",{children:t.name}),s.jsx("span",{className:"dot"}),s.jsx(iy,{})]}),s.jsx("button",{className:"theme-toggle",onClick:a,title:`Theme: ${r}`,children:Uc[r]}),s.jsx("button",{className:"nav-logout",onClick:n,children:"Logout"})]}):s.jsxs(s.Fragment,{children:[i&&s.jsxs("span",{title:"Running gateway version",style:{fontSize:"0.8rem",color:"var(--text-tertiary)",fontVariantNumeric:"tabular-nums"},children:["v",i]}),s.jsx("button",{className:"theme-toggle",onClick:a,title:`Theme: ${r}`,children:Uc[r]})]})}),t&&e&&s.jsx("button",{className:"mobile-menu-btn",onClick:e,"aria-label":"Menu",children:"☰"})]})})}function Rt(e,t){var n;if((n=t==null?void 0:t.revokedSet)!=null&&n.has(e.authorization_id))return"revoked";switch(e.sp_status){case"revoked":return"revoked";case"expired":return"expired";case"active":return"active";case"pending":return"pending"}return e.remaining_seconds===null||e.remaining_seconds<=0?"expired":e.missing_domains.length>0?"pending":"active"}function $f(e,t){const n={active:[],pending:[],expired:[],revoked:[]};for(const r of e)n[Rt(r,t)].push(r);return n}function At(e,t,n){const r=u.useRef(e);r.current=e,u.useEffect(()=>{let a=null;const o=()=>typeof document>"u"?!0:document.visibilityState==="visible",i=()=>{o()&&r.current()},l=()=>{a===null&&(a=setInterval(i,t))},c=()=>{a!==null&&(clearInterval(a),a=null)},d=()=>{o()?(r.current(),l()):c()};return o()&&(r.current(),l()),document.addEventListener("visibilitychange",d),()=>{c(),document.removeEventListener("visibilitychange",d)}},[t,n])}const Lf=u.createContext(null),ly=3e4,cy=5e3,uy=3e5;function dy(e,t,n){return t===0?"loading":e!=null&&e.running?"running":e!=null&&e.error?"error":e&&n?"starting":"not-running"}function fy({children:e}){const[t,n]=u.useState({manifests:[],integrations:[],activeSessions:0,mcpServerUp:null,manifestsError:!1,fetchCount:0,authHealth:{}}),r=u.useRef(null),a=u.useCallback(async()=>{let d=!1;const[f,g]=await Promise.all([A.getIntegrationManifests().catch(()=>(d=!0,{manifests:[]})),A.getMcpHealth().catch(()=>null)]);n(x=>({...x,manifests:f.manifests,integrations:(g==null?void 0:g.integrations)??x.integrations,activeSessions:(g==null?void 0:g.activeSessions)??x.activeSessions,mcpServerUp:!!g,manifestsError:d,fetchCount:x.fetchCount+1}));const p=f.manifests.filter(x=>x.oauth);if(p.length>0){const x=await Promise.all(p.map(async w=>[w.id,await A.getOAuthHealth(w.id)]));n(w=>({...w,authHealth:Object.fromEntries(x)}))}},[]),o=t.fetchCount>0&&t.manifests.some(d=>{const f=t.integrations.find(g=>g.id===d.id);return f&&!f.running});xe("integration-changed",a),At(a,o?cy:uy);const i=u.useMemo(()=>{const d=new Map(t.integrations.map(p=>[p.id,p])),f=Date.now();o&&r.current===null?r.current=f:o||(r.current=null);const g=r.current!==null&&f-r.current<ly;return t.manifests.map(p=>{const x=d.get(p.id),w=dy(x,t.fetchCount,g),v=t.authHealth[p.id];return{id:p.id,manifest:p,integration:x,state:w,authStatus:v==null?void 0:v.status,authAccount:v==null?void 0:v.account,authError:v==null?void 0:v.error}})},[t,o]),l=u.useMemo(()=>i.filter(d=>d.state==="not-running"||d.state==="error"||d.authStatus==="failed").length,[i]),c={loading:t.fetchCount===0,mcpServerUp:t.mcpServerUp,manifestsError:t.manifestsError,entries:i,attentionCount:l,activeSessions:t.activeSessions,refresh:a};return s.jsx(Lf.Provider,{value:c,children:e})}function bl(){const e=u.useContext(Lf);if(!e)throw new Error("useIntegrationStatus must be used inside IntegrationStatusProvider");return e}const my=[{to:"/",icon:"□",label:"Dashboard"},{to:"/proposals",icon:"▷",label:"Pending Approvals",statusKey:"proposals"},{to:"/authorizations",icon:"☰",label:"Authorizations",statusKey:"authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief",statusKey:"brief"},{to:"/audit",icon:"▣",label:"Receipts"},{to:"/groups",icon:"◉",label:"Team",teamOnly:!0},{to:"/integrations",icon:"⧗",label:"Integrations",statusKey:"integrations"},{to:"/settings",icon:"⚙",label:"AI Assistant",statusKey:"assistant"}];function py(){const{activeDomain:e}=$e(),[t,n]=u.useState({}),r=u.useCallback(async()=>{try{const[a,o,i,l,c]=await Promise.all([A.getCredential("ai-config").catch(()=>null),A.getMyAttestations().catch(()=>null),A.getProposals(e||"owner").catch(()=>null),A.getProposalsForApprover().catch(()=>null),A.getAgentContext().catch(()=>"")]),d={};if(a&&!a.configured&&(d.assistant=1),o){const x=$f(o).expired.length;x>0&&(d.authorizations=x)}const f=(i==null?void 0:i.length)??0,g=(l==null?void 0:l.length)??0,p=f+g;p>0&&(d.proposals=p),(!c||!c.trim())&&(d.brief=1),n(d)}catch{}},[e]);return xe("attestation-changed",r),xe("proposal-added",r),xe("proposal-resolved",r),xe("proposal-approved",r),xe("proposal-rejected",r),xe("team-membership-changed",r),At(r,3e5,e),t}const hy={marginLeft:"auto",minWidth:"1.25rem",height:"1.25rem",padding:"0 0.375rem",borderRadius:"0.625rem",background:"var(--warning)",color:"var(--bg-elevated)",fontSize:"0.7rem",fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},gy={position:"fixed",bottom:"1.5rem",left:"50%",transform:"translateX(-50%)",background:"var(--bg-elevated, #1e1e2e)",color:"var(--text-primary, #e2e8f0)",border:"1px solid var(--border)",borderRadius:"0.5rem",padding:"0.625rem 1rem",fontSize:"0.85rem",boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:9999,whiteSpace:"nowrap",pointerEvents:"none"};function yy(){const{mode:e,group:t,domain:n,activeTeam:r}=$e(),a=py(),{attentionCount:o}=bl(),i={...a};o>0&&(i.integrations=o);const l=my.filter(p=>!p.teamOnly||e==="team"),c=u.useRef(null),[d,f]=u.useState(null),g=St();return u.useEffect(()=>{if(c.current===null){c.current=e;return}c.current!==e&&(e==="team"&&r?f(`You are now acting in team context — ${r.name}`):e==="personal"&&f("You have left the team — back to personal context"),c.current=e)},[e,r]),u.useEffect(()=>{f(null)},[g.pathname]),s.jsxs("div",{className:"sidebar",children:[s.jsx("ul",{className:"sidebar-nav",children:l.map(p=>{const x=p.statusKey?i[p.statusKey]:0;return s.jsx("li",{children:s.jsxs(Sl,{to:p.to,end:p.to==="/",className:({isActive:w})=>`sidebar-item${w?" active":""}`,children:[s.jsx("span",{className:"icon",children:p.icon}),p.label,x?s.jsx("span",{style:hy,children:x}):null]})},p.to)})}),s.jsxs("div",{className:"sidebar-context",children:[s.jsx("div",{className:"ctx-label",children:"Active context"}),s.jsx("div",{className:"ctx-value",children:e==="personal"?"personal":t?`${t.name} / ${n}`:n})]}),d&&s.jsx("div",{style:gy,role:"status","aria-live":"polite",children:d})]})}const ho="suveren:updatedTo";function vy(e){return e==="npm"?"suveren-gateway stop; npm install -g @suveren/gateway@latest && suveren-gateway start --detach":e==="dev"?"git pull && pnpm install":"docker rm -f suveren-gateway 2>/dev/null; docker ps -q --filter publish=7400 --filter publish=7430 | xargs -r docker rm -f; docker pull ghcr.io/suverenai/suveren-gateway:latest && docker run -d --name suveren-gateway -p 7400:3000 -p 7430:3030 -v $HOME/.suveren:/app/data ghcr.io/suverenai/suveren-gateway"}function xy(){const e=document.querySelectorAll('[role="dialog"], .modal-overlay, .modal');for(const n of e)if(!n.closest(".update-overlay"))return!0;const t=document.activeElement;if(t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)){const n=t.value;if(n&&n.trim())return!0}return!1}function Mf(){const{updateAvailable:e,installMethod:t,version:n,latestVersion:r,serverRestarted:a,startFastPolling:o,dismiss:i}=jl(),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[g,p]=u.useState(()=>{try{const y=sessionStorage.getItem(ho);if(y)return sessionStorage.removeItem(ho),y}catch{}return null}),x=vy(t),w=u.useRef(null),v=y=>{try{sessionStorage.setItem(ho,y||r||"✓")}catch{}window.location.reload()};u.useEffect(()=>{if(!g)return;const y=setTimeout(()=>p(null),6e3);return()=>clearTimeout(y)},[g]),u.useEffect(()=>{if(!l||!a)return;const y=()=>xy()?!1:(v(n),!0);if(y())return;const S=setInterval(y,1500);return()=>clearInterval(S)},[l,a,n]),u.useEffect(()=>(document.body.classList.toggle("is-updating",l),()=>document.body.classList.remove("is-updating")),[l]);const j=e&&!l&&!g||!!g&&!l;u.useEffect(()=>{if(!j){document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner");return}document.body.classList.add("has-update-banner");const y=()=>{var T;const b=((T=w.current)==null?void 0:T.offsetHeight)??0;document.documentElement.style.setProperty("--update-banner-h",`${b}px`)};y();const S=new ResizeObserver(y);return w.current&&S.observe(w.current),()=>{S.disconnect(),document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner")}},[j]);const h=()=>{c(!0),o()},m=async()=>{try{await navigator.clipboard.writeText(x),f(!0),setTimeout(()=>f(!1),1800)}catch{}};return s.jsxs(s.Fragment,{children:[g&&!l&&s.jsx("div",{ref:w,className:"update-banner is-live",role:"status","aria-live":"polite",children:s.jsxs("div",{className:"update-banner-row",children:[s.jsxs("span",{className:"update-banner-text",children:["✓"," You","’","re on the latest version",g&&g!=="✓"?` — ${g} is live`:" — now live","."]}),s.jsx("button",{className:"update-banner-x",onClick:()=>p(null),"aria-label":"Dismiss",children:"×"})]})}),e&&!l&&!g&&s.jsx("div",{ref:w,className:"update-banner",role:"status","aria-live":"polite",children:s.jsxs("div",{className:"update-banner-row",children:[s.jsx("span",{className:"update-banner-text",children:"Update available."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("button",{className:"btn btn-sm btn-secondary",onClick:h,children:"Update"}),s.jsx("button",{className:"update-banner-x",onClick:i,"aria-label":"Dismiss",children:"×"})]})]})}),l&&s.jsx("div",{className:"update-overlay",children:s.jsxs("div",{className:"update-overlay-card",role:"dialog","aria-modal":"true","aria-label":"Finishing the update",children:[s.jsx("div",{className:"update-spinner"}),s.jsxs("h2",{children:["Finishing the update","…"]}),s.jsxs("p",{children:["Copy this command and run it in your terminal. The gateway will restart, and"," ",s.jsx("strong",{children:"this page updates automatically"})," when it comes back ","—"," no need to refresh."]}),s.jsxs("div",{className:"update-cmd-row",children:[s.jsx("code",{className:"update-cmd",children:x}),s.jsx("button",{className:"btn btn-sm btn-primary",onClick:m,children:d?"Copied":"Copy"})]}),s.jsxs("div",{className:"update-status",children:[s.jsx("span",{className:"update-pulse"})," Waiting for the gateway to restart","…"]}),s.jsxs("div",{className:"update-overlay-actions",children:[s.jsx("button",{className:"btn btn-primary",onClick:()=>v(n),children:"Reload now"}),s.jsx("button",{className:"btn btn-secondary",onClick:()=>c(!1),children:"Cancel"})]})]})})]})}const wy={system:"◑",light:"☀",dark:"☾"},Sy=[{to:"/",icon:"□",label:"Dashboard"},{to:"/proposals",icon:"▷",label:"Pending Approvals"},{to:"/authorizations",icon:"☰",label:"Authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief"},{to:"/audit",icon:"▣",label:"Receipts"},{to:"/groups",icon:"◉",label:"Team"},{to:"/integrations",icon:"⧗",label:"Integrations"},{to:"/settings",icon:"⚙",label:"AI Assistant"}];function jy({open:e,onClose:t}){const{user:n,activeGroup:r,activeDomain:a,logout:o}=$e(),{theme:i,toggle:l}=Af(),c=St();return u.useEffect(()=>{t()},[c.pathname]),e?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mobile-menu-backdrop",onClick:t}),s.jsxs("div",{className:"mobile-menu-panel",children:[n&&s.jsxs("div",{className:"mobile-menu-header",children:[s.jsx("strong",{children:n.name}),s.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-secondary)"},children:r?`${r.name} / ${a}`:a||"personal"})]}),s.jsx("nav",{className:"mobile-menu-nav",children:Sy.map(d=>s.jsxs(Sl,{to:d.to,end:d.to==="/",className:({isActive:f})=>`mobile-menu-item${f?" active":""}`,onClick:t,children:[s.jsx("span",{className:"icon",children:d.icon}),d.label]},d.to))}),s.jsxs("div",{className:"mobile-menu-footer",children:[s.jsxs("button",{className:"mobile-menu-action",onClick:()=>{l()},children:[s.jsx("span",{className:"icon",children:wy[i]}),"Theme: ",i]}),s.jsx("button",{className:"mobile-menu-action",onClick:()=>{o(),t()},children:"Logout"})]})]})]}):null}function ky(){const[e,t]=u.useState(!1);return s.jsxs(fy,{children:[s.jsx(kl,{onMenuToggle:()=>t(!e)}),s.jsx(Mf,{}),s.jsx(yy,{}),s.jsx(jy,{open:e,onClose:()=>t(!1)}),s.jsx("div",{className:"main-content",children:s.jsx("div",{className:"page-inner",children:s.jsx(xg,{})})})]})}function by(){const[e,t]=u.useState(""),{login:n,isLoading:r,error:a,clearError:o}=$e(),[i,l]=u.useState(null),c=async()=>{if(e.trim()){o();try{await n(e)}catch(g){if(g instanceof Pf){l(g.summary);return}}}},d=async()=>{l(null),o();try{await n(e,{confirmWipe:!0})}catch{}},f=()=>{l(null)};return s.jsxs(s.Fragment,{children:[s.jsx(kl,{}),s.jsx(Mf,{}),s.jsxs("div",{className:"login-split",children:[s.jsx("div",{className:"login-split-left",children:s.jsxs("div",{style:{maxWidth:"28rem"},children:[s.jsx("h1",{style:{fontSize:"clamp(2.25rem, 4vw, 3.25rem)",letterSpacing:"-0.03em",lineHeight:1.1,marginBottom:"1.25rem"},children:"Your agents, your intent, your rules."}),s.jsx("p",{style:{fontSize:"1.125rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"3rem"},children:"The gateway runs on your machine, between your agents and the tools they use. Your signature. Your bounds. Your receipts."})]})}),s.jsx("div",{className:"login-split-right",children:s.jsxs("div",{style:{width:"100%",maxWidth:"24rem"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsx("div",{style:{fontSize:"1.75rem",fontWeight:700,marginBottom:"0.5rem"},children:"Sign In"}),s.jsx("div",{style:{fontSize:"0.95rem",color:"var(--text-secondary)",lineHeight:1.5},children:"Enter your API key to manage authorizations."})]}),a&&s.jsx("div",{className:"error-message",children:a}),s.jsxs("div",{className:"form-group",style:{marginBottom:"1.5rem"},children:[s.jsx("label",{className:"form-label",children:"API Key"}),s.jsx("input",{className:"form-input",type:"password",placeholder:"hap_sk_...",value:e,onChange:g=>t(g.target.value),onKeyDown:g=>g.key==="Enter"&&c(),disabled:r,style:{padding:"0.75rem"}}),s.jsx("div",{className:"form-hint",children:"From your Suveren account."})]}),s.jsx("button",{className:"btn btn-primary btn-full btn-lg",onClick:c,disabled:r,style:{marginBottom:"2rem"},children:r?"Signing in...":"Sign In"}),s.jsx("div",{className:"login-divider",children:"New here?"}),s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsxs("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",marginBottom:"1rem",lineHeight:1.5},children:["Create an account on Suveren,",s.jsx("br",{}),"then come back to sign in."]}),s.jsx("a",{href:"https://www.suveren.ai/get-started",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-full",style:{textDecoration:"none"},children:"Create Account"})]}),s.jsxs("div",{style:{paddingTop:"1.75rem",borderTop:"1px solid var(--border)"},children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",marginBottom:"0.875rem"},children:"Getting started"}),s.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.8},children:[s.jsxs(s.Fragment,{children:["Create an account at ",s.jsx("a",{href:"https://www.suveren.ai/get-started",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:"Suveren"})]}),"Join or create a team to get domain authority","Sign in here with your API key to start authorizing agents"].map((g,p)=>s.jsxs("div",{style:{display:"flex",gap:"0.625rem",alignItems:"baseline",marginBottom:p<2?"0.5rem":0},children:[s.jsxs("span",{style:{color:"var(--accent)",fontWeight:700,fontSize:"0.95rem"},children:[p+1,"."]}),g]},p))})]})]})})]}),i&&s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"wipe-warning-title",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"1rem"},onClick:f,children:s.jsxs("div",{className:"card",onClick:g=>g.stopPropagation(),style:{maxWidth:520,width:"100%",margin:0},children:[s.jsx("h3",{id:"wipe-warning-title",className:"card-title",style:{marginBottom:"0.5rem"},children:"Sign in with a different account?"}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"0.75rem"},children:["This gateway already holds data for another account. Signing in with this API key will ",s.jsx("strong",{children:"permanently wipe"})," the following local data:"]}),s.jsxs("ul",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem",paddingLeft:"1.25rem",lineHeight:1.6},children:[s.jsxs("li",{children:[i.credentialCount," stored service credential",i.credentialCount===1?"":"s",i.credentialIds.length>0&&s.jsxs("span",{style:{color:"var(--text-tertiary)",fontSize:"0.825rem"},children:[" ","(",i.credentialIds.slice(0,5).join(", "),i.credentialIds.length>5?`, +${i.credentialIds.length-5} more`:"",")"]})]}),s.jsxs("li",{children:[i.serviceCount," configured integration",i.serviceCount===1?"":"s"]}),s.jsx("li",{children:"The local E2EE keypair (a new one will be generated for this account)"}),s.jsx("li",{children:"Any unsynchronised gate content stored locally"})]}),s.jsx("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Authorizations and receipts on the Service Provider are NOT affected — only this gateway's local state is wiped."}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-tertiary)",marginBottom:"1rem"},children:"If this isn't what you wanted, cancel and sign back in with the original API key, or use a different gateway instance for this account."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:f,disabled:r,children:"Cancel"}),s.jsx("button",{className:"btn btn-secondary",style:{color:"var(--danger, #e53e3e)"},onClick:d,disabled:r,children:r?"Signing in...":"Wipe local data and sign in"})]})]})})]})}function Cy(){const{setActiveContext:e}=$e(),t=Qt(),[n,r]=u.useState(""),[a,o]=u.useState(""),[i,l]=u.useState(""),[c,d]=u.useState(!1),f=async()=>{if(n.trim()){d(!0),l("");try{const p=await A.joinGroup(n.trim());e(p,p.myDomains[0]||""),t("/")}catch(p){l(p instanceof Error?p.message:"Failed to join group")}finally{d(!1)}}},g=async()=>{if(a.trim()){d(!0),l("");try{const p=await A.createGroup(a.trim());e(p,p.myDomains[0]||""),t("/")}catch(p){l(p instanceof Error?p.message:"Failed to create group")}finally{d(!1)}}};return s.jsxs(s.Fragment,{children:[s.jsx(kl,{}),s.jsx("div",{className:"main-content no-sidebar",style:{marginTop:"var(--nav-height)"},children:s.jsxs("div",{style:{maxWidth:"30rem",margin:"3rem auto",padding:"0 1rem"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsx("h2",{style:{fontSize:"1.5rem",marginBottom:"0.5rem"},children:"Join Your Team"}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6},children:"Join an existing team or create a new one to share authority across domains."})]}),i&&s.jsx("div",{className:"error-message",children:i}),s.jsxs("div",{className:"card",style:{marginBottom:"1rem"},children:[s.jsx("h4",{style:{fontSize:"0.95rem",marginBottom:"0.25rem"},children:"Join an existing group"}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Ask your team admin for an invite code."}),s.jsxs("div",{className:"invite-input-row",children:[s.jsx("input",{className:"form-input",placeholder:"Paste invite code...",value:n,onChange:p=>r(p.target.value),onKeyDown:p=>p.key==="Enter"&&f(),style:{fontFamily:"'SF Mono', Monaco, monospace",fontSize:"0.85rem"},disabled:c}),s.jsx("button",{className:"btn btn-primary",onClick:f,disabled:c,children:"Join"})]})]}),s.jsxs("div",{className:"card",children:[s.jsx("h4",{style:{fontSize:"0.95rem",marginBottom:"0.25rem"},children:"Create a new group"}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Start a new team and invite members. Assign domains after creation."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{className:"form-input",placeholder:"Group name (e.g., Acme Corp)",value:a,onChange:p=>o(p.target.value),onKeyDown:p=>p.key==="Enter"&&g(),style:{flex:1},disabled:c}),s.jsx("button",{className:"btn btn-secondary",onClick:g,disabled:c,children:"Create"})]})]})]})})]})}const hi="suveren-setup-ai-skipped",gi="suveren-setup-agent-done",yi="suveren-setup-dismissed",Ny={"hap-setup-ai-skipped":hi,"hap-setup-agent-done":gi,"hap-setup-dismissed":yi};function Ey(){for(const[e,t]of Object.entries(Ny)){const n=localStorage.getItem(e);n!==null&&localStorage.getItem(t)===null&&localStorage.setItem(t,n),n!==null&&localStorage.removeItem(e)}}Ey();const go={"claude-code":{label:"Claude Code",snippet:e=>JSON.stringify({mcpServers:{"suveren-gateway":{url:`${e}/sse`}}},null,2)},"claude-desktop":{label:"Claude Desktop",snippet:e=>`Add to ~/Library/Application Support/Claude/claude_desktop_config.json:
51
+ Please change the parent <Route path="${h}"> to <Route path="${h==="/"?"*":`${h}/*`}">.`)}let f=St(),g;if(t){let h=typeof t=="string"?mr(t):t;ve(c==="/"||((j=h.pathname)==null?void 0:j.startsWith(c)),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${h.pathname}" was given in the \`location\` prop.`),g=h}else g=f;let p=g.pathname||"/",x=p;if(c!=="/"){let h=c.replace(/^\//,"").split("/");x="/"+p.replace(/^\//,"").split("/").slice(h.length).join("/")}let w=mf(e,{pathname:x});wt(d||w!=null,`No routes matched location "${g.pathname}${g.search}${g.hash}" `),wt(w==null||w[w.length-1].route.element!==void 0||w[w.length-1].route.Component!==void 0||w[w.length-1].route.lazy!==void 0,`Matched leaf route at location "${g.pathname}${g.search}${g.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let v=dg(w&&w.map(h=>Object.assign({},h,{params:Object.assign({},i,h.params),pathname:Mt([c,r.encodeLocation?r.encodeLocation(h.pathname.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:h.pathname]),pathnameBase:h.pathnameBase==="/"?c:Mt([c,r.encodeLocation?r.encodeLocation(h.pathnameBase.replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:h.pathnameBase])})),a,n);return t&&v?u.createElement(ca.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...g},navigationType:"POP"}},v):v}function ig(){let e=gg(),t=Kh(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r="rgba(200,200,200, 0.5)",a={padding:"0.5rem",backgroundColor:r},o={padding:"2px 4px",backgroundColor:r},i=null;return console.error("Error handled by React Router default ErrorBoundary:",e),i=u.createElement(u.Fragment,null,u.createElement("p",null,"💿 Hey developer 👋"),u.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",u.createElement("code",{style:o},"ErrorBoundary")," or"," ",u.createElement("code",{style:o},"errorElement")," prop on your route.")),u.createElement(u.Fragment,null,u.createElement("h2",null,"Unexpected Application Error!"),u.createElement("h3",{style:{fontStyle:"italic"}},t),n?u.createElement("pre",{style:a},n):null,i)}var lg=u.createElement(ig,null),bf=class extends u.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=tg(e.digest);n&&(e=n)}let t=e!==void 0?u.createElement(zt.Provider,{value:this.props.routeContext},u.createElement(gl.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?u.createElement(cg,{error:e},t):t}};bf.contextType=Qh;var mo=new WeakMap;function cg({children:e,error:t}){let{basename:n}=u.useContext(dt);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let r=eg(t.digest);if(r){let a=mo.get(t);if(a)throw a;let o=yf(r.location,n);if(gf&&!mo.get(t))if(o.isExternal||r.reloadDocument)window.location.href=o.absoluteURL||o.to;else{const i=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(o.to,{replace:r.replace}));throw mo.set(t,i),i}return u.createElement("meta",{httpEquiv:"refresh",content:`0;url=${o.absoluteURL||o.to}`})}}return e}function ug({routeContext:e,match:t,children:n}){let r=u.useContext(pr);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),u.createElement(zt.Provider,{value:e},n)}function dg(e,t=[],n){let r=n==null?void 0:n.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let a=e,o=r==null?void 0:r.errors;if(o!=null){let f=a.findIndex(g=>g.route.id&&(o==null?void 0:o[g.route.id])!==void 0);ve(f>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(o).join(",")}`),a=a.slice(0,Math.min(a.length,f+1))}let i=!1,l=-1;if(n&&r){i=r.renderFallback;for(let f=0;f<a.length;f++){let g=a[f];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(l=f),g.route.id){let{loaderData:p,errors:x}=r,w=g.route.loader&&!p.hasOwnProperty(g.route.id)&&(!x||x[g.route.id]===void 0);if(g.route.lazy||w){n.isStatic&&(i=!0),l>=0?a=a.slice(0,l+1):a=[a[0]];break}}}}let c=n==null?void 0:n.onError,d=r&&c?(f,g)=>{var p,x;c(f,{location:r.location,params:((x=(p=r.matches)==null?void 0:p[0])==null?void 0:x.params)??{},unstable_pattern:Gh(r.matches),errorInfo:g})}:void 0;return a.reduceRight((f,g,p)=>{let x,w=!1,v=null,j=null;r&&(x=o&&g.route.id?o[g.route.id]:void 0,v=g.route.errorElement||lg,i&&(l<0&&p===0?(Cf("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),w=!0,j=null):l===p&&(w=!0,j=g.route.hydrateFallbackElement||null)));let h=t.concat(a.slice(0,p+1)),m=()=>{let y;return x?y=v:w?y=j:g.route.Component?y=u.createElement(g.route.Component,null):g.route.element?y=g.route.element:y=f,u.createElement(ug,{match:g,routeContext:{outlet:f,matches:h,isDataRoute:r!=null},children:y})};return r&&(g.route.ErrorBoundary||g.route.errorElement||p===0)?u.createElement(bf,{location:r.location,revalidation:r.revalidation,component:v,error:x,children:m(),routeContext:{outlet:null,matches:h,isDataRoute:!0},onError:d}):m()},null)}function yl(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function fg(e){let t=u.useContext(pr);return ve(t,yl(e)),t}function mg(e){let t=u.useContext(Ls);return ve(t,yl(e)),t}function pg(e){let t=u.useContext(zt);return ve(t,yl(e)),t}function vl(e){let t=pg(e),n=t.matches[t.matches.length-1];return ve(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function hg(){return vl("useRouteId")}function gg(){var r;let e=u.useContext(gl),t=mg("useRouteError"),n=vl("useRouteError");return e!==void 0?e:(r=t.errors)==null?void 0:r[n]}function yg(){let{router:e}=fg("useNavigate"),t=vl("useNavigate"),n=u.useRef(!1);return jf(()=>{n.current=!0}),u.useCallback(async(a,o={})=>{wt(n.current,Sf),n.current&&(typeof a=="number"?await e.navigate(a):await e.navigate(a,{fromRouteId:t,...o}))},[e,t])}var Oc={};function Cf(e,t,n){!t&&!Oc[e]&&(Oc[e]=!0,wt(!1,n))}u.memo(vg);function vg({routes:e,future:t,state:n,isStatic:r,onError:a}){return kf(e,void 0,{state:n,isStatic:r,onError:a})}function Zt({to:e,replace:t,state:n,relative:r}){ve(hr(),"<Navigate> may be used only in the context of a <Router> component.");let{static:a}=u.useContext(dt);wt(!a,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:o}=u.useContext(zt),{pathname:i}=St(),l=Qt(),c=$s(e,hl(o),i,r==="path"),d=JSON.stringify(c);return u.useEffect(()=>{l(JSON.parse(d),{replace:t,state:n,relative:r})},[l,d,r,t,n]),null}function xg(e){return sg(e.context)}function Re(e){ve(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function wg({basename:e="/",children:t=null,location:n,navigationType:r="POP",navigator:a,static:o=!1,unstable_useTransitions:i}){ve(!hr(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let l=e.replace(/^\/*/,"/"),c=u.useMemo(()=>({basename:l,navigator:a,static:o,unstable_useTransitions:i,future:{}}),[l,a,o,i]);typeof n=="string"&&(n=mr(n));let{pathname:d="/",search:f="",hash:g="",state:p=null,key:x="default",unstable_mask:w}=n,v=u.useMemo(()=>{let j=Gt(d,l);return j==null?null:{location:{pathname:j,search:f,hash:g,state:p,key:x,unstable_mask:w},navigationType:r}},[l,d,f,g,p,x,r,w]);return wt(v!=null,`<Router basename="${l}"> is not able to match the URL "${d}${f}${g}" because it does not start with the basename, so the <Router> won't render anything.`),v==null?null:u.createElement(dt.Provider,{value:c},u.createElement(ca.Provider,{children:t,value:v}))}function Sg({children:e,location:t}){return og(mi(e),t)}function mi(e,t=[]){let n=[];return u.Children.forEach(e,(r,a)=>{if(!u.isValidElement(r))return;let o=[...t,a];if(r.type===u.Fragment){n.push.apply(n,mi(r.props.children,o));return}ve(r.type===Re,`[${typeof r.type=="string"?r.type:r.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),ve(!r.props.index||!r.props.children,"An index route cannot have child routes.");let i={id:r.props.id||o.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,middleware:r.props.middleware,loader:r.props.loader,action:r.props.action,hydrateFallbackElement:r.props.hydrateFallbackElement,HydrateFallback:r.props.HydrateFallback,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.hasErrorBoundary===!0||r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(i.children=mi(r.props.children,o)),n.push(i)}),n}var Wa="get",Ha="application/x-www-form-urlencoded";function Ms(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function jg(e){return Ms(e)&&e.tagName.toLowerCase()==="button"}function kg(e){return Ms(e)&&e.tagName.toLowerCase()==="form"}function bg(e){return Ms(e)&&e.tagName.toLowerCase()==="input"}function Cg(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Ng(e,t){return e.button===0&&(!t||t==="_self")&&!Cg(e)}function pi(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function Eg(e,t){let n=pi(e);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(o=>{n.append(a,o)})}),n}var Ta=null;function Tg(){if(Ta===null)try{new FormData(document.createElement("form"),0),Ta=!1}catch{Ta=!0}return Ta}var zg=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function po(e){return e!=null&&!zg.has(e)?(wt(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Ha}"`),null):e}function Ig(e,t){let n,r,a,o,i;if(kg(e)){let l=e.getAttribute("action");r=l?Gt(l,t):null,n=e.getAttribute("method")||Wa,a=po(e.getAttribute("enctype"))||Ha,o=new FormData(e)}else if(jg(e)||bg(e)&&(e.type==="submit"||e.type==="image")){let l=e.form;if(l==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let c=e.getAttribute("formaction")||l.getAttribute("action");if(r=c?Gt(c,t):null,n=e.getAttribute("formmethod")||l.getAttribute("method")||Wa,a=po(e.getAttribute("formenctype"))||po(l.getAttribute("enctype"))||Ha,o=new FormData(l,e),!Tg()){let{name:d,type:f,value:g}=e;if(f==="image"){let p=d?`${d}.`:"";o.append(`${p}x`,"0"),o.append(`${p}y`,"0")}else d&&o.append(d,g)}}else{if(Ms(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n=Wa,r=null,a=Ha,i=e}return o&&a==="text/plain"&&(i=o,o=void 0),{action:r,method:n.toLowerCase(),encType:a,formData:o,body:i}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");function xl(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Pg(e,t,n,r){let a=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n?a.pathname.endsWith("/")?a.pathname=`${a.pathname}_.${r}`:a.pathname=`${a.pathname}.${r}`:a.pathname==="/"?a.pathname=`_root.${r}`:t&&Gt(a.pathname,t)==="/"?a.pathname=`${t.replace(/\/$/,"")}/_root.${r}`:a.pathname=`${a.pathname.replace(/\/$/,"")}.${r}`,a}async function Rg(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function _g(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function Ag(e,t,n){let r=await Promise.all(e.map(async a=>{let o=t.routes[a.route.id];if(o){let i=await Rg(o,n);return i.links?i.links():[]}return[]}));return Fg(r.flat(1).filter(_g).filter(a=>a.rel==="stylesheet"||a.rel==="preload").map(a=>a.rel==="stylesheet"?{...a,rel:"prefetch",as:"style"}:{...a,rel:"prefetch"}))}function Bc(e,t,n,r,a,o){let i=(c,d)=>n[d]?c.route.id!==n[d].route.id:!0,l=(c,d)=>{var f;return n[d].pathname!==c.pathname||((f=n[d].route.path)==null?void 0:f.endsWith("*"))&&n[d].params["*"]!==c.params["*"]};return o==="assets"?t.filter((c,d)=>i(c,d)||l(c,d)):o==="data"?t.filter((c,d)=>{var g;let f=r.routes[c.route.id];if(!f||!f.hasLoader)return!1;if(i(c,d)||l(c,d))return!0;if(c.route.shouldRevalidate){let p=c.route.shouldRevalidate({currentUrl:new URL(a.pathname+a.search+a.hash,window.origin),currentParams:((g=n[0])==null?void 0:g.params)||{},nextUrl:new URL(e,window.origin),nextParams:c.params,defaultShouldRevalidate:!0});if(typeof p=="boolean")return p}return!0}):[]}function $g(e,t,{includeHydrateFallback:n}={}){return Lg(e.map(r=>{let a=t.routes[r.route.id];if(!a)return[];let o=[a.module];return a.clientActionModule&&(o=o.concat(a.clientActionModule)),a.clientLoaderModule&&(o=o.concat(a.clientLoaderModule)),n&&a.hydrateFallbackModule&&(o=o.concat(a.hydrateFallbackModule)),a.imports&&(o=o.concat(a.imports)),o}).flat(1))}function Lg(e){return[...new Set(e)]}function Mg(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Fg(e,t){let n=new Set;return new Set(t),e.reduce((r,a)=>{let o=JSON.stringify(Mg(a));return n.has(o)||(n.add(o),r.push({key:o,link:a})),r},[])}function Nf(){let e=u.useContext(pr);return xl(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function Og(){let e=u.useContext(Ls);return xl(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}var wl=u.createContext(void 0);wl.displayName="FrameworkContext";function Ef(){let e=u.useContext(wl);return xl(e,"You must render this element inside a <HydratedRouter> element"),e}function Bg(e,t){let n=u.useContext(wl),[r,a]=u.useState(!1),[o,i]=u.useState(!1),{onFocus:l,onBlur:c,onMouseEnter:d,onMouseLeave:f,onTouchStart:g}=t,p=u.useRef(null);u.useEffect(()=>{if(e==="render"&&i(!0),e==="viewport"){let v=h=>{h.forEach(m=>{i(m.isIntersecting)})},j=new IntersectionObserver(v,{threshold:.5});return p.current&&j.observe(p.current),()=>{j.disconnect()}}},[e]),u.useEffect(()=>{if(r){let v=setTimeout(()=>{i(!0)},100);return()=>{clearTimeout(v)}}},[r]);let x=()=>{a(!0)},w=()=>{a(!1),i(!1)};return n?e!=="intent"?[o,p,{}]:[o,p,{onFocus:br(l,x),onBlur:br(c,w),onMouseEnter:br(d,x),onMouseLeave:br(f,w),onTouchStart:br(g,x)}]:[!1,p,{}]}function br(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Dg({page:e,...t}){let{router:n}=Nf(),r=u.useMemo(()=>mf(n.routes,e,n.basename),[n.routes,e,n.basename]);return r?u.createElement(Wg,{page:e,matches:r,...t}):null}function Ug(e){let{manifest:t,routeModules:n}=Ef(),[r,a]=u.useState([]);return u.useEffect(()=>{let o=!1;return Ag(e,t,n).then(i=>{o||a(i)}),()=>{o=!0}},[e,t,n]),r}function Wg({page:e,matches:t,...n}){let r=St(),{future:a,manifest:o,routeModules:i}=Ef(),{basename:l}=Nf(),{loaderData:c,matches:d}=Og(),f=u.useMemo(()=>Bc(e,t,d,o,r,"data"),[e,t,d,o,r]),g=u.useMemo(()=>Bc(e,t,d,o,r,"assets"),[e,t,d,o,r]),p=u.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let v=new Set,j=!1;if(t.forEach(m=>{var S;let y=o.routes[m.route.id];!y||!y.hasLoader||(!f.some(b=>b.route.id===m.route.id)&&m.route.id in c&&((S=i[m.route.id])!=null&&S.shouldRevalidate)||y.hasClientLoader?j=!0:v.add(m.route.id))}),v.size===0)return[];let h=Pg(e,l,a.unstable_trailingSlashAwareDataRequests,"data");return j&&v.size>0&&h.searchParams.set("_routes",t.filter(m=>v.has(m.route.id)).map(m=>m.route.id).join(",")),[h.pathname+h.search]},[l,a.unstable_trailingSlashAwareDataRequests,c,r,o,f,t,e,i]),x=u.useMemo(()=>$g(g,o),[g,o]),w=Ug(g);return u.createElement(u.Fragment,null,p.map(v=>u.createElement("link",{key:v,rel:"prefetch",as:"fetch",href:v,...n})),x.map(v=>u.createElement("link",{key:v,rel:"modulepreload",href:v,...n})),w.map(({key:v,link:j})=>u.createElement("link",{key:v,nonce:n.nonce,...j,crossOrigin:j.crossOrigin??n.crossOrigin})))}function Hg(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var Vg=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{Vg&&(window.__reactRouterVersion="7.13.1")}catch{}function Kg({basename:e,children:t,unstable_useTransitions:n,window:r}){let a=u.useRef();a.current==null&&(a.current=jh({window:r,v5Compat:!0}));let o=a.current,[i,l]=u.useState({action:o.action,location:o.location}),c=u.useCallback(d=>{n===!1?l(d):u.startTransition(()=>l(d))},[n]);return u.useLayoutEffect(()=>o.listen(c),[o,c]),u.createElement(wg,{basename:e,children:t,location:i.location,navigationType:i.action,navigator:o,unstable_useTransitions:n})}var Tf=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Ge=u.forwardRef(function({onClick:t,discover:n="render",prefetch:r="none",relative:a,reloadDocument:o,replace:i,unstable_mask:l,state:c,target:d,to:f,preventScrollReset:g,viewTransition:p,unstable_defaultShouldRevalidate:x,...w},v){let{basename:j,navigator:h,unstable_useTransitions:m}=u.useContext(dt),y=typeof f=="string"&&Tf.test(f),S=yf(f,j);f=S.to;let b=ng(f,{relative:a}),T=St(),E=null;if(l){let N=$s(l,[],T.unstable_mask?T.unstable_mask.pathname:"/",!0);j!=="/"&&(N.pathname=N.pathname==="/"?j:Mt([j,N.pathname])),E=h.createHref(N)}let[P,k,z]=Bg(r,w),O=Qg(f,{replace:i,unstable_mask:l,state:c,target:d,preventScrollReset:g,relative:a,viewTransition:p,unstable_defaultShouldRevalidate:x,unstable_useTransitions:m});function K(N){t&&t(N),N.defaultPrevented||O(N)}let V=!(S.isExternal||o),U=u.createElement("a",{...w,...z,href:(V?E:void 0)||S.absoluteURL||b,onClick:V?K:t,ref:Hg(v,k),target:d,"data-discover":!y&&n==="render"?"true":void 0});return P&&!y?u.createElement(u.Fragment,null,U,u.createElement(Dg,{page:b})):U});Ge.displayName="Link";var Sl=u.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:r="",end:a=!1,style:o,to:i,viewTransition:l,children:c,...d},f){let g=ua(i,{relative:d.relative}),p=St(),x=u.useContext(Ls),{navigator:w,basename:v}=u.useContext(dt),j=x!=null&&ey(g)&&l===!0,h=w.encodeLocation?w.encodeLocation(g).pathname:g.pathname,m=p.pathname,y=x&&x.navigation&&x.navigation.location?x.navigation.location.pathname:null;n||(m=m.toLowerCase(),y=y?y.toLowerCase():null,h=h.toLowerCase()),y&&v&&(y=Gt(y,v)||y);const S=h!=="/"&&h.endsWith("/")?h.length-1:h.length;let b=m===h||!a&&m.startsWith(h)&&m.charAt(S)==="/",T=y!=null&&(y===h||!a&&y.startsWith(h)&&y.charAt(h.length)==="/"),E={isActive:b,isPending:T,isTransitioning:j},P=b?t:void 0,k;typeof r=="function"?k=r(E):k=[r,b?"active":null,T?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let z=typeof o=="function"?o(E):o;return u.createElement(Ge,{...d,"aria-current":P,className:k,ref:f,style:z,to:i,viewTransition:l},typeof c=="function"?c(E):c)});Sl.displayName="NavLink";var Gg=u.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:r,replace:a,state:o,method:i=Wa,action:l,onSubmit:c,relative:d,preventScrollReset:f,viewTransition:g,unstable_defaultShouldRevalidate:p,...x},w)=>{let{unstable_useTransitions:v}=u.useContext(dt),j=qg(),h=Zg(l,{relative:d}),m=i.toLowerCase()==="get"?"get":"post",y=typeof l=="string"&&Tf.test(l),S=b=>{if(c&&c(b),b.defaultPrevented)return;b.preventDefault();let T=b.nativeEvent.submitter,E=(T==null?void 0:T.getAttribute("formmethod"))||i,P=()=>j(T||b.currentTarget,{fetcherKey:t,method:E,navigate:n,replace:a,state:o,relative:d,preventScrollReset:f,viewTransition:g,unstable_defaultShouldRevalidate:p});v&&n!==!1?u.startTransition(()=>P()):P()};return u.createElement("form",{ref:w,method:m,action:h,onSubmit:r?c:S,...x,"data-discover":!y&&e==="render"?"true":void 0})});Gg.displayName="Form";function Yg(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function zf(e){let t=u.useContext(pr);return ve(t,Yg(e)),t}function Qg(e,{target:t,replace:n,unstable_mask:r,state:a,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c,unstable_useTransitions:d}={}){let f=Qt(),g=St(),p=ua(e,{relative:i});return u.useCallback(x=>{if(Ng(x,t)){x.preventDefault();let w=n!==void 0?n:ra(g)===ra(p),v=()=>f(e,{replace:w,unstable_mask:r,state:a,preventScrollReset:o,relative:i,viewTransition:l,unstable_defaultShouldRevalidate:c});d?u.startTransition(()=>v()):v()}},[g,f,p,n,r,a,t,e,o,i,l,c,d])}function If(e){wt(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=u.useRef(pi(e)),n=u.useRef(!1),r=St(),a=u.useMemo(()=>Eg(r.search,n.current?null:t.current),[r.search]),o=Qt(),i=u.useCallback((l,c)=>{const d=pi(typeof l=="function"?l(new URLSearchParams(a)):l);n.current=!0,o("?"+d,c)},[o,a]);return[a,i]}var Jg=0,Xg=()=>`__${String(++Jg)}__`;function qg(){let{router:e}=zf("useSubmit"),{basename:t}=u.useContext(dt),n=hg(),r=e.fetch,a=e.navigate;return u.useCallback(async(o,i={})=>{let{action:l,method:c,encType:d,formData:f,body:g}=Ig(o,t);if(i.navigate===!1){let p=i.fetcherKey||Xg();await r(p,n,i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:g,formMethod:i.method||c,formEncType:i.encType||d,flushSync:i.flushSync})}else await a(i.action||l,{unstable_defaultShouldRevalidate:i.unstable_defaultShouldRevalidate,preventScrollReset:i.preventScrollReset,formData:f,body:g,formMethod:i.method||c,formEncType:i.encType||d,replace:i.replace,state:i.state,fromRouteId:n,flushSync:i.flushSync,viewTransition:i.viewTransition})},[r,a,t,n])}function Zg(e,{relative:t}={}){let{basename:n}=u.useContext(dt),r=u.useContext(zt);ve(r,"useFormAction must be used inside a RouteContext");let[a]=r.matches.slice(-1),o={...ua(e||".",{relative:t})},i=St();if(e==null){o.search=i.search;let l=new URLSearchParams(o.search),c=l.getAll("index");if(c.some(f=>f==="")){l.delete("index"),c.filter(g=>g).forEach(g=>l.append("index",g));let f=l.toString();o.search=f?`?${f}`:""}}return(!e||e===".")&&a.route.index&&(o.search=o.search?o.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(o.pathname=o.pathname==="/"?n:Mt([n,o.pathname])),ra(o)}function ey(e,{relative:t}={}){let n=u.useContext(xf);ve(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=zf("useViewTransitionState"),a=ua(e,{relative:t});if(!n.isTransitioning)return!1;let o=Gt(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=Gt(n.nextLocation.pathname,r)||n.nextLocation.pathname;return gs(a.pathname,i)!=null||gs(a.pathname,o)!=null}class Pf extends Error{constructor(n){super("different_account");Fs(this,"summary");this.name="DifferentAccountError",this.summary=n}}class ty{constructor(){Fs(this,"apiKey",null)}setApiKey(t){this.apiKey=t}clearApiKey(){this.apiKey=null}getApiKey(){return this.apiKey}async fetch(t,n){return globalThis.fetch(t,{...n,headers:{"Content-Type":"application/json",...this.apiKey?{"X-API-Key":this.apiKey}:{},...n==null?void 0:n.headers}})}async login(t,n={}){const r=await this.fetch("/auth/login",{method:"POST",headers:{"X-API-Key":t,"Content-Type":"application/json"},body:JSON.stringify({confirmWipe:n.confirmWipe===!0})});if(r.status===409){const o=await r.json().catch(()=>({}));if(o!=null&&o.wouldWipe)throw new Pf(o.summary??{credentialCount:0,serviceCount:0,credentialIds:[]})}if(!r.ok){const o=await r.json().catch(()=>({error:"Invalid API key"}));throw new Error(o.error||`Login failed: ${r.status}`)}return(await r.json()).user}async logout(){await this.fetch("/auth/logout",{method:"POST"})}async getGroups(){const t=await this.fetch("/api/groups");if(!t.ok)throw new Error(`Failed to fetch groups: ${t.status}`);const n=await t.json();return n.groups??n}async listProfiles(){const t=await this.fetch("/api/profiles");if(!t.ok)throw new Error(`Failed to fetch profiles: ${t.status}`);return(await t.json()).profiles}async getProfile(t){const n=await this.fetch(`/api/profiles/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch profile: ${n.status}`);return n.json()}async attest(t){const n=await this.fetch("/api/as/attest",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`Attest failed: ${n.status}`)}return n.json()}async getPending(t){const n=await this.fetch(`/api/attestations/pending?domain=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch pending: ${n.status}`);const r=await n.json();return r.pending??r}async getMyAttestations(t){const n=t?`?status=${encodeURIComponent(t)}`:"",r=await this.fetch(`/api/attestations/mine${n}`);if(!r.ok)throw new Error(`Failed to fetch attestations: ${r.status}`);return((await r.json()).attestations??[]).map(o=>{var i,l;return{authorization_id:o.authorization_id,profile_id:o.profileId,path:o.path,title:o.title??null,sp_status:o.status??null,frame:o.bounds??o.frame??{},required_domains:o.requiredDomains??[],attested_domains:o.attestedDomains??[],missing_domains:(o.requiredDomains??[]).filter(c=>!(o.attestedDomains??[]).includes(c)),deferred_commitment_domains:o.deferredCommitmentDomains??[],approvers_frozen:o.approversFrozen??[],above_cap:o.aboveCap??!1,created_at:o.createdAt?new Date(o.createdAt*1e3).toISOString():"",earliest_expiry:(i=o.attestations)!=null&&i.length?new Date(Math.min(...o.attestations.map(c=>c.expiresAt))*1e3).toISOString():null,remaining_seconds:(l=o.attestations)!=null&&l.length?Math.max(0,Math.min(...o.attestations.map(c=>c.expiresAt))-Math.floor(Date.now()/1e3)):null}})}async getDenials(t){const n=new URLSearchParams;t!=null&&t.since&&n.set("since",String(t.since)),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",a=await this.fetch(`/denials${r}`);if(!a.ok)throw new Error(`Failed to fetch denials: ${a.status}`);return a.json()}async getMyReceipts(t){const n=new URLSearchParams;t!=null&&t.date&&n.set("date",t.date),t!=null&&t.profile&&n.set("profile",t.profile),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!a.ok)throw new Error(`Failed to fetch receipts: ${a.status}`);return(await a.json()).receipts??[]}async revokeAttestation(t,n){const r=await this.fetch(`/api/authorizations/${encodeURIComponent(t)}/revoke`,{method:"POST",body:JSON.stringify({reason:n??"Revoked by user"})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to revoke"}));throw new Error(a.error||`Revoke failed: ${r.status}`)}}async getAttestations(t){const n=await this.fetch(`/api/attestations?authorization_id=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch attestations: ${n.status}`);return n.json()}async getGroupById(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch group: ${n.status}`);return n.json()}async createGroup(t){const n=await this.fetch("/api/groups",{method:"POST",body:JSON.stringify({name:t})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(o.error||`Create group failed: ${n.status}`)}const r=await n.json(),a=r.group||r;return{id:a.id,name:a.name,myDomains:a.myDomains||[],isAdmin:!0}}async joinGroup(t){const n=await this.fetch("/api/groups/join",{method:"POST",body:JSON.stringify({inviteCode:t})});if(!n.ok){const o=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(o.error||`Join group failed: ${n.status}`)}const r=await n.json(),a=r.group||r;return{id:a.id,name:a.name,myDomains:a.myDomains||[],isAdmin:a.isAdmin||!1}}async inviteToGroup(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/invite`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Unknown error"}));throw new Error(r.error||`Invite failed: ${n.status}`)}return n.json()}async getMyTeam(){const t=await this.fetch("/api/groups/me");if(!t.ok)return null;const n=await t.json();return n.group?{group:n.group,membership:n.membership}:null}async listUsers(){const t=await this.fetch("/api/users");return t.ok?(await t.json()).users??[]:[]}async setPubkey(t){const n=await this.fetch("/api/users/me/pubkey",{method:"PUT",body:JSON.stringify({pubkey:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to set pubkey"}));throw new Error(r.error||`setPubkey failed: ${n.status}`)}}async getPubkey(t){const n=await this.fetch(`/api/users/${encodeURIComponent(t)}/pubkey`);return n.status===404||!n.ok?null:(await n.json()).pubkey??null}async leaveTeam(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/leave`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to leave team"}));throw new Error(r.error||`Leave failed: ${n.status}`)}}async getVaultStatus(){const t=await this.fetch("/vault/status");if(!t.ok)throw new Error(`Failed to fetch vault status: ${t.status}`);return t.json()}async getCredential(t){const n=await this.fetch(`/vault/credentials/${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to check credential: ${n.status}`);return n.json()}async setCredential(t,n){const r=await this.fetch(`/vault/credentials/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)});if(!r.ok)throw new Error(`Failed to save credential: ${r.status}`)}async testCredential(t){const n=await this.fetch(`/vault/test/${encodeURIComponent(t)}`,{method:"POST"});if(!n.ok)throw new Error(`Test failed: ${n.status}`);return n.json()}async aiAssist(t){const n=await this.fetch("/ai/assist",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI request failed"}))).error,disclaimer:"AI surfaces reality. You supply intent."}}async aiIntentReview(t){const n=await this.fetch("/ai/intent-review",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI request failed"}))).error}}async aiTest(t){const n=await this.fetch("/ai/test",{method:"POST",body:JSON.stringify(t??{})});if(!n.ok)throw new Error(`AI test failed: ${n.status}`);return n.json()}async aiModels(t){const n=await this.fetch("/ai/models",{method:"POST",body:JSON.stringify(t??{})});if(!n.ok)throw new Error(`Model list failed: ${n.status}`);return n.json()}async getMcpHealth(){const t=await this.fetch("/mcp/health");if(!t.ok)throw new Error(`MCP server unreachable: ${t.status}`);return t.json()}async getMcpIntegrations(){const t=await this.fetch("/mcp/integrations");if(!t.ok)throw new Error(`Failed to fetch integrations: ${t.status}`);return t.json()}async getOAuthHealth(t){try{const n=await this.fetch(`/auth/oauth/${encodeURIComponent(t)}/health`);return n.ok?await n.json():{status:"unverified"}}catch{return{status:"unverified"}}}async getIntegrationManifests(){const t=await this.fetch("/mcp/integrations/manifests");if(!t.ok)throw new Error(`Failed to fetch manifests: ${t.status}`);return t.json()}async discoverScopeField(t,n){const r=await this.fetch(`/integrations/${encodeURIComponent(t)}/discover/${encodeURIComponent(n)}`);if(!r.ok){const a=await r.json().catch(()=>({error:`Discovery failed: ${r.status}`}));throw new Error(a.error)}return r.json()}async activateIntegration(t){const n=await this.fetch(`/mcp/integrations/${encodeURIComponent(t)}/activate`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed"}));throw new Error(r.error||`Failed: ${n.status}`)}return n.json()}async removeMcpIntegration(t){const n=await this.fetch(`/mcp/integrations/${encodeURIComponent(t)}`,{method:"DELETE"});if(!n.ok)throw new Error(`Failed to remove integration: ${n.status}`)}async setReadPolicy(t,n){const r=await this.fetch(`/integrations/${encodeURIComponent(t)}/read-policy`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({readAgeDays:n})});if(!r.ok){const a=await r.json().catch(()=>({error:`HTTP ${r.status}`}));throw new Error(a.error)}}async getTeamProfileConfig(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`);if(r.status===404||!r.ok)return null;const a=await r.json();return(a==null?void 0:a.config)??null}async setTeamProfileConfig(t,n,r){const a=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify(r)});if(!a.ok){const o=await a.json().catch(()=>({error:"Failed to set profile config"}));throw new Error(o.error||`setTeamProfileConfig failed: ${a.status}`)}}async encryptIntent(t,n){const r=await this.fetch("/api/encrypt-intent",{method:"POST",body:JSON.stringify({intent:t,recipients:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Encryption failed"}));throw new Error(a.error||`encryptIntent failed: ${r.status}`)}return r.json()}async getApproversPubkeys(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}/approvers/pubkeys`);return r.ok?(await r.json()).approvers??[]:[]}async deleteTeamProfileConfig(t,n){const r=await this.fetch(`/api/groups/${encodeURIComponent(t)}/profile-config/${encodeURIComponent(n)}`,{method:"DELETE"});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to delete profile config"}));throw new Error(a.error||`deleteTeamProfileConfig failed: ${r.status}`)}}async getProposals(t){const n=await this.fetch(`/api/proposals?domain=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch proposals: ${n.status}`);return(await n.json()).proposals??[]}async resolveProposal(t,n,r){const a=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/resolve`,{method:"POST",body:JSON.stringify({action:n,domain:r})});if(!a.ok){const o=await a.json().catch(()=>({error:"Failed"}));throw new Error(o.error||`Failed: ${a.status}`)}return a.json()}async getProposalsForApprover(){const t=await this.fetch("/api/proposals?approver=me");if(!t.ok)throw new Error(`Failed to fetch approver proposals: ${t.status}`);return(await t.json()).proposals??[]}async approveProposal(t){const n=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/approve`,{method:"POST"});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed"}));throw new Error(r.error||`approveProposal failed: ${n.status}`)}return n.json()}async rejectProposal(t,n){const r=await this.fetch(`/api/proposals/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({reason:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed"}));throw new Error(a.error||`rejectProposal failed: ${r.status}`)}return r.json()}async getAttestationIntent(t){const n=await this.fetch(`/api/authorizations/${encodeURIComponent(t)}/intent`);return n.status===404||n.status===403||!n.ok?null:n.json()}async decryptIntent(t){const n=await this.fetch("/api/decrypt-intent",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const a=await n.json().catch(()=>({error:"Decryption failed"}));throw new Error(a.error||`decryptIntent failed: ${n.status}`)}return(await n.json()).intent}async storeApprovedIntent(t,n){const r=await this.fetch("/api/approved-intents",{method:"POST",body:JSON.stringify({authorityId:t,intent:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed"}));throw new Error(a.error||`storeApprovedIntent failed: ${r.status}`)}}async listTeamAuthorizations(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/attestations`);if(!n.ok)throw new Error(`Failed to fetch team authorizations: ${n.status}`);return((await n.json()).items??[]).map(a=>{var l,c;const o=a.owner??{userId:""};return{authorization_id:a.authorization_id??a.authorizationId,profile_id:a.profileId??a.profile_id,path:a.path??"",title:a.title??null,sp_status:a.status??a.sp_status??null,frame:a.bounds??a.frame??{},required_domains:a.requiredDomains??a.required_domains??[],attested_domains:a.attestedDomains??a.attested_domains??[],missing_domains:(a.requiredDomains??a.required_domains??[]).filter(d=>!(a.attestedDomains??a.attested_domains??[]).includes(d)),deferred_commitment_domains:a.deferredCommitmentDomains??a.deferred_commitment_domains??[],approvers_frozen:a.approversFrozen??a.approvers_frozen??[],above_cap:a.aboveCap??a.above_cap??!1,created_at:a.createdAt?new Date(a.createdAt*1e3).toISOString():a.created_at??"",earliest_expiry:(l=a.attestations)!=null&&l.length?new Date(Math.min(...a.attestations.map(d=>d.expiresAt))*1e3).toISOString():null,remaining_seconds:(c=a.attestations)!=null&&c.length?Math.max(0,Math.min(...a.attestations.map(d=>d.expiresAt))-Math.floor(Date.now()/1e3)):null,owner:o}})}async listTeamReceipts(t){const n=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts`);if(!n.ok)throw new Error(`Failed to fetch team receipts: ${n.status}`);return(await n.json()).receipts??[]}async getMyReceiptsPage(t){const n=new URLSearchParams;t!=null&&t.before&&n.set("before",t.before),t!=null&&t.profile&&n.set("profile",t.profile),t!=null&&t.limit&&n.set("limit",String(t.limit));const r=n.toString(),a=await this.fetch(`/api/receipts/mine${r?"?"+r:""}`);if(!a.ok)throw new Error(`Failed to fetch receipts: ${a.status}`);const o=await a.json();return{receipts:o.receipts??[],nextBefore:o.nextBefore??null}}async listTeamReceiptsPage(t,n){const r=new URLSearchParams;n!=null&&n.before&&r.set("before",n.before),n!=null&&n.profile&&r.set("profile",n.profile),n!=null&&n.limit&&r.set("limit",String(n.limit));const a=r.toString(),o=await this.fetch(`/api/groups/${encodeURIComponent(t)}/receipts${a?"?"+a:""}`);if(!o.ok)throw new Error(`Failed to fetch team receipts: ${o.status}`);const i=await o.json();return{receipts:i.receipts??[],nextBefore:i.nextBefore??null}}async getThread(t){const n=t.sinceDays??7,r=t.status??"pending",a=t.domain||"owner",o=await this.getProposals(a);let i=[];if(r==="all"){const l=[],c=new Date;for(let f=0;f<n;f++){const g=new Date(c);g.setUTCDate(c.getUTCDate()-f),l.push(g.toISOString().slice(0,10))}i=(await Promise.all(l.map(f=>this.getMyReceipts({date:f,profile:t.profile})))).flat()}return{proposals:o,receipts:i}}async getAutostart(){const t=await this.fetch("/autostart");if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}async setAutostart(t){const n=await this.fetch("/autostart",{method:t?"POST":"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.message||`HTTP ${n.status}`)}}async getGateContent(t){const n=await this.fetch(`/gate-content?path=${encodeURIComponent(t)}`);if(!n.ok)throw new Error(`Failed to fetch gate content: ${n.status}`);return(await n.json()).entry??null}async resyncGates(){const t=await this.fetch("/resync-gates",{method:"POST"});if(!t.ok)throw new Error(`Failed to resync gates: ${t.status}`)}async getEnrichedAuthorizations(){const t=await this.fetch("/active-authorizations");if(!t.ok)throw new Error(`Failed to fetch authorizations: ${t.status}`);return(await t.json()).authorizations??[]}async pushGateContent(t){const n=await this.fetch("/gate-content",{method:"POST",body:JSON.stringify(t)});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to push gate content"}));throw new Error(r.error||`Push gate content failed: ${n.status}`)}}async getAgentContext(){const t=await this.fetch("/agent-brief/context");if(!t.ok)throw new Error(`Failed to fetch agent context: ${t.status}`);return(await t.json()).content}async saveAgentContext(t){const n=await this.fetch("/agent-brief/context",{method:"PUT",body:JSON.stringify({content:t})});if(!n.ok){const r=await n.json().catch(()=>({error:"Failed to save agent context"}));throw new Error(r.error||`Save failed: ${n.status}`)}}async aiChat(t){const n=await this.fetch("/ai/chat",{method:"POST",body:JSON.stringify(t)});return n.ok?n.json():{success:!1,error:(await n.json().catch(()=>({error:"AI chat failed"}))).error||`Chat failed: ${n.status}`}}async getAIPrompts(){const t=await this.fetch("/ai-prompts");if(!t.ok)throw new Error(`Failed to load AI prompts: ${t.status}`);return t.json()}async setAIPrompt(t,n){const r=await this.fetch(`/ai-prompts/${t}`,{method:"PUT",body:JSON.stringify({value:n})});if(!r.ok){const a=await r.json().catch(()=>({error:"Save failed"}));throw new Error(a.error||`Save failed: ${r.status}`)}}}const A=new ty,Rf=u.createContext(null);function ny({children:e}){const[t,n]=u.useState(null),[r,a]=u.useState("personal"),[o,i]=u.useState(null),[l,c]=u.useState(""),[d,f]=u.useState(null),[g,p]=u.useState(null),[x,w]=u.useState(!1),[v,j]=u.useState(""),h=u.useRef(!1),m=u.useRef(null),y=u.useCallback(async()=>{if(h.current)try{const P=await A.getMyTeam();if(P){const{group:k,membership:z}=P;f(k),p(z),a("team"),i(k);const O=m.current??z.domains[0]??"owner";c(O)}else f(null),p(null),a("personal")}catch{}},[]);u.useEffect(()=>{const P=()=>{document.visibilityState==="visible"&&y()};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[y]);const S=u.useCallback(async(P,k={})=>{w(!0),j("");try{A.setApiKey(P),h.current=!0;const z=await A.login(P,k);n(z),m.current=z.id;const O=await A.getGroups(),K=O.find(V=>V.isPersonal)??O[0]??null;i(K),c("owner"),await y()}catch(z){throw A.clearApiKey(),h.current=!1,j(z instanceof Error?z.message:"Login failed"),z}finally{w(!1)}},[y]),b=u.useCallback(async()=>{await A.logout(),A.clearApiKey(),h.current=!1,m.current=null,n(null),i(null),c(""),f(null),p(null),a("personal"),j("")},[]),T=u.useCallback(()=>j(""),[]),E=u.useCallback((P,k)=>{i(P),c(k)},[]);return s.jsx(Rf.Provider,{value:{user:t,mode:r,group:o,domain:l,groupId:(o==null?void 0:o.id)??null,activeTeam:d,activeMembership:g,isLoading:x,error:v,login:S,logout:b,clearError:T,activeGroup:o,activeDomain:l,groups:o?[o]:[],setActiveContext:E,refreshGroups:y},children:e})}function $e(){const e=u.useContext(Rf);if(!e)throw new Error("useAuth must be used within AuthProvider");return e}const _f=u.createContext(null);function ry({children:e}){const{user:t}=$e(),n=u.useRef(null),[r,a]=u.useState(!1),o=u.useRef(new Map),i=u.useCallback((l,c)=>{const d=o.current;return d.has(l)||d.set(l,new Set),d.get(l).add(c),()=>{var f;(f=d.get(l))==null||f.delete(c)}},[]);return u.useEffect(()=>{if(!t){n.current&&(n.current.close(),n.current=null,a(!1));return}if(n.current)return;const l=A.getApiKey();if(!l)return;const c=new EventSource(`/events?key=${encodeURIComponent(l)}`);n.current=c,c.onopen=()=>a(!0),c.onerror=()=>a(!1);const d=["integration-changed","attestation-changed","proposal-added","proposal-resolved","team-membership-changed","action-approval-needed","action-resolved","proposal-approved","proposal-rejected"];for(const f of d)c.addEventListener(f,g=>{let p;try{p=JSON.parse(g.data)}catch{p=null}const x=o.current.get(f);if(x)for(const w of x)try{w(p)}catch(v){console.error(`[EventSource] handler for "${f}" threw:`,v)}});return()=>{c.close(),n.current=null,a(!1)}},[t]),s.jsx(_f.Provider,{value:{connected:r,addListener:i},children:e})}function xe(e,t){const n=u.useContext(_f);if(!n)return;const{addListener:r}=n;u.useEffect(()=>r(e,t),[e,t,r])}const Or="suveren-theme",Dc="hap-theme";function za(e){return e!=="system"?e:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}(function(){const t=localStorage.getItem(Dc);t!==null&&localStorage.getItem(Or)===null&&localStorage.setItem(Or,t),t!==null&&localStorage.removeItem(Dc)})();function Af(){const[e,t]=u.useState(()=>{const o=localStorage.getItem(Or);return o==="light"||o==="dark"?o:"system"}),[n,r]=u.useState(()=>za(e));u.useEffect(()=>{const o=document.documentElement,i=za(e);o.setAttribute("data-theme",i),e==="system"?localStorage.removeItem(Or):localStorage.setItem(Or,e),r(za(e))},[e]),u.useEffect(()=>{if(e!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>r(za("system"));return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},[e]);const a=u.useCallback(()=>{t(o=>o==="system"?"light":o==="light"?"dark":"system")},[]);return{theme:e,effectiveTheme:n,toggle:a}}const ay=5*60*1e3,sy=2e3;function jl(){const[e,t]=u.useState(!1),[n,r]=u.useState("docker"),[a,o]=u.useState(""),[i,l]=u.useState(null),[c,d]=u.useState(!1),[f,g]=u.useState(!1),[p,x]=u.useState(!1),w=u.useRef(null);return u.useEffect(()=>{let v=!1;const j=(y=!1)=>{fetch(y?"/health?refresh=1":"/health").then(S=>S.json()).then(S=>{v||(S.installMethod&&r(S.installMethod),typeof S.latestVersion<"u"&&l(S.latestVersion),S.updateAvailable&&t(!0),S.version&&(o(S.version),w.current===null?w.current=S.version:S.version!==w.current&&S.version!=="dev"&&d(!0)))}).catch(()=>{})};j(!0);const h=setInterval(()=>j(!1),p?sy:ay),m=()=>{document.visibilityState==="visible"&&j(!1)};return document.addEventListener("visibilitychange",m),window.addEventListener("focus",m),()=>{v=!0,clearInterval(h),document.removeEventListener("visibilitychange",m),window.removeEventListener("focus",m)}},[p]),{updateAvailable:e&&!f,installMethod:n,version:a,latestVersion:i,serverRestarted:c,startFastPolling:()=>x(!0),dismiss:()=>g(!0)}}function oy(e){return e?e==="dev"?"dev":/^[0-9a-f]{40}$/i.test(e)?e.slice(0,7):e:""}const Uc={system:"◑",light:"☀",dark:"☾"};function iy(){const{mode:e,group:t,domain:n}=$e();return e==="personal"?s.jsx("span",{children:"personal"}):t?s.jsxs("span",{children:[t.name," / ",n]}):s.jsx("span",{children:n})}function kl({onMenuToggle:e}){const{user:t,logout:n}=$e(),{theme:r,toggle:a}=Af(),{version:o}=jl(),i=oy(o);return s.jsx("nav",{className:"top-nav",children:s.jsxs("div",{className:"top-nav-inner",children:[s.jsxs("div",{className:"logo-group",children:[s.jsx("span",{className:"logo",children:"Suveren"}),s.jsx("span",{className:"version-badge",children:"Local Gateway"})]}),s.jsx("div",{className:"nav-spacer"}),s.jsx("div",{className:"nav-actions nav-actions-desktop",children:t?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"user-chip",children:[s.jsx("strong",{children:t.name}),s.jsx("span",{className:"dot"}),s.jsx(iy,{})]}),s.jsx("button",{className:"theme-toggle",onClick:a,title:`Theme: ${r}`,children:Uc[r]}),s.jsx("button",{className:"nav-logout",onClick:n,children:"Logout"})]}):s.jsxs(s.Fragment,{children:[i&&s.jsxs("span",{title:"Running gateway version",style:{fontSize:"0.8rem",color:"var(--text-tertiary)",fontVariantNumeric:"tabular-nums"},children:["v",i]}),s.jsx("button",{className:"theme-toggle",onClick:a,title:`Theme: ${r}`,children:Uc[r]})]})}),t&&e&&s.jsx("button",{className:"mobile-menu-btn",onClick:e,"aria-label":"Menu",children:"☰"})]})})}function Rt(e,t){var n;if((n=t==null?void 0:t.revokedSet)!=null&&n.has(e.authorization_id))return"revoked";switch(e.sp_status){case"revoked":return"revoked";case"expired":return"expired";case"active":return"active";case"pending":return"pending"}return e.remaining_seconds===null||e.remaining_seconds<=0?"expired":e.missing_domains.length>0?"pending":"active"}function $f(e,t){const n={active:[],pending:[],expired:[],revoked:[]};for(const r of e)n[Rt(r,t)].push(r);return n}function At(e,t,n){const r=u.useRef(e);r.current=e,u.useEffect(()=>{let a=null;const o=()=>typeof document>"u"?!0:document.visibilityState==="visible",i=()=>{o()&&r.current()},l=()=>{a===null&&(a=setInterval(i,t))},c=()=>{a!==null&&(clearInterval(a),a=null)},d=()=>{o()?(r.current(),l()):c()};return o()&&(r.current(),l()),document.addEventListener("visibilitychange",d),()=>{c(),document.removeEventListener("visibilitychange",d)}},[t,n])}const Lf=u.createContext(null),ly=3e4,cy=5e3,uy=3e5;function dy(e,t,n){return t===0?"loading":e!=null&&e.running?"running":e!=null&&e.error?"error":e&&n?"starting":"not-running"}function fy({children:e}){const[t,n]=u.useState({manifests:[],integrations:[],activeSessions:0,mcpServerUp:null,manifestsError:!1,fetchCount:0,authHealth:{}}),r=u.useRef(null),a=u.useCallback(async()=>{let d=!1;const[f,g]=await Promise.all([A.getIntegrationManifests().catch(()=>(d=!0,{manifests:[]})),A.getMcpHealth().catch(()=>null)]);n(x=>({...x,manifests:f.manifests,integrations:(g==null?void 0:g.integrations)??x.integrations,activeSessions:(g==null?void 0:g.activeSessions)??x.activeSessions,mcpServerUp:!!g,manifestsError:d,fetchCount:x.fetchCount+1}));const p=f.manifests.filter(x=>x.oauth);if(p.length>0){const x=await Promise.all(p.map(async w=>[w.id,await A.getOAuthHealth(w.id)]));n(w=>({...w,authHealth:Object.fromEntries(x)}))}},[]),o=t.fetchCount>0&&t.manifests.some(d=>{const f=t.integrations.find(g=>g.id===d.id);return f&&!f.running});xe("integration-changed",a),At(a,o?cy:uy);const i=u.useMemo(()=>{const d=new Map(t.integrations.map(p=>[p.id,p])),f=Date.now();o&&r.current===null?r.current=f:o||(r.current=null);const g=r.current!==null&&f-r.current<ly;return t.manifests.map(p=>{const x=d.get(p.id),w=dy(x,t.fetchCount,g),v=t.authHealth[p.id];return{id:p.id,manifest:p,integration:x,state:w,authStatus:v==null?void 0:v.status,authAccount:v==null?void 0:v.account,authError:v==null?void 0:v.error}})},[t,o]),l=u.useMemo(()=>i.filter(d=>d.state==="not-running"||d.state==="error"||d.authStatus==="failed").length,[i]),c={loading:t.fetchCount===0,mcpServerUp:t.mcpServerUp,manifestsError:t.manifestsError,entries:i,attentionCount:l,activeSessions:t.activeSessions,refresh:a};return s.jsx(Lf.Provider,{value:c,children:e})}function bl(){const e=u.useContext(Lf);if(!e)throw new Error("useIntegrationStatus must be used inside IntegrationStatusProvider");return e}const my=[{to:"/",icon:"□",label:"Dashboard"},{to:"/proposals",icon:"▷",label:"Pending Approvals",statusKey:"proposals"},{to:"/authorizations",icon:"☰",label:"Authorizations",statusKey:"authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief",statusKey:"brief"},{to:"/audit",icon:"▣",label:"Receipts"},{to:"/groups",icon:"◉",label:"Team",teamOnly:!0},{to:"/integrations",icon:"⧗",label:"Integrations",statusKey:"integrations"},{to:"/settings",icon:"⚙",label:"AI Assistant",statusKey:"assistant"}];function py(){const{activeDomain:e}=$e(),[t,n]=u.useState({}),r=u.useCallback(async()=>{try{const[a,o,i,l,c]=await Promise.all([A.getCredential("ai-config").catch(()=>null),A.getMyAttestations().catch(()=>null),A.getProposals(e||"owner").catch(()=>null),A.getProposalsForApprover().catch(()=>null),A.getAgentContext().catch(()=>"")]),d={};if(a&&!a.configured&&(d.assistant=1),o){const x=$f(o).expired.length;x>0&&(d.authorizations=x)}const f=(i==null?void 0:i.length)??0,g=(l==null?void 0:l.length)??0,p=f+g;p>0&&(d.proposals=p),(!c||!c.trim())&&(d.brief=1),n(d)}catch{}},[e]);return xe("attestation-changed",r),xe("proposal-added",r),xe("proposal-resolved",r),xe("proposal-approved",r),xe("proposal-rejected",r),xe("team-membership-changed",r),At(r,3e5,e),t}const hy={marginLeft:"auto",minWidth:"1.25rem",height:"1.25rem",padding:"0 0.375rem",borderRadius:"0.625rem",background:"var(--warning)",color:"var(--bg-elevated)",fontSize:"0.7rem",fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},gy={position:"fixed",bottom:"1.5rem",left:"50%",transform:"translateX(-50%)",background:"var(--bg-elevated, #1e1e2e)",color:"var(--text-primary, #e2e8f0)",border:"1px solid var(--border)",borderRadius:"0.5rem",padding:"0.625rem 1rem",fontSize:"0.85rem",boxShadow:"0 4px 16px rgba(0,0,0,0.3)",zIndex:9999,whiteSpace:"nowrap",pointerEvents:"none"};function yy(){const{mode:e,group:t,domain:n,activeTeam:r}=$e(),a=py(),{attentionCount:o}=bl(),i={...a};o>0&&(i.integrations=o);const l=my.filter(p=>!p.teamOnly||e==="team"),c=u.useRef(null),[d,f]=u.useState(null),g=St();return u.useEffect(()=>{if(c.current===null){c.current=e;return}c.current!==e&&(e==="team"&&r?f(`You are now acting in team context — ${r.name}`):e==="personal"&&f("You have left the team — back to personal context"),c.current=e)},[e,r]),u.useEffect(()=>{f(null)},[g.pathname]),s.jsxs("div",{className:"sidebar",children:[s.jsx("ul",{className:"sidebar-nav",children:l.map(p=>{const x=p.statusKey?i[p.statusKey]:0;return s.jsx("li",{children:s.jsxs(Sl,{to:p.to,end:p.to==="/",className:({isActive:w})=>`sidebar-item${w?" active":""}`,children:[s.jsx("span",{className:"icon",children:p.icon}),p.label,x?s.jsx("span",{style:hy,children:x}):null]})},p.to)})}),s.jsxs("div",{className:"sidebar-context",children:[s.jsx("div",{className:"ctx-label",children:"Active context"}),s.jsx("div",{className:"ctx-value",children:e==="personal"?"personal":t?`${t.name} / ${n}`:n})]}),d&&s.jsx("div",{style:gy,role:"status","aria-live":"polite",children:d})]})}const ho="suveren:updatedTo";function vy(e){return e==="npm"?"npm install -g @suveren/gateway@latest && suveren-gateway restart":e==="dev"?"git pull && pnpm install":"docker rm -f suveren-gateway 2>/dev/null; docker ps -q --filter publish=7400 --filter publish=7430 | xargs -r docker rm -f; docker pull ghcr.io/suverenai/suveren-gateway:latest && docker run -d --name suveren-gateway -p 7400:3000 -p 7430:3030 -v $HOME/.suveren:/app/data ghcr.io/suverenai/suveren-gateway"}function xy(){const e=document.querySelectorAll('[role="dialog"], .modal-overlay, .modal');for(const n of e)if(!n.closest(".update-overlay"))return!0;const t=document.activeElement;if(t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)){const n=t.value;if(n&&n.trim())return!0}return!1}function Mf(){const{updateAvailable:e,installMethod:t,version:n,latestVersion:r,serverRestarted:a,startFastPolling:o,dismiss:i}=jl(),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[g,p]=u.useState(()=>{try{const y=sessionStorage.getItem(ho);if(y)return sessionStorage.removeItem(ho),y}catch{}return null}),x=vy(t),w=u.useRef(null),v=y=>{try{sessionStorage.setItem(ho,y||r||"✓")}catch{}window.location.reload()};u.useEffect(()=>{if(!g)return;const y=setTimeout(()=>p(null),6e3);return()=>clearTimeout(y)},[g]),u.useEffect(()=>{if(!l||!a)return;const y=()=>xy()?!1:(v(n),!0);if(y())return;const S=setInterval(y,1500);return()=>clearInterval(S)},[l,a,n]),u.useEffect(()=>(document.body.classList.toggle("is-updating",l),()=>document.body.classList.remove("is-updating")),[l]);const j=e&&!l&&!g||!!g&&!l;u.useEffect(()=>{if(!j){document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner");return}document.body.classList.add("has-update-banner");const y=()=>{var T;const b=((T=w.current)==null?void 0:T.offsetHeight)??0;document.documentElement.style.setProperty("--update-banner-h",`${b}px`)};y();const S=new ResizeObserver(y);return w.current&&S.observe(w.current),()=>{S.disconnect(),document.documentElement.style.removeProperty("--update-banner-h"),document.body.classList.remove("has-update-banner")}},[j]);const h=()=>{c(!0),o()},m=async()=>{try{await navigator.clipboard.writeText(x),f(!0),setTimeout(()=>f(!1),1800)}catch{}};return s.jsxs(s.Fragment,{children:[g&&!l&&s.jsx("div",{ref:w,className:"update-banner is-live",role:"status","aria-live":"polite",children:s.jsxs("div",{className:"update-banner-row",children:[s.jsxs("span",{className:"update-banner-text",children:["✓"," You","’","re on the latest version",g&&g!=="✓"?` — ${g} is live`:" — now live","."]}),s.jsx("button",{className:"update-banner-x",onClick:()=>p(null),"aria-label":"Dismiss",children:"×"})]})}),e&&!l&&!g&&s.jsx("div",{ref:w,className:"update-banner",role:"status","aria-live":"polite",children:s.jsxs("div",{className:"update-banner-row",children:[s.jsx("span",{className:"update-banner-text",children:"Update available."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[s.jsx("button",{className:"btn btn-sm btn-secondary",onClick:h,children:"Update"}),s.jsx("button",{className:"update-banner-x",onClick:i,"aria-label":"Dismiss",children:"×"})]})]})}),l&&s.jsx("div",{className:"update-overlay",children:s.jsxs("div",{className:"update-overlay-card",role:"dialog","aria-modal":"true","aria-label":"Finishing the update",children:[s.jsx("div",{className:"update-spinner"}),s.jsxs("h2",{children:["Finishing the update","…"]}),s.jsxs("p",{children:["Copy this command and run it in your terminal. The gateway will restart, and"," ",s.jsx("strong",{children:"this page updates automatically"})," when it comes back ","—"," no need to refresh."]}),s.jsxs("div",{className:"update-cmd-row",children:[s.jsx("code",{className:"update-cmd",children:x}),s.jsx("button",{className:"btn btn-sm btn-primary",onClick:m,children:d?"Copied":"Copy"})]}),s.jsxs("div",{className:"update-status",children:[s.jsx("span",{className:"update-pulse"})," Waiting for the gateway to restart","…"]}),s.jsxs("div",{className:"update-overlay-actions",children:[s.jsx("button",{className:"btn btn-primary",onClick:()=>v(n),children:"Reload now"}),s.jsx("button",{className:"btn btn-secondary",onClick:()=>c(!1),children:"Cancel"})]})]})})]})}const wy={system:"◑",light:"☀",dark:"☾"},Sy=[{to:"/",icon:"□",label:"Dashboard"},{to:"/proposals",icon:"▷",label:"Pending Approvals"},{to:"/authorizations",icon:"☰",label:"Authorizations"},{to:"/agent-brief",icon:"▤",label:"Agent Brief"},{to:"/audit",icon:"▣",label:"Receipts"},{to:"/groups",icon:"◉",label:"Team"},{to:"/integrations",icon:"⧗",label:"Integrations"},{to:"/settings",icon:"⚙",label:"AI Assistant"}];function jy({open:e,onClose:t}){const{user:n,activeGroup:r,activeDomain:a,logout:o}=$e(),{theme:i,toggle:l}=Af(),c=St();return u.useEffect(()=>{t()},[c.pathname]),e?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mobile-menu-backdrop",onClick:t}),s.jsxs("div",{className:"mobile-menu-panel",children:[n&&s.jsxs("div",{className:"mobile-menu-header",children:[s.jsx("strong",{children:n.name}),s.jsx("span",{style:{fontSize:"0.8rem",color:"var(--text-secondary)"},children:r?`${r.name} / ${a}`:a||"personal"})]}),s.jsx("nav",{className:"mobile-menu-nav",children:Sy.map(d=>s.jsxs(Sl,{to:d.to,end:d.to==="/",className:({isActive:f})=>`mobile-menu-item${f?" active":""}`,onClick:t,children:[s.jsx("span",{className:"icon",children:d.icon}),d.label]},d.to))}),s.jsxs("div",{className:"mobile-menu-footer",children:[s.jsxs("button",{className:"mobile-menu-action",onClick:()=>{l()},children:[s.jsx("span",{className:"icon",children:wy[i]}),"Theme: ",i]}),s.jsx("button",{className:"mobile-menu-action",onClick:()=>{o(),t()},children:"Logout"})]})]})]}):null}function ky(){const[e,t]=u.useState(!1);return s.jsxs(fy,{children:[s.jsx(kl,{onMenuToggle:()=>t(!e)}),s.jsx(Mf,{}),s.jsx(yy,{}),s.jsx(jy,{open:e,onClose:()=>t(!1)}),s.jsx("div",{className:"main-content",children:s.jsx("div",{className:"page-inner",children:s.jsx(xg,{})})})]})}function by(){const[e,t]=u.useState(""),{login:n,isLoading:r,error:a,clearError:o}=$e(),[i,l]=u.useState(null),c=async()=>{if(e.trim()){o();try{await n(e)}catch(g){if(g instanceof Pf){l(g.summary);return}}}},d=async()=>{l(null),o();try{await n(e,{confirmWipe:!0})}catch{}},f=()=>{l(null)};return s.jsxs(s.Fragment,{children:[s.jsx(kl,{}),s.jsx(Mf,{}),s.jsxs("div",{className:"login-split",children:[s.jsx("div",{className:"login-split-left",children:s.jsxs("div",{style:{maxWidth:"28rem"},children:[s.jsx("h1",{style:{fontSize:"clamp(2.25rem, 4vw, 3.25rem)",letterSpacing:"-0.03em",lineHeight:1.1,marginBottom:"1.25rem"},children:"Your agents, your intent, your rules."}),s.jsx("p",{style:{fontSize:"1.125rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"3rem"},children:"The gateway runs on your machine, between your agents and the tools they use. Your signature. Your bounds. Your receipts."})]})}),s.jsx("div",{className:"login-split-right",children:s.jsxs("div",{style:{width:"100%",maxWidth:"24rem"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsx("div",{style:{fontSize:"1.75rem",fontWeight:700,marginBottom:"0.5rem"},children:"Sign In"}),s.jsx("div",{style:{fontSize:"0.95rem",color:"var(--text-secondary)",lineHeight:1.5},children:"Enter your API key to manage authorizations."})]}),a&&s.jsx("div",{className:"error-message",children:a}),s.jsxs("div",{className:"form-group",style:{marginBottom:"1.5rem"},children:[s.jsx("label",{className:"form-label",children:"API Key"}),s.jsx("input",{className:"form-input",type:"password",placeholder:"hap_sk_...",value:e,onChange:g=>t(g.target.value),onKeyDown:g=>g.key==="Enter"&&c(),disabled:r,style:{padding:"0.75rem"}}),s.jsx("div",{className:"form-hint",children:"From your Suveren account."})]}),s.jsx("button",{className:"btn btn-primary btn-full btn-lg",onClick:c,disabled:r,style:{marginBottom:"2rem"},children:r?"Signing in...":"Sign In"}),s.jsx("div",{className:"login-divider",children:"New here?"}),s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsxs("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",marginBottom:"1rem",lineHeight:1.5},children:["Create an account on Suveren,",s.jsx("br",{}),"then come back to sign in."]}),s.jsx("a",{href:"https://www.suveren.ai/get-started",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-full",style:{textDecoration:"none"},children:"Create Account"})]}),s.jsxs("div",{style:{paddingTop:"1.75rem",borderTop:"1px solid var(--border)"},children:[s.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-tertiary)",marginBottom:"0.875rem"},children:"Getting started"}),s.jsx("div",{style:{fontSize:"0.85rem",color:"var(--text-secondary)",lineHeight:1.8},children:[s.jsxs(s.Fragment,{children:["Create an account at ",s.jsx("a",{href:"https://www.suveren.ai/get-started",target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)"},children:"Suveren"})]}),"Join or create a team to get domain authority","Sign in here with your API key to start authorizing agents"].map((g,p)=>s.jsxs("div",{style:{display:"flex",gap:"0.625rem",alignItems:"baseline",marginBottom:p<2?"0.5rem":0},children:[s.jsxs("span",{style:{color:"var(--accent)",fontWeight:700,fontSize:"0.95rem"},children:[p+1,"."]}),g]},p))})]})]})})]}),i&&s.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"wipe-warning-title",style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"1rem"},onClick:f,children:s.jsxs("div",{className:"card",onClick:g=>g.stopPropagation(),style:{maxWidth:520,width:"100%",margin:0},children:[s.jsx("h3",{id:"wipe-warning-title",className:"card-title",style:{marginBottom:"0.5rem"},children:"Sign in with a different account?"}),s.jsxs("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"0.75rem"},children:["This gateway already holds data for another account. Signing in with this API key will ",s.jsx("strong",{children:"permanently wipe"})," the following local data:"]}),s.jsxs("ul",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem",paddingLeft:"1.25rem",lineHeight:1.6},children:[s.jsxs("li",{children:[i.credentialCount," stored service credential",i.credentialCount===1?"":"s",i.credentialIds.length>0&&s.jsxs("span",{style:{color:"var(--text-tertiary)",fontSize:"0.825rem"},children:[" ","(",i.credentialIds.slice(0,5).join(", "),i.credentialIds.length>5?`, +${i.credentialIds.length-5} more`:"",")"]})]}),s.jsxs("li",{children:[i.serviceCount," configured integration",i.serviceCount===1?"":"s"]}),s.jsx("li",{children:"The local E2EE keypair (a new one will be generated for this account)"}),s.jsx("li",{children:"Any unsynchronised gate content stored locally"})]}),s.jsx("p",{style:{fontSize:"0.875rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Authorizations and receipts on the Service Provider are NOT affected — only this gateway's local state is wiped."}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-tertiary)",marginBottom:"1rem"},children:"If this isn't what you wanted, cancel and sign back in with the original API key, or use a different gateway instance for this account."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem",justifyContent:"flex-end"},children:[s.jsx("button",{className:"btn btn-ghost",onClick:f,disabled:r,children:"Cancel"}),s.jsx("button",{className:"btn btn-secondary",style:{color:"var(--danger, #e53e3e)"},onClick:d,disabled:r,children:r?"Signing in...":"Wipe local data and sign in"})]})]})})]})}function Cy(){const{setActiveContext:e}=$e(),t=Qt(),[n,r]=u.useState(""),[a,o]=u.useState(""),[i,l]=u.useState(""),[c,d]=u.useState(!1),f=async()=>{if(n.trim()){d(!0),l("");try{const p=await A.joinGroup(n.trim());e(p,p.myDomains[0]||""),t("/")}catch(p){l(p instanceof Error?p.message:"Failed to join group")}finally{d(!1)}}},g=async()=>{if(a.trim()){d(!0),l("");try{const p=await A.createGroup(a.trim());e(p,p.myDomains[0]||""),t("/")}catch(p){l(p instanceof Error?p.message:"Failed to create group")}finally{d(!1)}}};return s.jsxs(s.Fragment,{children:[s.jsx(kl,{}),s.jsx("div",{className:"main-content no-sidebar",style:{marginTop:"var(--nav-height)"},children:s.jsxs("div",{style:{maxWidth:"30rem",margin:"3rem auto",padding:"0 1rem"},children:[s.jsxs("div",{style:{textAlign:"center",marginBottom:"2.5rem"},children:[s.jsx("h2",{style:{fontSize:"1.5rem",marginBottom:"0.5rem"},children:"Join Your Team"}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6},children:"Join an existing team or create a new one to share authority across domains."})]}),i&&s.jsx("div",{className:"error-message",children:i}),s.jsxs("div",{className:"card",style:{marginBottom:"1rem"},children:[s.jsx("h4",{style:{fontSize:"0.95rem",marginBottom:"0.25rem"},children:"Join an existing group"}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Ask your team admin for an invite code."}),s.jsxs("div",{className:"invite-input-row",children:[s.jsx("input",{className:"form-input",placeholder:"Paste invite code...",value:n,onChange:p=>r(p.target.value),onKeyDown:p=>p.key==="Enter"&&f(),style:{fontFamily:"'SF Mono', Monaco, monospace",fontSize:"0.85rem"},disabled:c}),s.jsx("button",{className:"btn btn-primary",onClick:f,disabled:c,children:"Join"})]})]}),s.jsxs("div",{className:"card",children:[s.jsx("h4",{style:{fontSize:"0.95rem",marginBottom:"0.25rem"},children:"Create a new group"}),s.jsx("p",{style:{fontSize:"0.825rem",color:"var(--text-secondary)",marginBottom:"1rem"},children:"Start a new team and invite members. Assign domains after creation."}),s.jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[s.jsx("input",{className:"form-input",placeholder:"Group name (e.g., Acme Corp)",value:a,onChange:p=>o(p.target.value),onKeyDown:p=>p.key==="Enter"&&g(),style:{flex:1},disabled:c}),s.jsx("button",{className:"btn btn-secondary",onClick:g,disabled:c,children:"Create"})]})]})]})})]})}const hi="suveren-setup-ai-skipped",gi="suveren-setup-agent-done",yi="suveren-setup-dismissed",Ny={"hap-setup-ai-skipped":hi,"hap-setup-agent-done":gi,"hap-setup-dismissed":yi};function Ey(){for(const[e,t]of Object.entries(Ny)){const n=localStorage.getItem(e);n!==null&&localStorage.getItem(t)===null&&localStorage.setItem(t,n),n!==null&&localStorage.removeItem(e)}}Ey();const go={"claude-code":{label:"Claude Code",snippet:e=>JSON.stringify({mcpServers:{"suveren-gateway":{url:`${e}/sse`}}},null,2)},"claude-desktop":{label:"Claude Desktop",snippet:e=>`Add to ~/Library/Application Support/Claude/claude_desktop_config.json:
52
52
 
53
53
  ${JSON.stringify({mcpServers:{"suveren-gateway":{url:`${e}/sse`}}},null,2)}`},other:{label:"Other",snippet:e=>`Streamable HTTP: POST ${e}/mcp
54
54
  SSE transport: GET ${e}/sse
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Suveren</title>
7
- <script type="module" crossorigin src="/assets/index-DecSrutK.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-DoZvxHLN.js"></script>
8
8
  <link rel="stylesheet" crossorigin href="/assets/index-JHaCddDE.css">
9
9
  </head>
10
10
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suveren/gateway",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "description": "Suveren gateway — local agent gateway built in compliance with the Human Agency Protocol (HAP). Runs the UI, control plane, and MCP server in one Node process.",
5
5
  "type": "module",
6
6
  "main": "server.js",