@privy-io/js-sdk-core 0.35.5 → 0.35.6-beta-20241218042345

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"),a=require("./Error.js"),r=require("./Session.js"),n=require("./toAbortSignalTimeout.js"),o=require("./utils/toSearchParams.js");require("eventemitter3"),require("jose"),require("js-cookie"),require("./Token.js"),require("./utils/allSettled.js");const h="privy:caid";exports.PrivyInternal=class{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.35.5";_fetch;nativeAppIdentifier;callbacks;_cache=new Map;session;constructor(t){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 r.Session({storage:this._storage,isUsingServerCookies:!1,appId:t.appId}),this._fetch=e(fetch,{retries:3,retryDelay:500}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}setCallbacks(e){this.callbacks={...this.callbacks,...e}}get isReady(){return Boolean(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 a.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.createAnalyticsEvent("sdk_initialize",{})}}async fetch(e,{body:t,params:s,query:r,headers:n,options:h={onRequest:this._beforeRequest.bind(this)}}){const c=`${this.baseUrl}${i.getPathWithParams(e.path,s)}${o.toSearchParams(r)}`,l=new Request(c,{method:e.method,body:JSON.stringify(t),headers:n}),d=await h.onRequest(l),p=await this._fetch(l,d),u=await p.json();if(p.status>299)throw new a.PrivyApiError(u);return u}async _beforeRequestWithoutInitialize(e){const 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");const 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},options:{onRequest:this._beforeRequestWithoutInitialize.bind(this)}})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{const e=await this._storage.get(h);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){console.error("Unable to load clientId",e)}try{this._analyticsId=t.v4()}catch(e){console.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;try{await this._storage.put(h,this._analyticsId)}catch(e){console.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(h)}catch(e){console.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},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}catch(e){}}async refreshSession(){const e=await this.session.getRefreshToken()??void 0,t=e??"key",s=this._cache.get(t);if(s)return await s;const i=this._refreshSession(e);this._cache.set(t,i);try{return await i}catch(e){throw e}finally{this._cache.delete(t)}}async _refreshSession(e){const t=await this.session.getToken();if(!this.session.hasRefreshCredentials(t,e??null))throw await this._initialize(),new a.PrivyApiError({code:s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{const t=await this.fetch(i.RefreshSession,{body:{refresh_token:e},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}}),s=t.session_update_action;return this.callbacks?.setUser?.(t.user),"set"===s&&await this.session.updateWithTokensResponse(t),"clear"===s&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===s&&t.token&&(await this.session.storeToken(t.token),t.identity_token&&await this.session.storeIdentityToken(t.identity_token)),t}catch(e){throw e instanceof a.PrivyApiError&&e.code===s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),e}}async getAccessToken(){const[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);return!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t)?(await this.refreshSession(),await this.session.getToken()):e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{const e="privy:__storage__test",t="blobby";await this._storage.put(e,t);const s=await this._storage.get(e);return await this._storage.del(e),s===t}catch(e){return console.error(e),!1}}};
1
+ "use strict";var e=require("fetch-retry"),t=require("uuid"),s=require("@privy-io/api-base"),i=require("@privy-io/public-api"),a=require("./Error.js"),r=require("./Session.js"),n=require("./toAbortSignalTimeout.js"),o=require("./utils/toSearchParams.js");require("eventemitter3"),require("jose"),require("js-cookie"),require("./Token.js"),require("./utils/allSettled.js");const h="privy:caid";exports.PrivyInternal=class{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.35.6-beta-20241218042345";_fetch;nativeAppIdentifier;callbacks;_cache=new Map;session;constructor(t){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 r.Session({storage:this._storage,isUsingServerCookies:!1,appId:t.appId}),this._fetch=e(fetch,{retries:3,retryDelay:500}),this.session.on("error_storing_tokens",(e=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:e})}))}setCallbacks(e){this.callbacks={...this.callbacks,...e}}get isReady(){return Boolean(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 a.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.createAnalyticsEvent("sdk_initialize",{})}}async fetch(e,{body:t,params:s,query:r,headers:n,options:h={onRequest:this._beforeRequest.bind(this)}}){const c=`${this.baseUrl}${i.getPathWithParams(e.path,s)}${o.toSearchParams(r)}`,l=new Request(c,{method:e.method,body:JSON.stringify(t),headers:n}),d=await h.onRequest(l),p=await this._fetch(l,d),u=await p.json();if(p.status>299)throw new a.PrivyApiError(u);return u}async _beforeRequestWithoutInitialize(e){const 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");const 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},options:{onRequest:this._beforeRequestWithoutInitialize.bind(this)}})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{const e=await this._storage.get(h);if("string"==typeof e&&e.length>0)return this._analyticsId=e,e}catch(e){console.error("Unable to load clientId",e)}try{this._analyticsId=t.v4()}catch(e){console.error("Unable to generate uuidv4",e)}if(!this._analyticsId)return null;try{await this._storage.put(h,this._analyticsId)}catch(e){console.error(`Unable to store clientId: ${this._analyticsId}`,e)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(h)}catch(e){console.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},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}catch(e){}}async refreshSession(){const e=await this.session.getRefreshToken()??void 0,t=e??"key",s=this._cache.get(t);if(s)return await s;const i=this._refreshSession(e);this._cache.set(t,i);try{return await i}finally{this._cache.delete(t)}}async _refreshSession(e){const t=await this.session.getToken();if(!this.session.hasRefreshCredentials(t,e??null))throw await this._initialize(),new a.PrivyApiError({code:s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{const t=await this.fetch(i.RefreshSession,{body:{refresh_token:e},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}}),s=t.session_update_action;return this.callbacks?.setUser?.(t.user),"set"===s&&await this.session.updateWithTokensResponse(t),"clear"===s&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===s&&t.token&&(await this.session.storeToken(t.token),t.identity_token&&await this.session.storeIdentityToken(t.identity_token)),t}catch(e){throw e instanceof a.PrivyApiError&&e.code===s.PrivyErrorCode.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),e}}async getAccessToken(){const[e,t]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);return!this.session.tokenIsActive(e)&&this.session.hasRefreshCredentials(e,t)?(await this.refreshSession(),await this.session.getToken()):e}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{const e="privy:__storage__test",t="blobby";await this._storage.put(e,t);const s=await this._storage.get(e);return await this._storage.del(e),s===t}catch(e){return console.error(e),!1}}};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@privy-io/public-api");exports.default=class{_privyInternal;_wallet=void 0;_preparedMessage;constructor(e){this._privyInternal=e}async unlinkWallet(t){try{await this._privyInternal.fetch(e.SiweUnlink,{body:{address:t}});return(await this._privyInternal.refreshSession()).user}catch(e){throw e}}async linkWithSiwe(t,n,i){const r=n||this._wallet,s=i||this._preparedMessage;if(!r)throw new Error("A wallet must be provided in the init step or as an argument to linkWithSiwe");if(!s)throw new Error("A message must be generated and signed before being used to link a wallet to privy");try{await this._privyInternal.fetch(e.SiweLink,{body:{message:s,signature:t,chainId:r.chainId,walletClientType:r.walletClientType,connectorType:r.connectorType}});return(await this._privyInternal.refreshSession()).user}catch(e){throw e}}async loginWithSiwe(t,n,i,r){const s=n||this._wallet,a=i||this._preparedMessage;if(!s)throw new Error("A wallet must be provided in the init step or as an argument to loginWithSiwe");if(!a)throw new Error("A message must be generated and signed before being used to login to privy with a wallet");try{const n=await this._privyInternal.fetch(e.SiweAuthenticate,{body:{signature:t,message:a,chainId:s.chainId,walletClientType:s.walletClientType,connectorType:s.connectorType,mode:r}});return await this._privyInternal.session.updateWithTokensResponse(n),this._privyInternal.callbacks?.setUser?.(n.user),n}catch(e){throw e}}async init(t,n,i){this._wallet=t;const r=await this._privyInternal.fetch(e.SiweInit,{body:{address:t.address}}),{nonce:s}=r,a=`${(o={chainId:t.chainId.toString().replace("eip155:",""),address:t.address,issuedAt:(new Date).toISOString(),statement:"By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",domain:n,nonce:s,uri:i}).domain} wants you to sign in with your Ethereum account:\n${o.address}\n\n${o.statement}\n\nURI: ${o.uri}\nVersion: 1\nChain ID: ${o.chainId}\nNonce: ${o.nonce}\nIssued At: ${o.issuedAt}\nResources:\n- https://privy.io`;var o;return this._preparedMessage=a,{nonce:s,message:a}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@privy-io/public-api");exports.default=class{_privyInternal;_wallet=void 0;_preparedMessage;constructor(e){this._privyInternal=e}async unlinkWallet(t){await this._privyInternal.fetch(e.SiweUnlink,{body:{address:t}});return(await this._privyInternal.refreshSession()).user}async linkWithSiwe(t,n,i){const s=n||this._wallet,r=i||this._preparedMessage;if(!s)throw new Error("A wallet must be provided in the init step or as an argument to linkWithSiwe");if(!r)throw new Error("A message must be generated and signed before being used to link a wallet to privy");await this._privyInternal.fetch(e.SiweLink,{body:{message:r,signature:t,chainId:s.chainId,walletClientType:s.walletClientType,connectorType:s.connectorType}});return(await this._privyInternal.refreshSession()).user}async loginWithSiwe(t,n,i,s){const r=n||this._wallet,a=i||this._preparedMessage;if(!r)throw new Error("A wallet must be provided in the init step or as an argument to loginWithSiwe");if(!a)throw new Error("A message must be generated and signed before being used to login to privy with a wallet");const o=await this._privyInternal.fetch(e.SiweAuthenticate,{body:{signature:t,message:a,chainId:r.chainId,walletClientType:r.walletClientType,connectorType:r.connectorType,mode:s}});return await this._privyInternal.session.updateWithTokensResponse(o),this._privyInternal.callbacks?.setUser?.(o.user),o}async init(t,n,i){this._wallet=t;const s=await this._privyInternal.fetch(e.SiweInit,{body:{address:t.address}}),{nonce:r}=s,a=`${(o={chainId:t.chainId.toString().replace("eip155:",""),address:t.address,issuedAt:(new Date).toISOString(),statement:"By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",domain:n,nonce:r,uri:i}).domain} wants you to sign in with your Ethereum account:\n${o.address}\n\n${o.statement}\n\nURI: ${o.uri}\nVersion: 1\nChain ID: ${o.chainId}\nNonce: ${o.nonce}\nIssued At: ${o.issuedAt}\nResources:\n- https://privy.io`;var o;return this._preparedMessage=a,{nonce:r,message:a}}};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var n=require("@privy-io/public-api");exports.default=class{_privyInternal;constructor(n){this._privyInternal=n}async link(e,t,i){try{await this._privyInternal.fetch(n.SiweLinkSmartWallet,{body:{message:e,signature:t,smart_wallet_type:i}});return(await this._privyInternal.refreshSession()).user}catch(n){throw n}}async init(e){const t=await this._privyInternal.fetch(n.SiweInit,{body:{address:e.address}}),{nonce:i}=t;var s;return{nonce:i,message:`${(s={chainId:e.chainId.toString().replace("eip155:",""),address:e.address,issuedAt:(new Date).toISOString(),statement:"By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",domain:"privy.io",uri:"https://auth.privy.io",nonce:i}).domain} wants you to sign in with your Ethereum account:\n${s.address}\n\n${s.statement}\n\nURI: ${s.uri}\nVersion: 1\nChain ID: ${s.chainId}\nNonce: ${s.nonce}\nIssued At: ${s.issuedAt}\nResources:\n- https://privy.io`}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var n=require("@privy-io/public-api");exports.default=class{_privyInternal;constructor(n){this._privyInternal=n}async link(e,t,i){await this._privyInternal.fetch(n.SiweLinkSmartWallet,{body:{message:e,signature:t,smart_wallet_type:i}});return(await this._privyInternal.refreshSession()).user}async init(e){const t=await this._privyInternal.fetch(n.SiweInit,{body:{address:e.address}}),{nonce:i}=t;var s;return{nonce:i,message:`${(s={chainId:e.chainId.toString().replace("eip155:",""),address:e.address,issuedAt:(new Date).toISOString(),statement:"By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",domain:"privy.io",uri:"https://auth.privy.io",nonce:i}).domain} wants you to sign in with your Ethereum account:\n${s.address}\n\n${s.statement}\n\nURI: ${s.uri}\nVersion: 1\nChain ID: ${s.chainId}\nNonce: ${s.nonce}\nIssued At: ${s.issuedAt}\nResources:\n- https://privy.io`}}};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.default=class{_privyInternal;constructor(e){this._privyInternal=e}async get(){try{const{user:e}=await this._privyInternal.refreshSession();return{user:e}}catch(e){throw e}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.default=class{_privyInternal;constructor(e){this._privyInternal=e}async get(){const{user:e}=await this._privyInternal.refreshSession();return{user:e}}};
@@ -220,7 +220,7 @@ export type ICloudNativeRecoveryInput = {
220
220
  };
221
221
  export type SetRecoveryInput = {
222
222
  wallet: PrivyEthereumEmbeddedWalletAccount | PrivySolanaEmbeddedWalletAccount;
223
- } & (PasswordRecoveryInput | CloudRecoveryInput | ICloudNativeRecoveryInput);
223
+ } & (PasswordRecoveryInput | CloudRecoveryInput | ICloudNativeRecoveryInput | PrivyRecoveryInput);
224
224
  export interface SetRecoveryOutput {
225
225
  /** User object with the updated embedded wallet */
226
226
  user: PrivyUser;
@@ -220,7 +220,7 @@ export type ICloudNativeRecoveryInput = {
220
220
  };
221
221
  export type SetRecoveryInput = {
222
222
  wallet: PrivyEthereumEmbeddedWalletAccount | PrivySolanaEmbeddedWalletAccount;
223
- } & (PasswordRecoveryInput | CloudRecoveryInput | ICloudNativeRecoveryInput);
223
+ } & (PasswordRecoveryInput | CloudRecoveryInput | ICloudNativeRecoveryInput | PrivyRecoveryInput);
224
224
  export interface SetRecoveryOutput {
225
225
  /** User object with the updated embedded wallet */
226
226
  user: PrivyUser;
@@ -1 +1 @@
1
- import t from"fetch-retry";import{v4 as e}from"uuid";import{PrivyErrorCode as s}from"@privy-io/api-base";import{getPathWithParams as i,AppConfig as a,AnalyticsEvent as n,RefreshSession as r}from"@privy-io/public-api";import{PrivyClientError as o,PrivyApiError as c}from"./Error.mjs";import{Session as h}from"./Session.mjs";import l from"./toAbortSignalTimeout.mjs";import{toSearchParams as d}from"./utils/toSearchParams.mjs";import"eventemitter3";import"jose";import"js-cookie";import"./Token.mjs";import"./utils/allSettled.mjs";const p="privy:caid";class _{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.35.5";_fetch;nativeAppIdentifier;callbacks;_cache=new Map;session;constructor(e){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 h({storage:this._storage,isUsingServerCookies:!1,appId:e.appId}),this._fetch=t(fetch,{retries:3,retryDelay:500}),this.session.on("error_storing_tokens",(t=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:t})}))}setCallbacks(t){this.callbacks={...this.callbacks,...t}}get isReady(){return Boolean(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.createAnalyticsEvent("sdk_initialize",{})}}async fetch(t,{body:e,params:s,query:a,headers:n,options:r={onRequest:this._beforeRequest.bind(this)}}){const o=`${this.baseUrl}${i(t.path,s)}${d(a)}`,h=new Request(o,{method:t.method,body:JSON.stringify(e),headers:n}),l=await r.onRequest(h),p=await this._fetch(h,l),_=await p.json();if(p.status>299)throw new c(_);return _}async _beforeRequestWithoutInitialize(t){const e=await this.session.getToken(),s=new Headers(t.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),e&&s.set("Authorization",`Bearer ${e}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");const i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:l(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(t){return await this._initialize(),this._beforeRequestWithoutInitialize(t)}async _beforeRequest(t){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(t)}async getAppConfig(){return await this.fetch(a,{params:{app_id:this.appId},options:{onRequest:this._beforeRequestWithoutInitialize.bind(this)}})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{const t=await this._storage.get(p);if("string"==typeof t&&t.length>0)return this._analyticsId=t,t}catch(t){console.error("Unable to load clientId",t)}try{this._analyticsId=e()}catch(t){console.error("Unable to generate uuidv4",t)}if(!this._analyticsId)return null;try{await this._storage.put(p,this._analyticsId)}catch(t){console.error(`Unable to store clientId: ${this._analyticsId}`,t)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(p)}catch(t){console.error("Unable to delete clientId",t)}}async createAnalyticsEvent(t,e){try{await this.fetch(n,{body:{event_name:t,client_id:await this._getOrGenerateClientAnalyticsId(),payload:e},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}catch(t){}}async refreshSession(){const t=await this.session.getRefreshToken()??void 0,e=t??"key",s=this._cache.get(e);if(s)return await s;const i=this._refreshSession(t);this._cache.set(e,i);try{return await i}catch(t){throw t}finally{this._cache.delete(e)}}async _refreshSession(t){const e=await this.session.getToken();if(!this.session.hasRefreshCredentials(e,t??null))throw await this._initialize(),new c({code:s.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{const e=await this.fetch(r,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}}),s=e.session_update_action;return this.callbacks?.setUser?.(e.user),"set"===s&&await this.session.updateWithTokensResponse(e),"clear"===s&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===s&&e.token&&(await this.session.storeToken(e.token),e.identity_token&&await this.session.storeIdentityToken(e.identity_token)),e}catch(t){throw t instanceof c&&t.code===s.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),t}}async getAccessToken(){const[t,e]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);return!this.session.tokenIsActive(t)&&this.session.hasRefreshCredentials(t,e)?(await this.refreshSession(),await this.session.getToken()):t}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{const t="privy:__storage__test",e="blobby";await this._storage.put(t,e);const s=await this._storage.get(t);return await this._storage.del(t),s===e}catch(t){return console.error(t),!1}}}export{_ as PrivyInternal};
1
+ import t from"fetch-retry";import{v4 as e}from"uuid";import{PrivyErrorCode as s}from"@privy-io/api-base";import{getPathWithParams as i,AppConfig as a,AnalyticsEvent as n,RefreshSession as r}from"@privy-io/public-api";import{PrivyClientError as o,PrivyApiError as c}from"./Error.mjs";import{Session as h}from"./Session.mjs";import l from"./toAbortSignalTimeout.mjs";import{toSearchParams as d}from"./utils/toSearchParams.mjs";import"eventemitter3";import"jose";import"js-cookie";import"./Token.mjs";import"./utils/allSettled.mjs";const p="privy:caid";class _{baseUrl;_config;appId;appClientId;_storage;_analyticsId;_sdkVersion="js-sdk-core:0.35.6-beta-20241218042345";_fetch;nativeAppIdentifier;callbacks;_cache=new Map;session;constructor(e){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 h({storage:this._storage,isUsingServerCookies:!1,appId:e.appId}),this._fetch=t(fetch,{retries:3,retryDelay:500}),this.session.on("error_storing_tokens",(t=>{this.createAnalyticsEvent("error_updating_tokens_in_storage",{reason:t})}))}setCallbacks(t){this.callbacks={...this.callbacks,...t}}get isReady(){return Boolean(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.createAnalyticsEvent("sdk_initialize",{})}}async fetch(t,{body:e,params:s,query:a,headers:n,options:r={onRequest:this._beforeRequest.bind(this)}}){const o=`${this.baseUrl}${i(t.path,s)}${d(a)}`,h=new Request(o,{method:t.method,body:JSON.stringify(e),headers:n}),l=await r.onRequest(h),p=await this._fetch(h,l),_=await p.json();if(p.status>299)throw new c(_);return _}async _beforeRequestWithoutInitialize(t){const e=await this.session.getToken(),s=new Headers(t.headers);s.set("privy-app-id",this.appId),this.appClientId&&s.set("privy-client-id",this.appClientId),s.set("privy-client",this._sdkVersion),e&&s.set("Authorization",`Bearer ${e}`),s.set("Content-Type","application/json"),s.set("Accept","application/json");const i=await this._getOrGenerateClientAnalyticsId();return i&&s.set("privy-ca-id",i),this.nativeAppIdentifier&&s.set("x-native-app-identifier",this.nativeAppIdentifier),{signal:l(2e4),headers:s,credentials:"include"}}async beforeRequestWithoutRefresh(t){return await this._initialize(),this._beforeRequestWithoutInitialize(t)}async _beforeRequest(t){return await this._initialize(),await this.getAccessToken(),this.beforeRequestWithoutRefresh(t)}async getAppConfig(){return await this.fetch(a,{params:{app_id:this.appId},options:{onRequest:this._beforeRequestWithoutInitialize.bind(this)}})}async _getOrGenerateClientAnalyticsId(){if(this._analyticsId)return this._analyticsId;try{const t=await this._storage.get(p);if("string"==typeof t&&t.length>0)return this._analyticsId=t,t}catch(t){console.error("Unable to load clientId",t)}try{this._analyticsId=e()}catch(t){console.error("Unable to generate uuidv4",t)}if(!this._analyticsId)return null;try{await this._storage.put(p,this._analyticsId)}catch(t){console.error(`Unable to store clientId: ${this._analyticsId}`,t)}return this._analyticsId}async destroyClientAnalyticsId(){try{return await this._storage.del(p)}catch(t){console.error("Unable to delete clientId",t)}}async createAnalyticsEvent(t,e){try{await this.fetch(n,{body:{event_name:t,client_id:await this._getOrGenerateClientAnalyticsId(),payload:e},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}})}catch(t){}}async refreshSession(){const t=await this.session.getRefreshToken()??void 0,e=t??"key",s=this._cache.get(e);if(s)return await s;const i=this._refreshSession(t);this._cache.set(e,i);try{return await i}finally{this._cache.delete(e)}}async _refreshSession(t){const e=await this.session.getToken();if(!this.session.hasRefreshCredentials(e,t??null))throw await this._initialize(),new c({code:s.MISSING_OR_INVALID_TOKEN,error:"No tokens found in storage"});try{const e=await this.fetch(r,{body:{refresh_token:t},options:{onRequest:this.beforeRequestWithoutRefresh.bind(this)}}),s=e.session_update_action;return this.callbacks?.setUser?.(e.user),"set"===s&&await this.session.updateWithTokensResponse(e),"clear"===s&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),"ignore"===s&&e.token&&(await this.session.storeToken(e.token),e.identity_token&&await this.session.storeIdentityToken(e.identity_token)),e}catch(t){throw t instanceof c&&t.code===s.MISSING_OR_INVALID_TOKEN&&(await this.session.destroyLocalState(),this.callbacks?.setUser?.(null)),t}}async getAccessToken(){const[t,e]=await Promise.all([this.session.getToken(),this.session.getRefreshToken()]);return!this.session.tokenIsActive(t)&&this.session.hasRefreshCredentials(t,e)?(await this.refreshSession(),await this.session.getToken()):t}async getIdentityToken(){return await this.session.getIdentityToken()}async isStorageAccessible(){try{const t="privy:__storage__test",e="blobby";await this._storage.put(t,e);const s=await this._storage.get(t);return await this._storage.del(t),s===e}catch(t){return console.error(t),!1}}}export{_ as PrivyInternal};
@@ -1 +1 @@
1
- import{SiweUnlink as e,SiweLink as t,SiweAuthenticate as n,SiweInit as i}from"@privy-io/public-api";class r{_privyInternal;_wallet=void 0;_preparedMessage;constructor(e){this._privyInternal=e}async unlinkWallet(t){try{await this._privyInternal.fetch(e,{body:{address:t}});return(await this._privyInternal.refreshSession()).user}catch(e){throw e}}async linkWithSiwe(e,n,i){const r=n||this._wallet,s=i||this._preparedMessage;if(!r)throw new Error("A wallet must be provided in the init step or as an argument to linkWithSiwe");if(!s)throw new Error("A message must be generated and signed before being used to link a wallet to privy");try{await this._privyInternal.fetch(t,{body:{message:s,signature:e,chainId:r.chainId,walletClientType:r.walletClientType,connectorType:r.connectorType}});return(await this._privyInternal.refreshSession()).user}catch(e){throw e}}async loginWithSiwe(e,t,i,r){const s=t||this._wallet,a=i||this._preparedMessage;if(!s)throw new Error("A wallet must be provided in the init step or as an argument to loginWithSiwe");if(!a)throw new Error("A message must be generated and signed before being used to login to privy with a wallet");try{const t=await this._privyInternal.fetch(n,{body:{signature:e,message:a,chainId:s.chainId,walletClientType:s.walletClientType,connectorType:s.connectorType,mode:r}});return await this._privyInternal.session.updateWithTokensResponse(t),this._privyInternal.callbacks?.setUser?.(t.user),t}catch(e){throw e}}async init(e,t,n){this._wallet=e;const r=await this._privyInternal.fetch(i,{body:{address:e.address}}),{nonce:s}=r,a=`${(o={chainId:e.chainId.toString().replace("eip155:",""),address:e.address,issuedAt:(new Date).toISOString(),statement:"By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",domain:t,nonce:s,uri:n}).domain} wants you to sign in with your Ethereum account:\n${o.address}\n\n${o.statement}\n\nURI: ${o.uri}\nVersion: 1\nChain ID: ${o.chainId}\nNonce: ${o.nonce}\nIssued At: ${o.issuedAt}\nResources:\n- https://privy.io`;var o;return this._preparedMessage=a,{nonce:s,message:a}}}export{r as default};
1
+ import{SiweUnlink as e,SiweLink as t,SiweAuthenticate as n,SiweInit as i}from"@privy-io/public-api";class s{_privyInternal;_wallet=void 0;_preparedMessage;constructor(e){this._privyInternal=e}async unlinkWallet(t){await this._privyInternal.fetch(e,{body:{address:t}});return(await this._privyInternal.refreshSession()).user}async linkWithSiwe(e,n,i){const s=n||this._wallet,a=i||this._preparedMessage;if(!s)throw new Error("A wallet must be provided in the init step or as an argument to linkWithSiwe");if(!a)throw new Error("A message must be generated and signed before being used to link a wallet to privy");await this._privyInternal.fetch(t,{body:{message:a,signature:e,chainId:s.chainId,walletClientType:s.walletClientType,connectorType:s.connectorType}});return(await this._privyInternal.refreshSession()).user}async loginWithSiwe(e,t,i,s){const a=t||this._wallet,r=i||this._preparedMessage;if(!a)throw new Error("A wallet must be provided in the init step or as an argument to loginWithSiwe");if(!r)throw new Error("A message must be generated and signed before being used to login to privy with a wallet");const o=await this._privyInternal.fetch(n,{body:{signature:e,message:r,chainId:a.chainId,walletClientType:a.walletClientType,connectorType:a.connectorType,mode:s}});return await this._privyInternal.session.updateWithTokensResponse(o),this._privyInternal.callbacks?.setUser?.(o.user),o}async init(e,t,n){this._wallet=e;const s=await this._privyInternal.fetch(i,{body:{address:e.address}}),{nonce:a}=s,r=`${(o={chainId:e.chainId.toString().replace("eip155:",""),address:e.address,issuedAt:(new Date).toISOString(),statement:"By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",domain:t,nonce:a,uri:n}).domain} wants you to sign in with your Ethereum account:\n${o.address}\n\n${o.statement}\n\nURI: ${o.uri}\nVersion: 1\nChain ID: ${o.chainId}\nNonce: ${o.nonce}\nIssued At: ${o.issuedAt}\nResources:\n- https://privy.io`;var o;return this._preparedMessage=r,{nonce:a,message:r}}}export{s as default};
@@ -1 +1 @@
1
- import{SiweLinkSmartWallet as n,SiweInit as t}from"@privy-io/public-api";class i{_privyInternal;constructor(n){this._privyInternal=n}async link(t,i,e){try{await this._privyInternal.fetch(n,{body:{message:t,signature:i,smart_wallet_type:e}});return(await this._privyInternal.refreshSession()).user}catch(n){throw n}}async init(n){const i=await this._privyInternal.fetch(t,{body:{address:n.address}}),{nonce:e}=i;var s;return{nonce:e,message:`${(s={chainId:n.chainId.toString().replace("eip155:",""),address:n.address,issuedAt:(new Date).toISOString(),statement:"By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",domain:"privy.io",uri:"https://auth.privy.io",nonce:e}).domain} wants you to sign in with your Ethereum account:\n${s.address}\n\n${s.statement}\n\nURI: ${s.uri}\nVersion: 1\nChain ID: ${s.chainId}\nNonce: ${s.nonce}\nIssued At: ${s.issuedAt}\nResources:\n- https://privy.io`}}}export{i as default};
1
+ import{SiweLinkSmartWallet as n,SiweInit as t}from"@privy-io/public-api";class i{_privyInternal;constructor(n){this._privyInternal=n}async link(t,i,e){await this._privyInternal.fetch(n,{body:{message:t,signature:i,smart_wallet_type:e}});return(await this._privyInternal.refreshSession()).user}async init(n){const i=await this._privyInternal.fetch(t,{body:{address:n.address}}),{nonce:e}=i;var s;return{nonce:e,message:`${(s={chainId:n.chainId.toString().replace("eip155:",""),address:n.address,issuedAt:(new Date).toISOString(),statement:"By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.",domain:"privy.io",uri:"https://auth.privy.io",nonce:e}).domain} wants you to sign in with your Ethereum account:\n${s.address}\n\n${s.statement}\n\nURI: ${s.uri}\nVersion: 1\nChain ID: ${s.chainId}\nNonce: ${s.nonce}\nIssued At: ${s.issuedAt}\nResources:\n- https://privy.io`}}}export{i as default};
@@ -1 +1 @@
1
- class r{_privyInternal;constructor(r){this._privyInternal=r}async get(){try{const{user:r}=await this._privyInternal.refreshSession();return{user:r}}catch(r){throw r}}}export{r as default};
1
+ class r{_privyInternal;constructor(r){this._privyInternal=r}async get(){const{user:r}=await this._privyInternal.refreshSession();return{user:r}}}export{r as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@privy-io/js-sdk-core",
3
- "version": "0.35.5",
3
+ "version": "0.35.6-beta-20241218042345",
4
4
  "description": "Vanilla JS client for the Privy Auth API",
5
5
  "keywords": [
6
6
  "authentication",
@@ -68,7 +68,7 @@
68
68
  "@ethersproject/transactions": "^5.7.0",
69
69
  "@ethersproject/units": "^5.7.0",
70
70
  "@privy-io/api-base": "^1.4.1",
71
- "@privy-io/public-api": "2.15.6",
71
+ "@privy-io/public-api": "2.15.7-beta-20241218042345",
72
72
  "eventemitter3": "^5.0.1",
73
73
  "fetch-retry": "^5.0.6",
74
74
  "jose": "^4.15.5",