@stacknet/userutils 0.6.7 → 0.6.11

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 Fe=createContext(null);function vt(){let e=useContext(Fe);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function Ct({config:e,callbacks:t,children:a}){return jsx(Fe.Provider,{value:{config:e,callbacks:t},children:a})}function He(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[a,l]=useState(null),v=useCallback(async(f="phantom")=>{l(null);try{let d=typeof window<"u"?window:null,x=f==="phantom"?d?.phantom?.solana||d?.solana:d?.solflare;if(!x)return l(`${f} wallet not found`),null;let u=(await x.connect()).publicKey.toString();return t({connected:!0,address:u,chain:"solana",provider:f}),u}catch(d){return l(d.message||"Failed to connect wallet"),null}},[]),y=useCallback(async()=>{l(null);try{let d=(typeof window<"u"?window:null)?.ethereum;if(!d)return l("MetaMask not found"),null;let x=d;d.providers?.length&&(x=d.providers.find(n=>n.isMetaMask)||d);let u=(await x.request({method:"eth_requestAccounts"}))[0];return u?(t({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}},[]),h=useCallback(async(f,d)=>{l(null);let x=d?.chain||e.chain,i=d?.provider||e.provider,u=d?.address||e.address;try{if(x==="solana"){let n=typeof window<"u"?window:null,p=i==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!p)throw new Error("Wallet not available");let o=new TextEncoder().encode(f),g=await p.signMessage(o,"utf8"),m=new Uint8Array(g.signature||g),k="";for(let U=0;U<m.byteLength;U++)k+=String.fromCharCode(m[U]);return btoa(k)}if(x==="ethereum"){let p=(typeof window<"u"?window:null)?.ethereum;if(p?.providers?.length&&(p=p.providers.find(g=>g.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(n){return l(n.message||"Signing failed"),null}},[e]),c=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:a,connectSolana:v,connectEVM:y,signMessage:h,disconnect:c}}function _e(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(a=>a.trim()).find(a=>a.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 Qe(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(a=>a.trim()).find(a=>a.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function Ye(){let[e,t]=useState(null),[a,l]=useState(true),v=useCallback(()=>{let c=_e();c&&c.expiresAt>Date.now()?t({userId:c.userId,address:c.address,chain:c.chain,expiresAt:c.expiresAt,planId:c.planId,authMethod:c.authMethod}):t(null),l(false);},[]);useEffect(()=>{v();},[v]);let y=useCallback(async(c="")=>{try{let f=await fetch(`${c}/api/auth/session`);if(f.ok){let d=await f.json();if(d.session)return t(d.session),d.session}return t(null),null}catch{return null}},[]),h=!!e&&e.expiresAt>Date.now();return {session:e,loading:a,isAuthenticated:h,refresh:y,readSession:v}}function Ve(e="__csrf",t="x-csrf-token"){let[a,l]=useState(null);useEffect(()=>{l(Qe(e));},[e]);let v=a?{[t]:a}:{};return {token:a,headers:v}}var Lt="https://stacknet.magma-rpc.com/auth/bridge",le="stacknet-auth-bridge";function Je(e){let t=e?.bridgeUrl||Lt,a=e?.disabled||false,l=useRef(null),[v,y]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),h=useRef([]),c=useRef(false),f=useCallback(n=>{let p={...n,protocol:le};c.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(p,new URL(t).origin):h.current.push(p);},[t]);useEffect(()=>{if(a)return;let n=o=>{if(!(!o.data||o.data.protocol!==le)){try{if(o.origin!==new URL(t).origin)return}catch{return}switch(o.data.type){case "bridge:ready":c.current=true,y(g=>({...g,ready:true}));for(let g of h.current)l.current?.contentWindow?.postMessage(g,o.origin);h.current=[],l.current?.contentWindow?.postMessage({protocol:le,type:"auth:check"},o.origin),l.current?.contentWindow?.postMessage({protocol:le,type:"auth:resolve-stack"},o.origin);break;case "auth:status":y(g=>({...g,known:o.data.known,identity:o.data.identity,identityCount:o.data.identityCount||0}));break;case "auth:resolved-stack":y(g=>({...g,resolvedStackId:o.data.stackId||null}));break;}}};window.addEventListener("message",n);let p=document.createElement("iframe");return p.src=t,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",n),p.parentNode&&p.parentNode.removeChild(p),l.current=null,c.current=false;}},[t,a]);let d=useCallback(n=>{f({type:"auth:connected",...n});},[f]),x=useCallback(n=>{f({type:"auth:disconnected",...n});},[f]),i=useCallback(()=>{f({type:"auth:clear"}),y({ready:v.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[f,v.ready]),u=useCallback(()=>{f({type:"auth:check"});},[f]);return {...v,reportConnected:d,reportDisconnected:x,clearAll:i,refresh:u}}async function qe(e,t,a,l){let v=e.apiVersion||"v2",y=`${e.baseUrl}/api/${v}${a}`;try{let h=await fetch(y,{method:t,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),c=await h.json();return h.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(h){return {success:false,error:{code:"NETWORK_ERROR",message:h instanceof Error?h.message:"Network error"}}}}function Ke(e){return {getNetworkStatus:()=>qe(e,"GET","/network/status"),getWeb3Challenge:(t,a)=>qe(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:t,address:a})}}function Xe(e={apiBaseUrl:""}){let{wallet:t,connectSolana:a,connectEVM:l,signMessage:v,disconnect:y}=He(),{session:h,isAuthenticated:c,refresh:f,readSession:d}=Ye(),{headers:x}=Ve(),i=Je({disabled:typeof window>"u"}),[u,n]=useState(false),[p,o]=useState(null),[g,m]=useState(false),k=e.apiBaseUrl||"",U=e.stacknetUrl||"https://stacknet.magma-rpc.com",I=e.stackId||i.resolvedStackId||"",A=Ke({baseUrl:U,stackId:I}),H=useCallback(async(C,w,S,O)=>{n(true),o(null);try{let N=w;if(!N){let V=await S();if(!V)return n(!1),!1;N=V;}let T=await A.getWeb3Challenge(C,N);if(!T.success||!T.data)return o("Failed to get challenge"),n(!1),!1;let D=await v(T.data.message,{chain:C,provider:O,address:N});if(!D)return n(!1),!1;let $={chain:C,message:T.data.message,signature:D,stackId:I};C==="solana"&&($.publicKey=N);let B=await fetch(`${k}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify($)});if(!B.ok){let V=await B.json().catch(()=>({}));return o(V.error||"Authentication failed"),n(!1),!1}return i.reportConnected({address:N,chain:C,method:O||(C==="solana"?"phantom":"metamask"),stackId:I}),d(),n(!1),!0}catch(N){return o(N.message||"Authentication failed"),n(false),false}},[k,A,v,d,i,I]),P=useCallback(async(C="phantom")=>{let w=await a(C);return w?H("solana",w,()=>a(C),C):false},[a,H]),R=useCallback(async()=>{let C=await l();return C?H("ethereum",C,l,"metamask"):false},[l,H]),j=useCallback(async C=>{n(true),o(null);try{let w=await fetch(`${k}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:C})});if(!w.ok){let S=await w.json().catch(()=>({}));return o(S.error||"Invalid code"),n(!1),!1}return d(),n(!1),!0}catch(w){return o(w.message||"OTP verification failed"),n(false),false}},[k,d]),_=useCallback(async(C,w)=>{n(true),o(null);try{let S=w||`${window.location.origin}/api/auth/oauth/callback`,O=new URLSearchParams({provider:C,redirectUri:S,stackId:I}),N=await fetch(`${k}/api/auth/oauth/start?${O}`,{credentials:"include"});if(!N.ok){let D=await N.json().catch(()=>({}));return o(D.error||"Failed to start OAuth flow"),n(!1),!1}let T=await N.json();if(T.redirect_url){let D;try{D=new URL(T.redirect_url);}catch{return o("Invalid OAuth redirect URL"),n(!1),!1}let $=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return D.protocol!=="https:"||!$.some(B=>B.test(D.hostname))?(o(`Refusing to redirect to non-OAuth host: ${D.hostname}`),n(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",T.state||""),sessionStorage.setItem("oauth_provider",C)),window.location.href=D.toString(),!0)}return o("No redirect URL returned"),n(!1),!1}catch(S){return o(S.message||"OAuth flow failed"),n(false),false}},[k,I]),z=useCallback(async(C,w,S)=>{n(true),o(null);try{if(typeof sessionStorage<"u"){let N=sessionStorage.getItem("oauth_state"),T=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!N||N!==S)return o("OAuth state mismatch \u2014 refusing to complete login"),n(!1),!1;if(T&&T!==C)return o("OAuth provider mismatch \u2014 refusing to complete login"),n(!1),!1}let O=await fetch(`${k}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({provider:C,code:w,state:S,stackId:I})});if(!O.ok){let N=await O.json().catch(()=>({}));return o(N.error||"OAuth authentication failed"),n(!1),!1}return d(),n(!1),!0}catch(O){return o(O.message||"OAuth callback failed"),n(false),false}},[k,I,d]),G=useCallback(async()=>{t.address&&t.chain&&i.reportDisconnected({address:t.address,chain:t.chain,stackId:I});try{await fetch(`${k}/api/auth/logout`,{method:"POST",headers:x,credentials:"include"});}catch{}y(),d();},[k,x,y,d,t,i,I]);return useEffect(()=>{if(!e.autoConnect||g||c||!i.ready||!i.known||!i.identity)return;m(true);let{chain:C,method:w}=i.identity;C==="solana"&&(w==="phantom"||w==="solflare")?P(w):C==="ethereum"&&R();},[e.autoConnect,g,c,i,P,R]),{session:h,isAuthenticated:c,wallet:t,loading:u,error:p,authenticateSolana:P,authenticateEVM:R,authenticateOTP:j,authenticateOAuth:_,authenticateOAuthCallback:z,logout:G,refresh:()=>f(k),stackId:I,bridge:{ready:i.ready,known:i.known,identity:i.identity,identityCount:i.identityCount,resolvedStackId:i.resolvedStackId}}}function et(e,t="https://stacknet.magma-rpc.com"){let[a,l]=useState(null),[v,y]=useState(false),[h,c]=useState(null),f=useCallback(async x=>{y(true),c(null);try{let i=await fetch(`${t}/api/v2/stacks/${x}`);if(!i.ok)return c("Stack not found"),y(!1),null;let u=await i.json(),n=u.data?.stack||u.stack||u,p={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(p),y(!1),p}catch(i){return c(i.message),y(false),null}},[t]);useEffect(()=>{e&&f(e);},[e,f]);let d=a?jt(a):[];return {config:a,loading:v,error:h,identityProviders:d,fetchConfig:f}}function jt(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 a of e.oauthProviders)a.enabled&&t.push({type:"oauth",id:a.provider,name:a.provider});return t}function ce(e,t="#"){if(!e||typeof e!="string")return t;let a=e.trim();if(a===""||a==="#")return t;if(a.startsWith("/")||a.startsWith("./")||a.startsWith("../"))return a;try{let l=new URL(a);if(l.protocol==="http:"||l.protocol==="https:")return l.toString()}catch{}return t}function ne({length:e=6,onComplete:t,disabled:a=false,error:l,className:v="",inputClassName:y=""}){let [h,c]=useState(Array(e).fill("")),f=useCallback((i,u)=>{if(u.length>1){let p=u.replace(/\D/g,"").slice(0,e).split(""),o=[...h];p.forEach((m,k)=>{i+k<e&&(o[i+k]=m);}),c(o);let g=Math.min(i+p.length,e-1);document.getElementById(`userutils-otp-${g}`)?.focus(),o.every(m=>m!=="")&&setTimeout(()=>t(o.join("")),100);return}if(!/^\d?$/.test(u))return;let n=[...h];n[i]=u,c(n),u&&i<e-1&&document.getElementById(`userutils-otp-${i+1}`)?.focus(),u&&i===e-1&&n.every(p=>p!=="")&&setTimeout(()=>t(n.join("")),100);},[h,e,t]),d=useCallback((i,u)=>{if(u.key==="Backspace"&&!h[i]&&i>0){document.getElementById(`userutils-otp-${i-1}`)?.focus();let n=[...h];n[i-1]="",c(n);}if(u.key==="Enter"){let n=h.join("");n.length===e&&t(n);}},[h,e,t]);useCallback(()=>{c(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:v,children:[jsx("div",{className:"flex gap-2 justify-center",children:h.map((i,u)=>jsx("input",{id:`userutils-otp-${u}`,type:"text",inputMode:"numeric",maxLength:e,value:i,onChange:n=>f(u,n.target.value),onKeyDown:n=>d(u,n),disabled:a,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))}),l&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}ne.displayName="OTPInput";var Ot="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function de({className:e,style:t}){return jsx("img",{src:Ot,alt:"Phantom",className:e,style:t})}function ue({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Ie({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Me({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Ae({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Le({className:e,style:t}){return jsxs("svg",{className:e,style:t,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:"#000000"}),jsx("path",{d:"M21.3611 16.7384C21.3807 18.9244 23.2792 19.6519 23.3001 19.661C23.2841 19.7124 22.9971 20.6962 22.3005 21.7115C21.6987 22.5892 21.0742 23.4636 20.0904 23.4816C19.1237 23.4994 18.8127 22.9098 17.7076 22.9098C16.6029 22.9098 16.2574 23.4636 15.3423 23.4994C14.3928 23.5352 13.6694 22.5504 13.0626 21.676C11.8226 19.8879 10.8747 16.6229 12.1471 14.4182C12.7791 13.3234 13.9087 12.6304 15.1346 12.6126C16.0668 12.5948 16.9468 13.2378 17.5167 13.2378C18.0865 13.2378 19.1555 12.4647 20.2795 12.579C20.7501 12.5986 22.0715 12.7692 22.9207 14.0122C22.852 14.0549 21.3453 14.9328 21.3611 16.7384ZM19.5432 11.392C20.0472 10.7809 20.3862 9.93 20.2939 9.08325C19.5709 9.11221 18.6961 9.56574 18.1749 10.1763C17.708 10.717 17.2995 11.582 17.4096 12.4111C18.2158 12.4736 19.0391 12.003 19.5432 11.392Z",fill:"#FFFFFF"})]})}function Ht({config:e,onSuccess:t,title:a="Log in or Sign up",showWallets:l,showOTP:v,hideHeader:y,onOTPSubmit:h,otpLabel:c="Access Code",showPreviewCode:f=false,onPreviewCodeSubmit:d,previewCodeLabel:x="Preview Code",oauthInline:i,oauthFirst:u,className:n=""}){let p=Xe(e),{isAuthenticated:o,wallet:g,loading:m,error:k,authenticateSolana:U,authenticateEVM:I,authenticateOTP:A,authenticateOAuth:H,bridge:P,stackId:R}=p,j=!e.stackId&&!R,_=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:z,identityProviders:G,loading:C}=et(R||e.stackId||null,_),[w,S]=useState(j?"stack-select":"select"),[O,N]=useState(null),[T,D]=useState(false),[$,B]=useState("idle"),[V,he]=useState(""),[je,ye]=useState(false),[ke,J]=useState("idle"),[lt,se]=useState(""),[ze,ct]=useState([]),[dt,De]=useState(e.stackId||null),[ae,ut]=useState(false),[pt,ft]=useState(false);useEffect(()=>{if(typeof window>"u")return;let r=()=>{let Q=window;ut(!!(Q.phantom?.solana?.isPhantom||Q.solana?.isPhantom));let X=Q.ethereum;ft(!!(X?.isMetaMask||X?.providers?.some(ee=>ee.isMetaMask)));};r(),window.addEventListener("ethereum#initialized",r);let F=setTimeout(r,500);return ()=>{window.removeEventListener("ethereum#initialized",r),clearTimeout(F);}},[]),useEffect(()=>{w==="stack-select"&&R&&(De(R),S("select"));},[w,R]),useEffect(()=>{if(!(!P.ready||!j)&&P.identity){let r=[];P.resolvedStackId&&r.push({stackId:P.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(r.map(async F=>{try{let Q=await fetch(`${_}/api/v2/stacks/${F.stackId}`);if(Q.ok){let X=await Q.json(),ee=X.data?.stack||X;F.name=ee.displayName||ee.name,F.logoUrl=ee.logoUrl;}}catch{}return F})).then(ct);}},[P.ready,P.identity,P.resolvedStackId,j,_]),useEffect(()=>{o&&w==="success"&&t?.();},[o,w,t]);let Oe=l||(G.length>0?G.filter(r=>r.type==="wallet").map(r=>r.id):["phantom","metamask"]),Ee=v!==void 0?v:G.length>0?G.some(r=>r.type==="otp"):true,K=G.filter(r=>r.type==="oauth"),we=new Set(u||[]),Re=K.filter(r=>we.has(r.id)),be=i?K.filter(r=>!we.has(r.id)):K,We=async r=>{N(r),S("connecting"),await H(r)||S("error");},gt=async()=>{N("phantom"),S("connecting");let r=await U("phantom");S(r?"success":"error");},mt=async()=>{N("metamask"),S("connecting");let r=await I();S(r?"success":"error");},ht=async r=>{B("verifying"),he(""),await(h||A)(r)?(B("success"),S("success")):(B("error"),he("Invalid or expired code"),setTimeout(()=>B("idle"),2e3));},yt=async r=>{if(!/^\d{6}$/.test(r))return false;try{return (await fetch("/api/auth/preview-code",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:r})})).ok?(typeof window<"u"&&window.localStorage&&window.localStorage.setItem("stacknet-api-key",`pc_${r}`),!0):!1}catch{return false}},kt=async r=>{J("verifying"),se(""),await(d||yt)(r)?(J("success"),S("success"),t?.()):(J("error"),se("Invalid or expired preview code"),setTimeout(()=>J("idle"),2e3));},Be=()=>{S(j&&!dt?"stack-select":"select"),N(null),D(false),B("idle"),he(""),ye(false),J("idle"),se("");};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&&w!=="stack-select"&&jsx("img",{src:ce(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"})]}),w==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:ze.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),ze.map(r=>jsxs("button",{onClick:()=>{De(r.stackId),S("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:[r.logoUrl?jsx("img",{src:ce(r.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:r.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:r.name||r.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:r.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},r.stackId)),P.ready&&!P.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."})]}),w==="select"&&C&&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%"}})}),k&&w==="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:k}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Be,children:"Try Again"})]}),w==="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..."})]}),w==="connecting"&&m&&jsxs("div",{style:{border:"1px solid #27272a",background:"#25252f",padding:24,textAlign:"center"},children:[jsxs("div",{style:{width:40,height:40,margin:"0 auto 12px"},children:[O==="phantom"&&jsx(de,{style:W}),O==="metamask"&&jsx(ue,{style:W})]}),jsx("p",{style:{fontWeight:500,fontSize:14,color:"#fff"},children:g.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{style:{marginTop:4,fontSize:12,color:"#71717a"},children:"Please confirm in your wallet"}),jsx("button",{style:{marginTop:16,fontSize:14,color:"#71717a",background:"none",border:"none",cursor:"pointer"},onClick:Be,children:"Cancel"})]}),w==="select"&&!m&&!C&&jsxs(Fragment,{children:[Re.map(r=>jsxs("button",{onClick:()=>We(r.id),style:q,children:[jsx(rt,{provider:r.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:st(r.id,r.name)})]},r.id)),Oe.includes("phantom")&&jsxs("button",{onClick:gt,disabled:!ae,style:{...q,opacity:ae?1:.5,cursor:ae?"pointer":"not-allowed"},children:[jsx(de,{style:{...W,borderRadius:8}}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"Phantom"}),!ae&&jsx("span",{style:{fontSize:12,color:"#71717a"},children:"Not installed"})]}),Oe.includes("metamask")&&pt&&jsxs("button",{onClick:mt,style:q,children:[jsx(ue,{style:W}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"MetaMask"})]}),Ee&&!T&&jsxs("button",{onClick:()=>D(true),style:q,children:[jsx("div",{style:{...W,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",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("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:c})]}),f&&!je&&jsxs("button",{onClick:()=>ye(true),style:q,children:[jsx("div",{style:{...W,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",children:jsx("path",{d:"M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm80-80h400v-40H280v40Zm0-120h400v-240H280v240Z"})})}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:x})]}),f&&je&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit preview code"}),jsx(ne,{onComplete:kt,disabled:ke==="verifying",error:lt}),ke==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),ke==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),jsx("button",{onClick:()=>{ye(false),J("idle"),se("");},style:{display:"block",marginTop:16,marginLeft:"auto",marginRight:"auto",fontSize:13,color:"#71717a",background:"none",border:"none",cursor:"pointer"},children:"Cancel"})]}),Ee&&T&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit access code"}),jsx(ne,{onComplete:ht,disabled:$==="verifying",error:V}),$==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),$==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),z?.webPageUrl&&$==="idle"&&(ce(z.webPageUrl)==="#"?null:jsx(Fragment,{}))]}),(i?be:K).length>0&&(!i||be.length>0)&&jsxs(Fragment,{children:[!i&&Re.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 0"},children:[jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}}),jsx("span",{style:{fontSize:12,color:"#52525b"},children:"or continue with"}),jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}})]}),(i?be:K.filter(r=>!we.has(r.id))).map(r=>jsxs("button",{onClick:()=>We(r.id),style:q,children:[jsx(rt,{provider:r.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:st(r.id,r.name)})]},r.id))]})]})]})}var W={width:40,height:40,flexShrink:0},q={display:"flex",width:"100%",alignItems:"center",gap:12,borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:16,cursor:"pointer",transition:"background 0.15s"};function rt({provider:e}){switch(e){case "google":return jsx(Ie,{style:{...W,borderRadius:8}});case "discord":return jsx(Me,{style:{...W,borderRadius:8}});case "twitter":return jsx(Ae,{style:{...W,borderRadius:8}});case "apple":return jsx(Le,{style:{...W,borderRadius:8}});default:return jsx("div",{style:{...W,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e",fontSize:14,color:"#a1a1aa",fontFamily:"monospace"},children:e[0]?.toUpperCase()})}}function st(e,t){return {google:"Google",discord:"Discord",twitter:"Twitter",apple:"Apple"}[e]||t||e}function Qt(){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 at(e,t){let[a,l]=useState(null),[v,y]=useState(true),[h,c]=useState(false),[f,d]=useState(null),x=t?.apiBaseUrl??"",i=t?.scope===void 0||t?.scope==="global"?"global":`stack:${t.scope.stackId}`,u=useCallback(o=>{let g=encodeURIComponent(o);if(i==="global")return `${x}/api/user/profile/${g}`;let m=i.slice(6);return `${x}/api/v2/stacks/${encodeURIComponent(m)}/members/${g}/profile`},[x,i]),n=useCallback(async()=>{if(!e){l(null),y(false);return}y(true),d(null);try{let o=await fetch(u(e));if(o.ok){let g=await o.json(),m=g.profile||g.data?.profile||g;l({mid:m.mid||e,username:m.username||"",avatarUrl:m.avatar_url||m.avatarUrl,bio:m.bio,paymentAddress:m.payment_address||m.paymentAddress,createdAt:m.created_at||m.createdAt,updatedAt:m.updated_at||m.updatedAt});}else if(o.status===404)l({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(()=>{n();},[n]);let p=useCallback(async o=>{if(!e)return false;c(true),d(null);try{let g=Qt(),m={};o.username!==void 0&&(m.username=o.username),o.avatarUrl!==void 0&&(m.avatar_url=o.avatarUrl),o.bio!==void 0&&(m.bio=o.bio),o.paymentAddress!==void 0&&(m.payment_address=o.paymentAddress);let k=await fetch(u(e),{method:"PUT",headers:{"Content-Type":"application/json",...g?{"x-csrf-token":g}:{}},credentials:"same-origin",body:JSON.stringify(m)});if(!k.ok){let A=await k.json().catch(()=>({}));throw new Error(A.error||A.message||`Update failed: ${k.status}`)}let U=await k.json(),I=U.profile||U.data?.profile||U;return l(A=>({mid:A?.mid||e,username:o.username??A?.username??"",avatarUrl:o.avatarUrl??A?.avatarUrl,bio:o.bio??A?.bio,paymentAddress:o.paymentAddress??I.payment_address??I.paymentAddress??A?.paymentAddress,createdAt:A?.createdAt,updatedAt:I.updated_at||I.updatedAt||Date.now()})),!0}catch(g){return d(g instanceof Error?g.message:"Update failed"),false}finally{c(false);}},[e,u]);return {profile:a,loading:v,saving:h,error:f,updateProfile:p,refresh:n}}function Yt({mid:e,apiBaseUrl:t="",scope:a,onSave:l,className:v}){let{profile:y,loading:h,saving:c,error:f,updateProfile:d}=at(e,{apiBaseUrl:t,scope:a}),[x,i]=useState(null),[u,n]=useState(null),[p,o]=useState(null),g=useRef(null),[m,k]=useState(false),U=x??y?.username??"",I=u??y?.bio??"",A=p??y?.avatarUrl,H=useCallback(j=>{let _=j.target.files?.[0];if(!_)return;let z=new FileReader;z.onload=()=>{o(z.result),k(true);},z.readAsDataURL(_);},[]),P=async()=>{await d({username:U||void 0,avatarUrl:p??y?.avatarUrl,bio:I||void 0})&&(k(false),l?.());};if(h)return jsxs("div",{className:v,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 R=a==="global"||!a?"Global profile":`Stack profile (${a.stackId})`;return jsxs("div",{className:v,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:R}),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:()=>g.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:A?jsx("img",{src:A,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:U,onChange:j=>{i(j.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:g,type:"file",accept:"image/*",onChange:H,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:I,onChange:j=>{n(j.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}),m&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:P,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),n(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 Vt({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 Jt({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 Kt({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{Le as AppleIcon,Ht as ConnectWidget,Me as DiscordIcon,Jt as EthereumIcon,Ie as GoogleIcon,ue as MetaMaskIcon,ne as OTPInput,de as PhantomIcon,Yt as ProfileSettings,Vt as SolanaIcon,Kt as TelegramIcon,Ae as TwitterIcon,Ct as UserUtilsProvider,vt as useUserUtilsContext};
1
+ import {createContext,useContext,useState,useCallback,useEffect,useMemo,useRef}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var Ge=createContext(null);function Pt(){let e=useContext(Ge);if(!e)throw new Error("useUserUtilsContext must be used within <UserUtilsProvider>");return e}function Ut({config:e,callbacks:t,children:r}){return jsx(Ge.Provider,{value:{config:e,callbacks:t},children:r})}function Ve(){let[e,t]=useState({connected:false,address:null,chain:null,provider:null}),[r,l]=useState(null),k=useCallback(async(d="phantom")=>{l(null);try{let u=typeof window<"u"?window:null,x=d==="phantom"?u?.phantom?.solana||u?.solana:u?.solflare;if(!x)return l(`${d} wallet not found`),null;let p=(await x.connect()).publicKey.toString();return t({connected:!0,address:p,chain:"solana",provider:d}),p}catch(u){return l(u.message||"Failed to connect wallet"),null}},[]),y=useCallback(async()=>{l(null);try{let u=(typeof window<"u"?window:null)?.ethereum;if(!u)return l("MetaMask not found"),null;let x=u;u.providers?.length&&(x=u.providers.find(n=>n.isMetaMask)||u);let p=(await x.request({method:"eth_requestAccounts"}))[0];return p?(t({connected:!0,address:p,chain:"ethereum",provider:"metamask"}),p):(l("No account selected"),null)}catch(d){return l(d.message||"Failed to connect wallet"),null}},[]),m=useCallback(async(d,u)=>{l(null);let x=u?.chain||e.chain,i=u?.provider||e.provider,p=u?.address||e.address;try{if(x==="solana"){let n=typeof window<"u"?window:null,f=i==="solflare"?n?.solflare:n?.phantom?.solana||n?.solana;if(!f)throw new Error("Wallet not available");let o=new TextEncoder().encode(d),g=await f.signMessage(o,"utf8"),h=new Uint8Array(g.signature||g),w="";for(let T=0;T<h.byteLength;T++)w+=String.fromCharCode(h[T]);return btoa(w)}if(x==="ethereum"){let f=(typeof window<"u"?window:null)?.ethereum;if(f?.providers?.length&&(f=f.providers.find(g=>g.isMetaMask)||f),!f)throw new Error("MetaMask not available");return await f.request({method:"personal_sign",params:[d,p]})}throw new Error("No wallet connected")}catch(n){return l(n.message||"Signing failed"),null}},[e]),c=useCallback(()=>{t({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:r,connectSolana:k,connectEVM:y,signMessage:m,disconnect:c}}function Je(){if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(r=>r.trim()).find(r=>r.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 Ke(e="__csrf"){if(typeof document>"u")return null;let t=document.cookie.split(";").map(r=>r.trim()).find(r=>r.startsWith(`${e}=`));return t?t.slice(e.length+1):null}function et(){let[e,t]=useState(null),[r,l]=useState(true),k=useCallback(()=>{let c=Je();c&&c.expiresAt>Date.now()?t({userId:c.userId,address:c.address,chain:c.chain,expiresAt:c.expiresAt,planId:c.planId,authMethod:c.authMethod}):t(null),l(false);},[]);useEffect(()=>{k();},[k]);let y=useCallback(async(c="")=>{try{let d=await fetch(`${c}/api/auth/session`);if(d.ok){let u=await d.json();if(u.session)return t(u.session),u.session}return t(null),null}catch{return null}},[]),m=!!e&&e.expiresAt>Date.now();return {session:e,loading:r,isAuthenticated:m,refresh:y,readSession:k}}function tt(e="__csrf",t="x-csrf-token"){let[r,l]=useState(null);useEffect(()=>{l(Ke(e));},[e]);let k=r?{[t]:r}:{};return {token:r,headers:k}}var Rt="https://stacknet.magma-rpc.com/auth/bridge",ue="stacknet-auth-bridge";function nt(e){let t=e?.bridgeUrl||Rt,r=e?.disabled||false,l=useRef(null),[k,y]=useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),m=useRef([]),c=useRef(false),d=useCallback(n=>{let f={...n,protocol:ue};c.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(f,new URL(t).origin):m.current.push(f);},[t]);useEffect(()=>{if(r)return;let n=o=>{if(!(!o.data||o.data.protocol!==ue)){try{if(o.origin!==new URL(t).origin)return}catch{return}switch(o.data.type){case "bridge:ready":c.current=true,y(g=>({...g,ready:true}));for(let g of m.current)l.current?.contentWindow?.postMessage(g,o.origin);m.current=[],l.current?.contentWindow?.postMessage({protocol:ue,type:"auth:check"},o.origin),l.current?.contentWindow?.postMessage({protocol:ue,type:"auth:resolve-stack"},o.origin);break;case "auth:status":y(g=>({...g,known:o.data.known,identity:o.data.identity,identityCount:o.data.identityCount||0}));break;case "auth:resolved-stack":y(g=>({...g,resolvedStackId:o.data.stackId||null}));break;}}};window.addEventListener("message",n);let f=document.createElement("iframe");return f.src=t,f.style.display="none",f.setAttribute("aria-hidden","true"),f.setAttribute("tabindex","-1"),f.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(f),l.current=f,()=>{window.removeEventListener("message",n),f.parentNode&&f.parentNode.removeChild(f),l.current=null,c.current=false;}},[t,r]);let u=useCallback(n=>{d({type:"auth:connected",...n});},[d]),x=useCallback(n=>{d({type:"auth:disconnected",...n});},[d]),i=useCallback(()=>{d({type:"auth:clear"}),y({ready:k.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[d,k.ready]),p=useCallback(()=>{d({type:"auth:check"});},[d]);return {...k,reportConnected:u,reportDisconnected:x,clearAll:i,refresh:p}}async function ot(e,t,r,l){let k=e.apiVersion||"v2",y=`${e.baseUrl}/api/${k}${r}`;try{let m=await fetch(y,{method:t,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),c=await m.json();return m.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(m){return {success:false,error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}function rt(e){return {getNetworkStatus:()=>ot(e,"GET","/network/status"),getWeb3Challenge:(t,r)=>ot(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:t,address:r})}}function st(e={apiBaseUrl:""}){let{wallet:t,connectSolana:r,connectEVM:l,signMessage:k,disconnect:y}=Ve(),{session:m,isAuthenticated:c,refresh:d,readSession:u}=et(),{headers:x}=tt(),i=nt({disabled:typeof window>"u"}),[p,n]=useState(false),[f,o]=useState(null),[g,h]=useState(false),w=e.apiBaseUrl||"",T=e.stacknetUrl||"https://stacknet.magma-rpc.com",M=e.stackId||i.resolvedStackId||"",A=rt({baseUrl:T,stackId:M}),_=useCallback(async(C,b,S,W)=>{n(true),o(null);try{let N=b;if(!N){let q=await S();if(!q)return n(!1),!1;N=q;}let j=await A.getWeb3Challenge(C,N);if(!j.success||!j.data)return o("Failed to get challenge"),n(!1),!1;let O=await k(j.data.message,{chain:C,provider:W,address:N});if(!O)return n(!1),!1;let H={chain:C,message:j.data.message,signature:O,stackId:M};C==="solana"&&(H.publicKey=N);let B=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(H)});if(!B.ok){let q=await B.json().catch(()=>({}));return o(q.error||"Authentication failed"),n(!1),!1}return i.reportConnected({address:N,chain:C,method:W||(C==="solana"?"phantom":"metamask"),stackId:M}),u(),n(!1),!0}catch(N){return o(N.message||"Authentication failed"),n(false),false}},[w,A,k,u,i,M]),U=useCallback(async(C="phantom")=>{let b=await r(C);return b?_("solana",b,()=>r(C),C):false},[r,_]),$=useCallback(async()=>{let C=await l();return C?_("ethereum",C,l,"metamask"):false},[l,_]),z=useCallback(async C=>{n(true),o(null);try{let b=await fetch(`${w}/api/auth/otp`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:C})});if(!b.ok){let S=await b.json().catch(()=>({}));return o(S.error||"Invalid code"),n(!1),!1}return u(),n(!1),!0}catch(b){return o(b.message||"OTP verification failed"),n(false),false}},[w,u]),Q=useCallback(async(C,b)=>{n(true),o(null);try{let S=b||`${window.location.origin}/api/auth/oauth/callback`,W=new URLSearchParams({provider:C,redirectUri:S,stackId:M}),N=await fetch(`${w}/api/auth/oauth/start?${W}`,{credentials:"include"});if(!N.ok){let O=await N.json().catch(()=>({}));return o(O.error||"Failed to start OAuth flow"),n(!1),!1}let j=await N.json();if(j.redirect_url){let O;try{O=new URL(j.redirect_url);}catch{return o("Invalid OAuth redirect URL"),n(!1),!1}let H=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return O.protocol!=="https:"||!H.some(B=>B.test(O.hostname))?(o(`Refusing to redirect to non-OAuth host: ${O.hostname}`),n(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",j.state||""),sessionStorage.setItem("oauth_provider",C)),window.location.href=O.toString(),!0)}return o("No redirect URL returned"),n(!1),!1}catch(S){return o(S.message||"OAuth flow failed"),n(false),false}},[w,M]),D=useCallback(async(C,b,S)=>{n(true),o(null);try{if(typeof sessionStorage<"u"){let N=sessionStorage.getItem("oauth_state"),j=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!N||N!==S)return o("OAuth state mismatch \u2014 refusing to complete login"),n(!1),!1;if(j&&j!==C)return o("OAuth provider mismatch \u2014 refusing to complete login"),n(!1),!1}let W=await fetch(`${w}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({provider:C,code:b,state:S,stackId:M})});if(!W.ok){let N=await W.json().catch(()=>({}));return o(N.error||"OAuth authentication failed"),n(!1),!1}return u(),n(!1),!0}catch(W){return o(W.message||"OAuth callback failed"),n(false),false}},[w,M,u]),V=useCallback(async()=>{t.address&&t.chain&&i.reportDisconnected({address:t.address,chain:t.chain,stackId:M});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:x,credentials:"include"});}catch{}y(),u();},[w,x,y,u,t,i,M]);return useEffect(()=>{if(!e.autoConnect||g||c||!i.ready||!i.known||!i.identity)return;h(true);let{chain:C,method:b}=i.identity;C==="solana"&&(b==="phantom"||b==="solflare")?U(b):C==="ethereum"&&$();},[e.autoConnect,g,c,i,U,$]),{session:m,isAuthenticated:c,wallet:t,loading:p,error:f,authenticateSolana:U,authenticateEVM:$,authenticateOTP:z,authenticateOAuth:Q,authenticateOAuthCallback:D,logout:V,refresh:()=>d(w),stackId:M,bridge:{ready:i.ready,known:i.known,identity:i.identity,identityCount:i.identityCount,resolvedStackId:i.resolvedStackId}}}function at(e,t="https://stacknet.magma-rpc.com"){let[r,l]=useState(null),[k,y]=useState(false),[m,c]=useState(null),d=useCallback(async x=>{y(true),c(null);try{let i=await fetch(`${t}/api/v2/stacks/${x}`);if(!i.ok)return c("Stack not found"),y(!1),null;let p=await i.json(),n=p.data?.stack||p.stack||p,f={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(f),y(!1),f}catch(i){return c(i.message),y(false),null}},[t]);useEffect(()=>{e&&d(e);},[e,d]);let u=r?Ft(r):[];return {config:r,loading:k,error:m,identityProviders:u,fetchConfig:d}}function Ft(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 r of e.oauthProviders)r.enabled&&t.push({type:"oauth",id:r.provider,name:r.provider});return t}function pe(e,t="#"){if(!e||typeof e!="string")return t;let r=e.trim();if(r===""||r==="#")return t;if(r.startsWith("/")||r.startsWith("./")||r.startsWith("../"))return r;try{let l=new URL(r);if(l.protocol==="http:"||l.protocol==="https:")return l.toString()}catch{}return t}function oe({length:e=6,onComplete:t,disabled:r=false,error:l,className:k="",inputClassName:y=""}){let [m,c]=useState(Array(e).fill("")),d=useCallback((i,p)=>{if(p.length>1){let f=p.replace(/\D/g,"").slice(0,e).split(""),o=[...m];f.forEach((h,w)=>{i+w<e&&(o[i+w]=h);}),c(o);let g=Math.min(i+f.length,e-1);document.getElementById(`userutils-otp-${g}`)?.focus(),o.every(h=>h!=="")&&setTimeout(()=>t(o.join("")),100);return}if(!/^\d?$/.test(p))return;let n=[...m];n[i]=p,c(n),p&&i<e-1&&document.getElementById(`userutils-otp-${i+1}`)?.focus(),p&&i===e-1&&n.every(f=>f!=="")&&setTimeout(()=>t(n.join("")),100);},[m,e,t]),u=useCallback((i,p)=>{if(p.key==="Backspace"&&!m[i]&&i>0){document.getElementById(`userutils-otp-${i-1}`)?.focus();let n=[...m];n[i-1]="",c(n);}if(p.key==="Enter"){let n=m.join("");n.length===e&&t(n);}},[m,e,t]);useCallback(()=>{c(Array(e).fill("")),document.getElementById("userutils-otp-0")?.focus();},[e]);return jsxs("div",{className:k,children:[jsx("div",{className:"flex gap-2 justify-center",children:m.map((i,p)=>jsx("input",{id:`userutils-otp-${p}`,type:"text",inputMode:"numeric",maxLength:e,value:i,onChange:n=>d(p,n.target.value),onKeyDown:n=>u(p,n),disabled:r,autoFocus:p===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}`},p))}),l&&jsx("p",{className:"text-center text-sm text-red-400 mt-2",children:l})]})}oe.displayName="OTPInput";var Qt="stacknet:rl";function Ae(){return typeof window<"u"&&typeof window.localStorage<"u"}var re=new Map;function it(e){if(!Ae())return re.get(e)??null;try{let t=window.localStorage.getItem(e);if(!t)return null;let r=JSON.parse(t);return typeof r?.count=="number"&&typeof r?.windowStart=="number"?{count:r.count,windowStart:r.windowStart}:null}catch{return null}}function Zt(e,t){if(!Ae()){re.set(e,t);return}try{window.localStorage.setItem(e,JSON.stringify(t));}catch{re.set(e,t);}}function Gt(e){if(!Ae()){re.delete(e);return}try{window.localStorage.removeItem(e);}catch{re.delete(e);}}function Yt(e,t){return `${e}:${t}`}function fe(e,t){let r=t.storagePrefix||Qt,l=Yt(r,e);return {peek:()=>{let c=Date.now(),d=it(l);if(!d||c-d.windowStart>=t.windowMs)return {allowed:true,remaining:t.maxAttempts,retryAfterSecs:0};let u=Math.max(0,t.maxAttempts-d.count);return u>0?{allowed:true,remaining:u,retryAfterSecs:0}:{allowed:false,remaining:0,retryAfterSecs:Math.max(1,Math.ceil((d.windowStart+t.windowMs-c)/1e3))}},consume:()=>{let c=Date.now(),d=it(l);return (!d||c-d.windowStart>=t.windowMs)&&(d={count:0,windowStart:c}),d.count>=t.maxAttempts?{allowed:false,remaining:0,retryAfterSecs:Math.max(1,Math.ceil((d.windowStart+t.windowMs-c)/1e3))}:(d.count+=1,Zt(l,d),{allowed:true,remaining:Math.max(0,t.maxAttempts-d.count),retryAfterSecs:0})},reset:()=>Gt(l)}}var Vt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTA4IiBoZWlnaHQ9IjEwOCIgdmlld0JveD0iMCAwIDEwOCAxMDgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDgiIGhlaWdodD0iMTA4IiByeD0iMjYiIGZpbGw9IiNBQjlGRjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik00Ni41MjY3IDY5LjkyMjlDNDIuMDA1NCA3Ni44NTA5IDM0LjQyOTIgODUuNjE4MiAyNC4zNDggODUuNjE4MkMxOS41ODI0IDg1LjYxODIgMTUgODMuNjU2MyAxNSA3NS4xMzQyQzE1IDUzLjQzMDUgNDQuNjMyNiAxOS44MzI3IDcyLjEyNjggMTkuODMyN0M4Ny43NjggMTkuODMyNyA5NCAzMC42ODQ2IDk0IDQzLjAwNzlDOTQgNTguODI1OCA4My43MzU1IDc2LjkxMjIgNzMuNTMyMSA3Ni45MTIyQzcwLjI5MzkgNzYuOTEyMiA2OC43MDUzIDc1LjEzNDIgNjguNzA1MyA3Mi4zMTRDNjguNzA1MyA3MS41NzgzIDY4LjgyNzUgNzAuNzgxMiA2OS4wNzE5IDY5LjkyMjlDNjUuNTg5MyA3NS44Njk5IDU4Ljg2ODUgODEuMzg3OCA1Mi41NzU0IDgxLjM4NzhDNDcuOTkzIDgxLjM4NzggNDUuNjcxMyA3OC41MDYzIDQ1LjY3MTMgNzQuNDU5OEM0NS42NzEzIDcyLjk4ODQgNDUuOTc2OCA3MS40NTU2IDQ2LjUyNjcgNjkuOTIyOVpNODMuNjc2MSA0Mi41Nzk0QzgzLjY3NjEgNDYuMTcwNCA4MS41NTc1IDQ3Ljk2NTggNzkuMTg3NSA0Ny45NjU4Qzc2Ljc4MTYgNDcuOTY1OCA3NC42OTg5IDQ2LjE3MDQgNzQuNjk4OSA0Mi41Nzk0Qzc0LjY5ODkgMzguOTg4NSA3Ni43ODE2IDM3LjE5MzEgNzkuMTg3NSAzNy4xOTMxQzgxLjU1NzUgMzcuMTkzMSA4My42NzYxIDM4Ljk4ODUgODMuNjc2MSA0Mi41Nzk0Wk03MC4yMTAzIDQyLjU3OTVDNzAuMjEwMyA0Ni4xNzA0IDY4LjA5MTYgNDcuOTY1OCA2NS43MjE2IDQ3Ljk2NThDNjMuMzE1NyA0Ny45NjU4IDYxLjIzMyA0Ni4xNzA0IDYxLjIzMyA0Mi41Nzk1QzYxLjIzMyAzOC45ODg1IDYzLjMxNTcgMzcuMTkzMSA2NS43MjE2IDM3LjE5MzFDNjguMDkxNiAzNy4xOTMxIDcwLjIxMDMgMzguOTg4NSA3MC4yMTAzIDQyLjU3OTVaIiBmaWxsPSIjRkZGREY4Ii8+Cjwvc3ZnPgo=";function ge({className:e,style:t}){return jsx("img",{src:Vt,alt:"Phantom",className:e,style:t})}function me({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Le({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Pe({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Ue({className:e,style:t}){return jsxs("svg",{className:e,style:t,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 Te({className:e,style:t}){return jsxs("svg",{className:e,style:t,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:"#000000"}),jsx("path",{d:"M21.3611 16.7384C21.3807 18.9244 23.2792 19.6519 23.3001 19.661C23.2841 19.7124 22.9971 20.6962 22.3005 21.7115C21.6987 22.5892 21.0742 23.4636 20.0904 23.4816C19.1237 23.4994 18.8127 22.9098 17.7076 22.9098C16.6029 22.9098 16.2574 23.4636 15.3423 23.4994C14.3928 23.5352 13.6694 22.5504 13.0626 21.676C11.8226 19.8879 10.8747 16.6229 12.1471 14.4182C12.7791 13.3234 13.9087 12.6304 15.1346 12.6126C16.0668 12.5948 16.9468 13.2378 17.5167 13.2378C18.0865 13.2378 19.1555 12.4647 20.2795 12.579C20.7501 12.5986 22.0715 12.7692 22.9207 14.0122C22.852 14.0549 21.3453 14.9328 21.3611 16.7384ZM19.5432 11.392C20.0472 10.7809 20.3862 9.93 20.2939 9.08325C19.5709 9.11221 18.6961 9.56574 18.1749 10.1763C17.708 10.717 17.2995 11.582 17.4096 12.4111C18.2158 12.4736 19.0391 12.003 19.5432 11.392Z",fill:"#FFFFFF"})]})}function nn({config:e,onSuccess:t,title:r="Log in or Sign up",showWallets:l,showOTP:k,hideHeader:y,onOTPSubmit:m,otpLabel:c="Access Code",showPreviewCode:d=false,onPreviewCodeSubmit:u,previewCodeLabel:x="Preview Code",oauthInline:i,oauthFirst:p,className:n=""}){let f=st(e),{isAuthenticated:o,wallet:g,loading:h,error:w,authenticateSolana:T,authenticateEVM:M,authenticateOTP:A,authenticateOAuth:_,bridge:U,stackId:$}=f,z=!e.stackId&&!$,Q=e.stacknetUrl||"https://stacknet.magma-rpc.com",{config:D,identityProviders:V,loading:C}=at($||e.stackId||null,Q),[b,S]=useState(z?"stack-select":"select"),[W,N]=useState(null),[j,O]=useState(false),[H,B]=useState("idle"),[q,le]=useState(""),[Oe,ke]=useState(false),[be,Z]=useState("idle"),[ht,ee]=useState(""),[Ee,yt]=useState([]),[wt,Re]=useState(e.stackId||null),[kt,We]=useState(false);useEffect(()=>{We(false);},[D?.logoUrl]);let Be=useMemo(()=>fe("otp",{maxAttempts:3,windowMs:5*6e4}),[]),$e=useMemo(()=>fe("preview-code",{maxAttempts:3,windowMs:6e4}),[]),[ce,bt]=useState(false),[vt,Ct]=useState(false);useEffect(()=>{if(typeof window>"u")return;let s=()=>{let G=window;bt(!!(G.phantom?.solana?.isPhantom||G.solana?.isPhantom));let J=G.ethereum;Ct(!!(J?.isMetaMask||J?.providers?.some(E=>E.isMetaMask)));};s(),window.addEventListener("ethereum#initialized",s);let L=setTimeout(s,500);return ()=>{window.removeEventListener("ethereum#initialized",s),clearTimeout(L);}},[]),useEffect(()=>{b==="stack-select"&&$&&(Re($),S("select"));},[b,$]),useEffect(()=>{if(!(!U.ready||!z)&&U.identity){let s=[];U.resolvedStackId&&s.push({stackId:U.resolvedStackId,domain:typeof window<"u"?window.location.origin:""}),Promise.all(s.map(async L=>{try{let G=await fetch(`${Q}/api/v2/stacks/${L.stackId}`);if(G.ok){let J=await G.json(),E=J.data?.stack||J;L.name=E.displayName||E.name,L.logoUrl=E.logoUrl;}}catch{}return L})).then(yt);}},[U.ready,U.identity,U.resolvedStackId,z,Q]),useEffect(()=>{o&&b==="success"&&t?.();},[o,b,t]);let Fe=l||(V.length>0?V.filter(s=>s.type==="wallet").map(s=>s.id):["phantom","metamask"]),He=k!==void 0?k:V.length>0?V.some(s=>s.type==="otp"):true,te=V.filter(s=>s.type==="oauth"),ve=new Set(p||[]),_e=te.filter(s=>ve.has(s.id)),Ce=i?te.filter(s=>!ve.has(s.id)):te,Qe=async s=>{N(s),S("connecting"),await _(s)||S("error");},xt=async()=>{N("phantom"),S("connecting");let s=await T("phantom");S(s?"success":"error");},St=async()=>{N("metamask"),S("connecting");let s=await M();S(s?"success":"error");},Nt=async s=>{let L=Be.consume();if(!L.allowed){B("error"),le(`Too many attempts. Try again in ${L.retryAfterSecs}s.`),setTimeout(()=>B("idle"),3e3);return}if(B("verifying"),le(""),await(m||A)(s))Be.reset(),B("success"),S("success");else {B("error");let E=L.remaining;le(E>0?`Invalid or expired code. ${E} attempt${E===1?"":"s"} left.`:"Invalid or expired code."),setTimeout(()=>B("idle"),2e3);}},Mt=async s=>{if(!/^\d{6}$/.test(s))return false;try{return (await fetch("/api/auth/preview-code",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({code:s})})).ok?(typeof window<"u"&&window.localStorage&&window.localStorage.setItem("stacknet-api-key",`pc_${s}`),!0):!1}catch{return false}},It=async s=>{let L=$e.consume();if(!L.allowed){Z("error"),ee(`Too many attempts. Try again in ${L.retryAfterSecs}s.`),setTimeout(()=>Z("idle"),3e3);return}if(Z("verifying"),ee(""),await(u||Mt)(s))$e.reset(),Z("success"),S("success"),t?.();else {Z("error");let E=L.remaining;ee(E>0?`Invalid or expired preview code. ${E} attempt${E===1?"":"s"} left.`:"Invalid or expired preview code."),setTimeout(()=>Z("idle"),2e3);}},Ze=()=>{S(z&&!wt?"stack-select":"select"),N(null),O(false),B("idle"),le(""),ke(false),Z("idle"),ee("");};return jsxs("div",{className:`w-full max-w-md space-y-3 ${n}`,children:[!y&&jsxs("div",{className:"mb-6 text-center",children:[D?.logoUrl&&b!=="stack-select"&&!kt&&jsx("img",{src:pe(D.logoUrl),alt:D.displayName||"",className:"h-16 w-16 mx-auto mb-4 rounded-xl",onError:()=>We(true)}),D?.displayName&&jsx("p",{className:"text-sm text-zinc-400 mb-2 capitalize",children:D.displayName}),jsx("h1",{className:"font-semibold text-2xl text-white",children:"Log in or Sign up"})]}),b==="stack-select"&&jsxs("div",{className:"space-y-3",children:[jsx("p",{className:"text-center text-sm text-zinc-400 mb-4",children:Ee.length>0?"Select a network to continue":"No previous connections found. Enter a Stack ID to continue."}),Ee.map(s=>jsxs("button",{onClick:()=>{Re(s.stackId),S("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:[s.logoUrl?jsx("img",{src:pe(s.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:s.name?.[0]?.toUpperCase()||"S"}),jsxs("div",{className:"flex-1 text-left",children:[jsx("span",{className:"font-medium text-white",children:s.name||s.stackId}),jsx("p",{className:"text-xs text-zinc-500",children:s.domain})]}),jsx("span",{className:"text-xs text-zinc-600",children:"Previously connected"})]},s.stackId)),U.ready&&!U.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."})]}),b==="select"&&C&&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%"}})}),w&&b==="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:w}),jsx("button",{className:"mt-3 w-full text-sm text-zinc-400 hover:text-white",onClick:Ze,children:"Try Again"})]}),b==="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..."})]}),b==="connecting"&&h&&jsxs("div",{style:{border:"1px solid #27272a",background:"#25252f",padding:24,textAlign:"center"},children:[jsxs("div",{style:{width:40,height:40,margin:"0 auto 12px"},children:[W==="phantom"&&jsx(ge,{style:F}),W==="metamask"&&jsx(me,{style:F})]}),jsx("p",{style:{fontWeight:500,fontSize:14,color:"#fff"},children:g.connected?"Signing message...":"Connecting wallet..."}),jsx("p",{style:{marginTop:4,fontSize:12,color:"#71717a"},children:"Please confirm in your wallet"}),jsx("button",{style:{marginTop:16,fontSize:14,color:"#71717a",background:"none",border:"none",cursor:"pointer"},onClick:Ze,children:"Cancel"})]}),b==="select"&&!h&&!C&&jsxs(Fragment,{children:[_e.map(s=>jsxs("button",{onClick:()=>Qe(s.id),style:X,children:[jsx(pt,{provider:s.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:ft(s.id,s.name)})]},s.id)),Fe.includes("phantom")&&jsxs("button",{onClick:xt,disabled:!ce,style:{...X,opacity:ce?1:.5,cursor:ce?"pointer":"not-allowed"},children:[jsx(ge,{style:{...F,borderRadius:8}}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"Phantom"}),!ce&&jsx("span",{style:{fontSize:12,color:"#71717a"},children:"Not installed"})]}),Fe.includes("metamask")&&vt&&jsxs("button",{onClick:St,style:X,children:[jsx(me,{style:F}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:"MetaMask"})]}),He&&!j&&jsxs("button",{onClick:()=>O(true),style:X,children:[jsx("div",{style:{...F,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",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("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:c})]}),d&&!Oe&&jsxs("button",{onClick:()=>ke(true),style:X,children:[jsx("div",{style:{...F,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e"},children:jsx("svg",{xmlns:"http://www.w3.org/2000/svg",height:"20px",viewBox:"0 -960 960 960",width:"20px",fill:"#a1a1aa",children:jsx("path",{d:"M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h560q33 0 56.5 23.5T840-760v560q0 33-23.5 56.5T760-120H200Zm0-80h560v-560H200v560Zm80-80h400v-40H280v40Zm0-120h400v-240H280v240Z"})})}),jsx("span",{style:{flex:1,textAlign:"left",fontWeight:500,color:"#fff"},children:x})]}),d&&Oe&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit preview code"}),jsx(oe,{onComplete:It,disabled:be==="verifying",error:ht}),be==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),be==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),jsx("button",{onClick:()=>{ke(false),Z("idle"),ee("");},style:{display:"block",marginTop:16,marginLeft:"auto",marginRight:"auto",fontSize:13,color:"#71717a",background:"none",border:"none",cursor:"pointer"},children:"Cancel"})]}),He&&j&&jsxs("div",{style:{borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:24},children:[jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginBottom:16},children:"Enter your 6-digit access code"}),jsx(oe,{onComplete:Nt,disabled:H==="verifying",error:q}),H==="verifying"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#a1a1aa",marginTop:16},children:"Verifying..."}),H==="success"&&jsx("p",{style:{textAlign:"center",fontSize:14,color:"#4ade80",marginTop:16},children:"Verified!"}),D?.webPageUrl&&H==="idle"&&(pe(D.webPageUrl)==="#"?null:jsx(Fragment,{}))]}),(i?Ce:te).length>0&&(!i||Ce.length>0)&&jsxs(Fragment,{children:[!i&&_e.length===0&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 0"},children:[jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}}),jsx("span",{style:{fontSize:12,color:"#52525b"},children:"or continue with"}),jsx("div",{style:{flex:1,borderTop:"1px solid #27272a"}})]}),(i?Ce:te.filter(s=>!ve.has(s.id))).map(s=>jsxs("button",{onClick:()=>Qe(s.id),style:X,children:[jsx(pt,{provider:s.id}),jsx("span",{style:{fontWeight:500,color:"#fff"},children:ft(s.id,s.name)})]},s.id))]})]})]})}var F={width:50,height:50,flexShrink:0},X={display:"flex",width:"100%",alignItems:"center",gap:12,borderRadius:12,border:"1px solid #27272a",background:"#25252f",padding:16,cursor:"pointer",transition:"background 0.15s"};function pt({provider:e}){switch(e){case "google":return jsx(Le,{style:{...F,borderRadius:8}});case "discord":return jsx(Pe,{style:{...F,borderRadius:8}});case "twitter":return jsx(Ue,{style:{...F,borderRadius:8}});case "apple":return jsx(Te,{style:{...F,borderRadius:8}});default:return jsx("div",{style:{...F,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:8,border:"1px solid #3f3f46",background:"#2a2a3e",fontSize:14,color:"#a1a1aa",fontFamily:"monospace"},children:e[0]?.toUpperCase()})}}function ft(e,t){return {google:"Google",discord:"Discord",twitter:"Twitter",apple:"Apple"}[e]||t||e}function rn(){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 gt(e,t){let[r,l]=useState(null),[k,y]=useState(true),[m,c]=useState(false),[d,u]=useState(null),x=t?.apiBaseUrl??"",i=t?.scope===void 0||t?.scope==="global"?"global":`stack:${t.scope.stackId}`,p=useCallback(o=>{let g=encodeURIComponent(o);if(i==="global")return `${x}/api/user/profile/${g}`;let h=i.slice(6);return `${x}/api/v2/stacks/${encodeURIComponent(h)}/members/${g}/profile`},[x,i]),n=useCallback(async()=>{if(!e){l(null),y(false);return}y(true),u(null);try{let o=await fetch(p(e));if(o.ok){let g=await o.json(),h=g.profile||g.data?.profile||g;l({mid:h.mid||e,username:h.username||"",avatarUrl:h.avatar_url||h.avatarUrl,bio:h.bio,paymentAddress:h.payment_address||h.paymentAddress,createdAt:h.created_at||h.createdAt,updatedAt:h.updated_at||h.updatedAt});}else if(o.status===404)l({mid:e,username:""});else throw new Error(`${o.status}`)}catch(o){u(o instanceof Error?o.message:"Failed to load profile");}finally{y(false);}},[e,p]);useEffect(()=>{n();},[n]);let f=useCallback(async o=>{if(!e)return false;c(true),u(null);try{let g=rn(),h={};o.username!==void 0&&(h.username=o.username),o.avatarUrl!==void 0&&(h.avatar_url=o.avatarUrl),o.bio!==void 0&&(h.bio=o.bio),o.paymentAddress!==void 0&&(h.payment_address=o.paymentAddress);let w=await fetch(p(e),{method:"PUT",headers:{"Content-Type":"application/json",...g?{"x-csrf-token":g}:{}},credentials:"same-origin",body:JSON.stringify(h)});if(!w.ok){let A=await w.json().catch(()=>({}));throw new Error(A.error||A.message||`Update failed: ${w.status}`)}let T=await w.json(),M=T.profile||T.data?.profile||T;return l(A=>({mid:A?.mid||e,username:o.username??A?.username??"",avatarUrl:o.avatarUrl??A?.avatarUrl,bio:o.bio??A?.bio,paymentAddress:o.paymentAddress??M.payment_address??M.paymentAddress??A?.paymentAddress,createdAt:A?.createdAt,updatedAt:M.updated_at||M.updatedAt||Date.now()})),!0}catch(g){return u(g instanceof Error?g.message:"Update failed"),false}finally{c(false);}},[e,p]);return {profile:r,loading:k,saving:m,error:d,updateProfile:f,refresh:n}}function ln({mid:e,apiBaseUrl:t="",scope:r,onSave:l,className:k}){let{profile:y,loading:m,saving:c,error:d,updateProfile:u}=gt(e,{apiBaseUrl:t,scope:r}),[x,i]=useState(null),[p,n]=useState(null),[f,o]=useState(null),g=useRef(null),[h,w]=useState(false),T=x??y?.username??"",M=p??y?.bio??"",A=f??y?.avatarUrl,_=useCallback(z=>{let Q=z.target.files?.[0];if(!Q)return;let D=new FileReader;D.onload=()=>{o(D.result),w(true);},D.readAsDataURL(Q);},[]),U=async()=>{await u({username:T||void 0,avatarUrl:f??y?.avatarUrl,bio:M||void 0})&&(w(false),l?.());};if(m)return jsxs("div",{className:k,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 $=r==="global"||!r?"Global profile":`Stack profile (${r.stackId})`;return jsxs("div",{className:k,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:$}),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:()=>g.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:A?jsx("img",{src:A,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:T,onChange:z=>{i(z.target.value),w(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:g,type:"file",accept:"image/*",onChange:_,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:z=>{n(z.target.value),w(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"}})]})]}),d&&jsx("p",{style:{fontSize:13,color:"var(--x-color-red-500, #BF4D43)"},children:d}),h&&jsxs("div",{style:{display:"flex",gap:"0.5rem"},children:[jsx("button",{onClick:U,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),n(null),o(null),w(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 cn({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 dn({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 pn({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{Te as AppleIcon,nn as ConnectWidget,Pe as DiscordIcon,dn as EthereumIcon,Le as GoogleIcon,me as MetaMaskIcon,oe as OTPInput,ge as PhantomIcon,ln as ProfileSettings,cn as SolanaIcon,pn as TelegramIcon,Ue as TwitterIcon,Ut as UserUtilsProvider,fe as createClientRateLimiter,Pt as useUserUtilsContext};
@@ -1,2 +1,2 @@
1
- 'use strict';var react=require('react');function ce(){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 x(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 L(){let[e,n]=react.useState(null),[i,l]=react.useState(true),d=react.useCallback(()=>{let o=ce();o&&o.expiresAt>Date.now()?n({userId:o.userId,address:o.address,chain:o.chain,expiresAt:o.expiresAt,planId:o.planId,authMethod:o.authMethod}):n(null),l(false);},[]);react.useEffect(()=>{d();},[d]);let g=react.useCallback(async(o="")=>{try{let s=await fetch(`${o}/api/auth/session`);if(s.ok){let a=await s.json();if(a.session)return n(a.session),a.session}return n(null),null}catch{return null}},[]),f=!!e&&e.expiresAt>Date.now();return {session:e,loading:i,isAuthenticated:f,refresh:g,readSession:d}}function K(e="__csrf",n="x-csrf-token"){let[i,l]=react.useState(null);react.useEffect(()=>{l(x(e));},[e]);let d=i?{[n]:i}:{};return {token:i,headers:d}}function V(){let[e,n]=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,c=s==="phantom"?a?.phantom?.solana||a?.solana:a?.solflare;if(!c)return l(`${s} wallet not found`),null;let m=(await c.connect()).publicKey.toString();return n({connected:!0,address:m,chain:"solana",provider:s}),m}catch(a){return l(a.message||"Failed to connect wallet"),null}},[]),g=react.useCallback(async()=>{l(null);try{let a=(typeof window<"u"?window:null)?.ethereum;if(!a)return l("MetaMask not found"),null;let c=a;a.providers?.length&&(c=a.providers.find(t=>t.isMetaMask)||a);let m=(await c.request({method:"eth_requestAccounts"}))[0];return m?(n({connected:!0,address:m,chain:"ethereum",provider:"metamask"}),m):(l("No account selected"),null)}catch(s){return l(s.message||"Failed to connect wallet"),null}},[]),f=react.useCallback(async(s,a)=>{l(null);let c=a?.chain||e.chain,u=a?.provider||e.provider,m=a?.address||e.address;try{if(c==="solana"){let t=typeof window<"u"?window:null,p=u==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!p)throw new Error("Wallet not available");let r=new TextEncoder().encode(s),h=await p.signMessage(r,"utf8"),y=new Uint8Array(h.signature||h),w="";for(let A=0;A<y.byteLength;A++)w+=String.fromCharCode(y[A]);return btoa(w)}if(c==="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:[s,m]})}throw new Error("No wallet connected")}catch(t){return l(t.message||"Signing failed"),null}},[e]),o=react.useCallback(()=>{n({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:i,connectSolana:d,connectEVM:g,signMessage:f,disconnect:o}}var Ae="https://stacknet.magma-rpc.com/auth/bridge",D="stacknet-auth-bridge";function q(e){let n=e?.bridgeUrl||Ae,i=e?.disabled||false,l=react.useRef(null),[d,g]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),f=react.useRef([]),o=react.useRef(false),s=react.useCallback(t=>{let p={...t,protocol:D};o.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(p,new URL(n).origin):f.current.push(p);},[n]);react.useEffect(()=>{if(i)return;let t=r=>{if(!(!r.data||r.data.protocol!==D)){try{if(r.origin!==new URL(n).origin)return}catch{return}switch(r.data.type){case "bridge:ready":o.current=true,g(h=>({...h,ready:true}));for(let h of f.current)l.current?.contentWindow?.postMessage(h,r.origin);f.current=[],l.current?.contentWindow?.postMessage({protocol:D,type:"auth:check"},r.origin),l.current?.contentWindow?.postMessage({protocol:D,type:"auth:resolve-stack"},r.origin);break;case "auth:status":g(h=>({...h,known:r.data.known,identity:r.data.identity,identityCount:r.data.identityCount||0}));break;case "auth:resolved-stack":g(h=>({...h,resolvedStackId:r.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),l.current=p,()=>{window.removeEventListener("message",t),p.parentNode&&p.parentNode.removeChild(p),l.current=null,o.current=false;}},[n,i]);let a=react.useCallback(t=>{s({type:"auth:connected",...t});},[s]),c=react.useCallback(t=>{s({type:"auth:disconnected",...t});},[s]),u=react.useCallback(()=>{s({type:"auth:clear"}),g({ready:d.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[s,d.ready]),m=react.useCallback(()=>{s({type:"auth:check"});},[s]);return {...d,reportConnected:a,reportDisconnected:c,clearAll:u,refresh:m}}async function ge(e,n,i,l){let d=e.apiVersion||"v2",g=`${e.baseUrl}/api/${d}${i}`;try{let f=await fetch(g,{method:n,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),o=await f.json();return f.ok?o.success&&o.data!==void 0?{success:!0,data:o.data}:{success:!0,data:o}:{success:!1,error:o.error||{code:"UNKNOWN_ERROR",message:"Unknown error"}}}catch(f){return {success:false,error:{code:"NETWORK_ERROR",message:f instanceof Error?f.message:"Network error"}}}}function pe(e){return {getNetworkStatus:()=>ge(e,"GET","/network/status"),getWeb3Challenge:(n,i)=>ge(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:n,address:i})}}function Te(e={apiBaseUrl:""}){let{wallet:n,connectSolana:i,connectEVM:l,signMessage:d,disconnect:g}=V(),{session:f,isAuthenticated:o,refresh:s,readSession:a}=L(),{headers:c}=K(),u=q({disabled:typeof window>"u"}),[m,t]=react.useState(false),[p,r]=react.useState(null),[h,y]=react.useState(false),w=e.apiBaseUrl||"",A=e.stacknetUrl||"https://stacknet.magma-rpc.com",C=e.stackId||u.resolvedStackId||"",S=pe({baseUrl:A,stackId:C}),E=react.useCallback(async(k,P,O,R)=>{t(true),r(null);try{let v=P;if(!v){let B=await O();if(!B)return t(!1),!1;v=B;}let T=await S.getWeb3Challenge(k,v);if(!T.success||!T.data)return r("Failed to get challenge"),t(!1),!1;let U=await d(T.data.message,{chain:k,provider:R,address:v});if(!U)return t(!1),!1;let G={chain:k,message:T.data.message,signature:U,stackId:C};k==="solana"&&(G.publicKey=v);let J=await fetch(`${w}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(G)});if(!J.ok){let B=await J.json().catch(()=>({}));return r(B.error||"Authentication failed"),t(!1),!1}return u.reportConnected({address:v,chain:k,method:R||(k==="solana"?"phantom":"metamask"),stackId:C}),a(),t(!1),!0}catch(v){return r(v.message||"Authentication failed"),t(false),false}},[w,S,d,a,u,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]),b=react.useCallback(async k=>{t(true),r(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 O=await P.json().catch(()=>({}));return r(O.error||"Invalid code"),t(!1),!1}return a(),t(!1),!0}catch(P){return r(P.message||"OTP verification failed"),t(false),false}},[w,a]),I=react.useCallback(async(k,P)=>{t(true),r(null);try{let O=P||`${window.location.origin}/api/auth/oauth/callback`,R=new URLSearchParams({provider:k,redirectUri:O,stackId:C}),v=await fetch(`${w}/api/auth/oauth/start?${R}`,{credentials:"include"});if(!v.ok){let U=await v.json().catch(()=>({}));return r(U.error||"Failed to start OAuth flow"),t(!1),!1}let T=await v.json();if(T.redirect_url){let U;try{U=new URL(T.redirect_url);}catch{return r("Invalid OAuth redirect URL"),t(!1),!1}let G=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return U.protocol!=="https:"||!G.some(J=>J.test(U.hostname))?(r(`Refusing to redirect to non-OAuth host: ${U.hostname}`),t(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",T.state||""),sessionStorage.setItem("oauth_provider",k)),window.location.href=U.toString(),!0)}return r("No redirect URL returned"),t(!1),!1}catch(O){return r(O.message||"OAuth flow failed"),t(false),false}},[w,C]),N=react.useCallback(async(k,P,O)=>{t(true),r(null);try{if(typeof sessionStorage<"u"){let v=sessionStorage.getItem("oauth_state"),T=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!v||v!==O)return r("OAuth state mismatch \u2014 refusing to complete login"),t(!1),!1;if(T&&T!==k)return r("OAuth provider mismatch \u2014 refusing to complete login"),t(!1),!1}let R=await fetch(`${w}/api/auth/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({provider:k,code:P,state:O,stackId:C})});if(!R.ok){let v=await R.json().catch(()=>({}));return r(v.error||"OAuth authentication failed"),t(!1),!1}return a(),t(!1),!0}catch(R){return r(R.message||"OAuth callback failed"),t(false),false}},[w,C,a]),j=react.useCallback(async()=>{n.address&&n.chain&&u.reportDisconnected({address:n.address,chain:n.chain,stackId:C});try{await fetch(`${w}/api/auth/logout`,{method:"POST",headers:c,credentials:"include"});}catch{}g(),a();},[w,c,g,a,n,u,C]);return react.useEffect(()=>{if(!e.autoConnect||h||o||!u.ready||!u.known||!u.identity)return;y(true);let{chain:k,method:P}=u.identity;k==="solana"&&(P==="phantom"||P==="solflare")?$(P):k==="ethereum"&&W();},[e.autoConnect,h,o,u,$,W]),{session:f,isAuthenticated:o,wallet:n,loading:m,error:p,authenticateSolana:$,authenticateEVM:W,authenticateOTP:b,authenticateOAuth:I,authenticateOAuthCallback:N,logout:j,refresh:()=>s(w),stackId:C,bridge:{ready:u.ready,known:u.known,identity:u.identity,identityCount:u.identityCount,resolvedStackId:u.resolvedStackId}}}function Y(e,n="https://stacknet.magma-rpc.com"){let[i,l]=react.useState(null),[d,g]=react.useState(false),[f,o]=react.useState(null),s=react.useCallback(async c=>{g(true),o(null);try{let u=await fetch(`${n}/api/v2/stacks/${c}`);if(!u.ok)return o("Stack not found"),g(!1),null;let m=await u.json(),t=m.data?.stack||m.stack||m,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(r=>({provider:r.provider,clientId:r.clientId,enabled:r.enabled!==!1}))};return l(p),g(!1),p}catch(u){return o(u.message),g(false),null}},[n]);react.useEffect(()=>{e&&s(e);},[e,s]);let a=i?Re(i):[];return {config:i,loading:d,error:f,identityProviders:a,fetchConfig:s}}function Re(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 _e(e=""){let[n,i]=react.useState([]),[l,d]=react.useState(true),[g,f]=react.useState(null),o=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){f(s.message);}finally{d(false);}},[e]);return react.useEffect(()=>{o();},[o]),{plans:n,loading:l,error:g,refresh:o}}function We(e=""){let[n,i]=react.useState(null),[l,d]=react.useState(true),[g,f]=react.useState(null),o=react.useCallback(async()=>{try{let c=await fetch(`${e}/api/billing/subscription`);if(c.ok){let u=await c.json();i(u.plan?u:null);}}catch(c){f(c.message);}finally{d(false);}},[e]);react.useEffect(()=>{o();},[o]);let s=react.useCallback(async c=>{let u=x(),t=await(await fetch(`${e}/api/billing/subscribe`,{method:"POST",headers:{"Content-Type":"application/json",...u?{"x-csrf-token":u}:{}},body:JSON.stringify({planId:c})})).json();return t.url||t.checkoutUrl||null},[e]),a=react.useCallback(async()=>{let c=x();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:c?{"x-csrf-token":c}:{}})).ok?(await o(),true):false},[e,o]);return {subscription:n,loading:l,error:g,refresh:o,subscribe:s,cancel:a}}function Me(e=""){let[n,i]=react.useState(null),[l,d]=react.useState(true),[g,f]=react.useState(null),o=react.useCallback(async()=>{try{let s=await fetch(`${e}/api/billing/usage`);if(s.ok){let a=await s.json();i(a);}}catch(s){f(s.message);}finally{d(false);}},[e]);return react.useEffect(()=>{o();},[o]),{usage:n,loading:l,error:g,refresh:o}}function je(e=""){let[n,i]=react.useState(false),[l,d]=react.useState(null),g=react.useCallback(async o=>{i(true),d(null);try{let s=x(),a=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"x-csrf-token":s}:{}},body:JSON.stringify({amountCents:o})}),c=await a.json();return a.ok?c.url||null:(d(c.error||"Purchase failed"),null)}catch(s){return d(s.message),null}finally{i(false);}},[e]),f=react.useCallback(async o=>{i(true),d(null);try{let s=x(),a=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...s?{"x-csrf-token":s}:{}},body:JSON.stringify({sessionId:o})}),c=await a.json();return a.ok?c:(d(c.error||"Verification failed"),null)}catch(s){return d(s.message),null}finally{i(false);}},[e]);return {purchase:g,verifySession:f,loading:n,error:l}}function Be(e="",n){let[i,l]=react.useState([]),[d,g]=react.useState(true),[f,o]=react.useState(null),s=n?.limit||50,a=n?.offset||0,c=react.useCallback(async()=>{try{let u=await fetch(`${e}/api/billing/history?limit=${s}&offset=${a}`);if(u.ok){let m=await u.json();l(m.records||m.history||(Array.isArray(m)?m:[]));}}catch(u){o(u.message);}finally{g(false);}},[e,s,a]);return react.useEffect(()=>{c();},[c]),{records:i,loading:d,error:f,refresh:c}}function De(){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 He(e,n){let[i,l]=react.useState(null),[d,g]=react.useState(true),[f,o]=react.useState(false),[s,a]=react.useState(null),c=n?.apiBaseUrl??"",u=n?.scope===void 0||n?.scope==="global"?"global":`stack:${n.scope.stackId}`,m=react.useCallback(r=>{let h=encodeURIComponent(r);if(u==="global")return `${c}/api/user/profile/${h}`;let y=u.slice(6);return `${c}/api/v2/stacks/${encodeURIComponent(y)}/members/${h}/profile`},[c,u]),t=react.useCallback(async()=>{if(!e){l(null),g(false);return}g(true),a(null);try{let r=await fetch(m(e));if(r.ok){let h=await r.json(),y=h.profile||h.data?.profile||h;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(r.status===404)l({mid:e,username:""});else throw new Error(`${r.status}`)}catch(r){a(r instanceof Error?r.message:"Failed to load profile");}finally{g(false);}},[e,m]);react.useEffect(()=>{t();},[t]);let p=react.useCallback(async r=>{if(!e)return false;o(true),a(null);try{let h=De(),y={};r.username!==void 0&&(y.username=r.username),r.avatarUrl!==void 0&&(y.avatar_url=r.avatarUrl),r.bio!==void 0&&(y.bio=r.bio),r.paymentAddress!==void 0&&(y.payment_address=r.paymentAddress);let w=await fetch(m(e),{method:"PUT",headers:{"Content-Type":"application/json",...h?{"x-csrf-token":h}:{}},credentials:"same-origin",body:JSON.stringify(y)});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:r.username??S?.username??"",avatarUrl:r.avatarUrl??S?.avatarUrl,bio:r.bio??S?.bio,paymentAddress:r.paymentAddress??C.payment_address??C.paymentAddress??S?.paymentAddress,createdAt:S?.createdAt,updatedAt:C.updated_at||C.updatedAt||Date.now()})),!0}catch(h){return a(h instanceof Error?h.message:"Update failed"),false}finally{o(false);}},[e,m]);return {profile:i,loading:d,saving:f,error:s,updateProfile:p,refresh:t}}var be="google-identity-services",Ke="https://accounts.google.com/gsi/client";function Ve({stackId:e,stacknetUrl:n="https://stacknet.magma-rpc.com",apiBaseUrl:i="",autoPrompt:l=true,cancelOnTapOutside:d=true,onSuccess:g,onError:f,disabled:o=false}){let{config:s}=Y(e,n),{isAuthenticated:a,loading:c,readSession:u}=L(),[m,t]=react.useState(false),[p,r]=react.useState(null),[h,y]=react.useState(false),w=react.useRef(false),A=react.useRef(false),S=s?.oauthProviders?.find(b=>b.provider==="google"&&b.enabled&&b.clientId)?.clientId||null;react.useEffect(()=>{if(o||!S||typeof window>"u")return;if(document.getElementById(be)){y(true);return}let b=document.createElement("script");b.id=be,b.src=Ke,b.async=true,b.defer=true,b.onload=()=>y(true),b.onerror=()=>{r("Failed to load Google sign-in"),f?.("Failed to load Google Identity Services script");},document.head.appendChild(b);},[o,S,f]);let E=react.useCallback(async b=>{t(true),r(null);try{let I=await fetch(`${i}/api/auth/google/one-tap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:b.credential,stackId:e})});if(!I.ok){let j=(await I.json().catch(()=>({}))).error||"Google sign-in failed";r(j),f?.(j),t(!1);return}u(),t(!1),g?.();}catch(I){let N=I.message||"Google sign-in failed";r(N),f?.(N),t(false);}},[i,e,u,g,f]);react.useEffect(()=>{if(o){console.debug("[GoogleOneTap] Disabled");return}if(!h){console.debug("[GoogleOneTap] Script not loaded yet, clientId:",S);return}if(!S){console.debug("[GoogleOneTap] No Google clientId from stack config");return}if(c){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}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(b=>{b.isDisplayed?.()&&console.debug("[GoogleOneTap] Prompt displayed"),b.isNotDisplayed?.()&&console.debug("[GoogleOneTap] Not displayed:",b.getNotDisplayedReason?.()),b.isSkippedMoment?.()&&console.debug("[GoogleOneTap] Skipped:",b.getSkippedReason?.()),b.isDismissedMoment?.()&&console.debug("[GoogleOneTap] Dismissed:",b.getDismissedReason?.());})));},[o,h,S,c,a,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((b,I)=>{!b||!window.google?.accounts?.id||!w.current||window.google.accounts.id.renderButton(b,{theme:I?.theme||"filled_black",size:I?.size||"large",text:I?.text||"signin_with",width:I?.width});},[]);return {available:!!S,ready:h&&!!S,loading:m,error:p,prompt:$,renderButton:W,clientId:S}}var qe="/api";function Qe(e,n){return `${(n||(typeof window<"u"?window.location.origin:"")).replace(/\/$/,"")}/?ref=${encodeURIComponent(e)}`}function Xe(e={}){let{shareBaseUrl:n,autoMint:i=true}=e,[l,d]=react.useState(null),[g,f]=react.useState(true),[o,s]=react.useState(null),a=react.useCallback(async()=>{f(true),s(null);try{let m=i?"POST":"GET",t=await fetch(`${qe}/social/join-code`,{method:m,credentials:"include"});if(!t.ok){d(null),t.status===401?s("not_authenticated"):s(`HTTP ${t.status}`);return}let p=await t.json();d(p?.code??null);}catch(m){s(m?.message||"network_error"),d(null);}finally{f(false);}},[i]);react.useEffect(()=>{a();},[a]);let c=l?Qe(l,n):null,u=react.useCallback(async()=>{if(!c)return false;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(c),!0}catch{}return false},[c]);return {code:l,shareUrl:c,loading:g,error:o,refresh:a,copyShareLink:u}}
2
- exports.useAuthBridge=q;exports.useBillingHistory=Be;exports.useCSRFToken=K;exports.useGoogleOneTap=Ve;exports.useJoinCode=Xe;exports.usePlans=_e;exports.usePrepaidCheckout=je;exports.useProfile=He;exports.useSession=L;exports.useStackAuth=Te;exports.useStackConfig=Y;exports.useSubscription=We;exports.useUsage=Me;exports.useWeb3Wallet=V;
1
+ 'use strict';var react=require('react');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 O(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 W(){let[e,n]=react.useState(null),[i,l]=react.useState(true),d=react.useCallback(()=>{let s=de();s&&s.expiresAt>Date.now()?n({userId:s.userId,address:s.address,chain:s.chain,expiresAt:s.expiresAt,planId:s.planId,authMethod:s.authMethod}):n(null),l(false);},[]);react.useEffect(()=>{d();},[d]);let p=react.useCallback(async(s="")=>{try{let o=await fetch(`${s}/api/auth/session`);if(o.ok){let a=await o.json();if(a.session)return n(a.session),a.session}return n(null),null}catch{return null}},[]),m=!!e&&e.expiresAt>Date.now();return {session:e,loading:i,isAuthenticated:m,refresh:p,readSession:d}}function z(e="__csrf",n="x-csrf-token"){let[i,l]=react.useState(null);react.useEffect(()=>{l(O(e));},[e]);let d=i?{[n]:i}:{};return {token:i,headers:d}}function q(){let[e,n]=react.useState({connected:false,address:null,chain:null,provider:null}),[i,l]=react.useState(null),d=react.useCallback(async(o="phantom")=>{l(null);try{let a=typeof window<"u"?window:null,u=o==="phantom"?a?.phantom?.solana||a?.solana:a?.solflare;if(!u)return l(`${o} wallet not found`),null;let y=(await u.connect()).publicKey.toString();return n({connected:!0,address:y,chain:"solana",provider:o}),y}catch(a){return l(a.message||"Failed to connect wallet"),null}},[]),p=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(t=>t.isMetaMask)||a);let y=(await u.request({method:"eth_requestAccounts"}))[0];return y?(n({connected:!0,address:y,chain:"ethereum",provider:"metamask"}),y):(l("No account selected"),null)}catch(o){return l(o.message||"Failed to connect wallet"),null}},[]),m=react.useCallback(async(o,a)=>{l(null);let u=a?.chain||e.chain,c=a?.provider||e.provider,y=a?.address||e.address;try{if(u==="solana"){let t=typeof window<"u"?window:null,h=c==="solflare"?t?.solflare:t?.phantom?.solana||t?.solana;if(!h)throw new Error("Wallet not available");let r=new TextEncoder().encode(o),b=await h.signMessage(r,"utf8"),f=new Uint8Array(b.signature||b),g="";for(let I=0;I<f.byteLength;I++)g+=String.fromCharCode(f[I]);return btoa(g)}if(u==="ethereum"){let h=(typeof window<"u"?window:null)?.ethereum;if(h?.providers?.length&&(h=h.providers.find(b=>b.isMetaMask)||h),!h)throw new Error("MetaMask not available");return await h.request({method:"personal_sign",params:[o,y]})}throw new Error("No wallet connected")}catch(t){return l(t.message||"Signing failed"),null}},[e]),s=react.useCallback(()=>{n({connected:false,address:null,chain:null,provider:null}),l(null);},[]);return {wallet:e,error:i,connectSolana:d,connectEVM:p,signMessage:m,disconnect:s}}var Te="https://stacknet.magma-rpc.com/auth/bridge",H="stacknet-auth-bridge";function X(e){let n=e?.bridgeUrl||Te,i=e?.disabled||false,l=react.useRef(null),[d,p]=react.useState({ready:false,known:false,identity:null,identityCount:0,resolvedStackId:null}),m=react.useRef([]),s=react.useRef(false),o=react.useCallback(t=>{let h={...t,protocol:H};s.current&&l.current?.contentWindow?l.current.contentWindow.postMessage(h,new URL(n).origin):m.current.push(h);},[n]);react.useEffect(()=>{if(i)return;let t=r=>{if(!(!r.data||r.data.protocol!==H)){try{if(r.origin!==new URL(n).origin)return}catch{return}switch(r.data.type){case "bridge:ready":s.current=true,p(b=>({...b,ready:true}));for(let b of m.current)l.current?.contentWindow?.postMessage(b,r.origin);m.current=[],l.current?.contentWindow?.postMessage({protocol:H,type:"auth:check"},r.origin),l.current?.contentWindow?.postMessage({protocol:H,type:"auth:resolve-stack"},r.origin);break;case "auth:status":p(b=>({...b,known:r.data.known,identity:r.data.identity,identityCount:r.data.identityCount||0}));break;case "auth:resolved-stack":p(b=>({...b,resolvedStackId:r.data.stackId||null}));break;}}};window.addEventListener("message",t);let h=document.createElement("iframe");return h.src=n,h.style.display="none",h.setAttribute("aria-hidden","true"),h.setAttribute("tabindex","-1"),h.setAttribute("sandbox","allow-scripts allow-same-origin"),document.body.appendChild(h),l.current=h,()=>{window.removeEventListener("message",t),h.parentNode&&h.parentNode.removeChild(h),l.current=null,s.current=false;}},[n,i]);let a=react.useCallback(t=>{o({type:"auth:connected",...t});},[o]),u=react.useCallback(t=>{o({type:"auth:disconnected",...t});},[o]),c=react.useCallback(()=>{o({type:"auth:clear"}),p({ready:d.ready,known:false,identity:null,identityCount:0,resolvedStackId:null});},[o,d.ready]),y=react.useCallback(()=>{o({type:"auth:check"});},[o]);return {...d,reportConnected:a,reportDisconnected:u,clearAll:c,refresh:y}}async function me(e,n,i,l){let d=e.apiVersion||"v2",p=`${e.baseUrl}/api/${d}${i}`;try{let m=await fetch(p,{method:n,headers:{"Content-Type":"application/json"},body:l?JSON.stringify(l):void 0}),s=await m.json();return m.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(m){return {success:false,error:{code:"NETWORK_ERROR",message:m instanceof Error?m.message:"Network error"}}}}function he(e){return {getNetworkStatus:()=>me(e,"GET","/network/status"),getWeb3Challenge:(n,i)=>me(e,"POST",`/stacks/${encodeURIComponent(e.stackId)}/auth/web3/challenge`,{chain:n,address:i})}}function Re(e={apiBaseUrl:""}){let{wallet:n,connectSolana:i,connectEVM:l,signMessage:d,disconnect:p}=q(),{session:m,isAuthenticated:s,refresh:o,readSession:a}=W(),{headers:u}=z(),c=X({disabled:typeof window>"u"}),[y,t]=react.useState(false),[h,r]=react.useState(null),[b,f]=react.useState(false),g=e.apiBaseUrl||"",I=e.stacknetUrl||"https://stacknet.magma-rpc.com",C=e.stackId||c.resolvedStackId||"",S=he({baseUrl:I,stackId:C}),_=react.useCallback(async(k,P,T,R)=>{t(true),r(null);try{let v=P;if(!v){let F=await T();if(!F)return t(!1),!1;v=F;}let U=await S.getWeb3Challenge(k,v);if(!U.success||!U.data)return r("Failed to get challenge"),t(!1),!1;let x=await d(U.data.message,{chain:k,provider:R,address:v});if(!x)return t(!1),!1;let B={chain:k,message:U.data.message,signature:x,stackId:C};k==="solana"&&(B.publicKey=v);let J=await fetch(`${g}/api/auth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(B)});if(!J.ok){let F=await J.json().catch(()=>({}));return r(F.error||"Authentication failed"),t(!1),!1}return c.reportConnected({address:v,chain:k,method:R||(k==="solana"?"phantom":"metamask"),stackId:C}),a(),t(!1),!0}catch(v){return r(v.message||"Authentication failed"),t(false),false}},[g,S,d,a,c,C]),$=react.useCallback(async(k="phantom")=>{let P=await i(k);return P?_("solana",P,()=>i(k),k):false},[i,_]),L=react.useCallback(async()=>{let k=await l();return k?_("ethereum",k,l,"metamask"):false},[l,_]),w=react.useCallback(async k=>{t(true),r(null);try{let P=await fetch(`${g}/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 r(T.error||"Invalid code"),t(!1),!1}return a(),t(!1),!0}catch(P){return r(P.message||"OTP verification failed"),t(false),false}},[g,a]),A=react.useCallback(async(k,P)=>{t(true),r(null);try{let T=P||`${window.location.origin}/api/auth/oauth/callback`,R=new URLSearchParams({provider:k,redirectUri:T,stackId:C}),v=await fetch(`${g}/api/auth/oauth/start?${R}`,{credentials:"include"});if(!v.ok){let x=await v.json().catch(()=>({}));return r(x.error||"Failed to start OAuth flow"),t(!1),!1}let U=await v.json();if(U.redirect_url){let x;try{x=new URL(U.redirect_url);}catch{return r("Invalid OAuth redirect URL"),t(!1),!1}let B=[/(^|\.)accounts\.google\.com$/,/(^|\.)discord\.com$/,/(^|\.)github\.com$/,/(^|\.)x\.com$/,/(^|\.)twitter\.com$/,/(^|\.)apple\.com$/];return x.protocol!=="https:"||!B.some(J=>J.test(x.hostname))?(r(`Refusing to redirect to non-OAuth host: ${x.hostname}`),t(!1),!1):(typeof sessionStorage<"u"&&(sessionStorage.setItem("oauth_state",U.state||""),sessionStorage.setItem("oauth_provider",k)),window.location.href=x.toString(),!0)}return r("No redirect URL returned"),t(!1),!1}catch(T){return r(T.message||"OAuth flow failed"),t(false),false}},[g,C]),M=react.useCallback(async(k,P,T)=>{t(true),r(null);try{if(typeof sessionStorage<"u"){let v=sessionStorage.getItem("oauth_state"),U=sessionStorage.getItem("oauth_provider");if(sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("oauth_provider"),!v||v!==T)return r("OAuth state mismatch \u2014 refusing to complete login"),t(!1),!1;if(U&&U!==k)return r("OAuth provider mismatch \u2014 refusing to complete login"),t(!1),!1}let R=await fetch(`${g}/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(!R.ok){let v=await R.json().catch(()=>({}));return r(v.error||"OAuth authentication failed"),t(!1),!1}return a(),t(!1),!0}catch(R){return r(R.message||"OAuth callback failed"),t(false),false}},[g,C,a]),G=react.useCallback(async()=>{n.address&&n.chain&&c.reportDisconnected({address:n.address,chain:n.chain,stackId:C});try{await fetch(`${g}/api/auth/logout`,{method:"POST",headers:u,credentials:"include"});}catch{}p(),a();},[g,u,p,a,n,c,C]);return react.useEffect(()=>{if(!e.autoConnect||b||s||!c.ready||!c.known||!c.identity)return;f(true);let{chain:k,method:P}=c.identity;k==="solana"&&(P==="phantom"||P==="solflare")?$(P):k==="ethereum"&&L();},[e.autoConnect,b,s,c,$,L]),{session:m,isAuthenticated:s,wallet:n,loading:y,error:h,authenticateSolana:$,authenticateEVM:L,authenticateOTP:w,authenticateOAuth:A,authenticateOAuthCallback:M,logout:G,refresh:()=>o(g),stackId:C,bridge:{ready:c.ready,known:c.known,identity:c.identity,identityCount:c.identityCount,resolvedStackId:c.resolvedStackId}}}function ee(e,n="https://stacknet.magma-rpc.com"){let[i,l]=react.useState(null),[d,p]=react.useState(false),[m,s]=react.useState(null),o=react.useCallback(async u=>{p(true),s(null);try{let c=await fetch(`${n}/api/v2/stacks/${u}`);if(!c.ok)return s("Stack not found"),p(!1),null;let y=await c.json(),t=y.data?.stack||y.stack||y,h={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(r=>({provider:r.provider,clientId:r.clientId,enabled:r.enabled!==!1}))};return l(h),p(!1),h}catch(c){return s(c.message),p(false),null}},[n]);react.useEffect(()=>{e&&o(e);},[e,o]);let a=i?Ee(i):[];return {config:i,loading:d,error:m,identityProviders:a,fetchConfig:o}}function Ee(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 Me(e=""){let[n,i]=react.useState([]),[l,d]=react.useState(true),[p,m]=react.useState(null),s=react.useCallback(async()=>{try{let o=await fetch(`${e}/api/billing/plans`);if(o.ok){let a=await o.json();i(a.plans||a||[]);}}catch(o){m(o.message);}finally{d(false);}},[e]);return react.useEffect(()=>{s();},[s]),{plans:n,loading:l,error:p,refresh:s}}function Ne(e=""){let[n,i]=react.useState(null),[l,d]=react.useState(true),[p,m]=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){m(u.message);}finally{d(false);}},[e]);react.useEffect(()=>{s();},[s]);let o=react.useCallback(async u=>{let c=O(),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]),a=react.useCallback(async()=>{let u=O();return (await fetch(`${e}/api/billing/cancel`,{method:"POST",headers:u?{"x-csrf-token":u}:{}})).ok?(await s(),true):false},[e,s]);return {subscription:n,loading:l,error:p,refresh:s,subscribe:o,cancel:a}}function Be(e=""){let[n,i]=react.useState(null),[l,d]=react.useState(true),[p,m]=react.useState(null),s=react.useCallback(async()=>{try{let o=await fetch(`${e}/api/billing/usage`);if(o.ok){let a=await o.json();i(a);}}catch(o){m(o.message);}finally{d(false);}},[e]);return react.useEffect(()=>{s();},[s]),{usage:n,loading:l,error:p,refresh:s}}function Je(e=""){let[n,i]=react.useState(false),[l,d]=react.useState(null),p=react.useCallback(async s=>{i(true),d(null);try{let o=O(),a=await fetch(`${e}/api/billing/prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...o?{"x-csrf-token":o}:{}},body:JSON.stringify({amountCents:s})}),u=await a.json();return a.ok?u.url||null:(d(u.error||"Purchase failed"),null)}catch(o){return d(o.message),null}finally{i(false);}},[e]),m=react.useCallback(async s=>{i(true),d(null);try{let o=O(),a=await fetch(`${e}/api/billing/verify-prepaid`,{method:"POST",headers:{"Content-Type":"application/json",...o?{"x-csrf-token":o}:{}},body:JSON.stringify({sessionId:s})}),u=await a.json();return a.ok?u:(d(u.error||"Verification failed"),null)}catch(o){return d(o.message),null}finally{i(false);}},[e]);return {purchase:p,verifySession:m,loading:n,error:l}}function He(e="",n){let[i,l]=react.useState([]),[d,p]=react.useState(true),[m,s]=react.useState(null),o=n?.limit||50,a=n?.offset||0,u=react.useCallback(async()=>{try{let c=await fetch(`${e}/api/billing/history?limit=${o}&offset=${a}`);if(c.ok){let y=await c.json();l(y.records||y.history||(Array.isArray(y)?y:[]));}}catch(c){s(c.message);}finally{p(false);}},[e,o,a]);return react.useEffect(()=>{u();},[u]),{records:i,loading:d,error:m,refresh:u}}function Ve(){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 ze(e,n){let[i,l]=react.useState(null),[d,p]=react.useState(true),[m,s]=react.useState(false),[o,a]=react.useState(null),u=n?.apiBaseUrl??"",c=n?.scope===void 0||n?.scope==="global"?"global":`stack:${n.scope.stackId}`,y=react.useCallback(r=>{let b=encodeURIComponent(r);if(c==="global")return `${u}/api/user/profile/${b}`;let f=c.slice(6);return `${u}/api/v2/stacks/${encodeURIComponent(f)}/members/${b}/profile`},[u,c]),t=react.useCallback(async()=>{if(!e){l(null),p(false);return}p(true),a(null);try{let r=await fetch(y(e));if(r.ok){let b=await r.json(),f=b.profile||b.data?.profile||b;l({mid:f.mid||e,username:f.username||"",avatarUrl:f.avatar_url||f.avatarUrl,bio:f.bio,paymentAddress:f.payment_address||f.paymentAddress,createdAt:f.created_at||f.createdAt,updatedAt:f.updated_at||f.updatedAt});}else if(r.status===404)l({mid:e,username:""});else throw new Error(`${r.status}`)}catch(r){a(r instanceof Error?r.message:"Failed to load profile");}finally{p(false);}},[e,y]);react.useEffect(()=>{t();},[t]);let h=react.useCallback(async r=>{if(!e)return false;s(true),a(null);try{let b=Ve(),f={};r.username!==void 0&&(f.username=r.username),r.avatarUrl!==void 0&&(f.avatar_url=r.avatarUrl),r.bio!==void 0&&(f.bio=r.bio),r.paymentAddress!==void 0&&(f.payment_address=r.paymentAddress);let g=await fetch(y(e),{method:"PUT",headers:{"Content-Type":"application/json",...b?{"x-csrf-token":b}:{}},credentials:"same-origin",body:JSON.stringify(f)});if(!g.ok){let S=await g.json().catch(()=>({}));throw new Error(S.error||S.message||`Update failed: ${g.status}`)}let I=await g.json(),C=I.profile||I.data?.profile||I;return l(S=>({mid:S?.mid||e,username:r.username??S?.username??"",avatarUrl:r.avatarUrl??S?.avatarUrl,bio:r.bio??S?.bio,paymentAddress:r.paymentAddress??C.payment_address??C.paymentAddress??S?.paymentAddress,createdAt:S?.createdAt,updatedAt:C.updated_at||C.updatedAt||Date.now()})),!0}catch(b){return a(b instanceof Error?b.message:"Update failed"),false}finally{s(false);}},[e,y]);return {profile:i,loading:d,saving:m,error:o,updateProfile:h,refresh:t}}var ke="google-identity-services",qe="https://accounts.google.com/gsi/client";function Qe({stackId:e,stacknetUrl:n="https://stacknet.magma-rpc.com",apiBaseUrl:i="",autoPrompt:l=true,cancelOnTapOutside:d=true,onSuccess:p,onError:m,disabled:s=false}){let{config:o}=ee(e,n),{isAuthenticated:a,loading:u,readSession:c}=W(),[y,t]=react.useState(false),[h,r]=react.useState(null),[b,f]=react.useState(false),g=react.useRef(false),I=react.useRef(false),S=o?.oauthProviders?.find(w=>w.provider==="google"&&w.enabled&&w.clientId)?.clientId||null;react.useEffect(()=>{if(s||!S||typeof window>"u")return;if(document.getElementById(ke)){f(true);return}let w=document.createElement("script");w.id=ke,w.src=qe,w.async=true,w.defer=true,w.onload=()=>f(true),w.onerror=()=>{r("Failed to load Google sign-in"),m?.("Failed to load Google Identity Services script");},document.head.appendChild(w);},[s,S,m]);let _=react.useCallback(async w=>{t(true),r(null);try{let A=await fetch(`${i}/api/auth/google/one-tap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({credential:w.credential,stackId:e})});if(!A.ok){let G=(await A.json().catch(()=>({}))).error||"Google sign-in failed";r(G),m?.(G),t(!1);return}c(),t(!1),p?.();}catch(A){let M=A.message||"Google sign-in failed";r(M),m?.(M),t(false);}},[i,e,c,p,m]);react.useEffect(()=>{if(s){console.debug("[GoogleOneTap] Disabled");return}if(!b){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(a){console.debug("[GoogleOneTap] User already authenticated, skipping");return}if(!window.google?.accounts?.id){console.debug("[GoogleOneTap] GIS library not available on window");return}g.current||(console.debug("[GoogleOneTap] Initializing with clientId:",S),g.current=true,window.google.accounts.id.initialize({client_id:S,callback:_,auto_select:true,cancel_on_tap_outside:d}),l&&!I.current&&(I.current=true,console.debug("[GoogleOneTap] Showing prompt..."),window.google.accounts.id.prompt(w=>{w.isDisplayed?.()&&console.debug("[GoogleOneTap] Prompt displayed"),w.isNotDisplayed?.()&&console.debug("[GoogleOneTap] Not displayed:",w.getNotDisplayedReason?.()),w.isSkippedMoment?.()&&console.debug("[GoogleOneTap] Skipped:",w.getSkippedReason?.()),w.isDismissedMoment?.()&&console.debug("[GoogleOneTap] Dismissed:",w.getDismissedReason?.());})));},[s,b,S,u,a,_,l,d]),react.useEffect(()=>()=>{window.google?.accounts?.id&&g.current&&window.google.accounts.id.cancel();},[]);let $=react.useCallback(()=>{!window.google?.accounts?.id||!g.current||window.google.accounts.id.prompt();},[]),L=react.useCallback((w,A)=>{!w||!window.google?.accounts?.id||!g.current||window.google.accounts.id.renderButton(w,{theme:A?.theme||"filled_black",size:A?.size||"large",text:A?.text||"signin_with",width:A?.width});},[]);return {available:!!S,ready:b&&!!S,loading:y,error:h,prompt:$,renderButton:L,clientId:S}}var Ye="/api";function Ze(e,n){return `${(n||(typeof window<"u"?window.location.origin:"")).replace(/\/$/,"")}/?ref=${encodeURIComponent(e)}`}function et(e={}){let{shareBaseUrl:n,autoMint:i=true}=e,[l,d]=react.useState(null),[p,m]=react.useState(true),[s,o]=react.useState(null),a=react.useCallback(async()=>{m(true),o(null);try{let y=i?"POST":"GET",t=await fetch(`${Ye}/social/join-code`,{method:y,credentials:"include"});if(!t.ok){d(null),t.status===401?o("not_authenticated"):o(`HTTP ${t.status}`);return}let h=await t.json();d(h?.code??null);}catch(y){o(y?.message||"network_error"),d(null);}finally{m(false);}},[i]);react.useEffect(()=>{a();},[a]);let u=l?Ze(l,n):null,c=react.useCallback(async()=>{if(!u)return false;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(u),!0}catch{}return false},[u]);return {code:l,shareUrl:u,loading:p,error:s,refresh:a,copyShareLink:c}}var Ce="/api";function rt(e={}){let{shareBaseUrl:n}=e,[i,l]=react.useState([]),[d,p]=react.useState(null),[m,s]=react.useState(true),[o,a]=react.useState(false),[u,c]=react.useState(null),y=react.useCallback(async()=>{s(true),c(null);try{let f=await fetch(`${Ce}/social/invites`,{method:"GET",credentials:"include"});if(!f.ok){f.status===401?c("not_authenticated"):c(`HTTP ${f.status}`),l([]),p(null);return}let g=await f.json();l(Array.isArray(g.codes)?g.codes:[]),p(typeof g.limit=="number"?g.limit:null);}catch(f){c(f?.message||"network_error"),l([]),p(null);}finally{s(false);}},[]);react.useEffect(()=>{y();},[y]);let t=react.useCallback(async()=>{a(true),c(null);try{let f=await fetch(`${Ce}/social/invites`,{method:"POST",credentials:"include"}),g=await f.json().catch(()=>({}));return f.ok?(Array.isArray(g.codes)&&l(g.codes),typeof g.limit=="number"&&p(g.limit),g.minted??null):(f.status===409&&g.error==="code_limit_reached"?c("code_limit_reached"):f.status===401?c("not_authenticated"):c(g.error||`HTTP ${f.status}`),null)}catch(f){return c(f?.message||"network_error"),null}finally{a(false);}},[]),h=react.useCallback(f=>{let g=n??(typeof window<"u"?window.location.origin:null);return g?`${g.replace(/\/$/,"")}/?ref=${encodeURIComponent(f)}`:null},[n]),r=react.useCallback(async f=>{let g=h(f);if(!g)return false;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(g),!0}catch{}return false},[h]),b=react.useMemo(()=>d==null?null:Math.max(0,d-i.length),[d,i.length]);return {codes:i,limit:d,remaining:b,loading:m,minting:o,error:u,refresh:y,mint:t,buildShareUrl:h,copyShareLink:r}}
2
+ exports.useAuthBridge=X;exports.useBillingHistory=He;exports.useCSRFToken=z;exports.useGoogleOneTap=Qe;exports.useInvites=rt;exports.useJoinCode=et;exports.usePlans=Me;exports.usePrepaidCheckout=Je;exports.useProfile=ze;exports.useSession=W;exports.useStackAuth=Re;exports.useStackConfig=ee;exports.useSubscription=Ne;exports.useUsage=Be;exports.useWeb3Wallet=q;
@@ -344,4 +344,58 @@ interface UseJoinCodeConfig {
344
344
  }
345
345
  declare function useJoinCode(config?: UseJoinCodeConfig): UseJoinCodeResult;
346
346
 
347
- export { type BridgeIdentity, type GoogleOneTapConfig, type StackPublicConfig, type UseJoinCodeConfig, type UseJoinCodeResult, type WalletState, useAuthBridge, useBillingHistory, useCSRFToken, useGoogleOneTap, useJoinCode, usePlans, usePrepaidCheckout, useProfile, useSession, useStackAuth, useStackConfig, useSubscription, useUsage, useWeb3Wallet };
347
+ /**
348
+ * useInvites — fetch the signed-in user's full set of invite codes
349
+ * and let them mint new single-use codes (up to the per-owner cap).
350
+ *
351
+ * Backed by `/api/social/invites` (GET to list, POST to mint). Each
352
+ * code is single-use across the whole network: once redeemed via
353
+ * `?ref=<code>` on signup, the corresponding entry's `consumedByMid`
354
+ * + `consumedAt` are populated and the code can no longer be used.
355
+ *
356
+ * Use this in the new multi-slot invite UI. The legacy `useJoinCode`
357
+ * single-code hook still works for back-compat (it returns the user's
358
+ * first available code, minting one if none).
359
+ */
360
+ interface InviteCode {
361
+ code: string;
362
+ ownerMid: string;
363
+ createdAt: number;
364
+ timesUsed: number;
365
+ lastUsedAt: number | null;
366
+ consumedByMid: string | null;
367
+ consumedAt: number | null;
368
+ }
369
+ interface UseInvitesResult {
370
+ /** All of the user's codes (consumed + available), oldest first. */
371
+ codes: InviteCode[];
372
+ /** Per-owner cap from the server (e.g. 10). Null until first load. */
373
+ limit: number | null;
374
+ /** Slots still available to mint (limit - codes.length). */
375
+ remaining: number | null;
376
+ /** True while the initial list fetch is in flight. */
377
+ loading: boolean;
378
+ /** True while a mint POST is in flight. */
379
+ minting: boolean;
380
+ /** Last error (load or mint), if any. */
381
+ error: string | null;
382
+ /** Re-fetch the code list from the server. */
383
+ refresh: () => Promise<void>;
384
+ /** Mint a fresh single-use code. Throws on cap-reached / network error. */
385
+ mint: () => Promise<InviteCode | null>;
386
+ /**
387
+ * Build the share URL for a given code. Defaults to
388
+ * `${origin}/?ref=<code>`. Returns null in non-browser contexts when
389
+ * `shareBaseUrl` isn't supplied.
390
+ */
391
+ buildShareUrl: (code: string) => string | null;
392
+ /** Copy the share URL for a given code to the clipboard. */
393
+ copyShareLink: (code: string) => Promise<boolean>;
394
+ }
395
+ interface UseInvitesConfig {
396
+ /** Override the share-URL origin. Defaults to `window.location.origin`. */
397
+ shareBaseUrl?: string;
398
+ }
399
+ declare function useInvites(config?: UseInvitesConfig): UseInvitesResult;
400
+
401
+ export { type BridgeIdentity, type GoogleOneTapConfig, type InviteCode, type StackPublicConfig, type UseInvitesConfig, type UseInvitesResult, type UseJoinCodeConfig, type UseJoinCodeResult, type WalletState, useAuthBridge, useBillingHistory, useCSRFToken, useGoogleOneTap, useInvites, useJoinCode, usePlans, usePrepaidCheckout, useProfile, useSession, useStackAuth, useStackConfig, useSubscription, useUsage, useWeb3Wallet };
@@ -344,4 +344,58 @@ interface UseJoinCodeConfig {
344
344
  }
345
345
  declare function useJoinCode(config?: UseJoinCodeConfig): UseJoinCodeResult;
346
346
 
347
- export { type BridgeIdentity, type GoogleOneTapConfig, type StackPublicConfig, type UseJoinCodeConfig, type UseJoinCodeResult, type WalletState, useAuthBridge, useBillingHistory, useCSRFToken, useGoogleOneTap, useJoinCode, usePlans, usePrepaidCheckout, useProfile, useSession, useStackAuth, useStackConfig, useSubscription, useUsage, useWeb3Wallet };
347
+ /**
348
+ * useInvites — fetch the signed-in user's full set of invite codes
349
+ * and let them mint new single-use codes (up to the per-owner cap).
350
+ *
351
+ * Backed by `/api/social/invites` (GET to list, POST to mint). Each
352
+ * code is single-use across the whole network: once redeemed via
353
+ * `?ref=<code>` on signup, the corresponding entry's `consumedByMid`
354
+ * + `consumedAt` are populated and the code can no longer be used.
355
+ *
356
+ * Use this in the new multi-slot invite UI. The legacy `useJoinCode`
357
+ * single-code hook still works for back-compat (it returns the user's
358
+ * first available code, minting one if none).
359
+ */
360
+ interface InviteCode {
361
+ code: string;
362
+ ownerMid: string;
363
+ createdAt: number;
364
+ timesUsed: number;
365
+ lastUsedAt: number | null;
366
+ consumedByMid: string | null;
367
+ consumedAt: number | null;
368
+ }
369
+ interface UseInvitesResult {
370
+ /** All of the user's codes (consumed + available), oldest first. */
371
+ codes: InviteCode[];
372
+ /** Per-owner cap from the server (e.g. 10). Null until first load. */
373
+ limit: number | null;
374
+ /** Slots still available to mint (limit - codes.length). */
375
+ remaining: number | null;
376
+ /** True while the initial list fetch is in flight. */
377
+ loading: boolean;
378
+ /** True while a mint POST is in flight. */
379
+ minting: boolean;
380
+ /** Last error (load or mint), if any. */
381
+ error: string | null;
382
+ /** Re-fetch the code list from the server. */
383
+ refresh: () => Promise<void>;
384
+ /** Mint a fresh single-use code. Throws on cap-reached / network error. */
385
+ mint: () => Promise<InviteCode | null>;
386
+ /**
387
+ * Build the share URL for a given code. Defaults to
388
+ * `${origin}/?ref=<code>`. Returns null in non-browser contexts when
389
+ * `shareBaseUrl` isn't supplied.
390
+ */
391
+ buildShareUrl: (code: string) => string | null;
392
+ /** Copy the share URL for a given code to the clipboard. */
393
+ copyShareLink: (code: string) => Promise<boolean>;
394
+ }
395
+ interface UseInvitesConfig {
396
+ /** Override the share-URL origin. Defaults to `window.location.origin`. */
397
+ shareBaseUrl?: string;
398
+ }
399
+ declare function useInvites(config?: UseInvitesConfig): UseInvitesResult;
400
+
401
+ export { type BridgeIdentity, type GoogleOneTapConfig, type InviteCode, type StackPublicConfig, type UseInvitesConfig, type UseInvitesResult, type UseJoinCodeConfig, type UseJoinCodeResult, type WalletState, useAuthBridge, useBillingHistory, useCSRFToken, useGoogleOneTap, useInvites, useJoinCode, usePlans, usePrepaidCheckout, useProfile, useSession, useStackAuth, useStackConfig, useSubscription, useUsage, useWeb3Wallet };