@privy-io/react-auth 1.12.0-beta.5 → 1.12.0-beta.6

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,4 +1,4 @@
1
- import{useEffect as Wt,useState as ie}from"react";import Vt from"axios";import mi from"axios";var B=class extends Error{constructor(o,r){super(o);r instanceof Error&&(this.cause=r)}toString(){return`${this.type}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},Xe=class extends B{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},p=class extends B{constructor(o,r){super(o,r);this.type="client_error"}};var V=class extends B{constructor(o,r){super(o,r);this.type="connector_error"}},I=t=>{if(t instanceof B)return t;if(!mi.isAxiosError(t))return G(t);if(!t.response)return new Xe("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new Xe(e||"ApiError",t.response.status,o||r,t)},G=t=>t instanceof B?t:t instanceof Error?new p(t.message,t):new p(`Internal error: ${t}`);var go="1.12.0-beta.5";var wo="https://api.privy.io/v0",yo=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",et="4df5e2316331463a9130964bd6078dfa",Co=1e4,Ee=1400,vo=365*24*60*60,Ft=go,bo="ES256",xo="privy.io",Ae="privy:token",tt="privy:refresh_token",K="privy:active_wallet",ot="privy:wallet_type",Lo="walletconnect";var rt=class{constructor(e,o,r){this.appId=e,this.sdkVersion=Ft,this.session=o,this.defaults=r}async get(e,o){try{return await Vt.get(e,this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw I(r)}}async post(e,o,r){try{return await Vt.post(e,o,this.buildConfig(r))}catch(i){throw I(i)}}async delete(e,o){try{return await Vt.delete(e,this.buildConfig(o))}catch(r){throw I(r)}}buildConfig(e){return e=e||{},e.headers=e.headers||{},e.headers["privy-app-id"]=this.appId,e.headers["privy-client"]=`react-auth:${this.sdkVersion}`,this.session.token!==null&&(e.headers.authorization=`Bearer ${this.session.token}`),{...this.defaults,...e}}};import*as ke from"jose";var ne=class{static parse(e){try{return new ne(e)}catch{return null}}constructor(e){this.value=e,this._decoded=ke.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){let o=Date.now(),r=(this.expiration-e)*1e3;return o>=r}async isValid(e,o,r=0){let i=await ke.importSPKI(e,bo);try{return await ke.jwtVerify(this.value,i,{issuer:xo,audience:o,clockTolerance:r}),!0}catch{return!1}}};var se=class{constructor(e){this.promise=null;this.fn=e}execute(e){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}};var Gt=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,o){o!==void 0?this._cache[e]=o:this.del(e)}del(e){delete this._cache[e]}},Ht=class{get(e){let o=localStorage.getItem(e);return o===null?void 0:JSON.parse(o)}put(e,o){o!==void 0?localStorage.setItem(e,JSON.stringify(o)):this.del(e)}del(e){localStorage.removeItem(e)}};function gi(){return typeof window<"u"&&window.localStorage?new Ht:new Gt}var E=gi();function pe(t){return new Date(t*1e3)}function wi(t){return t.map(e=>{switch(e.type){case"wallet":return{address:e.address,type:e.type,verifiedAt:pe(e.verified_at),chainType:e.chain_type};case"email":return{address:e.address,type:e.type,verifiedAt:pe(e.verified_at)};case"phone":return{number:e.phoneNumber,type:e.type,verifiedAt:pe(e.verified_at)};case"google_oauth":return{subject:e.subject,email:e.email,name:e.name,type:e.type,verifiedAt:pe(e.verified_at)};case"twitter_oauth":return{subject:e.subject,username:e.username,name:e.name,type:e.type,verifiedAt:pe(e.verified_at)};case"discord_oauth":return{subject:e.subject,username:e.username,email:e.email,type:e.type,verifiedAt:pe(e.verified_at)};default:throw new p("Unrecognized account type")}})}function yi(t,e){return e.find(o=>o.type==="wallet"&&o.address===t)}function ue(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function Fe(t){let e=t.linkedAccounts.map(s=>s.type==="wallet"?s.address:null),r=E.get(K);if(!r||!e.includes(r)){E.del(K);let s=ue(t.linkedAccounts,"wallet");s&&(r=s.address,E.put(K,r))}let i=yi(r,t.linkedAccounts),n=Object.assign({},t);return n.wallet=i&&{address:i.address,chainType:i.chainType,chainId:i.chainId,walletType:i.walletType},n}function J(t){if(!t)return null;let e=wi(t.linked_accounts),o=ue(e,"wallet"),r=ue(e,"email"),i=ue(e,"phone"),n=ue(e,"google_oauth"),s=ue(e,"twitter_oauth"),c=ue(e,"discord_oauth"),f={id:t.id,createdAt:pe(t.created_at),linkedAccounts:e,email:r&&{address:r==null?void 0:r.address},phone:i&&{number:i==null?void 0:i.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:c&&{subject:c.subject,username:c.username,email:c.email}};return Fe(f)}var Eo=()=>"/api/v1/sessions",Ao=()=>"/api/v1/sessions/logout",ko=()=>"/api/v1/sessions/fork",_o=()=>"/api/v1/siwe/init",Po=()=>"/api/v1/siwe/authenticate",So=()=>"/api/v1/siwe/link",To=()=>"/api/v1/passwordless/init",Io=()=>"/api/v1/passwordless/authenticate",Ro=()=>"/api/v1/passwordless/link",Mo=()=>"/api/v1/passwordless_sms/init",Wo=()=>"/api/v1/passwordless_sms/authenticate",No=()=>"/api/v1/passwordless_sms/link",Oo=()=>"/api/v1/oauth/init",Uo=()=>"/api/v1/oauth/authenticate",Do=()=>"/api/v1/oauth/link",Fo=()=>"/api/v1/siwe/unlink",Vo=()=>"/api/v1/passwordless/unlink",Go=()=>"/api/v1/passwordless_sms/unlink",Ho=()=>"/api/v1/oauth/unlink";var Ci=30,it=class{constructor(){this.authenticateOnce=new se(async e=>this._authenticate(e)),this.linkOnce=new se(async e=>this._link(e)),this.refreshOnce=new se(this._refresh.bind(this)),this.destroyOnce=new se(this._destroy.bind(this)),this.forkSessionOnce=new se(this._forkSession.bind(this))}get token(){try{let e=E.get(Ae);return typeof e=="string"?new ne(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=E.get(tt);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let e=ne.parse(this.token);return e!==null&&!e.isExpired(Ci)}async hasValidToken(e,o,r=0){let i=ne.parse(this.token);return i!==null&&await i.isValid(e,o,r)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:i,is_new_user:n}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:J(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),G(o)}}async _link(e){try{let o=await e.link();return J(o)}catch(o){throw console.warn("Error linking account"),G(o)}}async _refresh(){if(!this.api)throw new p("Session has no API instance");let e=this.token,o=this.refreshToken;if(!e||!o)return null;try{let r=await this.api.post(Eo(),{refresh_token:o});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),J(r.data.user)}catch(r){throw G(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Ao(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new p("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(ko(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw G(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null),E.del(K)}storeToken(e){typeof e=="string"?E.put(Ae,e):E.del(Ae)}storeRefreshToken(e){typeof e=="string"?E.put(tt,e):E.del(tt)}};import{getAddress as Ai}from"@ethersproject/address";import zo from"@walletconnect/web3-provider";import{ErrorCode as vi}from"@ethersproject/logger";var _e=class extends V{constructor(){super("Wallet timeout");this.type="wallet_error"}},nt=t=>{if(t instanceof V)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new Pe(t);return t.code===vi.ACTION_REJECTED&&(e.details=he.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new Pe(t):new V("Unknown connector error",t)},Bt=class extends B{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},Pe=class extends Bt{constructor(o){var n,s,c;let r=o;super(r.message,r.code,r.data);let i=Object.values(he).find(f=>f.eipCode===r.code);this.details=i||he.UNKNOWN_ERROR,r.code===-32002&&((n=r.message)!=null&&n.includes("already pending for origin")?(s=r.message)!=null&&s.includes("wallet_requestPermissions")?this.details=he.E32002_CONNECTION_ALREADY_PENDING:this.details=he.E32002_REQUEST_ALREADY_PENDING:(c=r.message)!=null&&c.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=he.E32002_WALLET_LOCKED))}},bi={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_NOT_ALLOWED:{message:"You don\u2019t have access to this app",detail:"Try with a different address?",retryable:!0}},xi={E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:"Connection request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:"Resource request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:"Wallet might be locked",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}},Li={E4001_DEFAULT_USER_REJECTED_REQUEST:{eipCode:4001,message:"User Rejected Request",detail:"The user rejected the request.",default:!0,retryable:!0},E4100_DEFAULT_UNAUTHORIZED:{eipCode:4100,message:"Unauthorized",detail:"The requested method and/or account has not been authorized by the user.",default:!0,retryable:!1},E4200_DEFAULT_UNSUPPORTED_METHOD:{eipCode:4200,message:"Unsupported Method",detail:"The Provider does not support the requested method.",default:!0,retryable:!1},E4900_DEFAULT_DISCONNECTED:{eipCode:4900,message:"Disconnected",detail:"The Provider is disconnected from all chains.",default:!0,retryable:!0},E4901_DEFAULT_CHAIN_DISCONNECTED:{eipCode:4901,message:"Chain Disconnected",detail:"The Provider is not connected to the requested chain.",default:!0,retryable:!0},E32700_DEFAULT_PARSE_ERROR:{eipCode:-32700,message:"Parse error",detail:"Invalid JSON",default:!0,retryable:!1},E32600_DEFAULT_INVALID_REQUEST:{eipCode:-32600,message:"Invalid request",detail:"JSON is not a valid request object",default:!0,retryable:!1},E32601_DEFAULT_METHOD_NOT_FOUND:{eipCode:-32601,message:"Method not found",detail:"Method does not exist",default:!0,retryable:!1},E32602_DEFAULT_INVALID_PARAMS:{eipCode:-32602,message:"Invalid params",detail:"Invalid method parameters",default:!0,retryable:!1},E32603_DEFAULT_INTERNAL_ERROR:{eipCode:-32603,message:"Internal error",detail:"Internal JSON-RPC error",default:!0,retryable:!0},E32000_DEFAULT_INVALID_INPUT:{eipCode:-32e3,message:"Invalid input",detail:"Missing or invalid parameters",default:!0,retryable:!1},E32001_DEFAULT_RESOURCE_NOT_FOUND:{eipCode:-32001,message:"Resource not found",detail:"Requested resource not found",default:!0,retryable:!1},E32002_DEFAULT_RESOURCE_UNAVAILABLE:{eipCode:-32002,message:"Resource unavailable",detail:"Requested resource not available",default:!0,retryable:!0},E32003_DEFAULT_TRANSACTION_REJECTED:{eipCode:-32003,message:"Transaction rejected",detail:"Transaction creation failed",default:!0,retryable:!0},E32004_DEFAULT_METHOD_NOT_SUPPORTED:{eipCode:-32004,message:"Method not supported",detail:"Method is not implemented",default:!0,retryable:!1},E32005_DEFAULT_LIMIT_EXCEEDED:{eipCode:-32005,message:"Limit exceeded",detail:"Request exceeds defined limit",default:!0,retryable:!1},E32006_DEFAULT_JSON_RPC_VERSION_NOT_SUPPORTED:{eipCode:-32006,message:"JSON-RPC version not supported",detail:"Version of JSON-RPC protocol is not supported",default:!0,retryable:!1}},he={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...Li,...xi},Ve={...bi,...he};var Ei=12e4,zt=(t=new _e,e=Ei)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),me=class{constructor(e){this.removeListener=(e,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(e,o)};this.setProvider=e=>{this.walletProvider=e,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=e,this._subscriptions=[]}on(e,o){if(this.walletProvider)return this.walletProvider.on(e,o);this._subscriptions.push({eventName:e,listener:o})}request(e){if(!this.walletProvider)throw new V(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),zt()]).catch(o=>{throw nt(o)})}},fe=class extends me{constructor(o){super(o)}},st=class extends me{constructor(e){super(e)}sendAsync(e,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};import{Web3Provider as ki}from"@ethersproject/providers";var Bo=["metamask","coinbase_wallet","wallet_connect"];import _i from"@coinbase/wallet-sdk";var Pi=()=>{let t=`https://mainnet.infura.io/v3/${et}`,e=1;return new _i({appName:"Privy",darkMode:!1,headlessMode:!1}).makeWeb3Provider(t,e)},Zt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isMetaMask)return!0}return!1},at=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isCoinbaseWallet)return!0}return!1},Ge=class{constructor(){this.walletType=null;this.getEthereumProvider=()=>this.ethProvider;this.createSiweMessage=(e,o,r,i,n,s,c)=>`${r} wants you to sign in with your Ethereum account:
1
+ import{useEffect as Wt,useState as ie}from"react";import Vt from"axios";import mi from"axios";var B=class extends Error{constructor(o,r){super(o);r instanceof Error&&(this.cause=r)}toString(){return`${this.type}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},Xe=class extends B{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},p=class extends B{constructor(o,r){super(o,r);this.type="client_error"}};var V=class extends B{constructor(o,r){super(o,r);this.type="connector_error"}},I=t=>{if(t instanceof B)return t;if(!mi.isAxiosError(t))return G(t);if(!t.response)return new Xe("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new Xe(e||"ApiError",t.response.status,o||r,t)},G=t=>t instanceof B?t:t instanceof Error?new p(t.message,t):new p(`Internal error: ${t}`);var go="1.12.0-beta.6";var wo="https://api.privy.io/v0",yo=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",et="4df5e2316331463a9130964bd6078dfa",Co=1e4,Ee=1400,vo=365*24*60*60,Ft=go,bo="ES256",xo="privy.io",Ae="privy:token",tt="privy:refresh_token",K="privy:active_wallet",ot="privy:wallet_type",Lo="walletconnect";var rt=class{constructor(e,o,r){this.appId=e,this.sdkVersion=Ft,this.session=o,this.defaults=r}async get(e,o){try{return await Vt.get(e,this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw I(r)}}async post(e,o,r){try{return await Vt.post(e,o,this.buildConfig(r))}catch(i){throw I(i)}}async delete(e,o){try{return await Vt.delete(e,this.buildConfig(o))}catch(r){throw I(r)}}buildConfig(e){return e=e||{},e.headers=e.headers||{},e.headers["privy-app-id"]=this.appId,e.headers["privy-client"]=`react-auth:${this.sdkVersion}`,this.session.token!==null&&(e.headers.authorization=`Bearer ${this.session.token}`),{...this.defaults,...e}}};import*as ke from"jose";var ne=class{static parse(e){try{return new ne(e)}catch{return null}}constructor(e){this.value=e,this._decoded=ke.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){let o=Date.now(),r=(this.expiration-e)*1e3;return o>=r}async isValid(e,o,r=0){let i=await ke.importSPKI(e,bo);try{return await ke.jwtVerify(this.value,i,{issuer:xo,audience:o,clockTolerance:r}),!0}catch{return!1}}};var se=class{constructor(e){this.promise=null;this.fn=e}execute(e){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}};var Gt=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,o){o!==void 0?this._cache[e]=o:this.del(e)}del(e){delete this._cache[e]}},Ht=class{get(e){let o=localStorage.getItem(e);return o===null?void 0:JSON.parse(o)}put(e,o){o!==void 0?localStorage.setItem(e,JSON.stringify(o)):this.del(e)}del(e){localStorage.removeItem(e)}};function gi(){return typeof window<"u"&&window.localStorage?new Ht:new Gt}var E=gi();function pe(t){return new Date(t*1e3)}function wi(t){return t.map(e=>{switch(e.type){case"wallet":return{address:e.address,type:e.type,verifiedAt:pe(e.verified_at),chainType:e.chain_type};case"email":return{address:e.address,type:e.type,verifiedAt:pe(e.verified_at)};case"phone":return{number:e.phoneNumber,type:e.type,verifiedAt:pe(e.verified_at)};case"google_oauth":return{subject:e.subject,email:e.email,name:e.name,type:e.type,verifiedAt:pe(e.verified_at)};case"twitter_oauth":return{subject:e.subject,username:e.username,name:e.name,type:e.type,verifiedAt:pe(e.verified_at)};case"discord_oauth":return{subject:e.subject,username:e.username,email:e.email,type:e.type,verifiedAt:pe(e.verified_at)};default:throw new p("Unrecognized account type")}})}function yi(t,e){return e.find(o=>o.type==="wallet"&&o.address===t)}function ue(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function Fe(t){let e=t.linkedAccounts.map(s=>s.type==="wallet"?s.address:null),r=E.get(K);if(!r||!e.includes(r)){E.del(K);let s=ue(t.linkedAccounts,"wallet");s&&(r=s.address,E.put(K,r))}let i=yi(r,t.linkedAccounts),n=Object.assign({},t);return n.wallet=i&&{address:i.address,chainType:i.chainType,chainId:i.chainId,walletType:i.walletType},n}function J(t){if(!t)return null;let e=wi(t.linked_accounts),o=ue(e,"wallet"),r=ue(e,"email"),i=ue(e,"phone"),n=ue(e,"google_oauth"),s=ue(e,"twitter_oauth"),c=ue(e,"discord_oauth"),f={id:t.id,createdAt:pe(t.created_at),linkedAccounts:e,email:r&&{address:r==null?void 0:r.address},phone:i&&{number:i==null?void 0:i.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:c&&{subject:c.subject,username:c.username,email:c.email}};return Fe(f)}var Eo=()=>"/api/v1/sessions",Ao=()=>"/api/v1/sessions/logout",ko=()=>"/api/v1/sessions/fork",_o=()=>"/api/v1/siwe/init",Po=()=>"/api/v1/siwe/authenticate",So=()=>"/api/v1/siwe/link",To=()=>"/api/v1/passwordless/init",Io=()=>"/api/v1/passwordless/authenticate",Ro=()=>"/api/v1/passwordless/link",Mo=()=>"/api/v1/passwordless_sms/init",Wo=()=>"/api/v1/passwordless_sms/authenticate",No=()=>"/api/v1/passwordless_sms/link",Oo=()=>"/api/v1/oauth/init",Uo=()=>"/api/v1/oauth/authenticate",Do=()=>"/api/v1/oauth/link",Fo=()=>"/api/v1/siwe/unlink",Vo=()=>"/api/v1/passwordless/unlink",Go=()=>"/api/v1/passwordless_sms/unlink",Ho=()=>"/api/v1/oauth/unlink";var Ci=30,it=class{constructor(){this.authenticateOnce=new se(async e=>this._authenticate(e)),this.linkOnce=new se(async e=>this._link(e)),this.refreshOnce=new se(this._refresh.bind(this)),this.destroyOnce=new se(this._destroy.bind(this)),this.forkSessionOnce=new se(this._forkSession.bind(this))}get token(){try{let e=E.get(Ae);return typeof e=="string"?new ne(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=E.get(tt);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let e=ne.parse(this.token);return e!==null&&!e.isExpired(Ci)}async hasValidToken(e,o,r=0){let i=ne.parse(this.token);return i!==null&&await i.isValid(e,o,r)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:i,is_new_user:n}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:J(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),G(o)}}async _link(e){try{let o=await e.link();return J(o)}catch(o){throw console.warn("Error linking account"),G(o)}}async _refresh(){if(!this.api)throw new p("Session has no API instance");let e=this.token,o=this.refreshToken;if(!e||!o)return null;try{let r=await this.api.post(Eo(),{refresh_token:o});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),J(r.data.user)}catch(r){throw G(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Ao(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new p("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(ko(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw G(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null),E.del(K)}storeToken(e){typeof e=="string"?E.put(Ae,e):E.del(Ae)}storeRefreshToken(e){typeof e=="string"?E.put(tt,e):E.del(tt)}};import{getAddress as Ai}from"@ethersproject/address";import zo from"@walletconnect/web3-provider";import{ErrorCode as vi}from"@ethersproject/logger";var _e=class extends V{constructor(){super("Wallet timeout");this.type="wallet_error"}},nt=t=>{if(t instanceof V)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new Pe(t);return t.code===vi.ACTION_REJECTED&&(e.details=he.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new Pe(t):new V("Unknown connector error",t)},Bt=class extends B{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},Pe=class extends Bt{constructor(o){var n,s,c;let r=o;super(r.message,r.code,r.data);let i=Object.values(he).find(f=>f.eipCode===r.code);this.details=i||he.UNKNOWN_ERROR,r.code===-32002&&((n=r.message)!=null&&n.includes("already pending for origin")?(s=r.message)!=null&&s.includes("wallet_requestPermissions")?this.details=he.E32002_CONNECTION_ALREADY_PENDING:this.details=he.E32002_REQUEST_ALREADY_PENDING:(c=r.message)!=null&&c.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=he.E32002_WALLET_LOCKED))}},bi={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_NOT_ALLOWED:{message:"You don\u2019t have access to this app",detail:"Try with a different address?",retryable:!0}},xi={E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:"Connection request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:"Resource request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:"Wallet might be locked",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}},Li={E4001_DEFAULT_USER_REJECTED_REQUEST:{eipCode:4001,message:"User Rejected Request",detail:"The user rejected the request.",default:!0,retryable:!0},E4100_DEFAULT_UNAUTHORIZED:{eipCode:4100,message:"Unauthorized",detail:"The requested method and/or account has not been authorized by the user.",default:!0,retryable:!1},E4200_DEFAULT_UNSUPPORTED_METHOD:{eipCode:4200,message:"Unsupported Method",detail:"The Provider does not support the requested method.",default:!0,retryable:!1},E4900_DEFAULT_DISCONNECTED:{eipCode:4900,message:"Disconnected",detail:"The Provider is disconnected from all chains.",default:!0,retryable:!0},E4901_DEFAULT_CHAIN_DISCONNECTED:{eipCode:4901,message:"Chain Disconnected",detail:"The Provider is not connected to the requested chain.",default:!0,retryable:!0},E32700_DEFAULT_PARSE_ERROR:{eipCode:-32700,message:"Parse error",detail:"Invalid JSON",default:!0,retryable:!1},E32600_DEFAULT_INVALID_REQUEST:{eipCode:-32600,message:"Invalid request",detail:"JSON is not a valid request object",default:!0,retryable:!1},E32601_DEFAULT_METHOD_NOT_FOUND:{eipCode:-32601,message:"Method not found",detail:"Method does not exist",default:!0,retryable:!1},E32602_DEFAULT_INVALID_PARAMS:{eipCode:-32602,message:"Invalid params",detail:"Invalid method parameters",default:!0,retryable:!1},E32603_DEFAULT_INTERNAL_ERROR:{eipCode:-32603,message:"Internal error",detail:"Internal JSON-RPC error",default:!0,retryable:!0},E32000_DEFAULT_INVALID_INPUT:{eipCode:-32e3,message:"Invalid input",detail:"Missing or invalid parameters",default:!0,retryable:!1},E32001_DEFAULT_RESOURCE_NOT_FOUND:{eipCode:-32001,message:"Resource not found",detail:"Requested resource not found",default:!0,retryable:!1},E32002_DEFAULT_RESOURCE_UNAVAILABLE:{eipCode:-32002,message:"Resource unavailable",detail:"Requested resource not available",default:!0,retryable:!0},E32003_DEFAULT_TRANSACTION_REJECTED:{eipCode:-32003,message:"Transaction rejected",detail:"Transaction creation failed",default:!0,retryable:!0},E32004_DEFAULT_METHOD_NOT_SUPPORTED:{eipCode:-32004,message:"Method not supported",detail:"Method is not implemented",default:!0,retryable:!1},E32005_DEFAULT_LIMIT_EXCEEDED:{eipCode:-32005,message:"Limit exceeded",detail:"Request exceeds defined limit",default:!0,retryable:!1},E32006_DEFAULT_JSON_RPC_VERSION_NOT_SUPPORTED:{eipCode:-32006,message:"JSON-RPC version not supported",detail:"Version of JSON-RPC protocol is not supported",default:!0,retryable:!1}},he={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...Li,...xi},Ve={...bi,...he};var Ei=12e4,zt=(t=new _e,e=Ei)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),me=class{constructor(e){this.removeListener=(e,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(e,o)};this.setProvider=e=>{this.walletProvider=e,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=e,this._subscriptions=[]}on(e,o){if(this.walletProvider)return this.walletProvider.on(e,o);this._subscriptions.push({eventName:e,listener:o})}request(e){if(!this.walletProvider)throw new V(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),zt()]).catch(o=>{throw nt(o)})}},fe=class extends me{constructor(o){super(o)}},st=class extends me{constructor(e){super(e)}sendAsync(e,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};import{Web3Provider as ki}from"@ethersproject/providers";var Bo=["metamask","coinbase_wallet","wallet_connect"];import _i from"@coinbase/wallet-sdk";var Pi=()=>{let t=`https://mainnet.infura.io/v3/${et}`,e=1;return new _i({appName:"Privy",darkMode:!1,headlessMode:!1}).makeWeb3Provider(t,e)},Zt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isMetaMask)return!0}return!1},at=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isCoinbaseWallet)return!0}return!1},Ge=class{constructor(){this.walletType=null;this.getEthereumProvider=()=>this.ethProvider;this.createSiweMessage=(e,o,r,i,n,s,c)=>`${r} wants you to sign in with your Ethereum account:
2
2
  ${o}
3
3
 
4
4
  ${c}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var vi=Object.create;var ct=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Li=Object.getPrototypeOf,Ei=Object.prototype.hasOwnProperty;var Ai=(t,e)=>{for(var o in e)ct(t,o,{get:e[o],enumerable:!0})},So=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xi(e))!Ei.call(t,i)&&i!==o&&ct(t,i,{get:()=>e[i],enumerable:!(r=bi(e,i))||r.enumerable});return t};var C=(t,e,o)=>(o=t!=null?vi(Li(t)):{},So(e||!t||!t.__esModule?ct(o,"default",{value:t,enumerable:!0}):o,t)),ki=t=>So(ct({},"__esModule",{value:!0}),t);var Yn={};Ai(Yn,{AsExternalProvider:()=>ve,PrivyClient:()=>ze,PrivyConnector:()=>Be,PrivyProvider:()=>yi,PrivyProxyProvider:()=>Ce,VERSION:()=>ht,getAccessToken:()=>wi,usePrivy:()=>O});module.exports=ki(Yn);var z=require("react");var gt=C(require("axios"));var To=C(require("axios")),Q=class extends Error{constructor(o,r){super(o);r instanceof Error&&(this.cause=r)}toString(){return`${this.type}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},pt=class extends Q{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},u=class extends Q{constructor(o,r){super(o,r);this.type="client_error"}};var $=class extends Q{constructor(o,r){super(o,r);this.type="connector_error"}},N=t=>{if(t instanceof Q)return t;if(!To.default.isAxiosError(t))return K(t);if(!t.response)return new pt("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new pt(e||"ApiError",t.response.status,o||r,t)},K=t=>t instanceof Q?t:t instanceof Error?new u(t.message,t):new u(`Internal error: ${t}`);var Io="1.12.0-beta.5";var Ro="https://api.privy.io/v0",Mo=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",ut="4df5e2316331463a9130964bd6078dfa",Wo=1e4,De=1400,No=365*24*60*60,ht=Io,Oo="ES256",Uo="privy.io",Fe="privy:token",mt="privy:refresh_token",ne="privy:active_wallet",ft="privy:wallet_type",Do="walletconnect";var wt=class{constructor(e,o,r){this.appId=e,this.sdkVersion=ht,this.session=o,this.defaults=r}async get(e,o){try{return await gt.default.get(e,this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw N(r)}}async post(e,o,r){try{return await gt.default.post(e,o,this.buildConfig(r))}catch(i){throw N(i)}}async delete(e,o){try{return await gt.default.delete(e,this.buildConfig(o))}catch(r){throw N(r)}}buildConfig(e){return e=e||{},e.headers=e.headers||{},e.headers["privy-app-id"]=this.appId,e.headers["privy-client"]=`react-auth:${this.sdkVersion}`,this.session.token!==null&&(e.headers.authorization=`Bearer ${this.session.token}`),{...this.defaults,...e}}};var Ve=C(require("jose"));var we=class{static parse(e){try{return new we(e)}catch{return null}}constructor(e){this.value=e,this._decoded=Ve.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){let o=Date.now(),r=(this.expiration-e)*1e3;return o>=r}async isValid(e,o,r=0){let i=await Ve.importSPKI(e,Oo);try{return await Ve.jwtVerify(this.value,i,{issuer:Uo,audience:o,clockTolerance:r}),!0}catch{return!1}}};var ye=class{constructor(e){this.promise=null;this.fn=e}execute(e){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}};var Kt=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,o){o!==void 0?this._cache[e]=o:this.del(e)}del(e){delete this._cache[e]}},qt=class{get(e){let o=localStorage.getItem(e);return o===null?void 0:JSON.parse(o)}put(e,o){o!==void 0?localStorage.setItem(e,JSON.stringify(o)):this.del(e)}del(e){localStorage.removeItem(e)}};function Pi(){return typeof window<"u"&&window.localStorage?new qt:new Kt}var _=Pi();function Se(t){return new Date(t*1e3)}function Si(t){return t.map(e=>{switch(e.type){case"wallet":return{address:e.address,type:e.type,verifiedAt:Se(e.verified_at),chainType:e.chain_type};case"email":return{address:e.address,type:e.type,verifiedAt:Se(e.verified_at)};case"phone":return{number:e.phoneNumber,type:e.type,verifiedAt:Se(e.verified_at)};case"google_oauth":return{subject:e.subject,email:e.email,name:e.name,type:e.type,verifiedAt:Se(e.verified_at)};case"twitter_oauth":return{subject:e.subject,username:e.username,name:e.name,type:e.type,verifiedAt:Se(e.verified_at)};case"discord_oauth":return{subject:e.subject,username:e.username,email:e.email,type:e.type,verifiedAt:Se(e.verified_at)};default:throw new u("Unrecognized account type")}})}function Ti(t,e){return e.find(o=>o.type==="wallet"&&o.address===t)}function Te(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function Je(t){let e=t.linkedAccounts.map(s=>s.type==="wallet"?s.address:null),r=_.get(ne);if(!r||!e.includes(r)){_.del(ne);let s=Te(t.linkedAccounts,"wallet");s&&(r=s.address,_.put(ne,r))}let i=Ti(r,t.linkedAccounts),n=Object.assign({},t);return n.wallet=i&&{address:i.address,chainType:i.chainType,chainId:i.chainId,walletType:i.walletType},n}function ue(t){if(!t)return null;let e=Si(t.linked_accounts),o=Te(e,"wallet"),r=Te(e,"email"),i=Te(e,"phone"),n=Te(e,"google_oauth"),s=Te(e,"twitter_oauth"),p=Te(e,"discord_oauth"),w={id:t.id,createdAt:Se(t.created_at),linkedAccounts:e,email:r&&{address:r==null?void 0:r.address},phone:i&&{number:i==null?void 0:i.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:p&&{subject:p.subject,username:p.username,email:p.email}};return Je(w)}var Fo=()=>"/api/v1/sessions",Vo=()=>"/api/v1/sessions/logout",Go=()=>"/api/v1/sessions/fork",Ho=()=>"/api/v1/siwe/init",Bo=()=>"/api/v1/siwe/authenticate",zo=()=>"/api/v1/siwe/link",Zo=()=>"/api/v1/passwordless/init",jo=()=>"/api/v1/passwordless/authenticate",$o=()=>"/api/v1/passwordless/link",Ko=()=>"/api/v1/passwordless_sms/init",qo=()=>"/api/v1/passwordless_sms/authenticate",Yo=()=>"/api/v1/passwordless_sms/link",Jo=()=>"/api/v1/oauth/init",Qo=()=>"/api/v1/oauth/authenticate",Xo=()=>"/api/v1/oauth/link",er=()=>"/api/v1/siwe/unlink",tr=()=>"/api/v1/passwordless/unlink",or=()=>"/api/v1/passwordless_sms/unlink",rr=()=>"/api/v1/oauth/unlink";var Ii=30,yt=class{constructor(){this.authenticateOnce=new ye(async e=>this._authenticate(e)),this.linkOnce=new ye(async e=>this._link(e)),this.refreshOnce=new ye(this._refresh.bind(this)),this.destroyOnce=new ye(this._destroy.bind(this)),this.forkSessionOnce=new ye(this._forkSession.bind(this))}get token(){try{let e=_.get(Fe);return typeof e=="string"?new we(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=_.get(mt);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let e=we.parse(this.token);return e!==null&&!e.isExpired(Ii)}async hasValidToken(e,o,r=0){let i=we.parse(this.token);return i!==null&&await i.isValid(e,o,r)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:i,is_new_user:n}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:ue(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),K(o)}}async _link(e){try{let o=await e.link();return ue(o)}catch(o){throw console.warn("Error linking account"),K(o)}}async _refresh(){if(!this.api)throw new u("Session has no API instance");let e=this.token,o=this.refreshToken;if(!e||!o)return null;try{let r=await this.api.post(Fo(),{refresh_token:o});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),ue(r.data.user)}catch(r){throw K(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Vo(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new u("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(Go(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw K(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null),_.del(ne)}storeToken(e){typeof e=="string"?_.put(Fe,e):_.del(Fe)}storeRefreshToken(e){typeof e=="string"?_.put(mt,e):_.del(mt)}};var sr=require("@ethersproject/address"),Qt=C(require("@walletconnect/web3-provider"));var ir=require("@ethersproject/logger");var Ge=class extends ${constructor(){super("Wallet timeout");this.type="wallet_error"}},Ct=t=>{if(t instanceof $)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new He(t);return t.code===ir.ErrorCode.ACTION_REJECTED&&(e.details=Ie.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new He(t):new $("Unknown connector error",t)},Yt=class extends Q{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},He=class extends Yt{constructor(o){var n,s,p;let r=o;super(r.message,r.code,r.data);let i=Object.values(Ie).find(w=>w.eipCode===r.code);this.details=i||Ie.UNKNOWN_ERROR,r.code===-32002&&((n=r.message)!=null&&n.includes("already pending for origin")?(s=r.message)!=null&&s.includes("wallet_requestPermissions")?this.details=Ie.E32002_CONNECTION_ALREADY_PENDING:this.details=Ie.E32002_REQUEST_ALREADY_PENDING:(p=r.message)!=null&&p.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=Ie.E32002_WALLET_LOCKED))}},Ri={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_NOT_ALLOWED:{message:"You don\u2019t have access to this app",detail:"Try with a different address?",retryable:!0}},Mi={E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:"Connection request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:"Resource request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:"Wallet might be locked",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}},Wi={E4001_DEFAULT_USER_REJECTED_REQUEST:{eipCode:4001,message:"User Rejected Request",detail:"The user rejected the request.",default:!0,retryable:!0},E4100_DEFAULT_UNAUTHORIZED:{eipCode:4100,message:"Unauthorized",detail:"The requested method and/or account has not been authorized by the user.",default:!0,retryable:!1},E4200_DEFAULT_UNSUPPORTED_METHOD:{eipCode:4200,message:"Unsupported Method",detail:"The Provider does not support the requested method.",default:!0,retryable:!1},E4900_DEFAULT_DISCONNECTED:{eipCode:4900,message:"Disconnected",detail:"The Provider is disconnected from all chains.",default:!0,retryable:!0},E4901_DEFAULT_CHAIN_DISCONNECTED:{eipCode:4901,message:"Chain Disconnected",detail:"The Provider is not connected to the requested chain.",default:!0,retryable:!0},E32700_DEFAULT_PARSE_ERROR:{eipCode:-32700,message:"Parse error",detail:"Invalid JSON",default:!0,retryable:!1},E32600_DEFAULT_INVALID_REQUEST:{eipCode:-32600,message:"Invalid request",detail:"JSON is not a valid request object",default:!0,retryable:!1},E32601_DEFAULT_METHOD_NOT_FOUND:{eipCode:-32601,message:"Method not found",detail:"Method does not exist",default:!0,retryable:!1},E32602_DEFAULT_INVALID_PARAMS:{eipCode:-32602,message:"Invalid params",detail:"Invalid method parameters",default:!0,retryable:!1},E32603_DEFAULT_INTERNAL_ERROR:{eipCode:-32603,message:"Internal error",detail:"Internal JSON-RPC error",default:!0,retryable:!0},E32000_DEFAULT_INVALID_INPUT:{eipCode:-32e3,message:"Invalid input",detail:"Missing or invalid parameters",default:!0,retryable:!1},E32001_DEFAULT_RESOURCE_NOT_FOUND:{eipCode:-32001,message:"Resource not found",detail:"Requested resource not found",default:!0,retryable:!1},E32002_DEFAULT_RESOURCE_UNAVAILABLE:{eipCode:-32002,message:"Resource unavailable",detail:"Requested resource not available",default:!0,retryable:!0},E32003_DEFAULT_TRANSACTION_REJECTED:{eipCode:-32003,message:"Transaction rejected",detail:"Transaction creation failed",default:!0,retryable:!0},E32004_DEFAULT_METHOD_NOT_SUPPORTED:{eipCode:-32004,message:"Method not supported",detail:"Method is not implemented",default:!0,retryable:!1},E32005_DEFAULT_LIMIT_EXCEEDED:{eipCode:-32005,message:"Limit exceeded",detail:"Request exceeds defined limit",default:!0,retryable:!1},E32006_DEFAULT_JSON_RPC_VERSION_NOT_SUPPORTED:{eipCode:-32006,message:"JSON-RPC version not supported",detail:"Version of JSON-RPC protocol is not supported",default:!0,retryable:!1}},Ie={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...Wi,...Mi},Qe={...Ri,...Ie};var Ni=12e4,Jt=(t=new Ge,e=Ni)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),Ce=class{constructor(e){this.removeListener=(e,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(e,o)};this.setProvider=e=>{this.walletProvider=e,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=e,this._subscriptions=[]}on(e,o){if(this.walletProvider)return this.walletProvider.on(e,o);this._subscriptions.push({eventName:e,listener:o})}request(e){if(!this.walletProvider)throw new $(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),Jt()]).catch(o=>{throw Ct(o)})}},ve=class extends Ce{constructor(o){super(o)}},vt=class extends Ce{constructor(e){super(e)}sendAsync(e,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};var ar=require("@ethersproject/providers");var nr=["metamask","coinbase_wallet","wallet_connect"];var lr=C(require("@coinbase/wallet-sdk")),Oi=()=>{let t=`https://mainnet.infura.io/v3/${ut}`,e=1;return new lr.default({appName:"Privy",darkMode:!1,headlessMode:!1}).makeWeb3Provider(t,e)},Xt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isMetaMask)return!0}return!1},bt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isCoinbaseWallet)return!0}return!1},Be=class{constructor(){this.walletType=null;this.getEthereumProvider=()=>this.ethProvider;this.createSiweMessage=(e,o,r,i,n,s,p)=>`${r} wants you to sign in with your Ethereum account:
1
+ "use strict";var vi=Object.create;var ct=Object.defineProperty;var bi=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Li=Object.getPrototypeOf,Ei=Object.prototype.hasOwnProperty;var Ai=(t,e)=>{for(var o in e)ct(t,o,{get:e[o],enumerable:!0})},So=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xi(e))!Ei.call(t,i)&&i!==o&&ct(t,i,{get:()=>e[i],enumerable:!(r=bi(e,i))||r.enumerable});return t};var C=(t,e,o)=>(o=t!=null?vi(Li(t)):{},So(e||!t||!t.__esModule?ct(o,"default",{value:t,enumerable:!0}):o,t)),ki=t=>So(ct({},"__esModule",{value:!0}),t);var Yn={};Ai(Yn,{AsExternalProvider:()=>ve,PrivyClient:()=>ze,PrivyConnector:()=>Be,PrivyProvider:()=>yi,PrivyProxyProvider:()=>Ce,VERSION:()=>ht,getAccessToken:()=>wi,usePrivy:()=>O});module.exports=ki(Yn);var z=require("react");var gt=C(require("axios"));var To=C(require("axios")),Q=class extends Error{constructor(o,r){super(o);r instanceof Error&&(this.cause=r)}toString(){return`${this.type}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},pt=class extends Q{constructor(o,r,i,n){super(i,n);this.type=o;this.status=r}},u=class extends Q{constructor(o,r){super(o,r);this.type="client_error"}};var $=class extends Q{constructor(o,r){super(o,r);this.type="connector_error"}},N=t=>{if(t instanceof Q)return t;if(!To.default.isAxiosError(t))return K(t);if(!t.response)return new pt("api_error",null,t.message,t);let{type:e,message:o,error:r}=t.response.data;return new pt(e||"ApiError",t.response.status,o||r,t)},K=t=>t instanceof Q?t:t instanceof Error?new u(t.message,t):new u(`Internal error: ${t}`);var Io="1.12.0-beta.6";var Ro="https://api.privy.io/v0",Mo=process.env.NEXT_PUBLIC_PRIVY_AUTH_URL||"https://auth.privy.io",ut="4df5e2316331463a9130964bd6078dfa",Wo=1e4,De=1400,No=365*24*60*60,ht=Io,Oo="ES256",Uo="privy.io",Fe="privy:token",mt="privy:refresh_token",ne="privy:active_wallet",ft="privy:wallet_type",Do="walletconnect";var wt=class{constructor(e,o,r){this.appId=e,this.sdkVersion=ht,this.session=o,this.defaults=r}async get(e,o){try{return await gt.default.get(e,this.buildConfig({headers:{"Cache-Control":"no-cache"},...o}))}catch(r){throw N(r)}}async post(e,o,r){try{return await gt.default.post(e,o,this.buildConfig(r))}catch(i){throw N(i)}}async delete(e,o){try{return await gt.default.delete(e,this.buildConfig(o))}catch(r){throw N(r)}}buildConfig(e){return e=e||{},e.headers=e.headers||{},e.headers["privy-app-id"]=this.appId,e.headers["privy-client"]=`react-auth:${this.sdkVersion}`,this.session.token!==null&&(e.headers.authorization=`Bearer ${this.session.token}`),{...this.defaults,...e}}};var Ve=C(require("jose"));var we=class{static parse(e){try{return new we(e)}catch{return null}}constructor(e){this.value=e,this._decoded=Ve.decodeJwt(e)}get subject(){return this._decoded.sub}get expiration(){return this._decoded.exp}get issuer(){return this._decoded.iss}get audience(){return this._decoded.aud}isExpired(e=0){let o=Date.now(),r=(this.expiration-e)*1e3;return o>=r}async isValid(e,o,r=0){let i=await Ve.importSPKI(e,Oo);try{return await Ve.jwtVerify(this.value,i,{issuer:Uo,audience:o,clockTolerance:r}),!0}catch{return!1}}};var ye=class{constructor(e){this.promise=null;this.fn=e}execute(e){return this.promise===null&&(this.promise=(async()=>{try{return await this.fn(e)}finally{this.promise=null}})()),this.promise}};var Kt=class{constructor(){this._cache={}}get(e){return this._cache[e]}put(e,o){o!==void 0?this._cache[e]=o:this.del(e)}del(e){delete this._cache[e]}},qt=class{get(e){let o=localStorage.getItem(e);return o===null?void 0:JSON.parse(o)}put(e,o){o!==void 0?localStorage.setItem(e,JSON.stringify(o)):this.del(e)}del(e){localStorage.removeItem(e)}};function Pi(){return typeof window<"u"&&window.localStorage?new qt:new Kt}var _=Pi();function Se(t){return new Date(t*1e3)}function Si(t){return t.map(e=>{switch(e.type){case"wallet":return{address:e.address,type:e.type,verifiedAt:Se(e.verified_at),chainType:e.chain_type};case"email":return{address:e.address,type:e.type,verifiedAt:Se(e.verified_at)};case"phone":return{number:e.phoneNumber,type:e.type,verifiedAt:Se(e.verified_at)};case"google_oauth":return{subject:e.subject,email:e.email,name:e.name,type:e.type,verifiedAt:Se(e.verified_at)};case"twitter_oauth":return{subject:e.subject,username:e.username,name:e.name,type:e.type,verifiedAt:Se(e.verified_at)};case"discord_oauth":return{subject:e.subject,username:e.username,email:e.email,type:e.type,verifiedAt:Se(e.verified_at)};default:throw new u("Unrecognized account type")}})}function Ti(t,e){return e.find(o=>o.type==="wallet"&&o.address===t)}function Te(t,e){return t.sort((o,r)=>r.verifiedAt.getTime()-o.verifiedAt.getTime()),t.find(o=>o.type===e)}function Je(t){let e=t.linkedAccounts.map(s=>s.type==="wallet"?s.address:null),r=_.get(ne);if(!r||!e.includes(r)){_.del(ne);let s=Te(t.linkedAccounts,"wallet");s&&(r=s.address,_.put(ne,r))}let i=Ti(r,t.linkedAccounts),n=Object.assign({},t);return n.wallet=i&&{address:i.address,chainType:i.chainType,chainId:i.chainId,walletType:i.walletType},n}function ue(t){if(!t)return null;let e=Si(t.linked_accounts),o=Te(e,"wallet"),r=Te(e,"email"),i=Te(e,"phone"),n=Te(e,"google_oauth"),s=Te(e,"twitter_oauth"),p=Te(e,"discord_oauth"),w={id:t.id,createdAt:Se(t.created_at),linkedAccounts:e,email:r&&{address:r==null?void 0:r.address},phone:i&&{number:i==null?void 0:i.number},wallet:o&&{address:o.address,chainType:o.chainType,chainId:o.chainId,walletType:o.walletType},google:n&&{subject:n.subject,email:n.email,name:n.name},twitter:s&&{subject:s.subject,username:s.username,name:s.name},discord:p&&{subject:p.subject,username:p.username,email:p.email}};return Je(w)}var Fo=()=>"/api/v1/sessions",Vo=()=>"/api/v1/sessions/logout",Go=()=>"/api/v1/sessions/fork",Ho=()=>"/api/v1/siwe/init",Bo=()=>"/api/v1/siwe/authenticate",zo=()=>"/api/v1/siwe/link",Zo=()=>"/api/v1/passwordless/init",jo=()=>"/api/v1/passwordless/authenticate",$o=()=>"/api/v1/passwordless/link",Ko=()=>"/api/v1/passwordless_sms/init",qo=()=>"/api/v1/passwordless_sms/authenticate",Yo=()=>"/api/v1/passwordless_sms/link",Jo=()=>"/api/v1/oauth/init",Qo=()=>"/api/v1/oauth/authenticate",Xo=()=>"/api/v1/oauth/link",er=()=>"/api/v1/siwe/unlink",tr=()=>"/api/v1/passwordless/unlink",or=()=>"/api/v1/passwordless_sms/unlink",rr=()=>"/api/v1/oauth/unlink";var Ii=30,yt=class{constructor(){this.authenticateOnce=new ye(async e=>this._authenticate(e)),this.linkOnce=new ye(async e=>this._link(e)),this.refreshOnce=new ye(this._refresh.bind(this)),this.destroyOnce=new ye(this._destroy.bind(this)),this.forkSessionOnce=new ye(this._forkSession.bind(this))}get token(){try{let e=_.get(Fe);return typeof e=="string"?new we(e).value:null}catch(e){return console.error(e),this.destroyLocalState(),null}}get refreshToken(){try{let e=_.get(mt);return typeof e=="string"?e:null}catch(e){return console.error(e),this.destroyLocalState(),null}}hasRefreshCredentials(){return typeof this.token=="string"&&typeof this.refreshToken=="string"}hasActiveToken(){let e=we.parse(this.token);return e!==null&&!e.isExpired(Ii)}async hasValidToken(e,o,r=0){let i=we.parse(this.token);return i!==null&&await i.isValid(e,o,r)}authenticate(e){return this.authenticateOnce.execute(e)}link(e){return this.linkOnce.execute(e)}refresh(){return this.refreshOnce.execute()}forkSession(){return this.forkSessionOnce.execute()}destroy(){return this.destroyOnce.execute()}async _authenticate(e){try{let{token:o,refresh_token:r,user:i,is_new_user:n}=await e.authenticate();return this.storeToken(o),this.storeRefreshToken(r),{user:ue(i),isNewUser:n}}catch(o){throw console.warn("Error authenticating session"),K(o)}}async _link(e){try{let o=await e.link();return ue(o)}catch(o){throw console.warn("Error linking account"),K(o)}}async _refresh(){if(!this.api)throw new u("Session has no API instance");let e=this.token,o=this.refreshToken;if(!e||!o)return null;try{let r=await this.api.post(Fo(),{refresh_token:o});return this.storeToken(r.data.token),this.storeRefreshToken(r.data.refresh_token),ue(r.data.user)}catch(r){throw K(r)}}async _destroy(){var e;try{await((e=this.api)==null?void 0:e.post(Vo(),{refresh_token:this.refreshToken}))}catch{console.warn("Error destroying session")}this.destroyLocalState()}async _forkSession(){if(!this.api)throw new u("Session has no API instance");let e=this.refreshToken;try{let o=await this.api.post(Go(),{refresh_token:e});return this.storeToken(o.data.token),this.storeRefreshToken(o.data.refresh_token),o.data.new_session_refresh_token}catch(o){throw K(o)}}destroyLocalState(){this.storeToken(null),this.storeRefreshToken(null),_.del(ne)}storeToken(e){typeof e=="string"?_.put(Fe,e):_.del(Fe)}storeRefreshToken(e){typeof e=="string"?_.put(mt,e):_.del(mt)}};var sr=require("@ethersproject/address"),Qt=C(require("@walletconnect/web3-provider"));var ir=require("@ethersproject/logger");var Ge=class extends ${constructor(){super("Wallet timeout");this.type="wallet_error"}},Ct=t=>{if(t instanceof $)return t;if((t==null?void 0:t.code)&&(t==null?void 0:t.reason)){let e=new He(t);return t.code===ir.ErrorCode.ACTION_REJECTED&&(e.details=Ie.E4001_USER_REJECTED_REQUEST),e}return t!=null&&t.code?new He(t):new $("Unknown connector error",t)},Yt=class extends Q{constructor(o,r,i){super(o);this.type="provider_error";this.code=r,this.data=i}},He=class extends Yt{constructor(o){var n,s,p;let r=o;super(r.message,r.code,r.data);let i=Object.values(Ie).find(w=>w.eipCode===r.code);this.details=i||Ie.UNKNOWN_ERROR,r.code===-32002&&((n=r.message)!=null&&n.includes("already pending for origin")?(s=r.message)!=null&&s.includes("wallet_requestPermissions")?this.details=Ie.E32002_CONNECTION_ALREADY_PENDING:this.details=Ie.E32002_REQUEST_ALREADY_PENDING:(p=r.message)!=null&&p.includes("Already processing")&&r.message.includes("eth_requestAccounts")&&(this.details=Ie.E32002_WALLET_LOCKED))}},Ri={ERROR_USER_EXISTS:{message:"User already exists for this address",detail:"Try another address!",retryable:!1},ERROR_TIMED_OUT:{message:"Wallet request timed out",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_CONNECTION:{message:"Could not log in with wallet",detail:"Please try connecting again.",retryable:!0},ERROR_WALLET_NOT_ALLOWED:{message:"You don\u2019t have access to this app",detail:"Try with a different address?",retryable:!0}},Mi={E32002_CONNECTION_ALREADY_PENDING:{eipCode:-32002,message:"Connection request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_REQUEST_ALREADY_PENDING:{eipCode:-32002,message:"Resource request already pending",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E32002_WALLET_LOCKED:{eipCode:-32002,message:"Wallet might be locked",detail:"Don\u2019t see your wallet modal? Check your other browser windows.",retryable:!1},E4001_USER_REJECTED_REQUEST:{eipCode:4001,message:"Signature rejected",detail:"Please try signing again.",retryable:!0}},Wi={E4001_DEFAULT_USER_REJECTED_REQUEST:{eipCode:4001,message:"User Rejected Request",detail:"The user rejected the request.",default:!0,retryable:!0},E4100_DEFAULT_UNAUTHORIZED:{eipCode:4100,message:"Unauthorized",detail:"The requested method and/or account has not been authorized by the user.",default:!0,retryable:!1},E4200_DEFAULT_UNSUPPORTED_METHOD:{eipCode:4200,message:"Unsupported Method",detail:"The Provider does not support the requested method.",default:!0,retryable:!1},E4900_DEFAULT_DISCONNECTED:{eipCode:4900,message:"Disconnected",detail:"The Provider is disconnected from all chains.",default:!0,retryable:!0},E4901_DEFAULT_CHAIN_DISCONNECTED:{eipCode:4901,message:"Chain Disconnected",detail:"The Provider is not connected to the requested chain.",default:!0,retryable:!0},E32700_DEFAULT_PARSE_ERROR:{eipCode:-32700,message:"Parse error",detail:"Invalid JSON",default:!0,retryable:!1},E32600_DEFAULT_INVALID_REQUEST:{eipCode:-32600,message:"Invalid request",detail:"JSON is not a valid request object",default:!0,retryable:!1},E32601_DEFAULT_METHOD_NOT_FOUND:{eipCode:-32601,message:"Method not found",detail:"Method does not exist",default:!0,retryable:!1},E32602_DEFAULT_INVALID_PARAMS:{eipCode:-32602,message:"Invalid params",detail:"Invalid method parameters",default:!0,retryable:!1},E32603_DEFAULT_INTERNAL_ERROR:{eipCode:-32603,message:"Internal error",detail:"Internal JSON-RPC error",default:!0,retryable:!0},E32000_DEFAULT_INVALID_INPUT:{eipCode:-32e3,message:"Invalid input",detail:"Missing or invalid parameters",default:!0,retryable:!1},E32001_DEFAULT_RESOURCE_NOT_FOUND:{eipCode:-32001,message:"Resource not found",detail:"Requested resource not found",default:!0,retryable:!1},E32002_DEFAULT_RESOURCE_UNAVAILABLE:{eipCode:-32002,message:"Resource unavailable",detail:"Requested resource not available",default:!0,retryable:!0},E32003_DEFAULT_TRANSACTION_REJECTED:{eipCode:-32003,message:"Transaction rejected",detail:"Transaction creation failed",default:!0,retryable:!0},E32004_DEFAULT_METHOD_NOT_SUPPORTED:{eipCode:-32004,message:"Method not supported",detail:"Method is not implemented",default:!0,retryable:!1},E32005_DEFAULT_LIMIT_EXCEEDED:{eipCode:-32005,message:"Limit exceeded",detail:"Request exceeds defined limit",default:!0,retryable:!1},E32006_DEFAULT_JSON_RPC_VERSION_NOT_SUPPORTED:{eipCode:-32006,message:"JSON-RPC version not supported",detail:"Version of JSON-RPC protocol is not supported",default:!0,retryable:!1}},Ie={UNKNOWN_ERROR:{eipCode:0,message:"Unknown error",detail:"Unknown error",retryable:!0},...Wi,...Mi},Qe={...Ri,...Ie};var Ni=12e4,Jt=(t=new Ge,e=Ni)=>new Promise((o,r)=>setTimeout(()=>{r(t)},e)),Ce=class{constructor(e){this.removeListener=(e,o)=>{if(this.walletProvider)return this.walletProvider.removeListener(e,o)};this.setProvider=e=>{this.walletProvider=e,this._subscriptions.forEach(o=>{var r;(r=this.walletProvider)==null||r.on(o.eventName,o.listener)})};this.walletProvider=e,this._subscriptions=[]}on(e,o){if(this.walletProvider)return this.walletProvider.on(e,o);this._subscriptions.push({eventName:e,listener:o})}request(e){if(!this.walletProvider)throw new $(`A wallet request of type ${e.method} was made before setting a wallet provider.`);return Promise.race([this.walletProvider.request(e),Jt()]).catch(o=>{throw Ct(o)})}},ve=class extends Ce{constructor(o){super(o)}},vt=class extends Ce{constructor(e){super(e)}sendAsync(e,o){throw new Error("sendAsync is no longer supported by EIP-1193. Use the request method instead.")}};var ar=require("@ethersproject/providers");var nr=["metamask","coinbase_wallet","wallet_connect"];var lr=C(require("@coinbase/wallet-sdk")),Oi=()=>{let t=`https://mainnet.infura.io/v3/${ut}`,e=1;return new lr.default({appName:"Privy",darkMode:!1,headlessMode:!1}).makeWeb3Provider(t,e)},Xt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isMetaMask)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isMetaMask)return!0}return!1},bt=()=>{if(!window.ethereum)return!1;if(window.ethereum.isCoinbaseWallet)return!0;if(window.ethereum.providers){for(let t of window.ethereum.providers)if(t.isCoinbaseWallet)return!0}return!1},Be=class{constructor(){this.walletType=null;this.getEthereumProvider=()=>this.ethProvider;this.createSiweMessage=(e,o,r,i,n,s,p)=>`${r} wants you to sign in with your Ethereum account:
2
2
  ${o}
3
3
 
4
4
  ${p}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@privy-io/react-auth",
3
- "version": "1.12.0-beta.5",
3
+ "version": "1.12.0-beta.6",
4
4
  "description": "React client for the Privy Auth API",
5
5
  "keywords": [
6
6
  "authentication",
@@ -18,13 +18,13 @@
18
18
  },
19
19
  "license": "Apache-2.0",
20
20
  "main": "./dist/index.js",
21
- "module": "./dist/index.js",
21
+ "module": "./dist/esm/index.js",
22
22
  "types": "./dist/index.d.ts",
23
23
  "typings": "./dist/index",
24
24
  "exports": {
25
25
  ".": {
26
- "import": "./dist/index.js",
27
- "require": "./dist/index.cjs",
26
+ "require": "./dist/index.js",
27
+ "import": "./dist/esm/index.js",
28
28
  "types": "./dist/index.d.ts"
29
29
  }
30
30
  },