@stacknet/userutils 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import {createContext,useContext,useState,useCallback,useEffect,useRef}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var Ae=createContext(null);function at(){let e=useContext(Ae);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function it({config:e,callbacks:n,children:i}){return jsx(Ae.Provider,{value:{config:e,callbacks:n},children:i})}function je(){let[e,n]=useState({connected:false,address:null,chain:null,provider:null}),[i,c]=useState(null),w=useCallback(async(f="phantom")=>{c(null);try{let d=typeof window<"u"?window:null,N=f==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!N)return c(`${f} wallet not found`),null;let u=(await N.connect()).publicKey.toString();return n({connected:!0,address:u,chain:"solana",provider:f}),u}catch(d){return c(d.message||"Failed to connect wallet"),null}},[]),y=useCallback(async()=>{c(null);try{let d=(typeof window<"u"?window:null)?.ethereum;if(!d)return c("MetaMask not found"),null;let N=d;d.providers?.length&&(N=d.providers.find(t=>t.isMetaMask)||d);let u=(await N.request({method:"eth_requestAccounts"}))[0];return u?(n({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(c("No account selected"),null)}catch(f){return c(f.message||"Failed to connect wallet"),null}},[]),g=useCallback(async(f,d)=>{c(null);let N=d?.chain||e.chain,s=d?.provider||e.provider,u=d?.address||e.address;try{if(N==="solana"){let t=typeof window<"u"?window:null,p=s==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!p)throw new Error("Wallet not available");let o=new TextEncoder().encode(f),h=await p.signMessage(o,"utf8"),x=new Uint8Array(h.signature||h),k="";for(let A=0;A<x.byteLength;A++)k+=String.fromCharCode(x[A]);return btoa(k)}if(N==="ethereum"){let p=(typeof window<"u"?window:null)?.ethereum;if(p?.providers?.length&&(p=p.providers.find(h=>h.isMetaMask)||p),!p)throw new Error("MetaMask not available");return await p.request({method:"personal_sign",params:[f,u]})}throw new Error("No wallet connected")}catch(t){return c(t.message||"Signing failed"),null}},[e]),l=useCallback(()=>{n({connected:false,address:null,chain:null,provider:null}),c(null);},[]);return {wallet:e,error:i,connectSolana:w,connectEVM:y,signMessage:g,disconnect:l}}function De(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith("stackauth_session="));if(!e)return null;let n=e.slice(18);return JSON.parse(atob(n.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function Oe(e="__csrf"){if(typeof document>"u")return null;let n=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${e}=`));return n?n.slice(e.length+1):null}function Re(){let[e,n]=useState(null),[i,c]=useState(true),w=useCallback(()=>{let l=De();l&&l.expiresAt>Date.now()?n({userId:l.userId,address:l.address,chain:l.chain,expiresAt:l.expiresAt,planId:l.planId,authMethod:l.authMethod}):n(null),c(false);},[]);useEffect(()=>{w();},[w]);let y=useCallback(async(l="")=>{try{let f=await fetch(`${l}/api/auth/session`);if(f.ok){let d=await f.json();if(d.session)return n(d.session),d.session}return n(null),null}catch{return null}},[]),g=!!e&&e.expiresAt>Date.now();return {session:e,loading:i,isAuthenticated:g,refresh:y,readSession:w}}function We(e="__csrf",n="x-csrf-token"){let[i,c]=useState(null);useEffect(()=>{c(Oe(e));},[e]);let w=i?{[n]:i}:{};return {token:i,headers:w}}var mt="https://stacknet.magma-rpc.com/auth/bridge",oe="stacknet-auth-bridge";function Be(e){let n=e?.bridgeUrl||mt,i=e?.disabled||false,c=useRef(null),[w,y]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),g=useRef([]),l=useRef(false),f=useCallback(t=>{let p={...t,protocol:oe};l.current&&c.current?.contentWindow?c.current.contentWindow.postMessage(p,new URL(n).origin):g.current.push(p);},[n]);useEffect(()=>{if(i)return;let t=o=>{if(!(!o.data||o.data.protocol!==oe)){try{if(o.origin!==new URL(n).origin)return}catch{return}switch(o.data.type){case "bridge:ready":l.current=true,y(h=>({...h,ready:true}));for(let h of g.current)c.current?.contentWindow?.postMessage(h,o.origin);g.current=[],c.current?.contentWindow?.postMessage({protocol:oe,type:"auth:check"},o.origin),c.current?.contentWindow?.postMessage({protocol:oe,type:"auth:resolve-stack"},o.origin);break;case "auth:status":y(h=>({...h,known:o.data.known,identity:o.data.identity,identityCount:o.data.identityCount||0}));break;case "auth:resolved-stack":y(h=>({...h,resolvedStackId:o.data.stackId||null}));break;}}};window.addEventListener("message",t);let p=document.createElement("iframe");return p.src=n,p.style.display="none",p.setAttribute("aria-hidden","true"),p.setAttribute("tabindex","-1"),p.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(p),c.current=p,()=>{window.removeEventListener("message",t),p.parentNode&&p.parentNode.removeChild(p),c.current=null,l.current=false;}},[n,i]);let d=useCallback(t=>{f({type:"auth:connected",...t});},[f]),N=useCallback(t=>{f({type:"auth:disconnected",...t});},[f]),s=useCallback(()=>{f({type:"auth:clear"}),y({ready:w.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[f,w.ready]),u=useCallback(()=>{f({type:"auth:check"});},[f]);return {...w,reportConnected:d,reportDisconnected:N,clearAll:s,refresh:u}}async function Fe(e,n,i,c){let w=e.apiVersion||"v2",y=`${e.baseUrl}/api/${w}${i}`;try{let g=await fetch(y,{method:n,headers:{"Content-Type":"application/json"},body:c?JSON.stringify(c):void 0}),l=await g.json();return g.ok?l.success&&l.data!==void 0?{success:!0,data:l.data}:{success:!0,data:l}:{success:!1,error:l.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(g){return {success:false,error:{code:"NETWORK_ERROR",message:g instanceof Error?g.message:"Network error"}}}}function $e(e){return {getNetworkStatus:()=>Fe(e,"GET","/network/status"),getWeb3Challenge:(n,i)=>Fe(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:n,address:i})}}function He(e={apiBaseUrl:""}){let{wallet:n,connectSolana:i,connectEVM:c,signMessage:w,disconnect:y}=je(),{session:g,isAuthenticated:l,refresh:f,readSession:d}=Re(),{headers:N}=We(),s=Be({disabled:typeof window>"u"}),[u,t]=useState(false),[p,o]=useState(null),[h,x]=useState(false),k=e.apiBaseUrl||"",A=e.stacknetUrl||"https://stacknet.magma-rpc.com",m=e.stackId||s.resolvedStackId||"",T=$e({baseUrl:A,stackId:m}),E=useCallback(async(v,C,D,O)=>{t(true),o(null);try{let M=C;if(!M){let Y=await D();if(!Y)return t(!1),!1;M=Y;}let P=await T.getWeb3Challenge(v,M);if(!P.success||!P.data)return o("Failed to get challenge"),t(!1),!1;let _=await w(P.data.message,{chain:v,provider:O,address:M});if(!_)return t(!1),!1;let G={chain:v,message:P.data.message,signature:_,stackId:m};v==="solana"&&(G.publicKey=M);let Z=await fetch(`${k}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(G)});if(!Z.ok){let Y=await Z.json().catch(()=>({}));return o(Y.error||"Authentication failed"),t(!1),!1}return s.reportConnected({address:M,chain:v,method:O||(v==="solana"?"phantom":"metamask"),stackId:m}),d(),t(!1),!0}catch(M){return o(M.message||"Authentication failed"),t(false),false}},[k,T,w,d,s,m]),R=useCallback(async(v="phantom")=>{let C=await i(v);return C?E("solana",C,()=>i(v),v):false},[i,E]),z=useCallback(async()=>{let v=await c();return v?E("ethereum",v,c,"metamask"):false},[c,E]),U=useCallback(async v=>{t(true),o(null);try{let C=await fetch(`${k}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:v})});if(!C.ok){let D=await C.json().catch(()=>({}));return o(D.error||"Invalid code"),t(!1),!1}return d(),t(!1),!0}catch(C){return o(C.message||"OTP verification failed"),t(false),false}},[k,d]),$=useCallback(async(v,C)=>{t(true),o(null);try{let D=C||`${window.location.origin}/api/auth/oauth/callback`,O=new URLSearchParams({provider:v,redirectUri:D,stackId:m}),M=await fetch(`${k}/api/auth/oauth/start?${O}`);if(!M.ok){let _=await M.json().catch(()=>({}));return o(_.error||"Failed to start OAuth flow"),t(!1),!1}let P=await M.json();return P.redirect_url?(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",P.state||""),sessionStorage.setItem("oauth_provider",v)),window.location.href=P.redirect_url,!0):(o("No redirect URL returned"),t(!1),!1)}catch(D){return o(D.message||"OAuth flow failed"),t(false),false}},[k,m]),I=useCallback(async(v,C,D)=>{t(true),o(null);try{let O=await fetch(`${k}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:v,code:C,state:D,stackId:m})});if(!O.ok){let M=await O.json().catch(()=>({}));return o(M.error||"OAuth authentication failed"),t(!1),!1}return d(),t(!1),!0}catch(O){return o(O.message||"OAuth callback failed"),t(false),false}},[k,m,d]),j=useCallback(async()=>{n.address&&n.chain&&s.reportDisconnected({address:n.address,chain:n.chain,stackId:m});try{await fetch(`${k}/api/auth/logout`,{method:"POST",headers:N});}catch{}y(),d();},[k,N,y,d,n,s,m]);return useEffect(()=>{if(!e.autoConnect||h||l||!s.ready||!s.known||!s.identity)return;x(true);let{chain:v,method:C}=s.identity;v==="solana"&&(C==="phantom"||C==="solflare")?R(C):v==="ethereum"&&z();},[e.autoConnect,h,l,s,R,z]),{session:g,isAuthenticated:l,wallet:n,loading:u,error:p,authenticateSolana:R,authenticateEVM:z,authenticateOTP:U,authenticateOAuth:$,authenticateOAuthCallback:I,logout:j,refresh:()=>f(k),stackId:m,bridge:{ready:s.ready,known:s.known,identity:s.identity,identityCount:s.identityCount,resolvedStackId:s.resolvedStackId}}}function Qe(e,n="https://stacknet.magma-rpc.com"){let[i,c]=useState(null),[w,y]=useState(false),[g,l]=useState(null),f=useCallback(async N=>{y(true),l(null);try{let s=await fetch(`${n}/api/v2/stacks/${N}`);if(!s.ok)return l("Stack not found"),y(!1),null;let u=await s.json(),t=u.data?.stack||u.stack||u,p={id:t.id,name:t.name,displayName:t.displayName||t.name,description:t.description,logoUrl:t.logoUrl,webPageUrl:t.webPageUrl,allowedChains:t.allowedChains||[],features:t.features,stripeProvider:t.stripeProvider,oauthProviders:t.oauthProviders?.map(o=>({provider:o.provider,clientId:o.clientId,enabled:o.enabled!==!1}))};return c(p),y(!1),p}catch(s){return l(s.message),y(false),null}},[n]);useEffect(()=>{e&&f(e);},[e,f]);let d=i?kt(i):[];return {config:i,loading:w,error:g,identityProviders:d,fetchConfig:f}}function kt(e){let n=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(n.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),n.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&n.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&n.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let i of e.oauthProviders)i.enabled&&n.push({type:"oauth",id:i.provider,name:i.provider});return n}function re({length:e=6,onComplete:n,disabled:i=false,error:c,className:w="",inputClassName:y=""}){let [g,l]=useState(Array(e).fill("")),f=useCallback((s,u)=>{if(u.length>1){let p=u.replace(/\D/g,"").slice(0,e).split(""),o=[...g];p.forEach((x,k)=>{s+k<e&&(o[s+k]=x);}),l(o);let h=Math.min(s+p.length,e-1);document.getElementById(`userutils-otp-${h}`)?.focus(),o.every(x=>x!=="")&&setTimeout(()=>n(o.join("")),100);return}if(!/^\d?$/.test(u))return;let t=[...g];t[s]=u,l(t),u&&s<e-1&&document.getElementById(`userutils-otp-${s+1}`)?.focus(),u&&s===e-1&&t.every(p=>p!=="")&&setTimeout(()=>n(t.join("")),100);},[g,e,n]),d=useCallback((s,u)=>{if(u.key==="Backspace"&&!g[s]&&s>0){document.getElementById(`userutils-otp-${s-1}`)?.focus();let t=[...g];t[s-1]="",l(t);}if(u.key==="Enter"){let t=g.join("");t.length===e&&n(t);}},[g,e,n]);useCallback(()=>{l(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:w,children:[jsx("div",{className:"flex gap-2 justify-center",children:g.map((s,u)=>jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:s,onChange:t=>f(u,t.target.value),onKeyDown:t=>d(u,t),disabled:i,autoFocus:u===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${y}`},u))}),c&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:c})]})}re.displayName="OTPInput";var xt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function se({className:e}){return jsx("img",{src:xt,alt:"Phantom",className:e})}function ae({className:e}){return jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function ke({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function we({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function xe({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function ve({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Ne({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function Lt({config:e,onSuccess:n,title:i="Log in or Sign up",showWallets:c,showOTP:w,hideHeader:y,onOTPSubmit:g,otpLabel:l="Access Code",oauthInline:f,oauthFirst:d,className:N=""}){let s=He(e),{isAuthenticated:u,wallet:t,loading:p,error:o,authenticateSolana:h,authenticateEVM:x,authenticateOTP:k,authenticateOAuth:A,bridge:m,stackId:T}=s,E=!e.stackId&&!T,R=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:z,identityProviders:U,loading:$}=Qe(T||e.stackId||null,R),[I,j]=useState(E?"stack-select":"select"),[v,C]=useState(null),[D,O]=useState(false),[M,P]=useState("idle"),[_,G]=useState(""),[Z,Y]=useState([]),[Ke,Se]=useState(e.stackId||null),[te,qe]=useState(false),[Xe,et]=useState(false);useEffect(()=>{if(typeof window>"u")return;let a=()=>{let H=window;qe(!!(H.phantom?.solana?.isPhantom||H.solana?.isPhantom));let J=H.ethereum;et(!!(J?.isMetaMask||J?.providers?.some(K=>K.isMetaMask)));};a(),window.addEventListener("ethereum#initialized",a);let B=setTimeout(a,500);return ()=>{window.removeEventListener("ethereum#initialized",a),clearTimeout(B);}},[]),useEffect(()=>{I==="stack-select"&&T&&(Se(T),j("select"));},[I,T]),useEffect(()=>{if(!(!m.ready||!E)&&m.identity){let a=[];m.resolvedStackId&&a.push({stackId:m.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(a.map(async B=>{try{let H=await fetch(`${R}/api/v2/stacks/${B.stackId}`);if(H.ok){let J=await H.json(),K=J.data?.stack||J;B.name=K.displayName||K.name,B.logoUrl=K.logoUrl;}}catch{}return B})).then(Y);}},[m.ready,m.identity,m.resolvedStackId,E,R]),useEffect(()=>{u&&I==="success"&&n?.();},[u,I,n]);let Me=c||(U.length>0?U.filter(a=>a.type==="wallet").map(a=>a.id):["phantom","metamask"]),Ie=w!==void 0?w:U.length>0?U.some(a=>a.type==="otp"):true,V=U.filter(a=>a.type==="oauth"),ue=new Set(d||[]),Le=V.filter(a=>ue.has(a.id)),pe=f?V.filter(a=>!ue.has(a.id)):V,Ue=async a=>{C(a),j("connecting"),await A(a)||j("error");},tt=async()=>{C("phantom"),j("connecting");let a=await h("phantom");j(a?"success":"error");},nt=async()=>{C("metamask"),j("connecting");let a=await x();j(a?"success":"error");},ot=async a=>{P("verifying"),G(""),await(g||k)(a)?(P("success"),j("success")):(P("error"),G("Invalid or expired code"),setTimeout(()=>P("idle"),2e3));},Pe=()=>{j(E&&!Ke?"stack-select":"select"),C(null),O(false),P("idle"),G("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${N}`,children:[!y&&jsxs("div",{className:"mb-6 text-center",children:[z?.logoUrl&&I!=="stack-select"&&jsx("img",{src:z.logoUrl,alt:z.displayName||"",className:"h-16 w-16 mx-auto mb-4 rounded-xl"}),z?.displayName&&jsx("p",{className:"text-sm text-zinc-400 mb-2",children:z.displayName}),jsx("h1",{className:"font-semibold text-2xl text-white",children:"Log in or Sign up"})]}),I==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:Z.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),Z.map(a=>jsxs("button",{onClick:()=>{Se(a.stackId),j("select");},className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[a.logoUrl?jsx("img",{src:a.logoUrl,alt:"",className:"h-10 w-10 flex-shrink-0"}):jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:a.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:a.name||a.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:a.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},a.stackId)),m.ready&&!m.known&&jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),I==="select"&&$&&jsx("div",{className:"flex items-center justify-center py-8",children:jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),o&&I==="error"&&jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsx("p",{className:"text-center text-red-400 text-sm",children:o}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Pe,children:"Try Again"})]}),I==="success"&&jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),I==="connecting"&&p&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[v==="phantom"&&jsx(se,{className:"h-14 w-14"}),v==="metamask"&&jsx(ae,{className:"h-14 w-14"})]}),jsx("p",{className:"font-medium text-sm text-white",children:t.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:Pe,children:"Cancel"})]}),I==="select"&&!p&&!$&&jsxs(Fragment,{children:[Le.map(a=>jsxs("button",{onClick:()=>Ue(a.id),className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl overflow-hidden",children:jsx(Ze,{provider:a.id})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white capitalize",children:a.name})})]},a.id)),Me.includes("phantom")&&jsxs("button",{onClick:tt,disabled:!te,className:`flex w-full items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${te?"cursor-pointer":"cursor-not-allowed opacity-50"}`,children:[jsx(se,{className:"h-14 w-14 flex-shrink-0 rounded-xl"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!te&&jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsxs("div",{className:"flex items-center gap-2",children:[te&&jsx("span",{className:"rounded-full border border-zinc-700 px-3 py-1 text-xs text-zinc-500",children:"Last used"}),jsx(ke,{className:"h-8 w-8 rounded-xl"})]})]}),Me.includes("metamask")&&Xe&&jsxs("button",{onClick:nt,className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl bg-white p-2",children:jsx(ae,{className:"h-10 w-10"})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsx(we,{className:"h-8 w-8 rounded-xl"})]}),Ie&&!D&&jsxs("button",{onClick:()=>O(true),className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl border border-zinc-700 bg-[#2a2a3e]",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:l})})]}),Ie&&D&&jsxs("div",{className:"rounded-xl border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsx(re,{onComplete:ot,disabled:M==="verifying",error:_}),M==="verifying"&&jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),M==="success"&&jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),z?.webPageUrl&&M==="idle"&&jsx("a",{href:`${z.webPageUrl}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})]}),(f?pe:V).length>0&&(!f||pe.length>0)&&jsxs(Fragment,{children:[!f&&Le.length===0&&jsxs("div",{className:"flex items-center gap-3 py-1",children:[jsx("div",{className:"flex-1 border-t border-zinc-800"}),jsx("span",{className:"text-xs text-zinc-600",children:"or continue with"}),jsx("div",{className:"flex-1 border-t border-zinc-800"})]}),(f?pe:V.filter(a=>!ue.has(a.id))).map(a=>jsxs("button",{onClick:()=>Ue(a.id),className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center",children:jsx(Ze,{provider:a.id})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white capitalize",children:a.name})})]},a.id))]})]})]})}function Ze({provider:e}){switch(e){case "google":return jsx(xe,{className:"h-14 w-14 rounded-xl"});case "discord":return jsx(ve,{className:"h-14 w-14 rounded-xl"});case "twitter":return jsx(Ne,{className:"h-14 w-14 rounded-xl"});default:return jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-xl border border-zinc-700 bg-[#2a2a3e] text-sm text-zinc-400 font-mono",children:e[0]?.toUpperCase()})}}function Pt(){if(typeof document>"u")return null;let e=document.cookie.split(";").map(n=>n.trim()).find(n=>n.startsWith("__csrf="));return e?e.slice(7):null}function Je(e,n){let[i,c]=useState(null),[w,y]=useState(true),[g,l]=useState(false),[f,d]=useState(null),N=n?.apiBaseUrl??"",s=n?.scope??"global",u=useCallback(o=>s==="global"?`${N}/api/user/profile/${o}`:`${N}/api/v2/stacks/${s.stackId}/members/${o}/profile`,[N,s]),t=useCallback(async()=>{if(!e){c(null),y(false);return}y(true),d(null);try{let o=await fetch(u(e));if(o.ok){let h=await o.json(),x=h.profile||h.data?.profile||h;c({mid:x.mid||e,username:x.username||"",avatarUrl:x.avatar_url||x.avatarUrl,bio:x.bio,createdAt:x.created_at||x.createdAt,updatedAt:x.updated_at||x.updatedAt});}else if(o.status===404)c({mid:e,username:""});else throw new Error(`${o.status}`)}catch(o){d(o instanceof Error?o.message:"Failed to load profile");}finally{y(false);}},[e,u]);useEffect(()=>{t();},[t]);let p=useCallback(async o=>{if(!e)return false;l(true),d(null);try{let h=Pt(),x=await fetch(u(e),{method:"PUT",headers:{"Content-Type":"application/json",...h?{"x-csrf-token":h}:{}},credentials:"same-origin",body:JSON.stringify({username:o.username,avatar_url:o.avatarUrl,bio:o.bio})});if(!x.ok){let m=await x.json().catch(()=>({}));throw new Error(m.error||m.message||`Update failed: ${x.status}`)}let k=await x.json(),A=k.profile||k.data?.profile||k;return c(m=>({mid:m?.mid||e,username:o.username??m?.username??"",avatarUrl:o.avatarUrl??m?.avatarUrl,bio:o.bio??m?.bio,createdAt:m?.createdAt,updatedAt:A.updated_at||A.updatedAt||Date.now()})),!0}catch(h){return d(h instanceof Error?h.message:"Update failed"),false}finally{l(false);}},[e,u]);return {profile:i,loading:w,saving:g,error:f,updateProfile:p,refresh:t}}function jt({mid:e,apiBaseUrl:n="",scope:i,onSave:c,className:w}){let{profile:y,loading:g,saving:l,error:f,updateProfile:d}=Je(e,{apiBaseUrl:n,scope:i}),[N,s]=useState(null),[u,t]=useState(null),[p,o]=useState(null),h=useRef(null),[x,k]=useState(false),A=N??y?.username??"",m=u??y?.bio??"",T=p??y?.avatarUrl,E=useCallback(U=>{let $=U.target.files?.[0];if(!$)return;let I=new FileReader;I.onload=()=>{o(I.result),k(true);},I.readAsDataURL($);},[]),R=async()=>{await d({username:A||void 0,avatarUrl:p??y?.avatarUrl,bio:m||void 0})&&(k(false),c?.());};if(g)return jsxs("div",{className:w,style:{display:"grid",gap:"1.5rem"},children:[jsx("div",{style:{height:40,background:"var(--x-color-neutral-800, #333)",animation:"pulse 2s infinite"}}),jsx("div",{style:{height:40,background:"var(--x-color-neutral-800, #333)",animation:"pulse 2s infinite"}})]});let z=i==="global"||!i?"Global profile":`Stack profile (${i.stackId})`;return jsxs("div",{className:w,style:{display:"grid",gap:"1.5rem"},children:[jsx("p",{style:{fontSize:11,color:"var(--x-color-neutral-500, #91918D)",textTransform:"uppercase",letterSpacing:"0.05em"},children:z}),jsxs("div",{style:{display:"grid",gap:"1.5rem",gridTemplateColumns:"1fr 1fr"},children:[jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jsx("label",{style:{fontSize:14,color:"var(--x-color-neutral-400, #91918D)"},children:"Username"}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[jsx("button",{type:"button",onClick:()=>h.current?.click(),style:{width:40,height:40,flexShrink:0,cursor:"pointer",overflow:"hidden",background:"var(--x-color-neutral-800, #262625)",border:"none",position:"relative",display:"flex",alignItems:"center",justifyContent:"center"},children:T?jsx("img",{src:T,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--x-color-neutral-500, #91918D)"},children:[jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),jsx("circle",{cx:"12",cy:"7",r:"4"})]})}),jsx("input",{type:"text",value:A,onChange:U=>{s(U.target.value),k(true);},placeholder:"Enter username",maxLength:30,style:{flex:1,padding:"0.75rem 1rem",fontSize:14,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-100, #FAFAF7)",border:"none",outline:"none"}})]}),jsx("input",{ref:h,type:"file",accept:"image/*",onChange:E,style:{display:"none"}})]}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jsx("label",{style:{fontSize:14,color:"var(--x-color-neutral-400, #91918D)"},children:"Bio"}),jsx("input",{type:"text",value:m,onChange:U=>{t(U.target.value),k(true);},placeholder:"Tell us about yourself",maxLength:200,style:{width:"100%",padding:"0.75rem 1rem",fontSize:14,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-100, #FAFAF7)",border:"none",outline:"none"}})]})]}),f&&jsx("p",{style:{fontSize:13,color:"var(--x-color-red-500, #BF4D43)"},children:f}),x&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:R,disabled:l,style:{padding:"0.5rem 1.25rem",fontSize:13,fontWeight:700,background:"var(--x-color-blue-600, #165DFC)",color:"#FFF",border:"none",cursor:l?"wait":"pointer",opacity:l?.6:1},children:l?"Saving...":"Save"}),jsx("button",{onClick:()=>{s(null),t(null),o(null),k(false);},style:{padding:"0.5rem 1.25rem",fontSize:13,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-400, #91918D)",border:"none",cursor:"pointer"},children:"Cancel"}),jsx("p",{style:{fontSize:11,color:"var(--x-color-neutral-500, #666663)",alignSelf:"center",marginLeft:"0.5rem"},children:"Profile updates cost 10M tokens"})]})]})}function Dt({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
2
- export{Lt as ConnectWidget,ve as DiscordIcon,we as EthereumIcon,xe as GoogleIcon,ae as MetaMaskIcon,re as OTPInput,se as PhantomIcon,jt as ProfileSettings,ke as SolanaIcon,Dt as TelegramIcon,Ne as TwitterIcon,it as UserUtilsProvider,at as useUserUtilsContext};
1
+ import {createContext,useContext,useState,useCallback,useEffect,useRef}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var ze=createContext(null);function it(){let e=useContext(ze);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function lt({config:e,callbacks:o,children:s}){return jsx(ze.Provider,{value:{config:e,callbacks:o},children:s})}function De(){let[e,o]=useState({connected:false,address:null,chain:null,provider:null}),[s,l]=useState(null),x=useCallback(async(f="phantom")=>{l(null);try{let d=typeof window<"u"?window:null,N=f==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!N)return l(`${f} wallet not found`),null;let u=(await N.connect()).publicKey.toString();return o({connected:!0,address:u,chain:"solana",provider:f}),u}catch(d){return l(d.message||"Failed to connect wallet"),null}},[]),h=useCallback(async()=>{l(null);try{let d=(typeof window<"u"?window:null)?.ethereum;if(!d)return l("MetaMask not found"),null;let N=d;d.providers?.length&&(N=d.providers.find(t=>t.isMetaMask)||d);let u=(await N.request({method:"eth_requestAccounts"}))[0];return u?(o({connected:!0,address:u,chain:"ethereum",provider:"metamask"}),u):(l("No account selected"),null)}catch(f){return l(f.message||"Failed to connect wallet"),null}},[]),g=useCallback(async(f,d)=>{l(null);let N=d?.chain||e.chain,i=d?.provider||e.provider,u=d?.address||e.address;try{if(N==="solana"){let t=typeof window<"u"?window:null,p=i==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!p)throw new Error("Wallet not available");let n=new TextEncoder().encode(f),m=await p.signMessage(n,"utf8"),y=new Uint8Array(m.signature||m),k="";for(let P=0;P<y.byteLength;P++)k+=String.fromCharCode(y[P]);return btoa(k)}if(N==="ethereum"){let p=(typeof window<"u"?window:null)?.ethereum;if(p?.providers?.length&&(p=p.providers.find(m=>m.isMetaMask)||p),!p)throw new Error("MetaMask not available");return await p.request({method:"personal_sign",params:[f,u]})}throw new Error("No wallet connected")}catch(t){return l(t.message||"Signing failed"),null}},[e]),c=useCallback(()=>{o({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:s,connectSolana:x,connectEVM:h,signMessage:g,disconnect:c}}function Oe(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith("stackauth_session="));if(!e)return null;let o=e.slice(18);return JSON.parse(atob(o.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function Te(e="__csrf"){if(typeof document>"u")return null;let o=document.cookie.split(";").map(s=>s.trim()).find(s=>s.startsWith(`${e}=`));return o?o.slice(e.length+1):null}function We(){let[e,o]=useState(null),[s,l]=useState(true),x=useCallback(()=>{let c=Oe();c&&c.expiresAt>Date.now()?o({userId:c.userId,address:c.address,chain:c.chain,expiresAt:c.expiresAt,planId:c.planId,authMethod:c.authMethod}):o(null),l(false);},[]);useEffect(()=>{x();},[x]);let h=useCallback(async(c="")=>{try{let f=await fetch(`${c}/api/auth/session`);if(f.ok){let d=await f.json();if(d.session)return o(d.session),d.session}return o(null),null}catch{return null}},[]),g=!!e&&e.expiresAt>Date.now();return {session:e,loading:s,isAuthenticated:g,refresh:h,readSession:x}}function $e(e="__csrf",o="x-csrf-token"){let[s,l]=useState(null);useEffect(()=>{l(Te(e));},[e]);let x=s?{[o]:s}:{};return {token:s,headers:x}}var gt="https://stacknet.magma-rpc.com/auth/bridge",oe="stacknet-auth-bridge";function Be(e){let o=e?.bridgeUrl||gt,s=e?.disabled||false,l=useRef(null),[x,h]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),g=useRef([]),c=useRef(false),f=useCallback(t=>{let p={...t,protocol:oe};c.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(p,new URL(o).origin):g.current.push(p);},[o]);useEffect(()=>{if(s)return;let t=n=>{if(!(!n.data||n.data.protocol!==oe)){try{if(n.origin!==new URL(o).origin)return}catch{return}switch(n.data.type){case "bridge:ready":c.current=true,h(m=>({...m,ready:true}));for(let m of g.current)l.current?.contentWindow?.postMessage(m,n.origin);g.current=[],l.current?.contentWindow?.postMessage({protocol:oe,type:"auth:check"},n.origin),l.current?.contentWindow?.postMessage({protocol:oe,type:"auth:resolve-stack"},n.origin);break;case "auth:status":h(m=>({...m,known:n.data.known,identity:n.data.identity,identityCount:n.data.identityCount||0}));break;case "auth:resolved-stack":h(m=>({...m,resolvedStackId:n.data.stackId||null}));break;}}};window.addEventListener("message",t);let p=document.createElement("iframe");return p.src=o,p.style.display="none",p.setAttribute("aria-hidden","true"),p.setAttribute("tabindex","-1"),p.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(p),l.current=p,()=>{window.removeEventListener("message",t),p.parentNode&&p.parentNode.removeChild(p),l.current=null,c.current=false;}},[o,s]);let d=useCallback(t=>{f({type:"auth:connected",...t});},[f]),N=useCallback(t=>{f({type:"auth:disconnected",...t});},[f]),i=useCallback(()=>{f({type:"auth:clear"}),h({ready:x.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[f,x.ready]),u=useCallback(()=>{f({type:"auth:check"});},[f]);return {...x,reportConnected:d,reportDisconnected:N,clearAll:i,refresh:u}}async function Fe(e,o,s,l){let x=e.apiVersion||"v2",h=`${e.baseUrl}/api/${x}${s}`;try{let g=await fetch(h,{method:o,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),c=await g.json();return g.ok?c.success&&c.data!==void 0?{success:!0,data:c.data}:{success:!0,data:c}:{success:!1,error:c.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(g){return {success:false,error:{code:"NETWORK_ERROR",message:g instanceof Error?g.message:"Network error"}}}}function He(e){return {getNetworkStatus:()=>Fe(e,"GET","/network/status"),getWeb3Challenge:(o,s)=>Fe(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:o,address:s})}}function _e(e={apiBaseUrl:""}){let{wallet:o,connectSolana:s,connectEVM:l,signMessage:x,disconnect:h}=De(),{session:g,isAuthenticated:c,refresh:f,readSession:d}=We(),{headers:N}=$e(),i=Be({disabled:typeof window>"u"}),[u,t]=useState(false),[p,n]=useState(null),[m,y]=useState(false),k=e.apiBaseUrl||"",P=e.stacknetUrl||"https://stacknet.magma-rpc.com",w=e.stackId||i.resolvedStackId||"",I=He({baseUrl:P,stackId:w}),R=useCallback(async(v,C,D,T)=>{t(true),n(null);try{let S=C;if(!S){let Z=await D();if(!Z)return t(!1),!1;S=Z;}let U=await I.getWeb3Challenge(v,S);if(!U.success||!U.data)return n("Failed to get challenge"),t(!1),!1;let E=await x(U.data.message,{chain:v,provider:T,address:S});if(!E)return t(!1),!1;let B={chain:v,message:U.data.message,signature:E,stackId:w};v==="solana"&&(B.publicKey=S);let Q=await fetch(`${k}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(B)});if(!Q.ok){let Z=await Q.json().catch(()=>({}));return n(Z.error||"Authentication failed"),t(!1),!1}return i.reportConnected({address:S,chain:v,method:T||(v==="solana"?"phantom":"metamask"),stackId:w}),d(),t(!1),!0}catch(S){return n(S.message||"Authentication failed"),t(false),false}},[k,I,x,d,i,w]),W=useCallback(async(v="phantom")=>{let C=await s(v);return C?R("solana",C,()=>s(v),v):false},[s,R]),j=useCallback(async()=>{let v=await l();return v?R("ethereum",v,l,"metamask"):false},[l,R]),z=useCallback(async v=>{t(true),n(null);try{let C=await fetch(`${k}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:v})});if(!C.ok){let D=await C.json().catch(()=>({}));return n(D.error||"Invalid code"),t(!1),!1}return d(),t(!1),!0}catch(C){return n(C.message||"OTP verification failed"),t(false),false}},[k,d]),_=useCallback(async(v,C)=>{t(true),n(null);try{let D=C||`${window.location.origin}/api/auth/oauth/callback`,T=new URLSearchParams({provider:v,redirectUri:D,stackId:w}),S=await fetch(`${k}/api/auth/oauth/start?${T}`,{credentials:"include"});if(!S.ok){let E=await S.json().catch(()=>({}));return n(E.error||"Failed to start OAuth flow"),t(!1),!1}let U=await S.json();if(U.redirect_url){let E;try{E=new URL(U.redirect_url);}catch{return n("Invalid OAuth redirect URL"),t(!1),!1}let B=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return E.protocol!=="https:"||!B.some(Q=>Q.test(E.hostname))?(n(`Refusing to redirect to non-OAuth host: ${E.hostname}`),t(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",U.state||""),sessionStorage.setItem("oauth_provider",v)),window.location.href=E.toString(),!0)}return n("No redirect URL returned"),t(!1),!1}catch(D){return n(D.message||"OAuth flow failed"),t(false),false}},[k,w]),L=useCallback(async(v,C,D)=>{t(true),n(null);try{if(typeof sessionStorage<"u"){let S=sessionStorage.getItem("oauth_state"),U=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!S||S!==D)return n("OAuth state mismatch \u2014 refusing to complete login"),t(!1),!1;if(U&&U!==v)return n("OAuth provider mismatch \u2014 refusing to complete login"),t(!1),!1}let T=await fetch(`${k}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({provider:v,code:C,state:D,stackId:w})});if(!T.ok){let S=await T.json().catch(()=>({}));return n(S.error||"OAuth authentication failed"),t(!1),!1}return d(),t(!1),!0}catch(T){return n(T.message||"OAuth callback failed"),t(false),false}},[k,w,d]),O=useCallback(async()=>{o.address&&o.chain&&i.reportDisconnected({address:o.address,chain:o.chain,stackId:w});try{await fetch(`${k}/api/auth/logout`,{method:"POST",headers:N,credentials:"include"});}catch{}h(),d();},[k,N,h,d,o,i,w]);return useEffect(()=>{if(!e.autoConnect||m||c||!i.ready||!i.known||!i.identity)return;y(true);let{chain:v,method:C}=i.identity;v==="solana"&&(C==="phantom"||C==="solflare")?W(C):v==="ethereum"&&j();},[e.autoConnect,m,c,i,W,j]),{session:g,isAuthenticated:c,wallet:o,loading:u,error:p,authenticateSolana:W,authenticateEVM:j,authenticateOTP:z,authenticateOAuth:_,authenticateOAuthCallback:L,logout:O,refresh:()=>f(k),stackId:w,bridge:{ready:i.ready,known:i.known,identity:i.identity,identityCount:i.identityCount,resolvedStackId:i.resolvedStackId}}}function Qe(e,o="https://stacknet.magma-rpc.com"){let[s,l]=useState(null),[x,h]=useState(false),[g,c]=useState(null),f=useCallback(async N=>{h(true),c(null);try{let i=await fetch(`${o}/api/v2/stacks/${N}`);if(!i.ok)return c("Stack not found"),h(!1),null;let u=await i.json(),t=u.data?.stack||u.stack||u,p={id:t.id,name:t.name,displayName:t.displayName||t.name,description:t.description,logoUrl:t.logoUrl,webPageUrl:t.webPageUrl,allowedChains:t.allowedChains||[],features:t.features,stripeProvider:t.stripeProvider,oauthProviders:t.oauthProviders?.map(n=>({provider:n.provider,clientId:n.clientId,enabled:n.enabled!==!1}))};return l(p),h(!1),p}catch(i){return c(i.message),h(false),null}},[o]);useEffect(()=>{e&&f(e);},[e,f]);let d=s?wt(s):[];return {config:s,loading:x,error:g,identityProviders:d,fetchConfig:f}}function wt(e){let o=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(o.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),o.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&o.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&o.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let s of e.oauthProviders)s.enabled&&o.push({type:"oauth",id:s.provider,name:s.provider});return o}function re(e,o="#"){if(!e||typeof e!="string")return o;let s=e.trim();if(s===""||s==="#")return o;if(s.startsWith("/")||s.startsWith("./")||s.startsWith("../"))return s;try{let l=new URL(s);if(l.protocol==="http:"||l.protocol==="https:")return l.toString()}catch{}return o}function se({length:e=6,onComplete:o,disabled:s=false,error:l,className:x="",inputClassName:h=""}){let [g,c]=useState(Array(e).fill("")),f=useCallback((i,u)=>{if(u.length>1){let p=u.replace(/\D/g,"").slice(0,e).split(""),n=[...g];p.forEach((y,k)=>{i+k<e&&(n[i+k]=y);}),c(n);let m=Math.min(i+p.length,e-1);document.getElementById(`userutils-otp-${m}`)?.focus(),n.every(y=>y!=="")&&setTimeout(()=>o(n.join("")),100);return}if(!/^\d?$/.test(u))return;let t=[...g];t[i]=u,c(t),u&&i<e-1&&document.getElementById(`userutils-otp-${i+1}`)?.focus(),u&&i===e-1&&t.every(p=>p!=="")&&setTimeout(()=>o(t.join("")),100);},[g,e,o]),d=useCallback((i,u)=>{if(u.key==="Backspace"&&!g[i]&&i>0){document.getElementById(`userutils-otp-${i-1}`)?.focus();let t=[...g];t[i-1]="",c(t);}if(u.key==="Enter"){let t=g.join("");t.length===e&&o(t);}},[g,e,o]);useCallback(()=>{c(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:x,children:[jsx("div",{className:"flex gap-2 justify-center",children:g.map((i,u)=>jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:i,onChange:t=>f(u,t.target.value),onKeyDown:t=>d(u,t),disabled:s,autoFocus:u===0,className:`w-12 h-14 text-center text-xl font-mono bg-secondary border border-primary/10 text-foreground focus:outline-none focus:border-primary/30 disabled:opacity-50 ${h}`},u))}),l&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}se.displayName="OTPInput";var vt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function ae({className:e}){return jsx("img",{src:vt,alt:"Phantom",className:e})}function ie({className:e}){return jsxs("svg",{className:e,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 507.83 470.86",children:[jsx("polygon",{fill:"#e2761b",stroke:"#e2761b",strokeLinecap:"round",strokeLinejoin:"round",points:"482.09 0.5 284.32 147.38 320.9 60.72 482.09 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"25.54 0.5 221.72 148.77 186.93 60.72 25.54 0.5"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"410.93 340.97 358.26 421.67 470.96 452.67 503.36 342.76 410.93 340.97"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"4.67 342.76 36.87 452.67 149.57 421.67 96.9 340.97 4.67 342.76"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 111.8 252.13 223.7 257.1 219.73 136.85 143.21 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"364.42 204.62 286.91 135.46 284.32 257.1 396.03 252.13 364.42 204.62"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 216.75 388.87 158.71 343.55 149.57 421.67"}),jsx("polygon",{fill:"#e4761b",stroke:"#e4761b",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 358.26 421.67 348.92 343.55 290.88 388.87"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"358.26 421.67 290.88 388.87 296.25 432.8 295.65 451.28 358.26 421.67"}),jsx("polygon",{fill:"#d7c1b3",stroke:"#d7c1b3",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 212.18 451.28 211.78 432.8 216.75 388.87 149.57 421.67"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"213.17 314.54 157.12 298.04 196.67 279.95 213.17 314.54"}),jsx("polygon",{fill:"#233447",stroke:"#233447",strokeLinecap:"round",strokeLinejoin:"round",points:"294.46 314.54 310.96 279.95 350.71 298.04 294.46 314.54"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"149.57 421.67 159.11 340.97 96.9 342.76 149.57 421.67"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"348.72 340.97 358.26 421.67 410.93 342.76 348.72 340.97"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"396.03 252.13 284.32 257.1 294.66 314.54 311.16 279.95 350.91 298.04 396.03 252.13"}),jsx("polygon",{fill:"#cd6116",stroke:"#cd6116",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 196.87 279.95 213.17 314.54 223.7 257.1 111.8 252.13 157.12 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"111.8 252.13 158.71 343.55 157.12 298.04 111.8 252.13"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"350.91 298.04 348.92 343.55 396.03 252.13 350.91 298.04"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"223.7 257.1 213.17 314.54 226.29 382.31 229.27 293.07 223.7 257.1"}),jsx("polygon",{fill:"#e4751f",stroke:"#e4751f",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 278.96 292.87 281.34 382.31 294.66 314.54 284.32 257.1"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"294.66 314.54 281.34 382.31 290.88 388.87 348.92 343.55 350.91 298.04 294.66 314.54"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"157.12 298.04 158.71 343.55 216.75 388.87 226.29 382.31 213.17 314.54 157.12 298.04"}),jsx("polygon",{fill:"#c0ad9e",stroke:"#c0ad9e",strokeLinecap:"round",strokeLinejoin:"round",points:"295.65 451.28 296.25 432.8 291.28 428.42 216.35 428.42 211.78 432.8 212.18 451.28 149.57 421.67 171.43 439.55 215.75 470.36 291.88 470.36 336.4 439.55 358.26 421.67 295.65 451.28"}),jsx("polygon",{fill:"#161616",stroke:"#161616",strokeLinecap:"round",strokeLinejoin:"round",points:"290.88 388.87 281.34 382.31 226.29 382.31 216.75 388.87 211.78 432.8 216.35 428.42 291.28 428.42 296.25 432.8 290.88 388.87"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"490.44 156.92 507.33 75.83 482.09 0.5 290.88 142.41 364.42 204.62 468.37 235.03 491.43 208.2 481.49 201.05 497.39 186.54 485.07 177 500.97 164.87 490.44 156.92"}),jsx("polygon",{fill:"#763d16",stroke:"#763d16",strokeLinecap:"round",strokeLinejoin:"round",points:"0.5 75.83 17.39 156.92 6.66 164.87 22.56 177 10.44 186.54 26.34 201.05 16.4 208.2 39.26 235.03 143.21 204.62 216.75 142.41 25.54 0.5 0.5 75.83"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"468.37 235.03 364.42 204.62 396.03 252.13 348.92 343.55 410.93 342.76 503.36 342.76 468.37 235.03"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"143.21 204.62 39.26 235.03 4.67 342.76 96.9 342.76 158.71 343.55 111.8 252.13 143.21 204.62"}),jsx("polygon",{fill:"#f6851b",stroke:"#f6851b",strokeLinecap:"round",strokeLinejoin:"round",points:"284.32 257.1 290.88 142.41 321.1 60.72 186.93 60.72 216.75 142.41 223.7 257.1 226.09 293.27 226.29 382.31 281.34 382.31 281.74 293.27 284.32 257.1"})]})}function we({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",className:e||"h-5 w-5",children:[jsxs("linearGradient",{id:"sol-g",x1:"7.233",x2:"24.766",y1:"24.766",y2:"7.234",gradientUnits:"userSpaceOnUse",children:[jsx("stop",{offset:"0",stopColor:"#9945ff"}),jsx("stop",{offset:"0.2",stopColor:"#7962e7"}),jsx("stop",{offset:"1",stopColor:"#00d18c"})]}),jsx("path",{fill:"#10111a",d:"M0 0h32v32H0z"}),jsx("path",{fill:"url(#sol-g)",fillRule:"evenodd",d:"M9.873 20.41a.65.65 0 0 1 .476-.21l14.662.012a.323.323 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54zm15.376-2.862a.322.322 0 0 1-.238.54l-14.662.012a.64.64 0 0 1-.476-.21l-3.122-3.44a.323.323 0 0 1 .238-.54l14.662-.012a.64.64 0 0 1 .475.21zM9.873 7.81a.64.64 0 0 1 .476-.21l14.662.012a.322.322 0 0 1 .238.54l-3.123 3.438a.64.64 0 0 1-.475.21l-14.662-.012a.323.323 0 0 1-.238-.54z",clipRule:"evenodd"})]})}function xe({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",className:e||"h-5 w-5",children:[jsx("rect",{width:"20",height:"20",rx:"4",fill:"#627EEA",fillOpacity:"0.2"}),jsx("path",{fill:"#627EEA",d:"M10 3l-4 6.5 4 2.5 4-2.5L10 3z"}),jsx("path",{fill:"#627EEA",fillOpacity:"0.6",d:"M6 9.5L10 12l4-2.5L10 17 6 9.5z"})]})}function ve({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#F1F2F9"}),jsx("path",{d:"M26.1001 16.2273C26.1001 15.5182 26.0365 14.8364 25.9183 14.1818H16.5001V18.05H21.8819C21.6501 19.3 20.9456 20.3591 19.8865 21.0682V23.5773H23.1183C25.0092 21.8364 26.1001 19.2727 26.1001 16.2273Z",fill:"#4285F4"}),jsx("path",{d:"M16.5001 26C19.2001 26 21.4637 25.1046 23.1182 23.5773L19.8864 21.0682C18.991 21.6682 17.8455 22.0227 16.5001 22.0227C13.8955 22.0227 11.691 20.2637 10.9046 17.9H7.56372V20.4909C9.20917 23.7591 12.591 26 16.5001 26Z",fill:"#34A853"}),jsx("path",{d:"M10.9047 17.8999C10.7047 17.2999 10.591 16.659 10.591 15.9999C10.591 15.3408 10.7047 14.6999 10.9047 14.0999V11.509H7.56376C6.86376 12.9025 6.49951 14.4405 6.50012 15.9999C6.50012 17.6136 6.88649 19.1408 7.56376 20.4908L10.9047 17.8999Z",fill:"#FBBC05"}),jsx("path",{d:"M16.5001 9.97726C17.9682 9.97726 19.2864 10.4818 20.3228 11.4727L23.191 8.60454C21.4591 6.99091 19.1955 6 16.5001 6C12.591 6 9.20917 8.2409 7.56372 11.5091L10.9046 14.1C11.691 11.7364 13.8955 9.97726 16.5001 9.97726Z",fill:"#EA4335"})]})}function Ne({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"#5462EB"}),jsx("path",{d:"M23.5433 8.87438C22.2479 8.26174 20.8587 7.81038 19.4063 7.55187C19.3799 7.54688 19.3534 7.55934 19.3398 7.58428C19.1612 7.91179 18.9633 8.33905 18.8247 8.67487C17.2625 8.43382 15.7084 8.43382 14.1782 8.67487C14.0396 8.33158 13.8345 7.91179 13.6551 7.58428C13.6414 7.56018 13.615 7.54771 13.5886 7.55187C12.1369 7.80955 10.7478 8.26092 9.45159 8.87438C9.44037 8.87937 9.43075 8.88769 9.42437 8.89849C6.78947 12.9558 6.06766 16.9134 6.42176 20.8219C6.42336 20.841 6.43378 20.8593 6.4482 20.871C8.18663 22.1868 9.87059 22.9857 11.5233 23.5152C11.5497 23.5235 11.5778 23.5135 11.5946 23.491C11.9855 22.9408 12.334 22.3606 12.6328 21.7504C12.6505 21.7147 12.6336 21.6723 12.5976 21.6581C12.0448 21.442 11.5185 21.1785 11.0122 20.8793C10.9721 20.8552 10.9689 20.7961 11.0058 20.7679C11.1123 20.6856 11.2189 20.6 11.3206 20.5135C11.339 20.4977 11.3647 20.4944 11.3863 20.5044C14.7125 22.0696 18.3136 22.0696 21.6006 20.5044C21.6222 20.4936 21.6479 20.4969 21.6671 20.5127C21.7688 20.5991 21.8754 20.6856 21.9827 20.7679C22.0196 20.7961 22.0172 20.8552 21.9771 20.8793C21.4708 21.1843 20.9445 21.442 20.3909 21.6573C20.3548 21.6715 20.3388 21.7147 20.3564 21.7504C20.6617 22.3597 21.0101 22.9399 21.3939 23.4902C21.4099 23.5135 21.4387 23.5235 21.4652 23.5152C23.1259 22.9857 24.8099 22.1868 26.5483 20.871C26.5635 20.8593 26.5731 20.8419 26.5747 20.8228C26.9985 16.3041 25.8649 12.3789 23.5697 8.89931C23.5641 8.88769 23.5545 8.87937 23.5433 8.87438Z",fill:"#F7F7F7"})]})}function Ce({className:e}){return jsxs("svg",{className:e||"h-8 w-8",viewBox:"0 0 33 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsx("rect",{x:"0.5",width:"32",height:"32",rx:"4",fill:"black"}),jsx("path",{d:"M8.53901 8L14.7164 16.2153L8.5 22.8947H9.89907L15.3415 17.0468L19.7389 22.8947H24.5L17.975 14.2173L23.7612 8H22.3621L17.3499 13.3858L13.3001 8H8.53901ZM10.5964 9.02501H12.7837L22.4422 21.8695H20.255L10.5964 9.02501Z",fill:"#F7F7F7"})]})}function Ut({config:e,onSuccess:o,title:s="Log in or Sign up",showWallets:l,showOTP:x,hideHeader:h,onOTPSubmit:g,otpLabel:c="Access Code",oauthInline:f,oauthFirst:d,className:N=""}){let i=_e(e),{isAuthenticated:u,wallet:t,loading:p,error:n,authenticateSolana:m,authenticateEVM:y,authenticateOTP:k,authenticateOAuth:P,bridge:w,stackId:I}=i,R=!e.stackId&&!I,W=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:j,identityProviders:z,loading:_}=Qe(I||e.stackId||null,W),[L,O]=useState(R?"stack-select":"select"),[v,C]=useState(null),[D,T]=useState(false),[S,U]=useState("idle"),[E,B]=useState(""),[Q,Z]=useState([]),[qe,Ie]=useState(e.stackId||null),[te,Xe]=useState(false),[et,tt]=useState(false);useEffect(()=>{if(typeof window>"u")return;let a=()=>{let G=window;Xe(!!(G.phantom?.solana?.isPhantom||G.solana?.isPhantom));let J=G.ethereum;tt(!!(J?.isMetaMask||J?.providers?.some(K=>K.isMetaMask)));};a(),window.addEventListener("ethereum#initialized",a);let F=setTimeout(a,500);return ()=>{window.removeEventListener("ethereum#initialized",a),clearTimeout(F);}},[]),useEffect(()=>{L==="stack-select"&&I&&(Ie(I),O("select"));},[L,I]),useEffect(()=>{if(!(!w.ready||!R)&&w.identity){let a=[];w.resolvedStackId&&a.push({stackId:w.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(a.map(async F=>{try{let G=await fetch(`${W}/api/v2/stacks/${F.stackId}`);if(G.ok){let J=await G.json(),K=J.data?.stack||J;F.name=K.displayName||K.name,F.logoUrl=K.logoUrl;}}catch{}return F})).then(Z);}},[w.ready,w.identity,w.resolvedStackId,R,W]),useEffect(()=>{u&&L==="success"&&o?.();},[u,L,o]);let Me=l||(z.length>0?z.filter(a=>a.type==="wallet").map(a=>a.id):["phantom","metamask"]),Le=x!==void 0?x:z.length>0?z.some(a=>a.type==="otp"):true,V=z.filter(a=>a.type==="oauth"),pe=new Set(d||[]),Ue=V.filter(a=>pe.has(a.id)),fe=f?V.filter(a=>!pe.has(a.id)):V,Ae=async a=>{C(a),O("connecting"),await P(a)||O("error");},nt=async()=>{C("phantom"),O("connecting");let a=await m("phantom");O(a?"success":"error");},ot=async()=>{C("metamask"),O("connecting");let a=await y();O(a?"success":"error");},rt=async a=>{U("verifying"),B(""),await(g||k)(a)?(U("success"),O("success")):(U("error"),B("Invalid or expired code"),setTimeout(()=>U("idle"),2e3));},Pe=()=>{O(R&&!qe?"stack-select":"select"),C(null),T(false),U("idle"),B("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${N}`,children:[!h&&jsxs("div",{className:"mb-6 text-center",children:[j?.logoUrl&&L!=="stack-select"&&jsx("img",{src:re(j.logoUrl),alt:j.displayName||"",className:"h-16 w-16 mx-auto mb-4 rounded-xl"}),j?.displayName&&jsx("p",{className:"text-sm text-zinc-400 mb-2",children:j.displayName}),jsx("h1",{className:"font-semibold text-2xl text-white",children:"Log in or Sign up"})]}),L==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:Q.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),Q.map(a=>jsxs("button",{onClick:()=>{Ie(a.stackId),O("select");},className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[a.logoUrl?jsx("img",{src:re(a.logoUrl),alt:"",className:"h-10 w-10 flex-shrink-0"}):jsx("div",{className:"h-10 w-10 flex-shrink-0 bg-zinc-700 flex items-center justify-center text-zinc-400 text-sm font-mono",children:a.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:a.name||a.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:a.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},a.stackId)),w.ready&&!w.known&&jsx("p",{className:"text-center text-xs text-zinc-600 mt-4",children:"Connect to a stack for the first time to get started."})]}),L==="select"&&_&&jsx("div",{className:"flex items-center justify-center py-8",children:jsx("div",{className:"h-6 w-6 border-2 border-zinc-600 border-t-white animate-spin",style:{borderRadius:"50%"}})}),n&&L==="error"&&jsxs("div",{className:"mb-4 border border-red-500/30 bg-red-500/10 p-4",children:[jsx("p",{className:"text-center text-red-400 text-sm",children:n}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Pe,children:"Try Again"})]}),L==="success"&&jsxs("div",{className:"border border-green-500/30 bg-green-500/10 p-6 text-center",children:[jsx("p",{className:"font-medium text-green-400 text-sm",children:"Connected!"}),jsx("p",{className:"mt-1 text-xs text-zinc-400",children:"Redirecting..."})]}),L==="connecting"&&p&&jsxs("div",{className:"border border-zinc-800 bg-[#25252f] p-6 text-center",children:[jsxs("div",{className:"mx-auto mb-3 h-14 w-14 animate-pulse",children:[v==="phantom"&&jsx(ae,{className:"h-14 w-14"}),v==="metamask"&&jsx(ie,{className:"h-14 w-14"})]}),jsx("p",{className:"font-medium text-sm text-white",children:t.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Please confirm in your wallet"}),jsx("button",{className:"mt-4 text-sm text-zinc-500 hover:text-white",onClick:Pe,children:"Cancel"})]}),L==="select"&&!p&&!_&&jsxs(Fragment,{children:[Ue.map(a=>jsxs("button",{onClick:()=>Ae(a.id),className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl overflow-hidden",children:jsx(Ve,{provider:a.id})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white capitalize",children:a.name})})]},a.id)),Me.includes("phantom")&&jsxs("button",{onClick:nt,disabled:!te,className:`flex w-full items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a] ${te?"cursor-pointer":"cursor-not-allowed opacity-50"}`,children:[jsx(ae,{className:"h-14 w-14 flex-shrink-0 rounded-xl"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-lg text-white",children:"Phantom"}),!te&&jsx("p",{className:"text-xs text-zinc-500",children:"Not installed"})]}),jsxs("div",{className:"flex items-center gap-2",children:[te&&jsx("span",{className:"rounded-full border border-zinc-700 px-3 py-1 text-xs text-zinc-500",children:"Last used"}),jsx(we,{className:"h-8 w-8 rounded-xl"})]})]}),Me.includes("metamask")&&et&&jsxs("button",{onClick:ot,className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl bg-white p-2",children:jsx(ie,{className:"h-10 w-10"})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:"MetaMask"})}),jsx(xe,{className:"h-8 w-8 rounded-xl"})]}),Le&&!D&&jsxs("button",{onClick:()=>T(true),className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-xl border border-zinc-700 bg-[#2a2a3e]",children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"28px",viewBox:"0 -960 960 960",width:"28px",fill:"#e3e3e3",children:jsx("path",{d:"M160-160q-33 0-56.5-23.5T80-240v-480q0-33 23.5-56.5T160-800h640q33 0 56.5 23.5T880-720v480q0 33-23.5 56.5T800-160H160Z"})})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white",children:c})})]}),Le&&D&&jsxs("div",{className:"rounded-xl border border-zinc-800 bg-[#25252f] p-6 space-y-4",children:[jsx("p",{className:"text-center text-sm text-zinc-400",children:"Enter your 6-digit access code"}),jsx(se,{onComplete:rt,disabled:S==="verifying",error:E}),S==="verifying"&&jsx("p",{className:"text-center text-sm text-zinc-400 animate-pulse",children:"Verifying..."}),S==="success"&&jsx("p",{className:"text-center text-sm text-green-400",children:"Verified!"}),j?.webPageUrl&&S==="idle"&&(()=>{let a=re(j.webPageUrl);return a==="#"?null:jsx("a",{href:`${a.replace(/\/$/,"")}/connect/pair`,target:"_blank",rel:"noopener noreferrer",className:"block text-center text-sm text-zinc-500 hover:text-white transition-colors",children:"Get code"})})()]}),(f?fe:V).length>0&&(!f||fe.length>0)&&jsxs(Fragment,{children:[!f&&Ue.length===0&&jsxs("div",{className:"flex items-center gap-3 py-1",children:[jsx("div",{className:"flex-1 border-t border-zinc-800"}),jsx("span",{className:"text-xs text-zinc-600",children:"or continue with"}),jsx("div",{className:"flex-1 border-t border-zinc-800"})]}),(f?fe:V.filter(a=>!pe.has(a.id))).map(a=>jsxs("button",{onClick:()=>Ae(a.id),className:"flex w-full cursor-pointer items-center gap-4 rounded-xl border border-zinc-800 bg-[#25252f] p-4 transition-colors hover:bg-[#2d2d3a]",children:[jsx("div",{className:"flex h-14 w-14 flex-shrink-0 items-center justify-center",children:jsx(Ve,{provider:a.id})}),jsx("div",{className:"flex-1 text-left",children:jsx("span",{className:"font-medium text-lg text-white capitalize",children:a.name})})]},a.id))]})]})]})}function Ve({provider:e}){switch(e){case "google":return jsx(ve,{className:"h-14 w-14 rounded-xl"});case "discord":return jsx(Ne,{className:"h-14 w-14 rounded-xl"});case "twitter":return jsx(Ce,{className:"h-14 w-14 rounded-xl"});default:return jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-xl border border-zinc-700 bg-[#2a2a3e] text-sm text-zinc-400 font-mono",children:e[0]?.toUpperCase()})}}function Pt(){if(typeof document>"u")return null;let e=document.cookie.split(";").map(o=>o.trim()).find(o=>o.startsWith("__csrf="));return e?e.slice(7):null}function Ke(e,o){let[s,l]=useState(null),[x,h]=useState(true),[g,c]=useState(false),[f,d]=useState(null),N=o?.apiBaseUrl??"",i=o?.scope??"global",u=useCallback(n=>{let m=encodeURIComponent(n);return i==="global"?`${N}/api/user/profile/${m}`:`${N}/api/v2/stacks/${encodeURIComponent(i.stackId)}/members/${m}/profile`},[N,i]),t=useCallback(async()=>{if(!e){l(null),h(false);return}h(true),d(null);try{let n=await fetch(u(e));if(n.ok){let m=await n.json(),y=m.profile||m.data?.profile||m;l({mid:y.mid||e,username:y.username||"",avatarUrl:y.avatar_url||y.avatarUrl,bio:y.bio,paymentAddress:y.payment_address||y.paymentAddress,createdAt:y.created_at||y.createdAt,updatedAt:y.updated_at||y.updatedAt});}else if(n.status===404)l({mid:e,username:""});else throw new Error(`${n.status}`)}catch(n){d(n instanceof Error?n.message:"Failed to load profile");}finally{h(false);}},[e,u]);useEffect(()=>{t();},[t]);let p=useCallback(async n=>{if(!e)return false;c(true),d(null);try{let m=Pt(),y={};n.username!==void 0&&(y.username=n.username),n.avatarUrl!==void 0&&(y.avatar_url=n.avatarUrl),n.bio!==void 0&&(y.bio=n.bio),n.paymentAddress!==void 0&&(y.payment_address=n.paymentAddress);let k=await fetch(u(e),{method:"PUT",headers:{"Content-Type":"application/json",...m?{"x-csrf-token":m}:{}},credentials:"same-origin",body:JSON.stringify(y)});if(!k.ok){let I=await k.json().catch(()=>({}));throw new Error(I.error||I.message||`Update failed: ${k.status}`)}let P=await k.json(),w=P.profile||P.data?.profile||P;return l(I=>({mid:I?.mid||e,username:n.username??I?.username??"",avatarUrl:n.avatarUrl??I?.avatarUrl,bio:n.bio??I?.bio,paymentAddress:n.paymentAddress??w.payment_address??w.paymentAddress??I?.paymentAddress,createdAt:I?.createdAt,updatedAt:w.updated_at||w.updatedAt||Date.now()})),!0}catch(m){return d(m instanceof Error?m.message:"Update failed"),false}finally{c(false);}},[e,u]);return {profile:s,loading:x,saving:g,error:f,updateProfile:p,refresh:t}}function Dt({mid:e,apiBaseUrl:o="",scope:s,onSave:l,className:x}){let{profile:h,loading:g,saving:c,error:f,updateProfile:d}=Ke(e,{apiBaseUrl:o,scope:s}),[N,i]=useState(null),[u,t]=useState(null),[p,n]=useState(null),m=useRef(null),[y,k]=useState(false),P=N??h?.username??"",w=u??h?.bio??"",I=p??h?.avatarUrl,R=useCallback(z=>{let _=z.target.files?.[0];if(!_)return;let L=new FileReader;L.onload=()=>{n(L.result),k(true);},L.readAsDataURL(_);},[]),W=async()=>{await d({username:P||void 0,avatarUrl:p??h?.avatarUrl,bio:w||void 0})&&(k(false),l?.());};if(g)return jsxs("div",{className:x,style:{display:"grid",gap:"1.5rem"},children:[jsx("div",{style:{height:40,background:"var(--x-color-neutral-800, #333)",animation:"pulse 2s infinite"}}),jsx("div",{style:{height:40,background:"var(--x-color-neutral-800, #333)",animation:"pulse 2s infinite"}})]});let j=s==="global"||!s?"Global profile":`Stack profile (${s.stackId})`;return jsxs("div",{className:x,style:{display:"grid",gap:"1.5rem"},children:[jsx("p",{style:{fontSize:11,color:"var(--x-color-neutral-500, #91918D)",textTransform:"uppercase",letterSpacing:"0.05em"},children:j}),jsxs("div",{style:{display:"grid",gap:"1.5rem",gridTemplateColumns:"1fr 1fr"},children:[jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jsx("label",{style:{fontSize:14,color:"var(--x-color-neutral-400, #91918D)"},children:"Username"}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[jsx("button",{type:"button",onClick:()=>m.current?.click(),style:{width:40,height:40,flexShrink:0,cursor:"pointer",overflow:"hidden",background:"var(--x-color-neutral-800, #262625)",border:"none",position:"relative",display:"flex",alignItems:"center",justifyContent:"center"},children:I?jsx("img",{src:I,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--x-color-neutral-500, #91918D)"},children:[jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),jsx("circle",{cx:"12",cy:"7",r:"4"})]})}),jsx("input",{type:"text",value:P,onChange:z=>{i(z.target.value),k(true);},placeholder:"Enter username",maxLength:30,style:{flex:1,padding:"0.75rem 1rem",fontSize:14,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-100, #FAFAF7)",border:"none",outline:"none"}})]}),jsx("input",{ref:m,type:"file",accept:"image/*",onChange:R,style:{display:"none"}})]}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.5rem"},children:[jsx("label",{style:{fontSize:14,color:"var(--x-color-neutral-400, #91918D)"},children:"Bio"}),jsx("input",{type:"text",value:w,onChange:z=>{t(z.target.value),k(true);},placeholder:"Tell us about yourself",maxLength:200,style:{width:"100%",padding:"0.75rem 1rem",fontSize:14,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-100, #FAFAF7)",border:"none",outline:"none"}})]})]}),f&&jsx("p",{style:{fontSize:13,color:"var(--x-color-red-500, #BF4D43)"},children:f}),y&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:W,disabled:c,style:{padding:"0.5rem 1.25rem",fontSize:13,fontWeight:700,background:"var(--x-color-blue-600, #165DFC)",color:"#FFF",border:"none",cursor:c?"wait":"pointer",opacity:c?.6:1},children:c?"Saving...":"Save"}),jsx("button",{onClick:()=>{i(null),t(null),n(null),k(false);},style:{padding:"0.5rem 1.25rem",fontSize:13,background:"var(--x-color-neutral-800, #262625)",color:"var(--x-color-neutral-400, #91918D)",border:"none",cursor:"pointer"},children:"Cancel"}),jsx("p",{style:{fontSize:11,color:"var(--x-color-neutral-500, #666663)",alignSelf:"center",marginLeft:"0.5rem"},children:"Profile updates cost 10M tokens"})]})]})}function Ot({className:e}){return jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",className:e||"h-8 w-8",children:[jsx("rect",{width:"512",height:"512",rx:"15%",fill:"#37aee2"}),jsx("path",{fill:"#c8daea",d:"M199 404c-11 0-10-4-13-14l-32-105 245-144"}),jsx("path",{fill:"#a9c9dd",d:"M199 404c7 0 11-4 16-8l45-43-56-34"}),jsx("path",{fill:"#f6fbfe",d:"M204 319l135 99c14 9 26 4 30-14l55-258c5-22-9-32-24-25L79 245c-21 8-21 21-4 26l83 26 190-121c9-5 17-3 11 4"})]})}
2
+ export{Ut as ConnectWidget,Ne as DiscordIcon,xe as EthereumIcon,ve as GoogleIcon,ie as MetaMaskIcon,se as OTPInput,ae as PhantomIcon,Dt as ProfileSettings,we as SolanaIcon,Ot as TelegramIcon,Ce as TwitterIcon,lt as UserUtilsProvider,it as useUserUtilsContext};
@@ -1,56 +1,4 @@
1
- type Web3Chain = 'ethereum' | 'solana' | 'polygon' | 'arbitrum' | 'base';
2
- /**
3
- * Client-safe session metadata. Does NOT contain the JWT.
4
- * Use ServerSession (from @stacknet/userutils/server) for server-side code that needs the JWT.
5
- */
6
- interface Session {
7
- id: string;
8
- app_identity_id: string;
9
- global_identity_commitment: string;
10
- expires_at: number;
11
- created_at: number;
12
- stack_id?: string;
13
- signed_by: string[];
14
- user_id?: string;
15
- address?: string;
16
- chain?: Web3Chain;
17
- auth_method?: string;
18
- }
19
- /** Minimal public session info (safe for client-side, no JWT) */
20
- interface PublicSession {
21
- userId: string;
22
- address?: string;
23
- chain?: Web3Chain;
24
- expiresAt: number;
25
- planId?: string;
26
- authMethod?: string;
27
- }
28
- interface MPCNode {
29
- id: string;
30
- name: string;
31
- endpoint: string;
32
- status: 'online' | 'offline' | 'syncing';
33
- public_key_share: string;
34
- last_heartbeat: number;
35
- load: number;
36
- version: string;
37
- }
38
- interface APIResponse<T> {
39
- success: boolean;
40
- data?: T;
41
- error?: {
42
- code: string;
43
- message: string;
44
- };
45
- }
46
- interface NetworkStatus {
47
- total_nodes: number;
48
- online_nodes: number;
49
- current_leader: string;
50
- consensus_health: string;
51
- last_block_time: number;
52
- network_version: string;
53
- }
1
+ import { P as PublicSession } from './auth-DR2aYcor.cjs';
54
2
 
55
3
  interface BillingPlan {
56
4
  id: string;
@@ -158,6 +106,18 @@ interface ServerConfig {
158
106
  sessionMaxAge?: number;
159
107
  /** JWT expiry in seconds (default: 900 = 15 minutes) */
160
108
  jwtExpiry?: number;
109
+ /**
110
+ * Google OAuth client ID (single). Used by createGoogleOneTapHandler to
111
+ * validate the `aud` claim on incoming Google ID tokens. Required for
112
+ * Google One Tap — without it, an ID token issued to any other Google
113
+ * application could be replayed against this endpoint.
114
+ */
115
+ googleClientId?: string;
116
+ /**
117
+ * Google OAuth client IDs (multiple). Use when the stack accepts tokens
118
+ * from more than one Google client (e.g. web + native).
119
+ */
120
+ googleClientIds?: string[];
161
121
  }
162
122
 
163
- export type { APIResponse as A, BillingPlan as B, MPCNode as M, NetworkStatus as N, PrepaidCheckoutResult as P, Session as S, UsageSummary as U, Web3Chain as W, BillingRecord as a, PrepaidVerifyResult as b, PublicSession as c, Subscription as d, UserUtilsCallbacks as e, UserUtilsConfig as f, ServerConfig as g };
123
+ export type { BillingPlan as B, PrepaidCheckoutResult as P, Subscription as S, UsageSummary as U, BillingRecord as a, PrepaidVerifyResult as b, UserUtilsCallbacks as c, UserUtilsConfig as d, ServerConfig as e };
@@ -1,56 +1,4 @@
1
- type Web3Chain = 'ethereum' | 'solana' | 'polygon' | 'arbitrum' | 'base';
2
- /**
3
- * Client-safe session metadata. Does NOT contain the JWT.
4
- * Use ServerSession (from @stacknet/userutils/server) for server-side code that needs the JWT.
5
- */
6
- interface Session {
7
- id: string;
8
- app_identity_id: string;
9
- global_identity_commitment: string;
10
- expires_at: number;
11
- created_at: number;
12
- stack_id?: string;
13
- signed_by: string[];
14
- user_id?: string;
15
- address?: string;
16
- chain?: Web3Chain;
17
- auth_method?: string;
18
- }
19
- /** Minimal public session info (safe for client-side, no JWT) */
20
- interface PublicSession {
21
- userId: string;
22
- address?: string;
23
- chain?: Web3Chain;
24
- expiresAt: number;
25
- planId?: string;
26
- authMethod?: string;
27
- }
28
- interface MPCNode {
29
- id: string;
30
- name: string;
31
- endpoint: string;
32
- status: 'online' | 'offline' | 'syncing';
33
- public_key_share: string;
34
- last_heartbeat: number;
35
- load: number;
36
- version: string;
37
- }
38
- interface APIResponse<T> {
39
- success: boolean;
40
- data?: T;
41
- error?: {
42
- code: string;
43
- message: string;
44
- };
45
- }
46
- interface NetworkStatus {
47
- total_nodes: number;
48
- online_nodes: number;
49
- current_leader: string;
50
- consensus_health: string;
51
- last_block_time: number;
52
- network_version: string;
53
- }
1
+ import { P as PublicSession } from './auth-DR2aYcor.js';
54
2
 
55
3
  interface BillingPlan {
56
4
  id: string;
@@ -158,6 +106,18 @@ interface ServerConfig {
158
106
  sessionMaxAge?: number;
159
107
  /** JWT expiry in seconds (default: 900 = 15 minutes) */
160
108
  jwtExpiry?: number;
109
+ /**
110
+ * Google OAuth client ID (single). Used by createGoogleOneTapHandler to
111
+ * validate the `aud` claim on incoming Google ID tokens. Required for
112
+ * Google One Tap — without it, an ID token issued to any other Google
113
+ * application could be replayed against this endpoint.
114
+ */
115
+ googleClientId?: string;
116
+ /**
117
+ * Google OAuth client IDs (multiple). Use when the stack accepts tokens
118
+ * from more than one Google client (e.g. web + native).
119
+ */
120
+ googleClientIds?: string[];
161
121
  }
162
122
 
163
- export type { APIResponse as A, BillingPlan as B, MPCNode as M, NetworkStatus as N, PrepaidCheckoutResult as P, Session as S, UsageSummary as U, Web3Chain as W, BillingRecord as a, PrepaidVerifyResult as b, PublicSession as c, Subscription as d, UserUtilsCallbacks as e, UserUtilsConfig as f, ServerConfig as g };
123
+ export type { BillingPlan as B, PrepaidCheckoutResult as P, Subscription as S, UsageSummary as U, BillingRecord as a, PrepaidVerifyResult as b, UserUtilsCallbacks as c, UserUtilsConfig as d, ServerConfig as e };
@@ -0,0 +1,2 @@
1
+ 'use strict';function y(l){let{apiBaseUrl:i,stacknetUrl:d="https://stacknet.magma-rpc.com",stackId:u="",transport:o,serviceKey:h,onAuthSuccess:p,onAuthError:g,onLogout:f}=l;async function c(t){if(!t.ok){let r=await t.json().catch(()=>({})),a=new Error(r.error||`Authentication failed (${t.status})`);throw g?.(a),a}let e=await t.json(),n=e.token||e.jwt,s=e.session||{userId:e.user?.id||e.userId||e.sub||"",address:e.user?.address||e.address,chain:e.user?.chain||e.chain,expiresAt:e.expiresAt||Date.now()+10080*60*1e3,authMethod:e.authMethod||e.method};return n&&await o.storeCredentials(n,s),p?.(s),s}return {async login(t,e){let n=await fetch(`${i}/api/auth/callback/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t,password:e})});return c(n)},async loginWeb3({chain:t,address:e,message:n,signature:s}){let r={chain:t,message:n,signature:s,stackId:u};t==="solana"&&(r.publicKey=e);let a=await fetch(`${i}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return c(a)},async loginOTP(t){let e=await fetch(`${i}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});return c(e)},async getSession(){let t=await o.getStoredSession();if(t&&t.expiresAt>Date.now())return t;try{let e=await o.getHeaders(),n=await fetch(`${i}/api/auth/session`,{headers:e});if(n.ok){let s=await n.json();if(s.session)return s.session}}catch{if(t)return t}return null},async checkSession(){let t=await o.getToken();if(!t)return false;try{let e=await fetch(`${i}/api/history?limit=1`,{headers:{Authorization:`Bearer ${t}`}});return e.ok?!0:e.status===401?(await o.clear(),!1):!0}catch{return true}},async getChallenge(t,e){let s=`${d}/api/v2/stacks/${encodeURIComponent(u)}/auth/web3/challenge`,r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chain:t,address:e})});if(!r.ok)throw new Error("Failed to get challenge");let a=await r.json();return a.data||a},async logout(){try{let t=await o.getHeaders();await fetch(`${i}/api/auth/logout`,{method:"POST",headers:t});}catch{}await o.clear(),f?.();},async getHeaders(){let t=await o.getHeaders();return Object.keys(t).length>0?t:h?{Authorization:`Bearer ${h}`}:{}},async getToken(){return o.getToken()}}}
2
+ exports.createAuthClient=y;
@@ -0,0 +1,19 @@
1
+ import { a as AuthClientConfig, A as AuthClient } from '../types-CAoB_5kk.cjs';
2
+ export { b as AuthTransport } from '../types-CAoB_5kk.cjs';
3
+ import '../auth-DR2aYcor.cjs';
4
+
5
+ /**
6
+ * Platform-agnostic auth client factory.
7
+ *
8
+ * Works with any AuthTransport:
9
+ * - Web: cookie-based (server sets HttpOnly cookies)
10
+ * - Native: token-based (stores JWT in secure storage)
11
+ *
12
+ * Usage:
13
+ * const auth = createAuthClient({ apiBaseUrl, transport, stackId });
14
+ * await auth.login('user@example.com', 'password');
15
+ * const headers = await auth.getHeaders();
16
+ */
17
+ declare function createAuthClient(config: AuthClientConfig): AuthClient;
18
+
19
+ export { AuthClient, AuthClientConfig, createAuthClient };
@@ -0,0 +1,19 @@
1
+ import { a as AuthClientConfig, A as AuthClient } from '../types-Dghy_8Wh.js';
2
+ export { b as AuthTransport } from '../types-Dghy_8Wh.js';
3
+ import '../auth-DR2aYcor.js';
4
+
5
+ /**
6
+ * Platform-agnostic auth client factory.
7
+ *
8
+ * Works with any AuthTransport:
9
+ * - Web: cookie-based (server sets HttpOnly cookies)
10
+ * - Native: token-based (stores JWT in secure storage)
11
+ *
12
+ * Usage:
13
+ * const auth = createAuthClient({ apiBaseUrl, transport, stackId });
14
+ * await auth.login('user@example.com', 'password');
15
+ * const headers = await auth.getHeaders();
16
+ */
17
+ declare function createAuthClient(config: AuthClientConfig): AuthClient;
18
+
19
+ export { AuthClient, AuthClientConfig, createAuthClient };
@@ -0,0 +1,2 @@
1
+ function y(l){let{apiBaseUrl:i,stacknetUrl:d="https://stacknet.magma-rpc.com",stackId:u="",transport:o,serviceKey:h,onAuthSuccess:p,onAuthError:g,onLogout:f}=l;async function c(t){if(!t.ok){let r=await t.json().catch(()=>({})),a=new Error(r.error||`Authentication failed (${t.status})`);throw g?.(a),a}let e=await t.json(),n=e.token||e.jwt,s=e.session||{userId:e.user?.id||e.userId||e.sub||"",address:e.user?.address||e.address,chain:e.user?.chain||e.chain,expiresAt:e.expiresAt||Date.now()+10080*60*1e3,authMethod:e.authMethod||e.method};return n&&await o.storeCredentials(n,s),p?.(s),s}return {async login(t,e){let n=await fetch(`${i}/api/auth/callback/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t,password:e})});return c(n)},async loginWeb3({chain:t,address:e,message:n,signature:s}){let r={chain:t,message:n,signature:s,stackId:u};t==="solana"&&(r.publicKey=e);let a=await fetch(`${i}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return c(a)},async loginOTP(t){let e=await fetch(`${i}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});return c(e)},async getSession(){let t=await o.getStoredSession();if(t&&t.expiresAt>Date.now())return t;try{let e=await o.getHeaders(),n=await fetch(`${i}/api/auth/session`,{headers:e});if(n.ok){let s=await n.json();if(s.session)return s.session}}catch{if(t)return t}return null},async checkSession(){let t=await o.getToken();if(!t)return false;try{let e=await fetch(`${i}/api/history?limit=1`,{headers:{Authorization:`Bearer ${t}`}});return e.ok?!0:e.status===401?(await o.clear(),!1):!0}catch{return true}},async getChallenge(t,e){let s=`${d}/api/v2/stacks/${encodeURIComponent(u)}/auth/web3/challenge`,r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({chain:t,address:e})});if(!r.ok)throw new Error("Failed to get challenge");let a=await r.json();return a.data||a},async logout(){try{let t=await o.getHeaders();await fetch(`${i}/api/auth/logout`,{method:"POST",headers:t});}catch{}await o.clear(),f?.();},async getHeaders(){let t=await o.getHeaders();return Object.keys(t).length>0?t:h?{Authorization:`Bearer ${h}`}:{}},async getToken(){return o.getToken()}}}
2
+ export{y as createAuthClient};
@@ -1,2 +1,2 @@
1
- 'use strict';var react=require('react');function le(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith("stackauth_session="));if(!e)return null;let t=e.slice(18);return JSON.parse(atob(t.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function R(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function $(){let[e,t]=react.useState(null),[i,l]=react.useState(true),d=react.useCallback(()=>{let r=le();r&&r.expiresAt>Date.now()?t({userId:r.userId,address:r.address,chain:r.chain,expiresAt:r.expiresAt,planId:r.planId,authMethod:r.authMethod}):t(null),l(false);},[]);react.useEffect(()=>{d();},[d]);let f=react.useCallback(async(r="")=>{try{let s=await fetch(`${r}/api/auth/session`);if(s.ok){let a=await s.json();if(a.session)return t(a.session),a.session}return t(null),null}catch{return null}},[]),p=!!e&&e.expiresAt>Date.now();return {session:e,loading:i,isAuthenticated:p,refresh:f,readSession:d}}function J(e="__csrf",t="x-csrf-token"){let[i,l]=react.useState(null);react.useEffect(()=>{l(R(e));},[e]);let d=i?{[t]:i}:{};return {token:i,headers:d}}function V(){let[e,t]=react.useState({connected:false,address:null,chain:null,provider:null}),[i,l]=react.useState(null),d=react.useCallback(async(s="phantom")=>{l(null);try{let a=typeof window<"u"?window:null,u=s==="phantom"?a?.phantom?.solana||a?.solana:a?.solflare;if(!u)return l(`${s} wallet not found`),null;let h=(await u.connect()).publicKey.toString();return t({connected:!0,address:h,chain:"solana",provider:s}),h}catch(a){return l(a.message||"Failed to connect wallet"),null}},[]),f=react.useCallback(async()=>{l(null);try{let a=(typeof window<"u"?window:null)?.ethereum;if(!a)return l("MetaMask not found"),null;let u=a;a.providers?.length&&(u=a.providers.find(n=>n.isMetaMask)||a);let h=(await u.request({method:"eth_requestAccounts"}))[0];return h?(t({connected:!0,address:h,chain:"ethereum",provider:"metamask"}),h):(l("No account selected"),null)}catch(s){return l(s.message||"Failed to connect wallet"),null}},[]),p=react.useCallback(async(s,a)=>{l(null);let u=a?.chain||e.chain,c=a?.provider||e.provider,h=a?.address||e.address;try{if(u==="solana"){let n=typeof window<"u"?window:null,g=c==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!g)throw new Error("Wallet not available");let o=new TextEncoder().encode(s),m=await g.signMessage(o,"utf8"),k=new Uint8Array(m.signature||m),b="";for(let I=0;I<k.byteLength;I++)b+=String.fromCharCode(k[I]);return btoa(b)}if(u==="ethereum"){let g=(typeof window<"u"?window:null)?.ethereum;if(g?.providers?.length&&(g=g.providers.find(m=>m.isMetaMask)||g),!g)throw new Error("MetaMask not available");return await g.request({method:"personal_sign",params:[s,h]})}throw new Error("No wallet connected")}catch(n){return l(n.message||"Signing failed"),null}},[e]),r=react.useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:i,connectSolana:d,connectEVM:f,signMessage:p,disconnect:r}}var Pe="https://stacknet.magma-rpc.com/auth/bridge",B="stacknet-auth-bridge";function H(e){let t=e?.bridgeUrl||Pe,i=e?.disabled||false,l=react.useRef(null),[d,f]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),p=react.useRef([]),r=react.useRef(false),s=react.useCallback(n=>{let g={...n,protocol:B};r.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(g,new URL(t).origin):p.current.push(g);},[t]);react.useEffect(()=>{if(i)return;let n=o=>{if(!(!o.data||o.data.protocol!==B)){try{if(o.origin!==new URL(t).origin)return}catch{return}switch(o.data.type){case "bridge:ready":r.current=true,f(m=>({...m,ready:true}));for(let m of p.current)l.current?.contentWindow?.postMessage(m,o.origin);p.current=[],l.current?.contentWindow?.postMessage({protocol:B,type:"auth:check"},o.origin),l.current?.contentWindow?.postMessage({protocol:B,type:"auth:resolve-stack"},o.origin);break;case "auth:status":f(m=>({...m,known:o.data.known,identity:o.data.identity,identityCount:o.data.identityCount||0}));break;case "auth:resolved-stack":f(m=>({...m,resolvedStackId:o.data.stackId||null}));break;}}};window.addEventListener("message",n);let g=document.createElement("iframe");return g.src=t,g.style.display="none",g.setAttribute("aria-hidden","true"),g.setAttribute("tabindex","-1"),g.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(g),l.current=g,()=>{window.removeEventListener("message",n),g.parentNode&&g.parentNode.removeChild(g),l.current=null,r.current=false;}},[t,i]);let a=react.useCallback(n=>{s({type:"auth:connected",...n});},[s]),u=react.useCallback(n=>{s({type:"auth:disconnected",...n});},[s]),c=react.useCallback(()=>{s({type:"auth:clear"}),f({ready:d.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[s,d.ready]),h=react.useCallback(()=>{s({type:"auth:check"});},[s]);return {...d,reportConnected:a,reportDisconnected:u,clearAll:c,refresh:h}}async function fe(e,t,i,l){let d=e.apiVersion||"v2",f=`${e.baseUrl}/api/${d}${i}`;try{let p=await fetch(f,{method:t,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),r=await p.json();return p.ok?r.success&&r.data!==void 0?{success:!0,data:r.data}:{success:!0,data:r}:{success:!1,error:r.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(p){return {success:false,error:{code:"NETWORK_ERROR",message:p instanceof Error?p.message:"Network error"}}}}function pe(e){return {getNetworkStatus:()=>fe(e,"GET","/network/status"),getWeb3Challenge:(t,i)=>fe(e,"POST",`/stacks/${e.stackId}/auth/web3/challenge`,{chain:t,address:i})}}function Ie(e={apiBaseUrl:""}){let{wallet:t,connectSolana:i,connectEVM:l,signMessage:d,disconnect:f}=V(),{session:p,isAuthenticated:r,refresh:s,readSession:a}=$(),{headers:u}=J(),c=H({disabled:typeof window>"u"}),[h,n]=react.useState(false),[g,o]=react.useState(null),[m,k]=react.useState(false),b=e.apiBaseUrl||"",I=e.stacknetUrl||"https://stacknet.magma-rpc.com",S=e.stackId||c.resolvedStackId||"",v=pe({baseUrl:I,stackId:S}),E=react.useCallback(async(w,C,A,O)=>{n(true),o(null);try{let P=C;if(!P){let L=await A();if(!L)return n(!1),!1;P=L;}let x=await v.getWeb3Challenge(w,P);if(!x.success||!x.data)return o("Failed to get challenge"),n(!1),!1;let G=await d(x.data.message,{chain:w,provider:O,address:P});if(!G)return n(!1),!1;let oe={chain:w,message:x.data.message,signature:G,stackId:S};w==="solana"&&(oe.publicKey=P);let ie=await fetch(`${b}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(oe)});if(!ie.ok){let L=await ie.json().catch(()=>({}));return o(L.error||"Authentication failed"),n(!1),!1}return c.reportConnected({address:P,chain:w,method:O||(w==="solana"?"phantom":"metamask"),stackId:S}),a(),n(!1),!0}catch(P){return o(P.message||"Authentication failed"),n(false),false}},[b,v,d,a,c,S]),_=react.useCallback(async(w="phantom")=>{let C=await i(w);return C?E("solana",C,()=>i(w),w):false},[i,E]),N=react.useCallback(async()=>{let w=await l();return w?E("ethereum",w,l,"metamask"):false},[l,E]),y=react.useCallback(async w=>{n(true),o(null);try{let C=await fetch(`${b}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:w})});if(!C.ok){let A=await C.json().catch(()=>({}));return o(A.error||"Invalid code"),n(!1),!1}return a(),n(!1),!0}catch(C){return o(C.message||"OTP verification failed"),n(false),false}},[b,a]),T=react.useCallback(async(w,C)=>{n(true),o(null);try{let A=C||`${window.location.origin}/api/auth/oauth/callback`,O=new URLSearchParams({provider:w,redirectUri:A,stackId:S}),P=await fetch(`${b}/api/auth/oauth/start?${O}`);if(!P.ok){let G=await P.json().catch(()=>({}));return o(G.error||"Failed to start OAuth flow"),n(!1),!1}let x=await P.json();return x.redirect_url?(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",x.state||""),sessionStorage.setItem("oauth_provider",w)),window.location.href=x.redirect_url,!0):(o("No redirect URL returned"),n(!1),!1)}catch(A){return o(A.message||"OAuth flow failed"),n(false),false}},[b,S]),W=react.useCallback(async(w,C,A)=>{n(true),o(null);try{let O=await fetch(`${b}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:w,code:C,state:A,stackId:S})});if(!O.ok){let P=await O.json().catch(()=>({}));return o(P.error||"OAuth authentication failed"),n(!1),!1}return a(),n(!1),!0}catch(O){return o(O.message||"OAuth callback failed"),n(false),false}},[b,S,a]),M=react.useCallback(async()=>{t.address&&t.chain&&c.reportDisconnected({address:t.address,chain:t.chain,stackId:S});try{await fetch(`${b}/api/auth/logout`,{method:"POST",headers:u});}catch{}f(),a();},[b,u,f,a,t,c,S]);return react.useEffect(()=>{if(!e.autoConnect||m||r||!c.ready||!c.known||!c.identity)return;k(true);let{chain:w,method:C}=c.identity;w==="solana"&&(C==="phantom"||C==="solflare")?_(C):w==="ethereum"&&N();},[e.autoConnect,m,r,c,_,N]),{session:p,isAuthenticated:r,wallet:t,loading:h,error:g,authenticateSolana:_,authenticateEVM:N,authenticateOTP:y,authenticateOAuth:T,authenticateOAuthCallback:W,logout:M,refresh:()=>s(b),stackId:S,bridge:{ready:c.ready,known:c.known,identity:c.identity,identityCount:c.identityCount,resolvedStackId:c.resolvedStackId}}}function Q(e,t="https://stacknet.magma-rpc.com"){let[i,l]=react.useState(null),[d,f]=react.useState(false),[p,r]=react.useState(null),s=react.useCallback(async u=>{f(true),r(null);try{let c=await fetch(`${t}/api/v2/stacks/${u}`);if(!c.ok)return r("Stack not found"),f(!1),null;let h=await c.json(),n=h.data?.stack||h.stack||h,g={id:n.id,name:n.name,displayName:n.displayName||n.name,description:n.description,logoUrl:n.logoUrl,webPageUrl:n.webPageUrl,allowedChains:n.allowedChains||[],features:n.features,stripeProvider:n.stripeProvider,oauthProviders:n.oauthProviders?.map(o=>({provider:o.provider,clientId:o.clientId,enabled:o.enabled!==!1}))};return l(g),f(!1),g}catch(c){return r(c.message),f(false),null}},[t]);react.useEffect(()=>{e&&s(e);},[e,s]);let a=i?Oe(i):[];return {config:i,loading:d,error:p,identityProviders:a,fetchConfig:s}}function Oe(e){let t=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(t.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),t.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&t.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&t.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let i of e.oauthProviders)i.enabled&&t.push({type:"oauth",id:i.provider,name:i.provider});return t}function Ee(e=""){let[t,i]=react.useState([]),[l,d]=react.useState(true),[f,p]=react.useState(null),r=react.useCallback(async()=>{try{let s=await fetch(`${e}/api/billing/plans`);if(s.ok){let a=await s.json();i(a.plans||a||[]);}}catch(s){p(s.message);}finally{d(false);}},[e]);return react.useEffect(()=>{r();},[r]),{plans:t,loading:l,error:f,refresh:r}}function _e(e=""){let[t,i]=react.useState(null),[l,d]=react.useState(true),[f,p]=react.useState(null),r=react.useCallback(async()=>{try{let u=await fetch(`${e}/api/billing/subscription`);if(u.ok){let c=await u.json();i(c.plan?c:null);}}catch(u){p(u.message);}finally{d(false);}},[e]);react.useEffect(()=>{r();},[r]);let s=react.useCallback(async u=>{let c=R(),n=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...c?{"x-csrf-token":c}:{}},body:JSON.stringify({planId:u})})).json();return n.url||n.checkoutUrl||null},[e]),a=react.useCallback(async()=>{let u=R();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:u?{"x-csrf-token":u}:{}})).ok?(await r(),true):false},[e,r]);return {subscription:t,loading:l,error:f,refresh:r,subscribe:s,cancel:a}}function $e(e=""){let[t,i]=react.useState(null),[l,d]=react.useState(true),[f,p]=react.useState(null),r=react.useCallback(async()=>{try{let s=await fetch(`${e}/api/billing/usage`);if(s.ok){let a=await s.json();i(a);}}catch(s){p(s.message);}finally{d(false);}},[e]);return react.useEffect(()=>{r();},[r]),{usage:t,loading:l,error:f,refresh:r}}function je(e=""){let[t,i]=react.useState(false),[l,d]=react.useState(null),f=react.useCallback(async r=>{i(true),d(null);try{let s=R(),a=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"x-csrf-token":s}:{}},body:JSON.stringify({amountCents:r})}),u=await a.json();return a.ok?u.url||null:(d(u.error||"Purchase failed"),null)}catch(s){return d(s.message),null}finally{i(false);}},[e]),p=react.useCallback(async r=>{i(true),d(null);try{let s=R(),a=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"x-csrf-token":s}:{}},body:JSON.stringify({sessionId:r})}),u=await a.json();return a.ok?u:(d(u.error||"Verification failed"),null)}catch(s){return d(s.message),null}finally{i(false);}},[e]);return {purchase:f,verifySession:p,loading:t,error:l}}function Le(e="",t){let[i,l]=react.useState([]),[d,f]=react.useState(true),[p,r]=react.useState(null),s=t?.limit||50,a=t?.offset||0,u=react.useCallback(async()=>{try{let c=await fetch(`${e}/api/billing/history?limit=${s}&offset=${a}`);if(c.ok){let h=await c.json();l(h.records||h.history||(Array.isArray(h)?h:[]));}}catch(c){r(c.message);}finally{f(false);}},[e,s,a]);return react.useEffect(()=>{u();},[u]),{records:i,loading:d,error:p,refresh:u}}function Be(){if(typeof document>"u")return null;let e=document.cookie.split(";").map(t=>t.trim()).find(t=>t.startsWith("__csrf="));return e?e.slice(7):null}function De(e,t){let[i,l]=react.useState(null),[d,f]=react.useState(true),[p,r]=react.useState(false),[s,a]=react.useState(null),u=t?.apiBaseUrl??"",c=t?.scope??"global",h=react.useCallback(o=>c==="global"?`${u}/api/user/profile/${o}`:`${u}/api/v2/stacks/${c.stackId}/members/${o}/profile`,[u,c]),n=react.useCallback(async()=>{if(!e){l(null),f(false);return}f(true),a(null);try{let o=await fetch(h(e));if(o.ok){let m=await o.json(),k=m.profile||m.data?.profile||m;l({mid:k.mid||e,username:k.username||"",avatarUrl:k.avatar_url||k.avatarUrl,bio:k.bio,createdAt:k.created_at||k.createdAt,updatedAt:k.updated_at||k.updatedAt});}else if(o.status===404)l({mid:e,username:""});else throw new Error(`${o.status}`)}catch(o){a(o instanceof Error?o.message:"Failed to load profile");}finally{f(false);}},[e,h]);react.useEffect(()=>{n();},[n]);let g=react.useCallback(async o=>{if(!e)return false;r(true),a(null);try{let m=Be(),k=await fetch(h(e),{method:"PUT",headers:{"Content-Type":"application/json",...m?{"x-csrf-token":m}:{}},credentials:"same-origin",body:JSON.stringify({username:o.username,avatar_url:o.avatarUrl,bio:o.bio})});if(!k.ok){let S=await k.json().catch(()=>({}));throw new Error(S.error||S.message||`Update failed: ${k.status}`)}let b=await k.json(),I=b.profile||b.data?.profile||b;return l(S=>({mid:S?.mid||e,username:o.username??S?.username??"",avatarUrl:o.avatarUrl??S?.avatarUrl,bio:o.bio??S?.bio,createdAt:S?.createdAt,updatedAt:I.updated_at||I.updatedAt||Date.now()})),!0}catch(m){return a(m instanceof Error?m.message:"Update failed"),false}finally{r(false);}},[e,h]);return {profile:i,loading:d,saving:p,error:s,updateProfile:g,refresh:n}}var ye="google-identity-services",Je="https://accounts.google.com/gsi/client";function Ve({stackId:e,stacknetUrl:t="https://stacknet.magma-rpc.com",apiBaseUrl:i="",autoPrompt:l=true,cancelOnTapOutside:d=true,onSuccess:f,onError:p,disabled:r=false}){let{config:s}=Q(e,t),{isAuthenticated:a,loading:u,readSession:c}=$(),[h,n]=react.useState(false),[g,o]=react.useState(null),[m,k]=react.useState(false),b=react.useRef(false),I=react.useRef(false),v=s?.oauthProviders?.find(y=>y.provider==="google"&&y.enabled&&y.clientId)?.clientId||null;react.useEffect(()=>{if(r||!v||typeof window>"u")return;if(document.getElementById(ye)){k(true);return}let y=document.createElement("script");y.id=ye,y.src=Je,y.async=true,y.defer=true,y.onload=()=>k(true),y.onerror=()=>{o("Failed to load Google sign-in"),p?.("Failed to load Google Identity Services script");},document.head.appendChild(y);},[r,v,p]);let E=react.useCallback(async y=>{n(true),o(null);try{let T=await fetch(`${i}/api/auth/google/one-tap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:y.credential,stackId:e})});if(!T.ok){let M=(await T.json().catch(()=>({}))).error||"Google sign-in failed";o(M),p?.(M),n(!1);return}c(),n(!1),f?.();}catch(T){let W=T.message||"Google sign-in failed";o(W),p?.(W),n(false);}},[i,e,c,f,p]);react.useEffect(()=>{if(r){console.debug("[GoogleOneTap] Disabled");return}if(!m){console.debug("[GoogleOneTap] Script not loaded yet, clientId:",v);return}if(!v){console.debug("[GoogleOneTap] No Google clientId from stack config");return}if(u){console.debug("[GoogleOneTap] Session still loading");return}if(a){console.debug("[GoogleOneTap] User already authenticated, skipping");return}if(!window.google?.accounts?.id){console.debug("[GoogleOneTap] GIS library not available on window");return}b.current||(console.debug("[GoogleOneTap] Initializing with clientId:",v),b.current=true,window.google.accounts.id.initialize({client_id:v,callback:E,auto_select:true,cancel_on_tap_outside:d}),l&&!I.current&&(I.current=true,console.debug("[GoogleOneTap] Showing prompt..."),window.google.accounts.id.prompt(y=>{y.isDisplayed?.()&&console.debug("[GoogleOneTap] Prompt displayed"),y.isNotDisplayed?.()&&console.debug("[GoogleOneTap] Not displayed:",y.getNotDisplayedReason?.()),y.isSkippedMoment?.()&&console.debug("[GoogleOneTap] Skipped:",y.getSkippedReason?.()),y.isDismissedMoment?.()&&console.debug("[GoogleOneTap] Dismissed:",y.getDismissedReason?.());})));},[r,m,v,u,a,E,l,d]),react.useEffect(()=>()=>{window.google?.accounts?.id&&b.current&&window.google.accounts.id.cancel();},[]);let _=react.useCallback(()=>{!window.google?.accounts?.id||!b.current||window.google.accounts.id.prompt();},[]),N=react.useCallback((y,T)=>{!y||!window.google?.accounts?.id||!b.current||window.google.accounts.id.renderButton(y,{theme:T?.theme||"filled_black",size:T?.size||"large",text:T?.text||"signin_with",width:T?.width});},[]);return {available:!!v,ready:m&&!!v,loading:h,error:g,prompt:_,renderButton:N,clientId:v}}
2
- exports.useAuthBridge=H;exports.useBillingHistory=Le;exports.useCSRFToken=J;exports.useGoogleOneTap=Ve;exports.usePlans=Ee;exports.usePrepaidCheckout=je;exports.useProfile=De;exports.useSession=$;exports.useStackAuth=Ie;exports.useStackConfig=Q;exports.useSubscription=_e;exports.useUsage=$e;exports.useWeb3Wallet=V;
1
+ 'use strict';var react=require('react');function le(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith("stackauth_session="));if(!e)return null;let r=e.slice(18);return JSON.parse(atob(r.replace(/-/g,"+").replace(/_/g,"/")))}catch{return null}}function U(e="__csrf"){if(typeof document>"u")return null;let r=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${e}=`));return r?r.slice(e.length+1):null}function M(){let[e,r]=react.useState(null),[i,l]=react.useState(true),d=react.useCallback(()=>{let s=le();s&&s.expiresAt>Date.now()?r({userId:s.userId,address:s.address,chain:s.chain,expiresAt:s.expiresAt,planId:s.planId,authMethod:s.authMethod}):r(null),l(false);},[]);react.useEffect(()=>{d();},[d]);let f=react.useCallback(async(s="")=>{try{let a=await fetch(`${s}/api/auth/session`);if(a.ok){let o=await a.json();if(o.session)return r(o.session),o.session}return r(null),null}catch{return null}},[]),p=!!e&&e.expiresAt>Date.now();return {session:e,loading:i,isAuthenticated:p,refresh:f,readSession:d}}function V(e="__csrf",r="x-csrf-token"){let[i,l]=react.useState(null);react.useEffect(()=>{l(U(e));},[e]);let d=i?{[r]:i}:{};return {token:i,headers:d}}function z(){let[e,r]=react.useState({connected:false,address:null,chain:null,provider:null}),[i,l]=react.useState(null),d=react.useCallback(async(a="phantom")=>{l(null);try{let o=typeof window<"u"?window:null,u=a==="phantom"?o?.phantom?.solana||o?.solana:o?.solflare;if(!u)return l(`${a} wallet not found`),null;let h=(await u.connect()).publicKey.toString();return r({connected:!0,address:h,chain:"solana",provider:a}),h}catch(o){return l(o.message||"Failed to connect wallet"),null}},[]),f=react.useCallback(async()=>{l(null);try{let o=(typeof window<"u"?window:null)?.ethereum;if(!o)return l("MetaMask not found"),null;let u=o;o.providers?.length&&(u=o.providers.find(t=>t.isMetaMask)||o);let h=(await u.request({method:"eth_requestAccounts"}))[0];return h?(r({connected:!0,address:h,chain:"ethereum",provider:"metamask"}),h):(l("No account selected"),null)}catch(a){return l(a.message||"Failed to connect wallet"),null}},[]),p=react.useCallback(async(a,o)=>{l(null);let u=o?.chain||e.chain,c=o?.provider||e.provider,h=o?.address||e.address;try{if(u==="solana"){let t=typeof window<"u"?window:null,g=c==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!g)throw new Error("Wallet not available");let n=new TextEncoder().encode(a),m=await g.signMessage(n,"utf8"),b=new Uint8Array(m.signature||m),w="";for(let A=0;A<b.byteLength;A++)w+=String.fromCharCode(b[A]);return btoa(w)}if(u==="ethereum"){let g=(typeof window<"u"?window:null)?.ethereum;if(g?.providers?.length&&(g=g.providers.find(m=>m.isMetaMask)||g),!g)throw new Error("MetaMask not available");return await g.request({method:"personal_sign",params:[a,h]})}throw new Error("No wallet connected")}catch(t){return l(t.message||"Signing failed"),null}},[e]),s=react.useCallback(()=>{r({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:i,connectSolana:d,connectEVM:f,signMessage:p,disconnect:s}}var Pe="https://stacknet.magma-rpc.com/auth/bridge",J="stacknet-auth-bridge";function q(e){let r=e?.bridgeUrl||Pe,i=e?.disabled||false,l=react.useRef(null),[d,f]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),p=react.useRef([]),s=react.useRef(false),a=react.useCallback(t=>{let g={...t,protocol:J};s.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(g,new URL(r).origin):p.current.push(g);},[r]);react.useEffect(()=>{if(i)return;let t=n=>{if(!(!n.data||n.data.protocol!==J)){try{if(n.origin!==new URL(r).origin)return}catch{return}switch(n.data.type){case "bridge:ready":s.current=true,f(m=>({...m,ready:true}));for(let m of p.current)l.current?.contentWindow?.postMessage(m,n.origin);p.current=[],l.current?.contentWindow?.postMessage({protocol:J,type:"auth:check"},n.origin),l.current?.contentWindow?.postMessage({protocol:J,type:"auth:resolve-stack"},n.origin);break;case "auth:status":f(m=>({...m,known:n.data.known,identity:n.data.identity,identityCount:n.data.identityCount||0}));break;case "auth:resolved-stack":f(m=>({...m,resolvedStackId:n.data.stackId||null}));break;}}};window.addEventListener("message",t);let g=document.createElement("iframe");return g.src=r,g.style.display="none",g.setAttribute("aria-hidden","true"),g.setAttribute("tabindex","-1"),g.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(g),l.current=g,()=>{window.removeEventListener("message",t),g.parentNode&&g.parentNode.removeChild(g),l.current=null,s.current=false;}},[r,i]);let o=react.useCallback(t=>{a({type:"auth:connected",...t});},[a]),u=react.useCallback(t=>{a({type:"auth:disconnected",...t});},[a]),c=react.useCallback(()=>{a({type:"auth:clear"}),f({ready:d.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[a,d.ready]),h=react.useCallback(()=>{a({type:"auth:check"});},[a]);return {...d,reportConnected:o,reportDisconnected:u,clearAll:c,refresh:h}}async function fe(e,r,i,l){let d=e.apiVersion||"v2",f=`${e.baseUrl}/api/${d}${i}`;try{let p=await fetch(f,{method:r,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),s=await p.json();return p.ok?s.success&&s.data!==void 0?{success:!0,data:s.data}:{success:!0,data:s}:{success:!1,error:s.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(p){return {success:false,error:{code:"NETWORK_ERROR",message:p instanceof Error?p.message:"Network error"}}}}function pe(e){return {getNetworkStatus:()=>fe(e,"GET","/network/status"),getWeb3Challenge:(r,i)=>fe(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:r,address:i})}}function Ae(e={apiBaseUrl:""}){let{wallet:r,connectSolana:i,connectEVM:l,signMessage:d,disconnect:f}=z(),{session:p,isAuthenticated:s,refresh:a,readSession:o}=M(),{headers:u}=V(),c=q({disabled:typeof window>"u"}),[h,t]=react.useState(false),[g,n]=react.useState(null),[m,b]=react.useState(false),w=e.apiBaseUrl||"",A=e.stacknetUrl||"https://stacknet.magma-rpc.com",C=e.stackId||c.resolvedStackId||"",S=pe({baseUrl:A,stackId:C}),E=react.useCallback(async(k,P,T,x)=>{t(true),n(null);try{let v=P;if(!v){let D=await T();if(!D)return t(!1),!1;v=D;}let O=await S.getWeb3Challenge(k,v);if(!O.success||!O.data)return n("Failed to get challenge"),t(!1),!1;let R=await d(O.data.message,{chain:k,provider:x,address:v});if(!R)return t(!1),!1;let G={chain:k,message:O.data.message,signature:R,stackId:C};k==="solana"&&(G.publicKey=v);let F=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(G)});if(!F.ok){let D=await F.json().catch(()=>({}));return n(D.error||"Authentication failed"),t(!1),!1}return c.reportConnected({address:v,chain:k,method:x||(k==="solana"?"phantom":"metamask"),stackId:C}),o(),t(!1),!0}catch(v){return n(v.message||"Authentication failed"),t(false),false}},[w,S,d,o,c,C]),$=react.useCallback(async(k="phantom")=>{let P=await i(k);return P?E("solana",P,()=>i(k),k):false},[i,E]),W=react.useCallback(async()=>{let k=await l();return k?E("ethereum",k,l,"metamask"):false},[l,E]),y=react.useCallback(async k=>{t(true),n(null);try{let P=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:k})});if(!P.ok){let T=await P.json().catch(()=>({}));return n(T.error||"Invalid code"),t(!1),!1}return o(),t(!1),!0}catch(P){return n(P.message||"OTP verification failed"),t(false),false}},[w,o]),I=react.useCallback(async(k,P)=>{t(true),n(null);try{let T=P||`${window.location.origin}/api/auth/oauth/callback`,x=new URLSearchParams({provider:k,redirectUri:T,stackId:C}),v=await fetch(`${w}/api/auth/oauth/start?${x}`,{credentials:"include"});if(!v.ok){let R=await v.json().catch(()=>({}));return n(R.error||"Failed to start OAuth flow"),t(!1),!1}let O=await v.json();if(O.redirect_url){let R;try{R=new URL(O.redirect_url);}catch{return n("Invalid OAuth redirect URL"),t(!1),!1}let G=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return R.protocol!=="https:"||!G.some(F=>F.test(R.hostname))?(n(`Refusing to redirect to non-OAuth host: ${R.hostname}`),t(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",O.state||""),sessionStorage.setItem("oauth_provider",k)),window.location.href=R.toString(),!0)}return n("No redirect URL returned"),t(!1),!1}catch(T){return n(T.message||"OAuth flow failed"),t(false),false}},[w,C]),N=react.useCallback(async(k,P,T)=>{t(true),n(null);try{if(typeof sessionStorage<"u"){let v=sessionStorage.getItem("oauth_state"),O=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!v||v!==T)return n("OAuth state mismatch \u2014 refusing to complete login"),t(!1),!1;if(O&&O!==k)return n("OAuth provider mismatch \u2014 refusing to complete login"),t(!1),!1}let x=await fetch(`${w}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({provider:k,code:P,state:T,stackId:C})});if(!x.ok){let v=await x.json().catch(()=>({}));return n(v.error||"OAuth authentication failed"),t(!1),!1}return o(),t(!1),!0}catch(x){return n(x.message||"OAuth callback failed"),t(false),false}},[w,C,o]),j=react.useCallback(async()=>{r.address&&r.chain&&c.reportDisconnected({address:r.address,chain:r.chain,stackId:C});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:u,credentials:"include"});}catch{}f(),o();},[w,u,f,o,r,c,C]);return react.useEffect(()=>{if(!e.autoConnect||m||s||!c.ready||!c.known||!c.identity)return;b(true);let{chain:k,method:P}=c.identity;k==="solana"&&(P==="phantom"||P==="solflare")?$(P):k==="ethereum"&&W();},[e.autoConnect,m,s,c,$,W]),{session:p,isAuthenticated:s,wallet:r,loading:h,error:g,authenticateSolana:$,authenticateEVM:W,authenticateOTP:y,authenticateOAuth:I,authenticateOAuthCallback:N,logout:j,refresh:()=>a(w),stackId:C,bridge:{ready:c.ready,known:c.known,identity:c.identity,identityCount:c.identityCount,resolvedStackId:c.resolvedStackId}}}function Y(e,r="https://stacknet.magma-rpc.com"){let[i,l]=react.useState(null),[d,f]=react.useState(false),[p,s]=react.useState(null),a=react.useCallback(async u=>{f(true),s(null);try{let c=await fetch(`${r}/api/v2/stacks/${u}`);if(!c.ok)return s("Stack not found"),f(!1),null;let h=await c.json(),t=h.data?.stack||h.stack||h,g={id:t.id,name:t.name,displayName:t.displayName||t.name,description:t.description,logoUrl:t.logoUrl,webPageUrl:t.webPageUrl,allowedChains:t.allowedChains||[],features:t.features,stripeProvider:t.stripeProvider,oauthProviders:t.oauthProviders?.map(n=>({provider:n.provider,clientId:n.clientId,enabled:n.enabled!==!1}))};return l(g),f(!1),g}catch(c){return s(c.message),f(false),null}},[r]);react.useEffect(()=>{e&&a(e);},[e,a]);let o=i?Te(i):[];return {config:i,loading:d,error:p,identityProviders:o,fetchConfig:a}}function Te(e){let r=[];if(e.features?.web3Auth!==false&&(e.allowedChains.includes("solana")&&(r.push({type:"wallet",id:"phantom",name:"Phantom",chain:"solana"}),r.push({type:"wallet",id:"solflare",name:"Solflare",chain:"solana"})),(e.allowedChains.includes("ethereum")||e.allowedChains.includes("polygon")||e.allowedChains.includes("base"))&&r.push({type:"wallet",id:"metamask",name:"MetaMask",chain:"ethereum"})),e.features?.apiKeyAuth!==false&&r.push({type:"otp",id:"otp",name:"Access Code"}),e.features?.oauthAuth&&e.oauthProviders)for(let i of e.oauthProviders)i.enabled&&r.push({type:"oauth",id:i.provider,name:i.provider});return r}function Ue(e=""){let[r,i]=react.useState([]),[l,d]=react.useState(true),[f,p]=react.useState(null),s=react.useCallback(async()=>{try{let a=await fetch(`${e}/api/billing/plans`);if(a.ok){let o=await a.json();i(o.plans||o||[]);}}catch(a){p(a.message);}finally{d(false);}},[e]);return react.useEffect(()=>{s();},[s]),{plans:r,loading:l,error:f,refresh:s}}function _e(e=""){let[r,i]=react.useState(null),[l,d]=react.useState(true),[f,p]=react.useState(null),s=react.useCallback(async()=>{try{let u=await fetch(`${e}/api/billing/subscription`);if(u.ok){let c=await u.json();i(c.plan?c:null);}}catch(u){p(u.message);}finally{d(false);}},[e]);react.useEffect(()=>{s();},[s]);let a=react.useCallback(async u=>{let c=U(),t=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...c?{"x-csrf-token":c}:{}},body:JSON.stringify({planId:u})})).json();return t.url||t.checkoutUrl||null},[e]),o=react.useCallback(async()=>{let u=U();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:u?{"x-csrf-token":u}:{}})).ok?(await s(),true):false},[e,s]);return {subscription:r,loading:l,error:f,refresh:s,subscribe:a,cancel:o}}function Ne(e=""){let[r,i]=react.useState(null),[l,d]=react.useState(true),[f,p]=react.useState(null),s=react.useCallback(async()=>{try{let a=await fetch(`${e}/api/billing/usage`);if(a.ok){let o=await a.json();i(o);}}catch(a){p(a.message);}finally{d(false);}},[e]);return react.useEffect(()=>{s();},[s]),{usage:r,loading:l,error:f,refresh:s}}function Me(e=""){let[r,i]=react.useState(false),[l,d]=react.useState(null),f=react.useCallback(async s=>{i(true),d(null);try{let a=U(),o=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-csrf-token":a}:{}},body:JSON.stringify({amountCents:s})}),u=await o.json();return o.ok?u.url||null:(d(u.error||"Purchase failed"),null)}catch(a){return d(a.message),null}finally{i(false);}},[e]),p=react.useCallback(async s=>{i(true),d(null);try{let a=U(),o=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-csrf-token":a}:{}},body:JSON.stringify({sessionId:s})}),u=await o.json();return o.ok?u:(d(u.error||"Verification failed"),null)}catch(a){return d(a.message),null}finally{i(false);}},[e]);return {purchase:f,verifySession:p,loading:r,error:l}}function Ge(e="",r){let[i,l]=react.useState([]),[d,f]=react.useState(true),[p,s]=react.useState(null),a=r?.limit||50,o=r?.offset||0,u=react.useCallback(async()=>{try{let c=await fetch(`${e}/api/billing/history?limit=${a}&offset=${o}`);if(c.ok){let h=await c.json();l(h.records||h.history||(Array.isArray(h)?h:[]));}}catch(c){s(c.message);}finally{f(false);}},[e,a,o]);return react.useEffect(()=>{u();},[u]),{records:i,loading:d,error:p,refresh:u}}function De(){if(typeof document>"u")return null;let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith("__csrf="));return e?e.slice(7):null}function Be(e,r){let[i,l]=react.useState(null),[d,f]=react.useState(true),[p,s]=react.useState(false),[a,o]=react.useState(null),u=r?.apiBaseUrl??"",c=r?.scope??"global",h=react.useCallback(n=>{let m=encodeURIComponent(n);return c==="global"?`${u}/api/user/profile/${m}`:`${u}/api/v2/stacks/${encodeURIComponent(c.stackId)}/members/${m}/profile`},[u,c]),t=react.useCallback(async()=>{if(!e){l(null),f(false);return}f(true),o(null);try{let n=await fetch(h(e));if(n.ok){let m=await n.json(),b=m.profile||m.data?.profile||m;l({mid:b.mid||e,username:b.username||"",avatarUrl:b.avatar_url||b.avatarUrl,bio:b.bio,paymentAddress:b.payment_address||b.paymentAddress,createdAt:b.created_at||b.createdAt,updatedAt:b.updated_at||b.updatedAt});}else if(n.status===404)l({mid:e,username:""});else throw new Error(`${n.status}`)}catch(n){o(n instanceof Error?n.message:"Failed to load profile");}finally{f(false);}},[e,h]);react.useEffect(()=>{t();},[t]);let g=react.useCallback(async n=>{if(!e)return false;s(true),o(null);try{let m=De(),b={};n.username!==void 0&&(b.username=n.username),n.avatarUrl!==void 0&&(b.avatar_url=n.avatarUrl),n.bio!==void 0&&(b.bio=n.bio),n.paymentAddress!==void 0&&(b.payment_address=n.paymentAddress);let w=await fetch(h(e),{method:"PUT",headers:{"Content-Type":"application/json",...m?{"x-csrf-token":m}:{}},credentials:"same-origin",body:JSON.stringify(b)});if(!w.ok){let S=await w.json().catch(()=>({}));throw new Error(S.error||S.message||`Update failed: ${w.status}`)}let A=await w.json(),C=A.profile||A.data?.profile||A;return l(S=>({mid:S?.mid||e,username:n.username??S?.username??"",avatarUrl:n.avatarUrl??S?.avatarUrl,bio:n.bio??S?.bio,paymentAddress:n.paymentAddress??C.payment_address??C.paymentAddress??S?.paymentAddress,createdAt:S?.createdAt,updatedAt:C.updated_at||C.updatedAt||Date.now()})),!0}catch(m){return o(m instanceof Error?m.message:"Update failed"),false}finally{s(false);}},[e,h]);return {profile:i,loading:d,saving:p,error:a,updateProfile:g,refresh:t}}var ye="google-identity-services",Je="https://accounts.google.com/gsi/client";function He({stackId:e,stacknetUrl:r="https://stacknet.magma-rpc.com",apiBaseUrl:i="",autoPrompt:l=true,cancelOnTapOutside:d=true,onSuccess:f,onError:p,disabled:s=false}){let{config:a}=Y(e,r),{isAuthenticated:o,loading:u,readSession:c}=M(),[h,t]=react.useState(false),[g,n]=react.useState(null),[m,b]=react.useState(false),w=react.useRef(false),A=react.useRef(false),S=a?.oauthProviders?.find(y=>y.provider==="google"&&y.enabled&&y.clientId)?.clientId||null;react.useEffect(()=>{if(s||!S||typeof window>"u")return;if(document.getElementById(ye)){b(true);return}let y=document.createElement("script");y.id=ye,y.src=Je,y.async=true,y.defer=true,y.onload=()=>b(true),y.onerror=()=>{n("Failed to load Google sign-in"),p?.("Failed to load Google Identity Services script");},document.head.appendChild(y);},[s,S,p]);let E=react.useCallback(async y=>{t(true),n(null);try{let I=await fetch(`${i}/api/auth/google/one-tap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:y.credential,stackId:e})});if(!I.ok){let j=(await I.json().catch(()=>({}))).error||"Google sign-in failed";n(j),p?.(j),t(!1);return}c(),t(!1),f?.();}catch(I){let N=I.message||"Google sign-in failed";n(N),p?.(N),t(false);}},[i,e,c,f,p]);react.useEffect(()=>{if(s){console.debug("[GoogleOneTap] Disabled");return}if(!m){console.debug("[GoogleOneTap] Script not loaded yet, clientId:",S);return}if(!S){console.debug("[GoogleOneTap] No Google clientId from stack config");return}if(u){console.debug("[GoogleOneTap] Session still loading");return}if(o){console.debug("[GoogleOneTap] User already authenticated, skipping");return}if(!window.google?.accounts?.id){console.debug("[GoogleOneTap] GIS library not available on window");return}w.current||(console.debug("[GoogleOneTap] Initializing with clientId:",S),w.current=true,window.google.accounts.id.initialize({client_id:S,callback:E,auto_select:true,cancel_on_tap_outside:d}),l&&!A.current&&(A.current=true,console.debug("[GoogleOneTap] Showing prompt..."),window.google.accounts.id.prompt(y=>{y.isDisplayed?.()&&console.debug("[GoogleOneTap] Prompt displayed"),y.isNotDisplayed?.()&&console.debug("[GoogleOneTap] Not displayed:",y.getNotDisplayedReason?.()),y.isSkippedMoment?.()&&console.debug("[GoogleOneTap] Skipped:",y.getSkippedReason?.()),y.isDismissedMoment?.()&&console.debug("[GoogleOneTap] Dismissed:",y.getDismissedReason?.());})));},[s,m,S,u,o,E,l,d]),react.useEffect(()=>()=>{window.google?.accounts?.id&&w.current&&window.google.accounts.id.cancel();},[]);let $=react.useCallback(()=>{!window.google?.accounts?.id||!w.current||window.google.accounts.id.prompt();},[]),W=react.useCallback((y,I)=>{!y||!window.google?.accounts?.id||!w.current||window.google.accounts.id.renderButton(y,{theme:I?.theme||"filled_black",size:I?.size||"large",text:I?.text||"signin_with",width:I?.width});},[]);return {available:!!S,ready:m&&!!S,loading:h,error:g,prompt:$,renderButton:W,clientId:S}}
2
+ exports.useAuthBridge=q;exports.useBillingHistory=Ge;exports.useCSRFToken=V;exports.useGoogleOneTap=He;exports.usePlans=Ue;exports.usePrepaidCheckout=Me;exports.useProfile=Be;exports.useSession=M;exports.useStackAuth=Ae;exports.useStackConfig=Y;exports.useSubscription=_e;exports.useUsage=Ne;exports.useWeb3Wallet=z;
@@ -1,4 +1,5 @@
1
- import { c as PublicSession, W as Web3Chain, f as UserUtilsConfig, B as BillingPlan, d as Subscription, U as UsageSummary, b as PrepaidVerifyResult, a as BillingRecord } from '../config-BrziGArs.cjs';
1
+ import { P as PublicSession, W as Web3Chain } from '../auth-DR2aYcor.cjs';
2
+ import { d as UserUtilsConfig, B as BillingPlan, S as Subscription, U as UsageSummary, b as PrepaidVerifyResult, a as BillingRecord } from '../config-Bjh8PEhY.cjs';
2
3
  import { ProfileScope, UserProfile, ProfileUpdateInput } from '../types/index.cjs';
3
4
 
4
5
  /**
@@ -1,4 +1,5 @@
1
- import { c as PublicSession, W as Web3Chain, f as UserUtilsConfig, B as BillingPlan, d as Subscription, U as UsageSummary, b as PrepaidVerifyResult, a as BillingRecord } from '../config-BrziGArs.js';
1
+ import { P as PublicSession, W as Web3Chain } from '../auth-DR2aYcor.js';
2
+ import { d as UserUtilsConfig, B as BillingPlan, S as Subscription, U as UsageSummary, b as PrepaidVerifyResult, a as BillingRecord } from '../config-_ZjAzNkJ.js';
2
3
  import { ProfileScope, UserProfile, ProfileUpdateInput } from '../types/index.js';
3
4
 
4
5
  /**