import{F as e,H as t,I as n,U as r,c as i,n as a,t as o,v as s}from"./ApiController.js";var c=class{constructor(e){this.getNonce=e.getNonce}async createMessage(e){let t={accountAddress:e.accountAddress,chainId:e.chainId,version:`1`,domain:typeof document>`u`?`Unknown Domain`:document.location.host,uri:typeof document>`u`?`Unknown URI`:document.location.href,resources:this.resources,nonce:await this.getNonce(e),issuedAt:this.stringifyDate(new Date),statement:void 0,expirationTime:void 0,notBefore:void 0};return Object.assign(t,{toString:()=>this.stringify(t)})}stringify(e){let t=this.getNetworkName(e.chainId);return[`${e.domain} wants you to sign in with your ${t} account:`,e.accountAddress,e.statement?`\n${e.statement}\n`:``,`URI: ${e.uri}`,`Version: ${e.version}`,`Chain ID: ${e.chainId}`,`Nonce: ${e.nonce}`,e.issuedAt&&`Issued At: ${e.issuedAt}`,e.expirationTime&&`Expiration Time: ${e.expirationTime}`,e.notBefore&&`Not Before: ${e.notBefore}`,e.requestId&&`Request ID: ${e.requestId}`,e.resources?.length&&e.resources.reduce((e,t)=>`${e}\n- ${t}`,`Resources:`)].filter(e=>typeof e==`string`).join(`
`).trim()}getNetworkName(e){let n=a.getAllRequestedCaipNetworks();return t.getNetworkNameByCaipNetworkId(n,e)}stringifyDate(e){return e.toISOString()}},l=class{constructor(e={}){this.otpUuid=null,this.listeners={sessionChanged:[]},this.localAuthStorageKey=e.localAuthStorageKey||n.SIWX_AUTH_TOKEN,this.localNonceStorageKey=e.localNonceStorageKey||n.SIWX_NONCE_TOKEN,this.required=e.required??!0,this.messenger=new c({getNonce:this.getNonce.bind(this)})}async createMessage(e){return this.messenger.createMessage(e)}async addSession(e){let t=await this.request({method:`POST`,key:`authenticate`,body:{data:e.data,message:e.message,signature:e.signature,clientId:this.getClientId(),walletInfo:this.getWalletInfo()},headers:[`nonce`,`otp`]});this.setStorageToken(t.token,this.localAuthStorageKey),this.emit(`sessionChanged`,e),this.setAppKitAccountUser(u(t.token)),this.otpUuid=null}async getSessions(e,t){try{if(!this.getStorageToken(this.localAuthStorageKey))return[];let n=await this.request({method:`GET`,key:`me`,query:{},headers:[`auth`]});if(!n)return[];let r=n.address.toLowerCase()===t.toLowerCase(),i=n.caip2Network===e;if(!r||!i)return[];let a={data:{accountAddress:n.address,chainId:n.caip2Network},message:``,signature:``};return this.emit(`sessionChanged`,a),this.setAppKitAccountUser(n),[a]}catch{return[]}}async revokeSession(e,t){return Promise.resolve(this.clearStorageTokens())}async setSessions(e){if(e.length===0)this.clearStorageTokens();else{let t=e.find(e=>e.data.chainId===i()?.caipNetworkId)||e[0];await this.addSession(t)}}getRequired(){return this.required}async getSessionAccount(){if(!this.getStorageToken(this.localAuthStorageKey))throw Error(`Not authenticated`);return this.request({method:`GET`,key:`me`,body:void 0,query:{includeAppKitAccount:!0},headers:[`auth`]})}async setSessionAccountMetadata(e=null){if(!this.getStorageToken(this.localAuthStorageKey))throw Error(`Not authenticated`);return this.request({method:`PUT`,key:`account-metadata`,body:{metadata:e},headers:[`auth`]})}on(e,t){return this.listeners[e].push(t),()=>{this.listeners[e]=this.listeners[e].filter(e=>e!==t)}}removeAllListeners(){Object.keys(this.listeners).forEach(e=>{this.listeners[e]=[]})}async requestEmailOtp({email:e,account:t}){let n=await this.request({method:`POST`,key:`otp`,body:{email:e,account:t}});return this.otpUuid=n.uuid,this.messenger.resources=[`email:${e}`],n}confirmEmailOtp({code:e}){return this.request({method:`PUT`,key:`otp`,body:{code:e},headers:[`otp`]})}async request({method:e,key:t,query:n,body:i,headers:a}){let{projectId:o,st:s,sv:c}=this.getSDKProperties(),l=new URL(`${r.W3M_API_URL}/auth/v1/${String(t)}`);l.searchParams.set(`projectId`,o),l.searchParams.set(`st`,s),l.searchParams.set(`sv`,c),n&&Object.entries(n).forEach(([e,t])=>l.searchParams.set(e,String(t)));let u=await fetch(l,{method:e,body:i?JSON.stringify(i):void 0,headers:Array.isArray(a)?a.reduce((e,t)=>{switch(t){case`nonce`:e[`x-nonce-jwt`]=`Bearer ${this.getStorageToken(this.localNonceStorageKey)}`;break;case`auth`:e.Authorization=`Bearer ${this.getStorageToken(this.localAuthStorageKey)}`;break;case`otp`:this.otpUuid&&(e[`x-otp`]=this.otpUuid)}return e},{}):void 0});if(!u.ok)throw Error(await u.text());return u.headers.get(`content-type`)?.includes(`application/json`)?u.json():null}getStorageToken(t){return e.getItem(t)}setStorageToken(t,n){e.setItem(n,t)}clearStorageTokens(){this.otpUuid=null,e.removeItem(this.localAuthStorageKey),e.removeItem(this.localNonceStorageKey),this.emit(`sessionChanged`,void 0)}async getNonce(){let{nonce:e,token:t}=await this.request({method:`GET`,key:`nonce`});return this.setStorageToken(t,this.localNonceStorageKey),e}getClientId(){return s.state.clientId}getWalletInfo(){let e=a.getAccountData()?.connectedWalletInfo;if(!e)return;if(`social`in e&&`identifier`in e)return{type:`social`,social:e.social,identifier:e.identifier};let{name:t,icon:n}=e,r=`unknown`;switch(e.type){case`EXTERNAL`:case`INJECTED`:case`ANNOUNCED`:r=`extension`;break;case`WALLET_CONNECT`:r=`walletconnect`;break;default:r=`unknown`}return{type:r,name:t,icon:n}}getSDKProperties(){return o._getSdkProperties()}emit(e,t){this.listeners[e].forEach(e=>e(t))}setAppKitAccountUser(e){let{email:t}=e;t&&Object.values(r.CHAIN).forEach(e=>{a.setAccountProp(`user`,{email:t},e)})}};function u(e){let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=t[1];if(typeof n!=`string`)throw Error(`Invalid token`);let r=n.replace(/-/gu,`+`).replace(/_/gu,`/`),i=r.padEnd(r.length+(4-r.length%4)%4,`=`);return JSON.parse(atob(i))}export{l as ReownAuthentication};