@privy-io/js-sdk-core 0.52.3 → 0.52.4

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 +1 @@
1
- "use strict";var e=require("fetch-retry"),t=require("uuid"),s=require("@privy-io/api-base"),i=require("@privy-io/public-api"),r=require("../Error.js"),a=require("../Session.js"),n=require("../toAbortSignalTimeout.js"),o=require("../utils/toSearchParams.js"),h=require("./logger.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("eventemitter3"),require("jose"),require("js-cookie"),require("../Token.js"),require("../utils/allSettled.js"),require("../utils/noop.js");var c=/*#__PURE__*/l(e);let g="privy:caid";exports.PrivyInternal=class{setCallbacks(e){this.callbacks={...this.callbacks,...e}}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady)this.callbacks?.setIsReady?.(!0);else{if(!await this.isStorageAccessible())throw new r.PrivyClientError({code:"storage_error",error:"Unable to access storage"});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:s}){return`${this.baseUrl}${i.getPathWithParams(e.path,t)}${o.toSearchParams(s)}`}async fetch(e,{body:t,params:s,query:i,headers:a,onRequest:n=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:s,query:i}),{method:e.method,body:JSON.stringify(t),headers:a}),h=await n(o),l=await this._fetch(o,h),c=await l.json();if(l.status>299)throw new r.PrivyApiError(c);return c}async _beforeRequestWithoutInitialize(e){let t=await this.session.getToken(),s=new Headers(e.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),t&&s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");let i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:n.default(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequest(e){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(i.AppConfig,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(g);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error("Unable to load clientId",e)}try{this._analyticsId=t.v4()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;try{await this._storage.put(g,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(g)}catch(e){this.logger.error("Unable to delete clientId",e)}}async createAnalyticsEvent(e,t){try{await this.fetch(i.AnalyticsEvent,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(e){}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new r.PrivyClientError({code:"storage_error",error:"Unable to access storage"});let t=await this.session.getRefreshToken()??void 0,s=t??"key",i=this._cache.get(s);if(i)return this.logger.debug("[privy:refresh] found in-flight session refresh request, deduping"),await i;let a=this._refreshSession(t,e);this._cache.set(s,a);try{return await a}finally{this._cache.delete(s)}}async _refreshSession(e,t){let a=await this.session.getToken();if(!this.session.hasRefreshCredentials(a,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new r.PrivyApiError({code:s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{this.logger.debug(`[privy:refresh] fetching: ${i.RefreshSession.path}`);let s=await this.fetch(i.RefreshSession,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),r=s.session_update_action;return this.logger.debug(`[privy:refresh] response: ${r}`),t||this.callbacks?.setUser?.(s.user),"set"===r&&(await this.session.updateWithTokensResponse(s),this.logger.debug("[privy:refresh] tokens stored")),"clear"===r&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),t||this.callbacks?.setUser?.(null)),"ignore"===r&&s.token&&(await this.session.storeToken(s.token),this.logger.debug("[privy:refresh] access token stored"),s.identity_token&&(this.logger.debug("[privy:refresh] identity token stored"),await this.session.storeIdentityToken(s.identity_token))),this.logger.debug("[privy:refresh] returning response"),s}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof r.PrivyApiError&&e.code===s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),t||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getToken();return t.token||this.logger.debug("[privy:getAccessToken] expected token received null"),t.token===e&&this.logger.debug("[privy:getAccessToken] expected new token in response received existing"),s===e&&this.logger.debug("[privy:getAccessToken] expected new token in storage received existing"),t.token??s}return e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${t.v4()}`,s="blobby";await this._storage.put(e,s);let i=await this._storage.get(e);return await this._storage.del(e),i===s}catch(e){return this.logger.error(e),!1}}constructor(e){this._sdkVersion="js-sdk-core:0.52.3",this._cache=new Map,this.logger=h.toConsoleLogger({level:e.logLevel??"ERROR"}),this._storage=e.storage,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=e.baseUrl??"https://auth.privy.io",this.appId=e.appId,this.appClientId=e.appClientId,this._sdkVersion=e.sdkVersion??this._sdkVersion,this.callbacks=e.callbacks,this.nativeAppIdentifier=e.nativeAppIdentifier,this.session=new a.Session({storage:this._storage,isUsingServerCookies:!1,appId:e.appId}),this._fetch=c.default(globalThis.fetch,{retries:3,retryDelay:e=>3**e*500,retryOn:[408,409,425,500,502,503,504]}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}};
1
+ "use strict";var e=require("fetch-retry"),t=require("uuid"),s=require("@privy-io/api-base"),i=require("@privy-io/public-api"),r=require("../Error.js"),a=require("../Session.js"),n=require("../toAbortSignalTimeout.js"),o=require("../utils/toSearchParams.js"),h=require("./logger.js");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("eventemitter3"),require("jose"),require("js-cookie"),require("../Token.js"),require("../utils/allSettled.js"),require("../utils/noop.js");var c=/*#__PURE__*/l(e);let g="privy:caid";exports.PrivyInternal=class{setCallbacks(e){this.callbacks={...this.callbacks,...e}}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady)this.callbacks?.setIsReady?.(!0);else{if(!await this.isStorageAccessible())throw new r.PrivyClientError({code:"storage_error",error:"Unable to access storage"});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:s}){return`${this.baseUrl}${i.getPathWithParams(e.path,t)}${o.toSearchParams(s)}`}async fetch(e,{body:t,params:s,query:i,headers:a,onRequest:n=this._beforeRequest.bind(this)}){let o=new Request(this.getPath(e,{params:s,query:i}),{method:e.method,body:JSON.stringify(t),headers:a}),h=await n(o),l=await this._fetch(o,h),c=await l.json();if(l.status>299)throw new r.PrivyApiError(c);return c}async _beforeRequestWithoutInitialize(e){let t=await this.session.getToken(),s=new Headers(e.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),t&&s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");let i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:n.default(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequest(e){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(i.AppConfig,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(g);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error("Unable to load clientId",e)}try{this._analyticsId=t.v4()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;try{await this._storage.put(g,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(g)}catch(e){this.logger.error("Unable to delete clientId",e)}}async createAnalyticsEvent(e,t){try{await this.fetch(i.AnalyticsEvent,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(e){}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new r.PrivyClientError({code:"storage_error",error:"Unable to access storage"});let t=await this.session.getRefreshToken()??void 0,s=t??"key",i=this._cache.get(s);if(i)return this.logger.debug("[privy:refresh] found in-flight session refresh request, deduping"),await i;let a=this._refreshSession(t,e);this._cache.set(s,a);try{return await a}finally{this._cache.delete(s)}}async _refreshSession(e,t){let a=await this.session.getToken();if(!this.session.hasRefreshCredentials(a,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new r.PrivyApiError({code:s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{this.logger.debug(`[privy:refresh] fetching: ${i.RefreshSession.path}`);let s=await this.fetch(i.RefreshSession,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),r=s.session_update_action;return this.logger.debug(`[privy:refresh] response: ${r}`),t||this.callbacks?.setUser?.(s.user),"set"===r&&(await this.session.updateWithTokensResponse(s),this.logger.debug("[privy:refresh] tokens stored")),"clear"===r&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),t||this.callbacks?.setUser?.(null)),"ignore"===r&&s.token&&(await this.session.storeToken(s.token),this.logger.debug("[privy:refresh] access token stored"),s.identity_token&&(this.logger.debug("[privy:refresh] identity token stored"),await this.session.storeIdentityToken(s.identity_token))),this.logger.debug("[privy:refresh] returning response"),s}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof r.PrivyApiError&&e.code===s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),t||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getToken();return t.token||this.logger.debug("[privy:getAccessToken] expected token received null"),t.token===e&&this.logger.debug("[privy:getAccessToken] expected new token in response received existing"),s===e&&this.logger.debug("[privy:getAccessToken] expected new token in storage received existing"),t.token??s}return e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${t.v4()}`,s="blobby";await this._storage.put(e,s);let i=await this._storage.get(e);return await this._storage.del(e),i===s}catch(e){return this.logger.error(e),!1}}constructor(e){this._sdkVersion="js-sdk-core:0.52.4",this._cache=new Map,this.logger=h.toConsoleLogger({level:e.logLevel??"ERROR"}),this._storage=e.storage,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=e.baseUrl??"https://auth.privy.io",this.appId=e.appId,this.appClientId=e.appClientId,this._sdkVersion=e.sdkVersion??this._sdkVersion,this.callbacks=e.callbacks,this.nativeAppIdentifier=e.nativeAppIdentifier,this.session=new a.Session({storage:this._storage,isUsingServerCookies:!1,appId:e.appId}),this._fetch=c.default(globalThis.fetch,{retries:3,retryDelay:e=>3**e*500,retryOn:[408,409,425,500,502,503,504]}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}};
@@ -1 +1 @@
1
- "use strict";var e=require("../../action/delegatedActions/utils.js"),t=require("../../wallet-api/get-wallet.js"),r=require("../../wallet-api/unified-wallet.js"),a=require("../../wallet-api/update-wallet.js");async function i(e){let{user:t}=await e.user.get();if(!t)throw Error("Could not refresh user");return{user:t}}function s(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}require("../../utils/getAllUserEmbeddedEthereumWallets.js"),require("../../utils/getAllUserEmbeddedSolanaWallets.js"),require("../../utils/getUserEmbeddedEthereumWallet.js"),require("../../utils/getUserEmbeddedSolanaWallet.js"),require("@privy-io/public-api"),require("../../wallet-api/generate-authorization-signature.js"),require("canonicalize"),require("../../Error.js"),exports.addSessionSigners=async function({client:l,wallet:d,signers:n}){if("ethereum"!==d.chain_type&&"solana"!==d.chain_type)throw Error("Session signers are only supported for Ethereum and Solana wallets");if(r.isUnifiedWallet(d)){if(0===n.length)throw Error("Must specify at least one signer to add.");let e={wallet_id:d.id},r=await t.getWallet(l,e);await a.updateWallet(l,e,s(l),{additional_signers:r.additional_signers.concat(n)})}else{if(d.delegated)return i(l);if(n.length>0)throw Error("addSessionSigners is only supported for TEE execution and this app uses On-device execution. Use the useHeadlessDelegatedActions hook to manage server side access on behalf of your users. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let{user:t}=await l.user.get(),r=e.getRootWalletForDelegation(d,t);if(!r)throw Error("Unable to determine root address for delegated address.");await l.embeddedWallet.delegateWallets({rootWallet:{address:r.address,chainType:r.chain_type,imported:r.imported},delegatedWallets:[{address:d.address,chainType:d.chain_type,walletIndex:d.wallet_index}]})}return i(l)},exports.removeSessionSigners=async function({client:e,wallet:t}){if(r.isUnifiedWallet(t)){let r={wallet_id:t.id};await a.updateWallet(e,r,s(e),{additional_signers:[]})}else await e.delegated.revoke();return i(e)};
1
+ "use strict";var e=require("../../action/delegatedActions/utils.js"),t=require("../../wallet-api/get-wallet.js"),r=require("../../wallet-api/unified-wallet.js"),i=require("../../wallet-api/update-wallet.js");async function a(e){let{user:t}=await e.user.get();if(!t)throw Error("Could not refresh user");return{user:t}}function l(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}require("../../utils/getAllUserEmbeddedEthereumWallets.js"),require("../../utils/getAllUserEmbeddedSolanaWallets.js"),require("../../utils/getUserEmbeddedEthereumWallet.js"),require("../../utils/getUserEmbeddedSolanaWallet.js"),require("@privy-io/public-api"),require("../../wallet-api/generate-authorization-signature.js"),require("canonicalize"),require("../../Error.js"),exports.addSessionSigners=async function({client:s,wallet:n,signers:d}){if("ethereum"!==n.chain_type&&"solana"!==n.chain_type)throw Error("Session signers are only supported for Ethereum and Solana wallets");if(r.isUnifiedWallet(n)){if(0===d.length)throw Error("Must specify at least one signer to add.");let e={wallet_id:n.id},r=await t.getWallet(s,e);await i.updateWallet(s,e,l(s),{additional_signers:r.additional_signers.concat(d)})}else{if(n.delegated)return a(s);if(d.length>0)throw Error("Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let{user:t}=await s.user.get(),r=e.getRootWalletForDelegation(n,t);if(!r)throw Error("Unable to determine root address for delegated address.");await s.embeddedWallet.delegateWallets({rootWallet:{address:r.address,chainType:r.chain_type,imported:r.imported},delegatedWallets:[{address:n.address,chainType:n.chain_type,walletIndex:n.wallet_index}]})}return a(s)},exports.removeSessionSigners=async function({client:e,wallet:t}){if(r.isUnifiedWallet(t)){let r={wallet_id:t.id};await i.updateWallet(e,r,l(e),{additional_signers:[]})}else await e.delegated.revoke();return a(e)};
@@ -7487,7 +7487,7 @@ type Cluster = 'devnet' | 'testnet' | 'mainnet-beta';
7487
7487
  type SolanaCluster = {
7488
7488
  /**
7489
7489
  * The network name
7490
- * Refer to {@link https://solana-labs.github.io/solana-web3.js/types/Cluster.html Cluster} for more information
7490
+ * Refer to {@link https://solana-foundation.github.io/solana-web3.js/types/Cluster.html Cluster} for more information
7491
7491
  * */
7492
7492
  name: Cluster;
7493
7493
  /** The RPC endpoint */
@@ -7487,7 +7487,7 @@ type Cluster = 'devnet' | 'testnet' | 'mainnet-beta';
7487
7487
  type SolanaCluster = {
7488
7488
  /**
7489
7489
  * The network name
7490
- * Refer to {@link https://solana-labs.github.io/solana-web3.js/types/Cluster.html Cluster} for more information
7490
+ * Refer to {@link https://solana-foundation.github.io/solana-web3.js/types/Cluster.html Cluster} for more information
7491
7491
  * */
7492
7492
  name: Cluster;
7493
7493
  /** The RPC endpoint */
@@ -1 +1 @@
1
- import e from"fetch-retry";import{v4 as t}from"uuid";import{PrivyErrorCode as s}from"@privy-io/api-base";import{getPathWithParams as i,AppConfig as r,AnalyticsEvent as a,RefreshSession as n}from"@privy-io/public-api";import{PrivyClientError as o,PrivyApiError as h}from"../Error.mjs";import{Session as l}from"../Session.mjs";import c from"../toAbortSignalTimeout.mjs";import{toSearchParams as g}from"../utils/toSearchParams.mjs";import{toConsoleLogger as d}from"./logger.mjs";import"eventemitter3";import"jose";import"js-cookie";import"../Token.mjs";import"../utils/allSettled.mjs";import"../utils/noop.mjs";let p="privy:caid";class u{setCallbacks(e){this.callbacks={...this.callbacks,...e}}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady)this.callbacks?.setIsReady?.(!0);else{if(!await this.isStorageAccessible())throw new o({code:"storage_error",error:"Unable to access storage"});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:s}){return`${this.baseUrl}${i(e.path,t)}${g(s)}`}async fetch(e,{body:t,params:s,query:i,headers:r,onRequest:a=this._beforeRequest.bind(this)}){let n=new Request(this.getPath(e,{params:s,query:i}),{method:e.method,body:JSON.stringify(t),headers:r}),o=await a(n),l=await this._fetch(n,o),c=await l.json();if(l.status>299)throw new h(c);return c}async _beforeRequestWithoutInitialize(e){let t=await this.session.getToken(),s=new Headers(e.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),t&&s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");let i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:c(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequest(e){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(r,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(p);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error("Unable to load clientId",e)}try{this._analyticsId=t()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;try{await this._storage.put(p,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(p)}catch(e){this.logger.error("Unable to delete clientId",e)}}async createAnalyticsEvent(e,t){try{await this.fetch(a,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(e){}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new o({code:"storage_error",error:"Unable to access storage"});let t=await this.session.getRefreshToken()??void 0,s=t??"key",i=this._cache.get(s);if(i)return this.logger.debug("[privy:refresh] found in-flight session refresh request, deduping"),await i;let r=this._refreshSession(t,e);this._cache.set(s,r);try{return await r}finally{this._cache.delete(s)}}async _refreshSession(e,t){let i=await this.session.getToken();if(!this.session.hasRefreshCredentials(i,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new h({code:s.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{this.logger.debug(`[privy:refresh] fetching: ${n.path}`);let s=await this.fetch(n,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),i=s.session_update_action;return this.logger.debug(`[privy:refresh] response: ${i}`),t||this.callbacks?.setUser?.(s.user),"set"===i&&(await this.session.updateWithTokensResponse(s),this.logger.debug("[privy:refresh] tokens stored")),"clear"===i&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),t||this.callbacks?.setUser?.(null)),"ignore"===i&&s.token&&(await this.session.storeToken(s.token),this.logger.debug("[privy:refresh] access token stored"),s.identity_token&&(this.logger.debug("[privy:refresh] identity token stored"),await this.session.storeIdentityToken(s.identity_token))),this.logger.debug("[privy:refresh] returning response"),s}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof h&&e.code===s.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),t||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getToken();return t.token||this.logger.debug("[privy:getAccessToken] expected token received null"),t.token===e&&this.logger.debug("[privy:getAccessToken] expected new token in response received existing"),s===e&&this.logger.debug("[privy:getAccessToken] expected new token in storage received existing"),t.token??s}return e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${t()}`,s="blobby";await this._storage.put(e,s);let i=await this._storage.get(e);return await this._storage.del(e),i===s}catch(e){return this.logger.error(e),!1}}constructor(t){this._sdkVersion="js-sdk-core:0.52.3",this._cache=new Map,this.logger=d({level:t.logLevel??"ERROR"}),this._storage=t.storage,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=t.baseUrl??"https://auth.privy.io",this.appId=t.appId,this.appClientId=t.appClientId,this._sdkVersion=t.sdkVersion??this._sdkVersion,this.callbacks=t.callbacks,this.nativeAppIdentifier=t.nativeAppIdentifier,this.session=new l({storage:this._storage,isUsingServerCookies:!1,appId:t.appId}),this._fetch=e(globalThis.fetch,{retries:3,retryDelay:e=>3**e*500,retryOn:[408,409,425,500,502,503,504]}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}}export{u as PrivyInternal};
1
+ import e from"fetch-retry";import{v4 as t}from"uuid";import{PrivyErrorCode as s}from"@privy-io/api-base";import{getPathWithParams as i,AppConfig as r,AnalyticsEvent as a,RefreshSession as n}from"@privy-io/public-api";import{PrivyClientError as o,PrivyApiError as h}from"../Error.mjs";import{Session as l}from"../Session.mjs";import c from"../toAbortSignalTimeout.mjs";import{toSearchParams as g}from"../utils/toSearchParams.mjs";import{toConsoleLogger as d}from"./logger.mjs";import"eventemitter3";import"jose";import"js-cookie";import"../Token.mjs";import"../utils/allSettled.mjs";import"../utils/noop.mjs";let p="privy:caid";class u{setCallbacks(e){this.callbacks={...this.callbacks,...e}}get isReady(){return!!this._config}get config(){return this._config}get caid(){return this._analyticsId}async _initialize(){if(this.isReady)this.callbacks?.setIsReady?.(!0);else{if(!await this.isStorageAccessible())throw new o({code:"storage_error",error:"Unable to access storage"});this._config=await this.getAppConfig(),this._config?.custom_api_url&&(this.baseUrl=this._config.custom_api_url,this.session.isUsingServerCookies=!0),this.callbacks?.setIsReady?.(!0),this._sdkVersion.startsWith("react-auth:")||this.createAnalyticsEvent("sdk_initialize",{})}}getPath(e,{params:t,query:s}){return`${this.baseUrl}${i(e.path,t)}${g(s)}`}async fetch(e,{body:t,params:s,query:i,headers:r,onRequest:a=this._beforeRequest.bind(this)}){let n=new Request(this.getPath(e,{params:s,query:i}),{method:e.method,body:JSON.stringify(t),headers:r}),o=await a(n),l=await this._fetch(n,o),c=await l.json();if(l.status>299)throw new h(c);return c}async _beforeRequestWithoutInitialize(e){let t=await this.session.getToken(),s=new Headers(e.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),t&&s.set("Authorization",`Bearer ${t}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");let i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:c(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(e){return await this._initialize(),this._beforeRequestWithoutInitialize(e)}async _beforeRequest(e){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(e)}async getAppConfig(){return await this.fetch(r,{params:{app_id:this.appId},onRequest:this._beforeRequestWithoutInitialize.bind(this)})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{let e=await this._storage.get(p);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){this.logger.error("Unable to load clientId",e)}try{this._analyticsId=t()}catch(e){this.logger.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;try{await this._storage.put(p,this._analyticsId)}catch(e){this.logger.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(p)}catch(e){this.logger.error("Unable to delete clientId",e)}}async createAnalyticsEvent(e,t){try{await this.fetch(a,{body:{event_name:e,client_id:await this._getOrGenerateClientAnalyticsId(),payload:t},onRequest:this.beforeRequestWithoutRefresh.bind(this)})}catch(e){}}async refreshSession(e=!1){if(!await this.isStorageAccessible())throw new o({code:"storage_error",error:"Unable to access storage"});let t=await this.session.getRefreshToken()??void 0,s=t??"key",i=this._cache.get(s);if(i)return this.logger.debug("[privy:refresh] found in-flight session refresh request, deduping"),await i;let r=this._refreshSession(t,e);this._cache.set(s,r);try{return await r}finally{this._cache.delete(s)}}async _refreshSession(e,t){let i=await this.session.getToken();if(!this.session.hasRefreshCredentials(i,e??null))throw this.logger.debug("[privy:refresh] missing tokens, skipping request"),await this._initialize(),new h({code:s.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{this.logger.debug(`[privy:refresh] fetching: ${n.path}`);let s=await this.fetch(n,{body:{refresh_token:e},onRequest:this.beforeRequestWithoutRefresh.bind(this)}),i=s.session_update_action;return this.logger.debug(`[privy:refresh] response: ${i}`),t||this.callbacks?.setUser?.(s.user),"set"===i&&(await this.session.updateWithTokensResponse(s),this.logger.debug("[privy:refresh] tokens stored")),"clear"===i&&(await this.session.destroyLocalState(),this.logger.debug("[privy:refresh] tokens cleared"),t||this.callbacks?.setUser?.(null)),"ignore"===i&&s.token&&(await this.session.storeToken(s.token),this.logger.debug("[privy:refresh] access token stored"),s.identity_token&&(this.logger.debug("[privy:refresh] identity token stored"),await this.session.storeIdentityToken(s.identity_token))),this.logger.debug("[privy:refresh] returning response"),s}catch(e){throw this.logger.debug(`[privy:refresh] error: ${e.message??"unknown error"}`),e instanceof h&&e.code===s.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),t||this.callbacks?.setUser?.(null)),e}}async getAccessToken(){let[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);if(!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t)){let t=await this.refreshSession(),s=await this.session.getToken();return t.token||this.logger.debug("[privy:getAccessToken] expected token received null"),t.token===e&&this.logger.debug("[privy:getAccessToken] expected new token in response received existing"),s===e&&this.logger.debug("[privy:getAccessToken] expected new token in storage received existing"),t.token??s}return e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{let e=`privy:__storage__test-${t()}`,s="blobby";await this._storage.put(e,s);let i=await this._storage.get(e);return await this._storage.del(e),i===s}catch(e){return this.logger.error(e),!1}}constructor(t){this._sdkVersion="js-sdk-core:0.52.4",this._cache=new Map,this.logger=d({level:t.logLevel??"ERROR"}),this._storage=t.storage,this._analyticsId=null,this._getOrGenerateClientAnalyticsId(),this.baseUrl=t.baseUrl??"https://auth.privy.io",this.appId=t.appId,this.appClientId=t.appClientId,this._sdkVersion=t.sdkVersion??this._sdkVersion,this.callbacks=t.callbacks,this.nativeAppIdentifier=t.nativeAppIdentifier,this.session=new l({storage:this._storage,isUsingServerCookies:!1,appId:t.appId}),this._fetch=e(globalThis.fetch,{retries:3,retryDelay:e=>3**e*500,retryOn:[408,409,425,500,502,503,504]}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}}export{u as PrivyInternal};
@@ -1 +1 @@
1
- import{getRootWalletForDelegation as e}from"../../action/delegatedActions/utils.mjs";import{getWallet as t}from"../../wallet-api/get-wallet.mjs";import{isUnifiedWallet as r}from"../../wallet-api/unified-wallet.mjs";import{updateWallet as a}from"../../wallet-api/update-wallet.mjs";import"../../utils/getAllUserEmbeddedEthereumWallets.mjs";import"../../utils/getAllUserEmbeddedSolanaWallets.mjs";import"../../utils/getUserEmbeddedEthereumWallet.mjs";import"../../utils/getUserEmbeddedSolanaWallet.mjs";import"@privy-io/public-api";import"../../wallet-api/generate-authorization-signature.mjs";import"canonicalize";import"../../Error.mjs";async function i({client:i,wallet:s,signers:d}){if("ethereum"!==s.chain_type&&"solana"!==s.chain_type)throw Error("Session signers are only supported for Ethereum and Solana wallets");if(r(s)){if(0===d.length)throw Error("Must specify at least one signer to add.");let e={wallet_id:s.id},r=await t(i,e);await a(i,e,o(i),{additional_signers:r.additional_signers.concat(d)})}else{if(s.delegated)return l(i);if(d.length>0)throw Error("addSessionSigners is only supported for TEE execution and this app uses On-device execution. Use the useHeadlessDelegatedActions hook to manage server side access on behalf of your users. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let{user:t}=await i.user.get(),r=e(s,t);if(!r)throw Error("Unable to determine root address for delegated address.");await i.embeddedWallet.delegateWallets({rootWallet:{address:r.address,chainType:r.chain_type,imported:r.imported},delegatedWallets:[{address:s.address,chainType:s.chain_type,walletIndex:s.wallet_index}]})}return l(i)}async function s({client:e,wallet:t}){if(r(t)){let r={wallet_id:t.id};await a(e,r,o(e),{additional_signers:[]})}else await e.delegated.revoke();return l(e)}async function l(e){let{user:t}=await e.user.get();if(!t)throw Error("Could not refresh user");return{user:t}}function o(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}export{i as addSessionSigners,s as removeSessionSigners};
1
+ import{getRootWalletForDelegation as e}from"../../action/delegatedActions/utils.mjs";import{getWallet as t}from"../../wallet-api/get-wallet.mjs";import{isUnifiedWallet as r}from"../../wallet-api/unified-wallet.mjs";import{updateWallet as i}from"../../wallet-api/update-wallet.mjs";import"../../utils/getAllUserEmbeddedEthereumWallets.mjs";import"../../utils/getAllUserEmbeddedSolanaWallets.mjs";import"../../utils/getUserEmbeddedEthereumWallet.mjs";import"../../utils/getUserEmbeddedSolanaWallet.mjs";import"@privy-io/public-api";import"../../wallet-api/generate-authorization-signature.mjs";import"canonicalize";import"../../Error.mjs";async function a({client:a,wallet:s,signers:o}){if("ethereum"!==s.chain_type&&"solana"!==s.chain_type)throw Error("Session signers are only supported for Ethereum and Solana wallets");if(r(s)){if(0===o.length)throw Error("Must specify at least one signer to add.");let e={wallet_id:s.id},r=await t(a,e);await i(a,e,n(a),{additional_signers:r.additional_signers.concat(o)})}else{if(s.delegated)return l(a);if(o.length>0)throw Error("Specifying signers in addSessionSigners is only supported for TEE execution and this app uses On-device execution. Pass an empty array for signers instead. Learn more https://docs.privy.io/recipes/tee-wallet-migration-guide");let{user:t}=await a.user.get(),r=e(s,t);if(!r)throw Error("Unable to determine root address for delegated address.");await a.embeddedWallet.delegateWallets({rootWallet:{address:r.address,chainType:r.chain_type,imported:r.imported},delegatedWallets:[{address:s.address,chainType:s.chain_type,walletIndex:s.wallet_index}]})}return l(a)}async function s({client:e,wallet:t}){if(r(t)){let r={wallet_id:t.id};await i(e,r,n(e),{additional_signers:[]})}else await e.delegated.revoke();return l(e)}async function l(e){let{user:t}=await e.user.get();if(!t)throw Error("Could not refresh user");return{user:t}}function n(e){return(...t)=>e.embeddedWallet.signWithUserSigner(...t)}export{a as addSessionSigners,s as removeSessionSigners};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@privy-io/js-sdk-core",
3
- "version": "0.52.3",
3
+ "version": "0.52.4",
4
4
  "description": "Vanilla JS client for the Privy Auth API",
5
5
  "keywords": [
6
6
  "authentication",
@@ -69,7 +69,7 @@
69
69
  "@ethersproject/transactions": "^5.7.0",
70
70
  "@ethersproject/units": "^5.7.0",
71
71
  "@privy-io/api-base": "1.5.2",
72
- "@privy-io/public-api": "2.37.0",
72
+ "@privy-io/public-api": "2.37.1",
73
73
  "canonicalize": "^2.0.0",
74
74
  "@privy-io/chains": "0.0.2",
75
75
  "eventemitter3": "^5.0.1",