@donotdev/auth 0.0.13 → 0.0.15
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.
- package/dist/constants.d.ts +3 -47
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/useAuth.js +1 -1
- package/package.json +4 -4
- package/dist/FirebaseAccountLinking.d.ts +0 -29
- package/dist/FirebaseAccountLinking.d.ts.map +0 -1
- package/dist/FirebaseAccountLinking.js +0 -1
- package/dist/FirebaseAuth.d.ts +0 -607
- package/dist/FirebaseAuth.d.ts.map +0 -1
- package/dist/FirebaseAuth.js +0 -1
- package/dist/FirebaseSmartRecovery.d.ts +0 -52
- package/dist/FirebaseSmartRecovery.d.ts.map +0 -1
- package/dist/FirebaseSmartRecovery.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"FirebaseAuth.d.ts","sourceRoot":"","sources":["../src/FirebaseAuth.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACV,QAAQ,EACR,UAAU,EACV,aAAa,EACb,YAAY,EAKZ,SAAS,EACT,WAAW,EACZ,MAAM,gBAAgB,CAAC;AA6BxB,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAuE7D;;;;;;GAMG;AACH,qBAAa,YAAa,YAAW,YAAY;IAC/C,OAAO,CAAC,GAAG,CAAsB;IACjC,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,KAAK,CAA0C;IACvD,OAAO,CAAC,YAAY,CAA8C;IAClE,OAAO,CAAC,WAAW,CAA4B;;IAM/C;;;;;;;OAOG;IACH,QAAQ,CAAC,KAAK,EAAE,SAAS,GAAG,WAAW,GAAG,IAAI;IAI9C;;;;;;;;OAQG;IACH,OAAO,KAAK,UAAU,GAKrB;IAED;;;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C,IAAI,CAAC;IAMxC;;;OAGG;IACG,eAAe,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAOjE;;OAEG;IACH,wBAAwB,IAAI,IAAI;IAIhC;;;;;OAKG;IACH,cAAc,IAAI,IAAI;IAetB;;;;;;;;;;;;;OAaG;IACG,0BAA0B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAmBlE;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAQ5B;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAS7B;;;;;;;;OAQG;YACW,oBAAoB;IAalC;;;;;;;;;;OAUG;IACH,OAAO,CAAC,wBAAwB;IAyChC;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;IAsBzB;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;IAaxB;;;;;;;;;OASG;IACH,OAAO,CAAC,8BAA8B;IAgDtC;;;;;;;OAOG;IACH,KAAK,IAAI,IAAI;CAUd;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,oBAA4C,CAAC"}
|
package/dist/FirebaseAuth.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toast as l}from"@donotdev/components";import{createSingleton as A,safeSessionStorage as d,handleError as a,isDev as m,isClient as p,ClaimsCache as R,getAuthPartnerIdByFirebaseId as S,getRoleFromClaims as v}from"@donotdev/core";import{AUTH_PARTNERS as k,SUBSCRIPTION_TIERS as P,USER_ROLES as T,createDefaultUserProfile as b}from"@donotdev/core";import{getFirebaseSDK as C,GoogleAuthProvider as L,GithubAuthProvider as N,FacebookAuthProvider as F,TwitterAuthProvider as D,OAuthProvider as w,EmailAuthProvider as U}from"@donotdev/firebase";import{getAuthMethod as y}from"./constants";import{PARTNER_STATE as o,EMAIL_VERIFICATION_STATUS as E}from"./constants";import{handleOAuthLinking as M,clearAccountLinkingState as W}from"./FirebaseAccountLinking";import{handleSmartRecovery as f}from"./FirebaseSmartRecovery";async function z(I,t,e){const i=w.credentialFromError(t),r=t.customData?._tokenResponse?.verifiedProvider?.[0]||i?.providerId||t.customData?.providerId;return r?S(r):null}class O{sdk;initialized=!1;store=null;popupTimeout=null;claimsCache=null;constructor(){this.sdk=C()}setStore(t){this.store=t}get storeState(){if(!this.store)throw new Error("[FirebaseAuth] Store not set. Call setStore() first.");return this.store}async initialize(){if(!this.initialized)try{await this.sdk.initialize();try{await this.processRedirectResult(!0)}catch(t){a(t,{userMessage:"Redirect processing failed",context:{operation:"processRedirectResult"},severity:"warning",showNotification:!1})}this.initialized=!0}catch(t){throw a(t,{userMessage:"Failed to initialize authentication",showNotification:!1})}}async processRedirectResult(t=!1){this.store&&this.store.setLoading(!0);try{const e=new Promise((r,s)=>setTimeout(()=>s(new Error("Redirect check timeout")),1e4)),i=await Promise.race([this.sdk.getRedirectResult(),e]).catch(r=>{if(r.message==="Redirect check timeout")return null;throw r});i?.user&&(await this.handleAuthStateChange(i.user),await this.checkPendingLinking(),d.removeItem("pendingAuthPartnerId"),l("success","Signed in successfully!"))}catch(e){if(e.code==="auth/account-exists-with-different-credential"){const i=w.credentialFromError(e)?.providerId||e.customData?._tokenResponse?.providerId,r=i?S(i):d.getItem("pendingAuthPartnerId");if(r)try{await f(e,()=>Promise.resolve(),{partnerId:r,method:"redirect"},this.getSmartRecoveryDeps());return}catch(s){a(s,{userMessage:"Failed to link accounts. Please try again.",showNotification:!t})}}if(a(e,{userMessage:"Authentication failed. Please try again.",showNotification:!t,context:{operation:"processRedirectResult"}}),e.code!=="auth/account-exists-with-different-credential")try{this.clearAccountLinkingState(),d.removeItem("pendingAuthPartnerId")}catch(i){a(i)}}finally{this.store&&this.store.setLoading(!1)}}ensureInitialized(){if(!this.initialized)throw new Error("FirebaseAuth not initialized. Call initialize() first.")}getAppConfig(){if(typeof globalThis<"u"){const t=globalThis._DNDEV_APP_CONFIG_;if(t)return t}return null}initializeClaimsCache(){if(this.claimsCache)return;const e=this.getAppConfig()?.features?.offlineTrustEnabled??!1;this.claimsCache=new R({offlineTrustEnabled:e,userId:this.storeState?.userId??null})}onAuthStateChanged(t){return this.sdk.onAuthStateChanged(async e=>{e?await this.handleAuthStateChange(e):this.handleSignOut(),e&&await this.checkPendingLinking();const i=e?this.convertToAuthUser(e):null;t(i)})}async handleAuthStateChange(t){if(!this.store)return;const e=this.convertToAuthUser(t);this.initializeClaimsCache(),this.claimsCache&&this.claimsCache.setUserId(e.id),this.storeState.clearAllPartnerStates();let i={userId:e.id,tier:P.FREE,status:"active",isActive:!0,features:[],subscriptionId:null,customerId:e.id,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()},r=T.USER;try{const u=(await this.sdk.getIdTokenResult(t,!0))?.claims||{};if(m(),u.subscription){const c=u.subscription;i={userId:e.id,tier:c.tier||P.FREE,status:c.status||"active",isActive:c.status==="active",features:c.features||[],subscriptionId:c.subscriptionId||null,customerId:c.customerId||e.id,subscriptionEnd:c.subscriptionEnd||null,cancelAtPeriodEnd:!!c.cancelAtPeriodEnd,updatedAt:c.updatedAt||new Date().toISOString()}}r=v(u),m()}catch(n){n?.code==="auth/network-request-failed"||n?.originalCode==="auth/network-request-failed"||n?.message?.includes("network")||a(n,{userMessage:"Failed to get custom claims",context:{operation:"getCustomClaims"},severity:"warning"})}e.role=r,m();const s={...b(e.id),role:r};m(),this.storeState.setAuthenticated(e,i,s)}handleSignOut(){this.store&&(this.claimsCache&&this.claimsCache.setUserId(null),this.storeState.clearAllPartnerStates(),this.storeState.setUnauthenticated())}async signInWithEmail(t,e){this.ensureInitialized(),this.storeState.setPartnerState("password",o.LOADING);try{const i=await this.sdk.signInWithEmail(t,e);return l("success","Signed in successfully!"),this.storeState.setPartnerState("password",o.IDLE),this.createAuthResult(i.user)}catch(i){try{return await f(i,()=>this.sdk.signInWithEmail(t,e),{email:t,partnerId:"password"},this.getSmartRecoveryDeps())}catch(r){throw this.storeState.setPartnerState("password",o.ERROR),r}}}async createUserWithEmail(t,e){this.ensureInitialized(),this.storeState.setPartnerState("password",o.LOADING);try{const i=await this.sdk.createUserWithEmail(t,e);return l("success","Account created successfully!"),this.storeState.setPartnerState("password",o.IDLE),this.createAuthResult(i.user,!0)}catch(i){try{const r=await f(i,()=>this.sdk.createUserWithEmail(t,e),{email:t,partnerId:"password"},this.getSmartRecoveryDeps());if(!r)throw new Error("Account creation failed");return r}catch(r){throw this.storeState.setPartnerState("password",o.ERROR),r}}}async signInWithEmailAndPassword(t,e){const i=await this.signInWithEmail(t,e);if(!i)throw new Error("Sign in did not return a result");return i.user}async createUserWithEmailAndPassword(t,e){return(await this.createUserWithEmail(t,e)).user}async updateUserProfile(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)return;const i={};t.displayName!==void 0&&(i.displayName=t.displayName),t.photoURL!==void 0&&(i.photoURL=t.photoURL),Object.keys(i).length!==0&&await this.sdk.updateProfile(e,i)}async getAccessToken(){const t=await this.sdk.getCurrentUser();if(!t)return null;try{return await this.sdk.getIdToken(t,!1)}catch{return null}}async refreshToken(){const t=await this.sdk.getCurrentUser();if(!t)return null;try{return await this.sdk.getIdToken(t,!0)}catch{return null}}async signInWithPartner(t,e){const i=y(e);this.ensureInitialized(),this.storeState.setPartnerState(t,o.LOADING);try{const r=this.createProviderFromConfig(t);let s;return i==="popup"?(s=await this.handlePopupAuth(t,async()=>await this.sdk.signInWithPopup(r)),s===null?(this.storeState.setPartnerState(t,o.IDLE),null):(l("success","Signed in successfully!"),this.storeState.setPartnerState(t,o.IDLE),this.createAuthResult(s.user))):(d.setItem("pendingAuthPartnerId",t),await this.sdk.signInWithRedirect(r),null)}catch(r){try{const s=await f(r,()=>{const n=this.createProviderFromConfig(t);return i==="popup"?this.sdk.signInWithPopup(n):this.sdk.signInWithRedirect(n)},{partnerId:t,method:i},this.getSmartRecoveryDeps());return s===null?(this.storeState.setPartnerState(t,o.IDLE),null):s}catch(s){throw this.storeState.setPartnerState(t,o.ERROR),s}}}async linkWithPartner(t,e){const i=y(e);this.ensureInitialized();const r=await this.sdk.getCurrentUser();if(!r)throw a(new Error("No authenticated user"),{userMessage:"You must be signed in to link accounts",context:{operation:"linkWithPartner",partnerId:t},showNotification:!0});this.storeState.setPartnerState(t,o.LOADING);try{const s=this.createProviderFromConfig(t);if(i==="popup"){const n=await this.sdk.linkWithPopup(r,s);return l("success",`Successfully linked ${t} account!`),this.storeState.setPartnerState(t,o.IDLE),this.createAuthResult(n.user)}else return await this.sdk.linkWithRedirect(r,s),null}catch(s){const n=s;let u="Failed to link account",c={operation:"linkWithPartner",partnerId:t,errorCode:n.code};switch(n.code){case"auth/operation-not-allowed":u="Account linking is disabled. Contact support for assistance.";break;case"auth/provider-already-linked":u="This account is already linked to your profile.";break;case"auth/credential-already-in-use":u="This account is already linked to another profile.";break;case"auth/requires-recent-login":u="Please sign out and sign back in, then try linking again.";break;default:u=`Failed to link ${t} account. Please try again.`}throw this.storeState.setPartnerState(t,o.ERROR),a(s,{userMessage:u,context:c,showNotification:!0})}}async handlePopupAuth(t,e){this.clearPopupMonitoring(),this.popupTimeout=setTimeout(()=>{this.storeState.setPartnerState(t,o.IDLE),this.clearPopupMonitoring()},3e4);try{const i=await e();return this.clearPopupMonitoring(),i}catch(i){if(this.clearPopupMonitoring(),i.code==="auth/popup-closed-by-user"||i.code==="auth/cancelled-popup-request")return null;throw i}}clearPopupMonitoring(){this.popupTimeout&&(clearTimeout(this.popupTimeout),this.popupTimeout=null)}async signInWithGoogleCredential(t){this.ensureInitialized(),this.storeState.setPartnerState("google",o.LOADING);try{const e=await this.sdk.signInWithGoogleCredential(t);return l("success","Signed in with Google!"),this.storeState.setPartnerState("google",o.IDLE),this.createAuthResult(e.user)}catch(e){try{return await f(e,()=>this.sdk.signInWithGoogleCredential(t),{partnerId:"google",method:"redirect"},this.getSmartRecoveryDeps())}catch(i){throw this.storeState.setPartnerState("google",o.ERROR),i}}}async getRedirectResult(){this.ensureInitialized();try{const t=await this.sdk.getRedirectResult();return t?.user?(l("success","Signed in successfully!"),this.createAuthResult(t.user)):null}catch(t){try{return await f(t,()=>this.sdk.getRedirectResult(),{method:"redirect"},this.getSmartRecoveryDeps())}catch(e){throw e}}}async checkPendingLinking(){const t=d.getItem("accountLinkingInfo"),e=d.getItem("originalCredential");if(!(!t||!e))try{const i=JSON.parse(t),r=JSON.parse(e),s=await this.sdk.getCurrentUser();if(!s)return;const n=this.convertToAuthUser(s),u=k[i.newProvider];if(!u)return;if(n.providerData?.some(g=>g.providerId===u.firebaseProviderId)||!1){this.clearAccountLinkingState();return}const h=this.createCredentialFromStoredData(r);if(!h){this.clearAccountLinkingState();return}await this.sdk.linkWithCredential(s,h),this.clearAccountLinkingState(),l("success","Accounts linked successfully!")}catch(i){throw this.clearAccountLinkingState(),a(i,{userMessage:"Account linking failed",showNotification:!0})}}async sendSignInLinkToEmail(t,e){this.ensureInitialized();try{if(!e?.url)throw new Error('sendSignInLinkToEmail requires actionCodeSettings with a non-empty "url". Pass { url: "https://yourapp.com/finishSignIn", handleCodeInApp: true }.');await this.sdk.sendSignInLinkToEmail(t,e),l("success","Sign-in link sent to your email!")}catch(i){throw a(i,{userMessage:"Failed to send sign-in link",showNotification:!0})}}async signInWithEmailLink(t,e){this.ensureInitialized(),this.storeState.setPartnerState("emailLink",o.LOADING);try{const i=await this.sdk.signInWithEmailLink(t,e);return l("success","Signed in successfully!"),this.storeState.setPartnerState("emailLink",o.IDLE),this.createAuthResult(i.user)}catch(i){try{return await f(i,()=>this.sdk.signInWithEmailLink(t,e),{email:t,partnerId:"emailLink"},this.getSmartRecoveryDeps())}catch(r){throw this.storeState.setPartnerState("emailLink",o.ERROR),r}}}isSignInWithEmailLink(t){if(!t&&!p())return!1;const e=t||(p()?window.location.href:"");return this.sdk.isSignInWithEmailLink(e)}async sendPasswordResetEmail(t){this.ensureInitialized();try{await this.sdk.sendPasswordResetEmail(t),l("success","Password reset email sent!")}catch(e){throw a(e,{userMessage:"Failed to send password reset email",showNotification:!0})}}async updatePassword(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)throw a(new Error("No authenticated user"),{userMessage:"You must be signed in to update your password",showNotification:!0});try{await this.sdk.updatePassword(e,t),l("success","Password updated successfully!")}catch(i){throw a(i,{userMessage:"Failed to update password",showNotification:!0})}}async sendEmailVerification(){this.ensureInitialized();const t=await this.sdk.getCurrentUser();if(!t)throw a(new Error("No authenticated user"),{userMessage:"You must be signed in to verify your email",showNotification:!0});try{this.storeState.setEmailVerificationStatus(E.PENDING),await this.sdk.sendEmailVerification(t),l("success","Verification email sent!")}catch(e){throw this.storeState.setEmailVerificationStatus(E.PENDING),a(e,{userMessage:"Failed to send verification email",showNotification:!0})}}async getEmailVerificationStatus(){this.ensureInitialized();const t=await this.sdk.getCurrentUser();return t?{status:t.emailVerified?"verified":"pending"}:{status:"pending",error:"No authenticated user"}}async isEmailVerificationEnabled(){return!0}async getIdTokenResult(t=!1){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)return null;try{return await this.sdk.getIdTokenResult(e,t)}catch(i){throw a(i,{userMessage:"Failed to get authentication token"})}}async getCustomClaims(){this.ensureInitialized(),this.initializeClaimsCache();const t=await this.sdk.getCurrentUser();if(!t)return{};if(!this.claimsCache)try{return(await this.sdk.getIdTokenResult(t,!0))?.claims||{}}catch(e){throw a(e,{userMessage:"Failed to get user permissions"})}return this.claimsCache.getClaims(async()=>(await this.sdk.getIdTokenResult(t,!0))?.claims||{})}async getCustomClaim(t){this.ensureInitialized();try{return(await this.getCustomClaims())[t]??null}catch(e){throw a(e,{userMessage:"Failed to get user permission"})}}async hasRole(t){this.ensureInitialized();try{const e=await this.getCustomClaim("role");if(this.store&&e){const i=this.storeState.userProfile;i&&this.storeState.setAuthenticated(this.storeState.user,this.storeState.userSubscription,{...i,role:e})}return e===t}catch(e){throw a(e,{userMessage:"Failed to verify user role"})}}async hasTier(t){this.ensureInitialized(),this.initializeClaimsCache();try{const i=(await this.getCustomClaims()).subscription?.tier;if(this.store&&i){const r=this.storeState.userSubscription;r&&this.storeState.setAuthenticated(this.storeState.user,{...r,tier:i},this.storeState.userProfile)}return i===t}catch(e){const r=this.getAppConfig()?.features?.offlineTrustEnabled??!1,s=p()?navigator.onLine:!1;if(!r&&!s)throw a(e,{userMessage:"Failed to verify subscription tier"});return!1}}async hasFeature(t){this.ensureInitialized(),this.initializeClaimsCache();const i=this.storeState.getCustomClaimsLocal()?.features||[],r=Array.isArray(i)&&i.includes(t);if(!this.claimsCache)try{const h=(await this.getCustomClaims()).features||[];return Array.isArray(h)&&h.includes(t)}catch(c){throw a(c,{userMessage:"Failed to verify feature access"})}const s=p()?navigator.onLine:!1,u=this.getAppConfig()?.features?.offlineTrustEnabled??!1;if(s)try{const h=(await this.getCustomClaims()).features||[],g=Array.isArray(h)&&h.includes(t);return g}catch{return r}else return u?r:!1}async getCurrentUser(){const t=await this.sdk.getCurrentUser();return t?this.convertToAuthUser(t):null}async signOut(){this.ensureInitialized(),this.clearPopupMonitoring();try{d.removeItem("accountLinkingInfo"),await this.clearCachedClaims(),await this.sdk.signOut(),l("info","Signed out successfully")}catch(t){throw a(t,{userMessage:"Failed to sign out",showNotification:!0})}}async reauthenticateWithPassword(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e||!e.email)throw new Error("No authenticated user");try{const i=U.credential(e.email,t);await this.sdk.reauthenticateWithCredential(e,i)}catch(i){throw a(i,{userMessage:"Re-authentication failed. Please check your password.",showNotification:!0})}}async reauthenticateWithProvider(t,e){this.ensureInitialized();const i=await this.sdk.getCurrentUser();if(!i)throw new Error("No authenticated user");const r=y(e);try{const s=this.createProviderFromConfig(t);if(r==="popup")await this.sdk.reauthenticateWithPopup(i,s);else{await this.sdk.reauthenticateWithRedirect(i,s);return}}catch(s){throw s.code==="auth/popup-closed-by-user"||s.code==="auth/cancelled-popup-request"||s.code==="auth/popup-blocked"?new Error("REAUTH_CANCELLED"):a(s,{userMessage:"Re-authentication failed. Please try again.",showNotification:!0})}}getPrimaryProvider(t){if(!t.providerData||t.providerData.length===0)return null;const e=t.providerData[0]?.providerId;return e?e==="password"||e==="emailLink"?"password":e.startsWith("google.com")?"google":e.startsWith("github.com")?"github":e.startsWith("microsoft.com")?"microsoft":e.startsWith("apple.com")?"apple":e.startsWith("facebook.com")?"facebook":e.startsWith("twitter.com")?"twitter":null:null}async deleteAccount(t){this.ensureInitialized();const e=await this.sdk.getCurrentUser();if(!e)throw new Error("No authenticated user");const i=async()=>{const r=this.getAppConfig()?.auth,s=r&&typeof r=="object"?r.deleteUserFunction:void 0;if(s)try{await s(e.uid)}catch{m()}await this.sdk.deleteUser(e),l("success","Account deleted successfully")};try{await i()}catch(r){if(r.code==="auth/requires-recent-login"){const s=this.getPrimaryProvider(e);if(!s)throw a(r,{userMessage:"Unable to determine authentication provider",showNotification:!0});if(s!=="password")try{await this.reauthenticateWithProvider(s),await i();return}catch(n){throw n.message==="REAUTH_CANCELLED"?new Error("REAUTH_CANCELLED"):a(n,{userMessage:"Re-authentication failed. Please try again.",showNotification:!0})}if(!t)throw new Error("REQUIRES_PASSWORD");try{await this.reauthenticateWithPassword(t),await i();return}catch(n){throw a(n,{userMessage:"Re-authentication failed. Please check your password.",showNotification:!0})}}throw a(r,{userMessage:"Failed to delete account",showNotification:!0})}}async clearCachedClaims(){this.claimsCache&&await this.claimsCache.clearClaims()}async setCachedClaims(t){this.initializeClaimsCache(),this.claimsCache&&await this.claimsCache.setClaims(t)}clearAccountLinkingState(){W()}resetAuthState(){this.store&&(Object.keys(k).forEach(t=>{this.storeState.setPartnerState(t,o.IDLE)}),this.storeState.clearAuthError())}async fetchSignInMethodsForEmail(t){this.ensureInitialized();try{return await this.sdk.fetchSignInMethodsForEmail(t)}catch(e){throw a(e,{userMessage:"Failed to check sign-in methods"})}}getSmartRecoveryDeps(){return{sdk:this.sdk,handleAccountLinking:this.handleAccountLinking.bind(this),createAuthResult:this.createAuthResult.bind(this)}}getAccountLinkingDeps(){return{sdk:this.sdk,createProviderFromConfig:this.createProviderFromConfig.bind(this),createAuthResult:this.createAuthResult.bind(this),getExistingProvider:z}}async handleAccountLinking(t,e,i){return await M(t,e,i,this.getAccountLinkingDeps())}createProviderFromConfig(t){const e=k[t];if(!e||!e.firebaseProviderId)throw new Error(`Unsupported partner: ${t}`);let i;switch(t){case"google":i=this.sdk.createGoogleProvider();break;case"github":i=this.sdk.createGithubProvider();break;case"facebook":i=this.sdk.createFacebookProvider();break;case"twitter":i=this.sdk.createTwitterProvider();break;case"microsoft":i=this.sdk.createMicrosoftProvider();break;case"apple":i=this.sdk.createAppleProvider();break;default:i=this.sdk.createOAuthProvider(e.firebaseProviderId)}return e.customParameters&&i.setCustomParameters(e.customParameters),e.scopes&&e.scopes.length>0&&e.scopes.forEach(r=>i.addScope(r)),i}convertToAuthUser(t){return{id:t.uid,email:t.email||null,displayName:t.displayName||null,photoURL:t.photoURL||null,emailVerified:t.emailVerified||!1,lastLoginAt:t.metadata.lastSignInTime||new Date().toISOString(),providerData:t.providerData.map(e=>({providerId:e.providerId,uid:e.uid,displayName:e.displayName,email:e.email,photoURL:e.photoURL,phoneNumber:e.phoneNumber}))}}createAuthResult(t,e=!1){return{user:this.convertToAuthUser(t),success:!0,isNewUser:e}}createCredentialFromStoredData(t){try{if(!t||!t.providerId)return null;switch(t.providerId){case"google.com":return L.credential(t.idToken||null,t.accessToken||null);case"github.com":return N.credential(t.accessToken);case"facebook.com":return F.credential(t.accessToken);case"twitter.com":return D.credential(t.accessToken,t.secret||t.oauthTokenSecret);default:return t.idToken?new w(t.providerId).credential({idToken:t.idToken,accessToken:t.accessToken}):t.accessToken?new w(t.providerId).credential({accessToken:t.accessToken}):null}}catch(e){return a(e,{showNotification:!1,severity:"warning",context:{operation:"_getCredentialFromData"}}),null}}reset(){this.initialized=!1,this.sdk=C(),this.store=null,this.claimsCache=null,this.popupTimeout&&(clearTimeout(this.popupTimeout),this.popupTimeout=null)}}const $=A(()=>new O);export{O as FirebaseAuth,$ as getFirebaseAuth};
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { type AuthResult, type AuthPartnerId } from '@donotdev/core';
|
|
2
|
-
import { type AuthMethod } from './constants';
|
|
3
|
-
/**
|
|
4
|
-
* Context information for smart recovery
|
|
5
|
-
*
|
|
6
|
-
* @version 0.0.1
|
|
7
|
-
* @since 0.0.1
|
|
8
|
-
* @author AMBROISE PARK Consulting
|
|
9
|
-
*/
|
|
10
|
-
export interface SmartRecoveryContext {
|
|
11
|
-
email?: string;
|
|
12
|
-
partnerId?: AuthPartnerId;
|
|
13
|
-
method?: AuthMethod;
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Dependencies required for smart recovery
|
|
17
|
-
*
|
|
18
|
-
* @version 0.0.1
|
|
19
|
-
* @since 0.0.1
|
|
20
|
-
* @author AMBROISE PARK Consulting
|
|
21
|
-
*/
|
|
22
|
-
export interface SmartRecoveryDependencies {
|
|
23
|
-
sdk: any;
|
|
24
|
-
handleAccountLinking: (error: any, attemptedProvider: AuthPartnerId, method: AuthMethod) => Promise<AuthResult | null>;
|
|
25
|
-
createAuthResult: (user: any, isNewUser?: boolean) => AuthResult;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Centralized smart recovery handler
|
|
29
|
-
*
|
|
30
|
-
* Handles all Firebase error scenarios with appropriate recovery strategies.
|
|
31
|
-
* Wraps unrecoverable errors with handleError() before throwing.
|
|
32
|
-
*
|
|
33
|
-
* **Recovery Strategies:**
|
|
34
|
-
* - Network issues: Linear backoff (1s, 2s, 3s)
|
|
35
|
-
* - Rate limiting: Exponential backoff (2s, 4s, 8s)
|
|
36
|
-
* - Internal errors: Simple retry with 2s delay
|
|
37
|
-
* - Account linking: Delegate to account linking handler
|
|
38
|
-
* - User cancellation: Return null (not an error)
|
|
39
|
-
*
|
|
40
|
-
* @param error - Firebase error object
|
|
41
|
-
* @param operation - Operation to retry
|
|
42
|
-
* @param context - Context information for recovery
|
|
43
|
-
* @param deps - Dependencies for recovery operations
|
|
44
|
-
* @returns Auth result or null if user cancelled
|
|
45
|
-
* @throws DoNotDevError if recovery fails
|
|
46
|
-
*
|
|
47
|
-
* @version 0.0.1
|
|
48
|
-
* @since 0.0.1
|
|
49
|
-
* @author AMBROISE PARK Consulting
|
|
50
|
-
*/
|
|
51
|
-
export declare function handleSmartRecovery(error: any, operation: () => Promise<any>, context: SmartRecoveryContext, deps: SmartRecoveryDependencies): Promise<AuthResult | null>;
|
|
52
|
-
//# sourceMappingURL=FirebaseSmartRecovery.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"FirebaseSmartRecovery.d.ts","sourceRoot":"","sources":["../src/FirebaseSmartRecovery.ts"],"names":[],"mappings":"AAYA,OAAO,EAGL,KAAK,UAAU,EACf,KAAK,aAAa,EACnB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAE7D;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACnC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,MAAM,CAAC,EAAE,UAAU,CAAC;CACrB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,yBAAyB;IACxC,GAAG,EAAE,GAAG,CAAC;IACT,oBAAoB,EAAE,CACpB,KAAK,EAAE,GAAG,EACV,iBAAiB,EAAE,aAAa,EAChC,MAAM,EAAE,UAAU,KACf,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;IAChC,gBAAgB,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC,EAAE,OAAO,KAAK,UAAU,CAAC;CAClE;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,mBAAmB,CACvC,KAAK,EAAE,GAAG,EACV,SAAS,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC,EAC7B,OAAO,EAAE,oBAAoB,EAC7B,IAAI,EAAE,yBAAyB,GAC9B,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAkF5B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toast as c}from"@donotdev/components";import{handleError as s,isDev as u}from"@donotdev/core";import{getAuthMethod as d}from"./constants";async function g(e,o,r,a){if(e.code==="auth/network-request-failed"){c("info","Connection issue - retrying...");try{return await l(o,a)}catch(t){throw s(t,{userMessage:"Network connection failed. Please check your internet and try again.",context:{operation:"network-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/too-many-requests"){c("info","Rate limited - retrying with backoff...");try{return await h(o,a)}catch(t){throw s(t,{userMessage:"Too many attempts. Please wait a moment and try again.",context:{operation:"rate-limit-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/internal-error"){c("info","Temporary issue - retrying...");try{return await y(o,a)}catch(t){throw s(t,{userMessage:"A temporary error occurred. Please try again.",context:{operation:"internal-error-retry",originalError:e.code},showNotification:!0})}}if(e.code==="auth/account-exists-with-different-credential")try{return await a.handleAccountLinking(e,r.partnerId,r.method?d(r.method):d())}catch(t){throw s(t,{userMessage:"Failed to link accounts. Please try again.",context:{operation:"account-linking",originalError:e.code},showNotification:!0})}if(e.code==="auth/popup-closed-by-user"||e.code==="auth/cancelled-popup-request"||e.code==="auth/popup-blocked"||e.message?.includes("popup")||e.message?.includes("cancelled")||e.message?.includes("closed"))return null;throw s(e,{userMessage:w(e.code),context:{operation:"smart-recovery",errorCode:e.code},showNotification:!0})}async function l(e,o,r=3){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/network-request-failed")throw t;const i=a*1e3;u(),await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}async function h(e,o,r=3){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/too-many-requests")throw t;const i=Math.pow(2,a)*1e3;u(),await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}async function y(e,o,r=2){for(let a=1;a<=r;a++)try{const t=await e();return o.createAuthResult(t.user)}catch(t){if(a===r||t.code!=="auth/internal-error")throw t;const i=2e3;u(),await new Promise(n=>setTimeout(n,i))}throw new Error("Max retries exceeded")}function w(e){return{"auth/invalid-email":"Invalid email address","auth/user-disabled":"This account has been disabled","auth/user-not-found":"No account found with this email","auth/wrong-password":"Incorrect password","auth/email-already-in-use":"An account already exists with this email","auth/weak-password":"Password is too weak","auth/operation-not-allowed":"This sign-in method is not enabled","auth/invalid-credential":"Invalid credentials provided","auth/invalid-verification-code":"Invalid verification code","auth/invalid-verification-id":"Invalid verification ID","auth/expired-action-code":"This link has expired","auth/invalid-action-code":"Invalid or expired link","auth/credential-already-in-use":"This credential is already associated with another account","auth/requires-recent-login":"Please sign in again to continue","auth/popup-blocked":"Popup was blocked by your browser. Please allow popups and try again."}[e]||"An authentication error occurred"}export{g as handleSmartRecovery};
|