@ackplus/nest-auth-react 1.1.8 → 1.1.29

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.
Files changed (71) hide show
  1. package/README.md +58 -4
  2. package/dist/context/auth-context.d.ts +21 -0
  3. package/dist/context/auth-context.js +23 -0
  4. package/dist/context/auth-context.js.map +1 -0
  5. package/dist/context/auth-provider.d.ts +16 -0
  6. package/dist/context/auth-provider.js +200 -0
  7. package/dist/context/auth-provider.js.map +1 -0
  8. package/dist/guards/auth-guard.d.ts +8 -0
  9. package/dist/guards/auth-guard.js +21 -0
  10. package/dist/guards/auth-guard.js.map +1 -0
  11. package/dist/guards/guest-guard.d.ts +8 -0
  12. package/dist/guards/guest-guard.js +21 -0
  13. package/dist/guards/guest-guard.js.map +1 -0
  14. package/dist/guards/require-permission.d.ts +10 -0
  15. package/dist/guards/require-permission.js +24 -0
  16. package/dist/guards/require-permission.js.map +1 -0
  17. package/dist/guards/require-role.d.ts +10 -0
  18. package/dist/guards/require-role.js +24 -0
  19. package/dist/guards/require-role.js.map +1 -0
  20. package/dist/hooks/use-access-token.d.ts +1 -0
  21. package/dist/hooks/use-access-token.js +21 -0
  22. package/dist/hooks/use-access-token.js.map +1 -0
  23. package/dist/hooks/use-auth-status.d.ts +8 -0
  24. package/dist/hooks/use-auth-status.js +12 -0
  25. package/dist/hooks/use-auth-status.js.map +1 -0
  26. package/dist/hooks/use-auth.d.ts +2 -0
  27. package/dist/hooks/use-auth.js +10 -0
  28. package/dist/hooks/use-auth.js.map +1 -0
  29. package/dist/hooks/use-has-role.d.ts +2 -0
  30. package/dist/hooks/use-has-role.js +16 -0
  31. package/dist/hooks/use-has-role.js.map +1 -0
  32. package/dist/hooks/use-session.d.ts +2 -0
  33. package/dist/hooks/use-session.js +7 -0
  34. package/dist/hooks/use-session.js.map +1 -0
  35. package/dist/hooks/use-user.d.ts +2 -0
  36. package/dist/hooks/use-user.js +7 -0
  37. package/dist/hooks/use-user.js.map +1 -0
  38. package/dist/index.d.ts +18 -0
  39. package/dist/index.js +18 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/next/create-next-auth-helpers.d.ts +20 -0
  42. package/dist/next/create-next-auth-helpers.js +88 -0
  43. package/dist/next/create-next-auth-helpers.js.map +1 -0
  44. package/dist/next/next-auth-provider.d.ts +10 -0
  45. package/dist/next/next-auth-provider.js +17 -0
  46. package/dist/next/next-auth-provider.js.map +1 -0
  47. package/dist/sync/cross-tab-sync.d.ts +24 -0
  48. package/dist/sync/cross-tab-sync.js +109 -0
  49. package/dist/sync/cross-tab-sync.js.map +1 -0
  50. package/package.json +43 -30
  51. package/client/create-client.d.ts +0 -63
  52. package/client/create-client.d.ts.map +0 -1
  53. package/context/auth-context.d.ts +0 -50
  54. package/context/auth-context.d.ts.map +0 -1
  55. package/context/mfa-service-context.d.ts +0 -5
  56. package/context/mfa-service-context.d.ts.map +0 -1
  57. package/hooks/use-auth.d.ts +0 -50
  58. package/hooks/use-auth.d.ts.map +0 -1
  59. package/hooks/use-mfa.d.ts +0 -23
  60. package/hooks/use-mfa.d.ts.map +0 -1
  61. package/index.cjs +0 -6
  62. package/index.d.ts +0 -13
  63. package/index.js +0 -2779
  64. package/provider/nest-auth-provider.d.ts +0 -15
  65. package/provider/nest-auth-provider.d.ts.map +0 -1
  66. package/storage/token-storage.d.ts +0 -3
  67. package/storage/token-storage.d.ts.map +0 -1
  68. package/utils/errors.d.ts +0 -6
  69. package/utils/errors.d.ts.map +0 -1
  70. package/utils/request.d.ts +0 -10
  71. package/utils/request.d.ts.map +0 -1
package/index.cjs DELETED
@@ -1,6 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Fe=require("react/jsx-runtime"),A=require("react");var ot=(e=>(e.EMAIL="email",e.PHONE="phone",e.GOOGLE="google",e.FACEBOOK="facebook",e.APPLE="apple",e.GITHUB="github",e.MICROSOFT="microsoft",e))(ot||{}),Ie=(e=>(e.TOTP="totp",e.SMS="sms",e.EMAIL="email",e.BACKUP_CODE="backup_code",e))(Ie||{}),x=(e=>(e.IDLE="idle",e.LOADING="loading",e.AUTHENTICATED="authenticated",e.UNAUTHENTICATED="unauthenticated",e.MFA_REQUIRED="mfa_required",e.EXPIRED="expired",e))(x||{}),W=(e=>(e.SINGLE="single",e.MULTI="multi",e))(W||{}),_=(e=>(e.SIGNED_IN="signed_in",e.SIGNED_OUT="signed_out",e.REGISTERED="registered",e.TOKEN_REFRESHED="token_refreshed",e.MFA_REQUIRED="mfa_required",e.MFA_VERIFIED="mfa_verified",e.MFA_SETUP_COMPLETED="mfa_setup_completed",e.PASSWORD_CHANGED="password_changed",e.PASSWORD_RESET_REQUESTED="password_reset_requested",e.PASSWORD_RESET_COMPLETED="password_reset_completed",e.PROFILE_LOADED="profile_loaded",e.PROFILE_UPDATED="profile_updated",e.CONFIG_LOADED="config_loaded",e.ERROR="error",e.NETWORK_ERROR="network_error",e.VALIDATION_ERROR="validation_error",e))(_||{});const Mt=Ie,Bt="email",Ht="phone",jt="google",qt="facebook",Gt="apple";function zt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var be={exports:{}},Me;function $t(){return Me||(Me=1,(function(e){var t=Object.prototype.hasOwnProperty,n="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(n=!1));function r(f,l,c){this.fn=f,this.context=l,this.once=c||!1}function i(f,l,c,p,T){if(typeof c!="function")throw new TypeError("The listener must be a function");var R=new r(c,p||f,T),d=n?n+l:l;return f._events[d]?f._events[d].fn?f._events[d]=[f._events[d],R]:f._events[d].push(R):(f._events[d]=R,f._eventsCount++),f}function o(f,l){--f._eventsCount===0?f._events=new s:delete f._events[l]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,p;if(this._eventsCount===0)return l;for(p in c=this._events)t.call(c,p)&&l.push(n?p.slice(1):p);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,p=this._events[c];if(!p)return[];if(p.fn)return[p.fn];for(var T=0,R=p.length,d=new Array(R);T<R;T++)d[T]=p[T].fn;return d},a.prototype.listenerCount=function(l){var c=n?n+l:l,p=this._events[c];return p?p.fn?1:p.length:0},a.prototype.emit=function(l,c,p,T,R,d){var y=n?n+l:l;if(!this._events[y])return!1;var h=this._events[y],b=arguments.length,O,S;if(h.fn){switch(h.once&&this.removeListener(l,h.fn,void 0,!0),b){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,c),!0;case 3:return h.fn.call(h.context,c,p),!0;case 4:return h.fn.call(h.context,c,p,T),!0;case 5:return h.fn.call(h.context,c,p,T,R),!0;case 6:return h.fn.call(h.context,c,p,T,R,d),!0}for(S=1,O=new Array(b-1);S<b;S++)O[S-1]=arguments[S];h.fn.apply(h.context,O)}else{var v=h.length,C;for(S=0;S<v;S++)switch(h[S].once&&this.removeListener(l,h[S].fn,void 0,!0),b){case 1:h[S].fn.call(h[S].context);break;case 2:h[S].fn.call(h[S].context,c);break;case 3:h[S].fn.call(h[S].context,c,p);break;case 4:h[S].fn.call(h[S].context,c,p,T);break;default:if(!O)for(C=1,O=new Array(b-1);C<b;C++)O[C-1]=arguments[C];h[S].fn.apply(h[S].context,O)}}return!0},a.prototype.on=function(l,c,p){return i(this,l,c,p,!1)},a.prototype.once=function(l,c,p){return i(this,l,c,p,!0)},a.prototype.removeListener=function(l,c,p,T){var R=n?n+l:l;if(!this._events[R])return this;if(!c)return o(this,R),this;var d=this._events[R];if(d.fn)d.fn===c&&(!T||d.once)&&(!p||d.context===p)&&o(this,R);else{for(var y=0,h=[],b=d.length;y<b;y++)(d[y].fn!==c||T&&!d[y].once||p&&d[y].context!==p)&&h.push(d[y]);h.length?this._events[R]=h.length===1?h[0]:h:o(this,R)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&o(this,c)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a})(be)),be.exports}var Vt=$t();const it=zt(Vt),at=A.createContext(void 0),Kt=()=>{const e=A.useContext(at);if(!e)throw new Error("useAuth must be used within NestAuthProvider");return e},ct=A.createContext(null),Jt=()=>{const e=A.useContext(ct);if(!e)throw new Error("useMfa must be used within NestAuthProvider");return e};class Wt extends Error{status;data;constructor(t,n,s){super(t),this.name="AuthClientError",this.status=n,this.data=s}}const Xt=(e,t)=>{if(!t)return e;if(/^https?:\/\//i.test(t))return t;const n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`;return`${n}${s}`},Be=async(e,t,n={})=>{const{method:s="POST",body:r,headers:i={},tokens:o,signal:a}=n,f=Xt(e.baseUrl,t),l={"Content-Type":"application/json",...e.defaultHeaders,...i};o?.accessToken&&(l.Authorization=`Bearer ${o.accessToken}`);const c=await fetch(f,{method:s,headers:l,body:r!==void 0?JSON.stringify(r):void 0,credentials:"include",signal:a}),p=await c.text(),T=p?Qt(p):void 0;if(!c.ok)throw new Wt(T?.message||`Request failed with status ${c.status}`,c.status,T);return T},Qt=e=>{try{return JSON.parse(e)}catch{return}},Yt={login:"/auth/login",register:"/auth/signup",logout:"/auth/logout",logoutAll:"/auth/logout-all",refresh:"/auth/refresh-token",me:"/auth/user",session:"/auth/session",sendMfaCode:"/auth/send-2fa-code",verifyMfa:"/auth/verify-2fa",forgotPassword:"/auth/forgot-password",verifyForgotPasswordOtp:"/auth/verify-forgot-password-otp",resetPasswordWithToken:"/auth/reset-password-with-token",changePassword:"/auth/change-password",mfaStatus:"/auth/mfa/status",toggleMfa:"/auth/mfa/toggle",mfaDevices:"/auth/mfa/devices",removeMfaDevice:"/auth/mfa/devices",setupTotp:"/auth/mfa/setup-totp",verifyTotpSetup:"/auth/mfa/verify-totp-setup",generateRecoveryCode:"/auth/mfa/generate-recovery-code",resetTotp:"/auth/mfa/reset-totp",clientConfig:"/auth/client-config",config:"/auth/config",profile:"/auth/profile",tenants:"/auth/tenants",sendEmailVerification:"/auth/send-email-verification",verifyEmail:"/auth/verify-email"},Zt={providers:{email:{enabled:!1},phone:{enabled:!1}},emailAuth:{enabled:!1},phoneAuth:{enabled:!1},registration:{enabled:!1},mfa:{enabled:!1,methods:[]},tenants:{mode:W.SINGLE,defaultTenantId:null,options:[]},sso:{enabled:!1,providers:[]},ui:void 0},en=e=>e!==null&&typeof e=="object"&&"emailAuth"in e&&"phoneAuth"in e,tn=e=>({baseUrl:e.baseUrl,endpoints:{...Yt,...e.endpoints||{}},defaultHeaders:e.defaultHeaders}),ut=e=>{const t=tn(e),n=(s,r={})=>{const i=t.endpoints[s];return Be(t,i,{method:r.method??"POST",body:r.body,tokens:r.tokens??null})};return{login:s=>n("login",{body:(()=>{const{providerName:r,provider:i,providerId:o,...a}=s;return{providerName:r??i??o,...a}})()}),register:s=>n("register",{body:s}),logout:s=>n("logout",{tokens:s??null}),logoutAll:s=>n("logoutAll",{tokens:s??null}),refreshToken:s=>n("refresh",{body:s}),getProfile:s=>n("me",{method:"GET",tokens:s??null}),getSession:s=>n("session",{method:"GET",tokens:s??null}),sendMfaCode:(s,r)=>n("sendMfaCode",{body:{method:r},tokens:s??null}),verifyMfa:(s,r)=>n("verifyMfa",{body:r,tokens:s??null}),forgotPassword:s=>n("forgotPassword",{body:s}),verifyForgotPasswordOtp:s=>n("verifyForgotPasswordOtp",{body:s}),resetPasswordWithToken:s=>n("resetPasswordWithToken",{body:s}),changePassword:(s,r)=>n("changePassword",{body:s,tokens:r??null}),getMfaStatus:s=>n("mfaStatus",{method:"GET",tokens:s??null}),toggleMfa:(s,r)=>n("toggleMfa",{body:r,tokens:s??null}),listMfaDevices:s=>n("mfaDevices",{method:"GET",tokens:s??null}),removeMfaDevice:(s,r)=>Be(t,`${t.endpoints.removeMfaDevice}/${r}`,{method:"DELETE",tokens:s??null}),setupTotp:s=>n("setupTotp",{tokens:s??null}),verifyTotpSetup:(s,r)=>n("verifyTotpSetup",{body:r,tokens:s??null}),generateRecoveryCode:s=>n("generateRecoveryCode",{tokens:s??null}),resetTotp:(s,r)=>n("resetTotp",{body:{code:r},tokens:s??null}),fetchClientConfig:async()=>{const s=await n("clientConfig",{method:"GET"});return en(s)?s:s?.data??Zt},fetchTenants:async s=>{const r=await n("tenants",{method:"GET",tokens:s??null});return Array.isArray(r)?r:r?.data??[]},sendEmailVerification:s=>n("sendEmailVerification",{tokens:s??null}),verifyEmail:(s,r)=>n("verifyEmail",{body:{otp:r},tokens:s??null})}},nn="nest-auth/tokens",sn=e=>!!e&&typeof e.getTokens=="function",rn=e=>{if(typeof window>"u")return!1;try{const t=window[e],n="__nest-auth-test__";return t.setItem(n,"1"),t.removeItem(n),!0}catch{return!1}},lt=()=>{let e=null;return{getTokens:()=>e,setTokens:t=>{e=t},clear:()=>{e=null}}},He=(e,t)=>{const n=lt();if(!rn(e))return n;const s=window[e];return{getTokens:()=>{const r=s.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return s.removeItem(t),null}},setTokens:r=>{if(!r){s.removeItem(t),n.setTokens(null);return}s.setItem(t,JSON.stringify(r)),n.setTokens(r)},clear:()=>{s.removeItem(t),n.clear()}}},ft=e=>{if(sn(e))return e;const{strategy:t="localStorage",storageKey:n=nn}=e??{};switch(t){case"localStorage":return He("localStorage",n);case"sessionStorage":return He("sessionStorage",n);case"memory":default:return lt()}},je={status:null,isLoadingStatus:!1,isPerformingAction:!1,lastError:null},qe=e=>e instanceof Error?e:typeof e=="string"?new Error(e):new Error("An unexpected MFA error occurred");class dt{client;events;readTokens;state=je;emitter=new it;constructor(t){this.client=t.client,this.events=t.events,this.readTokens=t.readTokens}setTokenResolver(t){this.readTokens=t}subscribe(t){return this.emitter.on("change",t),t(this.state),()=>this.emitter.off("change",t)}getSnapshot(){return this.state}reset(){this.updateState(je)}ensureTokens(){const t=this.readTokens();if(!t?.accessToken)throw new Error("Cannot perform MFA actions without an authenticated session");return t}updateState(t){this.state={...this.state,...t},this.emitter.emit("change",this.state)}async withAction(t){this.updateState({isPerformingAction:!0,lastError:null});try{return await t()}catch(n){const s=qe(n);throw this.updateState({lastError:s}),this.dispatchEvent(_.ERROR,s),s}finally{this.updateState({isPerformingAction:!1})}}dispatchEvent(t,n){this.events.emit(t,{type:t,payload:n})}async getStatus(t=!1){if(!t&&this.state.status)return this.state.status;let n;try{n=this.ensureTokens()}catch(s){throw this.updateState({status:null}),s}this.updateState({isLoadingStatus:!0,lastError:null});try{const s=await this.client.getMfaStatus(n);return this.updateState({status:s,isLoadingStatus:!1}),s}catch(s){const r=qe(s);throw this.updateState({isLoadingStatus:!1,lastError:r}),this.dispatchEvent(_.ERROR,r),r}}async refreshStatus(){return this.getStatus(!0)}async toggleMfa(t){return this.withAction(async()=>{const n=this.ensureTokens(),s=await this.client.toggleMfa(n,t);return await this.refreshStatus().catch(()=>{}),s})}async setupTotp(){return this.withAction(async()=>{const t=this.ensureTokens();return await this.client.setupTotp(t)})}async verifyTotpSetup(t){return this.withAction(async()=>{const n=this.ensureTokens(),s=await this.client.verifyTotpSetup(n,t);return await this.refreshStatus().catch(()=>{}),s})}async generateRecoveryCode(){return this.withAction(async()=>{const t=this.ensureTokens(),n=await this.client.generateRecoveryCode(t);return await this.refreshStatus().catch(()=>{}),n})}async resetTotp(t){return this.withAction(async()=>{const n=this.ensureTokens(),s=await this.client.resetTotp(n,t);return await this.refreshStatus().catch(()=>{}),s})}async removeDevice(t){return this.withAction(async()=>{const n=this.ensureTokens(),s=await this.client.removeMfaDevice(n,t);return await this.refreshStatus().catch(()=>{}),s})}async ensureStatusLoaded(){if(!this.state.status&&!this.state.isLoadingStatus)try{await this.getStatus()}catch{}}getAvailableMethods(){return this.state.status?.availableMethods??[]}}const U={providers:{email:{enabled:!1},phone:{enabled:!1}},emailAuth:{enabled:!1},phoneAuth:{enabled:!1},registration:{enabled:!1},mfa:{enabled:!1,methods:[]},tenants:{mode:W.SINGLE,defaultTenantId:null,options:[]},sso:{enabled:!1,providers:[]},ui:void 0},ke=e=>({...U,...e,emailAuth:{...U.emailAuth,...e?.emailAuth},phoneAuth:{...U.phoneAuth,...e?.phoneAuth},registration:{...U.registration,...e?.registration},mfa:{...U.mfa,...e?.mfa,methods:e?.mfa?.methods??U.mfa.methods},tenants:e?.tenants?{...U.tenants,...e.tenants,options:e.tenants.options??U.tenants?.options??[]}:U.tenants,sso:e?.sso?{...U.sso,...e.sso,providers:e.sso.providers??U.sso?.providers??[]}:U.sso,ui:e?.ui??U.ui}),on=(e,t)=>{const n=e.getTokens(),s=t.initialBackendConfig?ke(t.initialBackendConfig):null,r=s?.tenants?.defaultTenantId??null;return{status:n?x.LOADING:x.IDLE,isLoading:!!n,isLoadingUser:!!n,user:null,session:null,tokens:n??null,error:null,isMfaRequired:!1,mfaMethods:[],backendConfig:s,tenantId:r}},an=(e,t)=>{switch(t.type){case"SET_STATUS":return{...e,status:t.status};case"SET_LOADING":return{...e,isLoading:t.value};case"SET_LOADING_USER":return{...e,isLoadingUser:t.value};case"SET_USER":return{...e,user:t.user,isLoadingUser:!1};case"SET_SESSION":return{...e,session:t.session};case"SET_TOKENS":return{...e,tokens:t.tokens};case"SET_ERROR":return{...e,error:t.error};case"SET_MFA_REQUIRED":return{...e,isMfaRequired:!0,mfaMethods:t.methods,status:x.AUTHENTICATED};case"CLEAR_MFA":return{...e,isMfaRequired:!1,mfaMethods:[]};case"SET_BACKEND_CONFIG":return{...e,backendConfig:t.config};case"SET_TENANT":return{...e,tenantId:t.tenantId??null};case"RESET":return{status:x.UNAUTHENTICATED,isLoading:!1,isLoadingUser:!1,user:null,session:null,tokens:null,error:null,isMfaRequired:!1,mfaMethods:[],backendConfig:e.backendConfig,tenantId:e.backendConfig?.tenants?.defaultTenantId??null};default:return e}},N=(e,t,n)=>{e.emit(t,{type:t,payload:n})},cn=e=>e&&typeof e.getTokens=="function"?e:ft(e),un=e=>{const t=A.useRef(void 0),n=A.useRef(void 0);return(!t.current||n.current!==e.tokenStorage)&&(t.current=cn(e.tokenStorage),n.current=e.tokenStorage),t.current},ln=({config:e,children:t,loadingFallback:n=null,autoLoadProfile:s=!0})=>{const r=un(e),i=A.useRef(new it),[o,a]=A.useReducer(an,on(r,e)),f=A.useMemo(()=>ut({baseUrl:e.baseUrl,endpoints:e.endpoints,defaultHeaders:e.defaultHeaders}),[e.baseUrl,e.endpoints,e.defaultHeaders]),l=A.useRef(o.tokens);l.current=o.tokens;const c=()=>r.getTokens()??l.current??null,p=A.useRef(null);p.current?p.current.setTokenResolver(c):p.current=new dt({client:f,events:i.current,readTokens:c});const T=p.current,R=m=>{if(!m||!m.accessToken){r.clear(),a({type:"SET_TOKENS",tokens:null}),l.current=null,T?.reset();return}r.setTokens(m),a({type:"SET_TOKENS",tokens:m}),l.current=m,r.getTokens()?.accessToken||console.error("[NestAuth] Warning: Tokens were not persisted correctly to storage")},d=async(m,E={})=>m.isRequiresMfa?(a({type:"SET_MFA_REQUIRED",methods:o.backendConfig?.mfa.methods??[]}),N(i.current,_.MFA_REQUIRED,{methods:o.backendConfig?.mfa.methods??[]}),m):(m.accessToken&&R({accessToken:m.accessToken,refreshToken:m.refreshToken??null}),a({type:"CLEAR_MFA"}),E.skipProfileFetch?m.user&&(a({type:"SET_USER",user:m.user??null}),a({type:"SET_STATUS",status:x.AUTHENTICATED}),N(i.current,_.SIGNED_IN,{user:m.user,tokens:{accessToken:m.accessToken??"",refreshToken:m.refreshToken??null}}),$("login")):(await y(),$("login")),m),y=async()=>{const m=c();if(!m?.accessToken)return null;try{a({type:"SET_LOADING",value:!0}),a({type:"SET_LOADING_USER",value:!0});const E=await f.getProfile(m),w=await f.getSession(m).catch(()=>null);a({type:"SET_USER",user:E}),a({type:"SET_SESSION",session:w}),a({type:"SET_STATUS",status:x.AUTHENTICATED}),a({type:"SET_LOADING",value:!1}),N(i.current,_.PROFILE_LOADED,{user:E,session:w});const j=c();return e.onSignedIn?.({user:E,session:w,tokens:j??m}),T?.ensureStatusLoaded(),E}catch(E){return a({type:"SET_ERROR",error:E}),a({type:"SET_LOADING",value:!1}),a({type:"SET_LOADING_USER",value:!1}),E?.status===401||E?.status===403||E?.message?.includes("Unauthorized")||E?.message?.includes("Forbidden")?(a({type:"SET_STATUS",status:x.UNAUTHENTICATED}),r.clear()):console.warn("[NestAuth] Failed to load profile, but keeping tokens:",E),null}},h=async()=>{try{a({type:"SET_LOADING",value:!0});const m=await f.fetchClientConfig(),E=ke(m);return a({type:"SET_BACKEND_CONFIG",config:E}),a({type:"SET_TENANT",tenantId:E.tenants.defaultTenantId??null}),N(i.current,_.CONFIG_LOADED,E),E}catch(m){if(console.error("[NestAuth] Failed to fetch backend config:",m),a({type:"SET_ERROR",error:m}),e.initialBackendConfig){const E=ke(e.initialBackendConfig);return a({type:"SET_BACKEND_CONFIG",config:E}),E}return o.backendConfig??null}finally{a({type:"SET_LOADING",value:!1})}};A.useEffect(()=>{let m=!0;return m&&(async()=>{e.autoFetchConfig&&await h();const w=c();s&&w?.accessToken?await y():w||a({type:"SET_STATUS",status:x.UNAUTHENTICATED})})(),()=>{m=!1}},[e.autoFetchConfig,s,o.tokens?.accessToken]);const b=()=>a({type:"SET_ERROR",error:null}),O=async m=>{a({type:"SET_LOADING",value:!0}),b();try{const E=await f.login({...m,tenantId:m.tenantId??o.tenantId??void 0}),w=await d(E);return a({type:"SET_LOADING",value:!1}),w}catch(E){throw a({type:"SET_ERROR",error:E}),a({type:"SET_LOADING",value:!1}),N(i.current,_.ERROR,E),E}},S=async m=>{a({type:"SET_LOADING",value:!0}),b();try{const E=await f.register({...m,tenantId:m.tenantId??o.tenantId??void 0}),w=await d(E);return a({type:"SET_LOADING",value:!1}),w}catch(E){throw a({type:"SET_ERROR",error:E}),a({type:"SET_LOADING",value:!1}),N(i.current,_.ERROR,E),E}},v=async()=>{const m=c();if(!m){a({type:"RESET"}),r.clear();return}a({type:"SET_LOADING",value:!0}),b();try{await f.logout(m),r.clear(),a({type:"RESET"}),N(i.current,_.SIGNED_OUT),e.onSignedOut?.(),$("logout")}catch(E){throw a({type:"SET_ERROR",error:E}),N(i.current,_.ERROR,E),E}finally{a({type:"SET_LOADING",value:!1})}},C=async()=>{const m=c();if(m){a({type:"SET_LOADING",value:!0}),b();try{await f.logoutAll(m),r.clear(),a({type:"RESET"}),N(i.current,_.SIGNED_OUT),e.onSignedOut?.(),$("logout")}catch(E){throw a({type:"SET_ERROR",error:E}),N(i.current,_.ERROR,E),E}finally{a({type:"SET_LOADING",value:!1})}}},G=async()=>{const m=c();if(!m?.refreshToken)return null;try{const E=await f.refreshToken({refreshToken:m.refreshToken}),w={accessToken:E.accessToken,refreshToken:E.refreshToken??m.refreshToken};return R(w),N(i.current,_.TOKEN_REFRESHED,w),e.onTokenRefreshed?.(w),s&&await y(),E}catch(E){return a({type:"SET_ERROR",error:E}),r.clear(),a({type:"RESET"}),N(i.current,_.ERROR,E),null}},L=async m=>{const E=c();if(!E)throw new Error("Cannot send MFA code without an authenticated session");return f.sendMfaCode(E,m)},ne=async m=>{const E=c();if(!E)throw new Error("Cannot verify MFA without an authenticated session");a({type:"SET_LOADING",value:!0}),b();try{const w=await f.verifyMfa(E,m);a({type:"CLEAR_MFA"});const j=await d(w);return a({type:"SET_LOADING",value:!1}),$("afterMfa"),j}catch(w){throw a({type:"SET_ERROR",error:w}),a({type:"SET_LOADING",value:!1}),N(i.current,_.ERROR,w),w}},Q=m=>f.forgotPassword(m),ce=m=>f.verifyForgotPasswordOtp(m),ue=m=>f.resetPasswordWithToken(m),Y=async m=>{const E=c();if(!E?.accessToken)throw new Error("Cannot change password without an authenticated session");a({type:"SET_LOADING",value:!0});try{const w=await f.changePassword(m,E),j={accessToken:w.accessToken,refreshToken:w.refreshToken??E.refreshToken??null};return R(j),N(i.current,_.TOKEN_REFRESHED,j),e.onTokenRefreshed?.(j),await y(),a({type:"SET_LOADING",value:!1}),w}catch(w){throw a({type:"SET_ERROR",error:w}),a({type:"SET_LOADING",value:!1}),N(i.current,_.ERROR,w),w}},V=async()=>{const m=c();if(!m)throw new Error("Cannot send email verification without an authenticated session");a({type:"SET_LOADING",value:!0});try{return await f.sendEmailVerification(m)}catch(E){throw a({type:"SET_ERROR",error:E}),N(i.current,_.ERROR,E),E}finally{a({type:"SET_LOADING",value:!1})}},z=async m=>{const E=c();if(!E)throw new Error("Cannot verify email without an authenticated session");a({type:"SET_LOADING",value:!0});try{const w=await f.verifyEmail(E,m);return await y(),w}catch(w){throw a({type:"SET_ERROR",error:w}),N(i.current,_.ERROR,w),w}finally{a({type:"SET_LOADING",value:!1})}},le=(m,E)=>{if(E?.persist===!1){a({type:"SET_TOKENS",tokens:m}),l.current=m,m?.accessToken||T?.reset();return}R(m)},F=m=>{a({type:"SET_TENANT",tenantId:m})},fe=m=>{a({type:"SET_USER",user:m})},M=m=>{m&&(e.onRedirect?e.onRedirect(m):typeof window<"u"&&(window.location.href=m))},$=m=>{const E=e.redirects?.[m];E&&M(E)},Re={status:o.status,user:o.user,session:o.session,tokens:o.tokens,isMfaRequired:o.isMfaRequired,mfaMethods:o.mfaMethods,backendConfig:o.backendConfig??void 0,tenantId:o.tenantId??void 0,error:o.error,isLoading:o.isLoading||o.status===x.LOADING,isLoadingUser:o.isLoadingUser,baseUrl:e.baseUrl,events:i.current,login:O,register:S,logout:v,logoutAll:C,refresh:G,sendMfaCode:L,verifyMfa:ne,forgotPassword:Q,verifyForgotPasswordOtp:ce,resetPasswordWithToken:ue,changePassword:Y,sendEmailVerification:V,verifyEmail:z,fetchBackendConfig:h,setTokens:le,setTenantId:F,clearError:b,setUser:fe,redirects:e.redirects,navigate:M},H=o.isLoading&&n?n:t;return Fe.jsx(at.Provider,{value:Re,children:Fe.jsx(ct.Provider,{value:T,children:H})})};function ht(e,t){return function(){return e.apply(t,arguments)}}const{toString:fn}=Object.prototype,{getPrototypeOf:Pe}=Object,{iterator:ye,toStringTag:pt}=Symbol,Te=(e=>t=>{const n=fn.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),B=e=>(e=e.toLowerCase(),t=>Te(t)===e),ge=e=>t=>typeof t===e,{isArray:ee}=Array,Z=ge("undefined");function re(e){return e!==null&&!Z(e)&&e.constructor!==null&&!Z(e.constructor)&&I(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const mt=B("ArrayBuffer");function dn(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&mt(e.buffer),t}const hn=ge("string"),I=ge("function"),Et=ge("number"),oe=e=>e!==null&&typeof e=="object",pn=e=>e===!0||e===!1,he=e=>{if(Te(e)!=="object")return!1;const t=Pe(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(pt in e)&&!(ye in e)},mn=e=>{if(!oe(e)||re(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},En=B("Date"),yn=B("File"),Tn=B("Blob"),gn=B("FileList"),Sn=e=>oe(e)&&I(e.pipe),wn=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||I(e.append)&&((t=Te(e))==="formdata"||t==="object"&&I(e.toString)&&e.toString()==="[object FormData]"))},Rn=B("URLSearchParams"),[bn,An,On,_n]=["ReadableStream","Request","Response","Headers"].map(B),kn=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ie(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let s,r;if(typeof e!="object"&&(e=[e]),ee(e))for(s=0,r=e.length;s<r;s++)t.call(null,e[s],s,e);else{if(re(e))return;const i=n?Object.getOwnPropertyNames(e):Object.keys(e),o=i.length;let a;for(s=0;s<o;s++)a=i[s],t.call(null,e[a],a,e)}}function yt(e,t){if(re(e))return null;t=t.toLowerCase();const n=Object.keys(e);let s=n.length,r;for(;s-- >0;)if(r=n[s],t===r.toLowerCase())return r;return null}const K=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Tt=e=>!Z(e)&&e!==K;function Ce(){const{caseless:e,skipUndefined:t}=Tt(this)&&this||{},n={},s=(r,i)=>{const o=e&&yt(n,i)||i;he(n[o])&&he(r)?n[o]=Ce(n[o],r):he(r)?n[o]=Ce({},r):ee(r)?n[o]=r.slice():(!t||!Z(r))&&(n[o]=r)};for(let r=0,i=arguments.length;r<i;r++)arguments[r]&&ie(arguments[r],s);return n}const Cn=(e,t,n,{allOwnKeys:s}={})=>(ie(t,(r,i)=>{n&&I(r)?e[i]=ht(r,n):e[i]=r},{allOwnKeys:s}),e),vn=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Nn=(e,t,n,s)=>{e.prototype=Object.create(t.prototype,s),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Dn=(e,t,n,s)=>{let r,i,o;const a={};if(t=t||{},e==null)return t;do{for(r=Object.getOwnPropertyNames(e),i=r.length;i-- >0;)o=r[i],(!s||s(o,e,t))&&!a[o]&&(t[o]=e[o],a[o]=!0);e=n!==!1&&Pe(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Ln=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const s=e.indexOf(t,n);return s!==-1&&s===n},In=e=>{if(!e)return null;if(ee(e))return e;let t=e.length;if(!Et(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Pn=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Pe(Uint8Array)),Un=(e,t)=>{const s=(e&&e[ye]).call(e);let r;for(;(r=s.next())&&!r.done;){const i=r.value;t.call(e,i[0],i[1])}},xn=(e,t)=>{let n;const s=[];for(;(n=e.exec(t))!==null;)s.push(n);return s},Fn=B("HTMLFormElement"),Mn=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,s,r){return s.toUpperCase()+r}),Ge=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Bn=B("RegExp"),gt=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),s={};ie(n,(r,i)=>{let o;(o=t(r,i,e))!==!1&&(s[i]=o||r)}),Object.defineProperties(e,s)},Hn=e=>{gt(e,(t,n)=>{if(I(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const s=e[n];if(I(s)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},jn=(e,t)=>{const n={},s=r=>{r.forEach(i=>{n[i]=!0})};return ee(e)?s(e):s(String(e).split(t)),n},qn=()=>{},Gn=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function zn(e){return!!(e&&I(e.append)&&e[pt]==="FormData"&&e[ye])}const $n=e=>{const t=new Array(10),n=(s,r)=>{if(oe(s)){if(t.indexOf(s)>=0)return;if(re(s))return s;if(!("toJSON"in s)){t[r]=s;const i=ee(s)?[]:{};return ie(s,(o,a)=>{const f=n(o,r+1);!Z(f)&&(i[a]=f)}),t[r]=void 0,i}}return s};return n(e,0)},Vn=B("AsyncFunction"),Kn=e=>e&&(oe(e)||I(e))&&I(e.then)&&I(e.catch),St=((e,t)=>e?setImmediate:t?((n,s)=>(K.addEventListener("message",({source:r,data:i})=>{r===K&&i===n&&s.length&&s.shift()()},!1),r=>{s.push(r),K.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",I(K.postMessage)),Jn=typeof queueMicrotask<"u"?queueMicrotask.bind(K):typeof process<"u"&&process.nextTick||St,Wn=e=>e!=null&&I(e[ye]),u={isArray:ee,isArrayBuffer:mt,isBuffer:re,isFormData:wn,isArrayBufferView:dn,isString:hn,isNumber:Et,isBoolean:pn,isObject:oe,isPlainObject:he,isEmptyObject:mn,isReadableStream:bn,isRequest:An,isResponse:On,isHeaders:_n,isUndefined:Z,isDate:En,isFile:yn,isBlob:Tn,isRegExp:Bn,isFunction:I,isStream:Sn,isURLSearchParams:Rn,isTypedArray:Pn,isFileList:gn,forEach:ie,merge:Ce,extend:Cn,trim:kn,stripBOM:vn,inherits:Nn,toFlatObject:Dn,kindOf:Te,kindOfTest:B,endsWith:Ln,toArray:In,forEachEntry:Un,matchAll:xn,isHTMLForm:Fn,hasOwnProperty:Ge,hasOwnProp:Ge,reduceDescriptors:gt,freezeMethods:Hn,toObjectSet:jn,toCamelCase:Mn,noop:qn,toFiniteNumber:Gn,findKey:yt,global:K,isContextDefined:Tt,isSpecCompliantForm:zn,toJSONObject:$n,isAsyncFn:Vn,isThenable:Kn,setImmediate:St,asap:Jn,isIterable:Wn};function g(e,t,n,s,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),s&&(this.request=s),r&&(this.response=r,this.status=r.status?r.status:null)}u.inherits(g,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:u.toJSONObject(this.config),code:this.code,status:this.status}}});const wt=g.prototype,Rt={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Rt[e]={value:e}});Object.defineProperties(g,Rt);Object.defineProperty(wt,"isAxiosError",{value:!0});g.from=(e,t,n,s,r,i)=>{const o=Object.create(wt);u.toFlatObject(e,o,function(c){return c!==Error.prototype},l=>l!=="isAxiosError");const a=e&&e.message?e.message:"Error",f=t==null&&e?e.code:t;return g.call(o,a,f,n,s,r),e&&o.cause==null&&Object.defineProperty(o,"cause",{value:e,configurable:!0}),o.name=e&&e.name||"Error",i&&Object.assign(o,i),o};const Xn=null;function ve(e){return u.isPlainObject(e)||u.isArray(e)}function bt(e){return u.endsWith(e,"[]")?e.slice(0,-2):e}function ze(e,t,n){return e?e.concat(t).map(function(r,i){return r=bt(r),!n&&i?"["+r+"]":r}).join(n?".":""):t}function Qn(e){return u.isArray(e)&&!e.some(ve)}const Yn=u.toFlatObject(u,{},null,function(t){return/^is[A-Z]/.test(t)});function Se(e,t,n){if(!u.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=u.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,h){return!u.isUndefined(h[y])});const s=n.metaTokens,r=n.visitor||c,i=n.dots,o=n.indexes,f=(n.Blob||typeof Blob<"u"&&Blob)&&u.isSpecCompliantForm(t);if(!u.isFunction(r))throw new TypeError("visitor must be a function");function l(d){if(d===null)return"";if(u.isDate(d))return d.toISOString();if(u.isBoolean(d))return d.toString();if(!f&&u.isBlob(d))throw new g("Blob is not supported. Use a Buffer instead.");return u.isArrayBuffer(d)||u.isTypedArray(d)?f&&typeof Blob=="function"?new Blob([d]):Buffer.from(d):d}function c(d,y,h){let b=d;if(d&&!h&&typeof d=="object"){if(u.endsWith(y,"{}"))y=s?y:y.slice(0,-2),d=JSON.stringify(d);else if(u.isArray(d)&&Qn(d)||(u.isFileList(d)||u.endsWith(y,"[]"))&&(b=u.toArray(d)))return y=bt(y),b.forEach(function(S,v){!(u.isUndefined(S)||S===null)&&t.append(o===!0?ze([y],v,i):o===null?y:y+"[]",l(S))}),!1}return ve(d)?!0:(t.append(ze(h,y,i),l(d)),!1)}const p=[],T=Object.assign(Yn,{defaultVisitor:c,convertValue:l,isVisitable:ve});function R(d,y){if(!u.isUndefined(d)){if(p.indexOf(d)!==-1)throw Error("Circular reference detected in "+y.join("."));p.push(d),u.forEach(d,function(b,O){(!(u.isUndefined(b)||b===null)&&r.call(t,b,u.isString(O)?O.trim():O,y,T))===!0&&R(b,y?y.concat(O):[O])}),p.pop()}}if(!u.isObject(e))throw new TypeError("data must be an object");return R(e),t}function $e(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(s){return t[s]})}function Ue(e,t){this._pairs=[],e&&Se(e,this,t)}const At=Ue.prototype;At.append=function(t,n){this._pairs.push([t,n])};At.toString=function(t){const n=t?function(s){return t.call(this,s,$e)}:$e;return this._pairs.map(function(r){return n(r[0])+"="+n(r[1])},"").join("&")};function Zn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ot(e,t,n){if(!t)return e;const s=n&&n.encode||Zn;u.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let i;if(r?i=r(t,n):i=u.isURLSearchParams(t)?t.toString():new Ue(t,n).toString(s),i){const o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class Ve{constructor(){this.handlers=[]}use(t,n,s){return this.handlers.push({fulfilled:t,rejected:n,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){u.forEach(this.handlers,function(s){s!==null&&t(s)})}}const _t={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},es=typeof URLSearchParams<"u"?URLSearchParams:Ue,ts=typeof FormData<"u"?FormData:null,ns=typeof Blob<"u"?Blob:null,ss={isBrowser:!0,classes:{URLSearchParams:es,FormData:ts,Blob:ns},protocols:["http","https","file","blob","url","data"]},xe=typeof window<"u"&&typeof document<"u",Ne=typeof navigator=="object"&&navigator||void 0,rs=xe&&(!Ne||["ReactNative","NativeScript","NS"].indexOf(Ne.product)<0),os=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",is=xe&&window.location.href||"http://localhost",as=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:xe,hasStandardBrowserEnv:rs,hasStandardBrowserWebWorkerEnv:os,navigator:Ne,origin:is},Symbol.toStringTag,{value:"Module"})),D={...as,...ss};function cs(e,t){return Se(e,new D.classes.URLSearchParams,{visitor:function(n,s,r,i){return D.isNode&&u.isBuffer(n)?(this.append(s,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function us(e){return u.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function ls(e){const t={},n=Object.keys(e);let s;const r=n.length;let i;for(s=0;s<r;s++)i=n[s],t[i]=e[i];return t}function kt(e){function t(n,s,r,i){let o=n[i++];if(o==="__proto__")return!0;const a=Number.isFinite(+o),f=i>=n.length;return o=!o&&u.isArray(r)?r.length:o,f?(u.hasOwnProp(r,o)?r[o]=[r[o],s]:r[o]=s,!a):((!r[o]||!u.isObject(r[o]))&&(r[o]=[]),t(n,s,r[o],i)&&u.isArray(r[o])&&(r[o]=ls(r[o])),!a)}if(u.isFormData(e)&&u.isFunction(e.entries)){const n={};return u.forEachEntry(e,(s,r)=>{t(us(s),r,n,0)}),n}return null}function fs(e,t,n){if(u.isString(e))try{return(t||JSON.parse)(e),u.trim(e)}catch(s){if(s.name!=="SyntaxError")throw s}return(n||JSON.stringify)(e)}const ae={transitional:_t,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const s=n.getContentType()||"",r=s.indexOf("application/json")>-1,i=u.isObject(t);if(i&&u.isHTMLForm(t)&&(t=new FormData(t)),u.isFormData(t))return r?JSON.stringify(kt(t)):t;if(u.isArrayBuffer(t)||u.isBuffer(t)||u.isStream(t)||u.isFile(t)||u.isBlob(t)||u.isReadableStream(t))return t;if(u.isArrayBufferView(t))return t.buffer;if(u.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(i){if(s.indexOf("application/x-www-form-urlencoded")>-1)return cs(t,this.formSerializer).toString();if((a=u.isFileList(t))||s.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return Se(a?{"files[]":t}:t,f&&new f,this.formSerializer)}}return i||r?(n.setContentType("application/json",!1),fs(t)):t}],transformResponse:[function(t){const n=this.transitional||ae.transitional,s=n&&n.forcedJSONParsing,r=this.responseType==="json";if(u.isResponse(t)||u.isReadableStream(t))return t;if(t&&u.isString(t)&&(s&&!this.responseType||r)){const o=!(n&&n.silentJSONParsing)&&r;try{return JSON.parse(t,this.parseReviver)}catch(a){if(o)throw a.name==="SyntaxError"?g.from(a,g.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:D.classes.FormData,Blob:D.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};u.forEach(["delete","get","head","post","put","patch"],e=>{ae.headers[e]={}});const ds=u.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),hs=e=>{const t={};let n,s,r;return e&&e.split(`
2
- `).forEach(function(o){r=o.indexOf(":"),n=o.substring(0,r).trim().toLowerCase(),s=o.substring(r+1).trim(),!(!n||t[n]&&ds[n])&&(n==="set-cookie"?t[n]?t[n].push(s):t[n]=[s]:t[n]=t[n]?t[n]+", "+s:s)}),t},Ke=Symbol("internals");function se(e){return e&&String(e).trim().toLowerCase()}function pe(e){return e===!1||e==null?e:u.isArray(e)?e.map(pe):String(e)}function ps(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(e);)t[s[1]]=s[2];return t}const ms=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ae(e,t,n,s,r){if(u.isFunction(s))return s.call(this,t,n);if(r&&(t=n),!!u.isString(t)){if(u.isString(s))return t.indexOf(s)!==-1;if(u.isRegExp(s))return s.test(t)}}function Es(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,s)=>n.toUpperCase()+s)}function ys(e,t){const n=u.toCamelCase(" "+t);["get","set","has"].forEach(s=>{Object.defineProperty(e,s+n,{value:function(r,i,o){return this[s].call(this,t,r,i,o)},configurable:!0})})}let P=class{constructor(t){t&&this.set(t)}set(t,n,s){const r=this;function i(a,f,l){const c=se(f);if(!c)throw new Error("header name must be a non-empty string");const p=u.findKey(r,c);(!p||r[p]===void 0||l===!0||l===void 0&&r[p]!==!1)&&(r[p||f]=pe(a))}const o=(a,f)=>u.forEach(a,(l,c)=>i(l,c,f));if(u.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if(u.isString(t)&&(t=t.trim())&&!ms(t))o(hs(t),n);else if(u.isObject(t)&&u.isIterable(t)){let a={},f,l;for(const c of t){if(!u.isArray(c))throw TypeError("Object iterator must return a key-value pair");a[l=c[0]]=(f=a[l])?u.isArray(f)?[...f,c[1]]:[f,c[1]]:c[1]}o(a,n)}else t!=null&&i(n,t,s);return this}get(t,n){if(t=se(t),t){const s=u.findKey(this,t);if(s){const r=this[s];if(!n)return r;if(n===!0)return ps(r);if(u.isFunction(n))return n.call(this,r,s);if(u.isRegExp(n))return n.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=se(t),t){const s=u.findKey(this,t);return!!(s&&this[s]!==void 0&&(!n||Ae(this,this[s],s,n)))}return!1}delete(t,n){const s=this;let r=!1;function i(o){if(o=se(o),o){const a=u.findKey(s,o);a&&(!n||Ae(s,s[a],a,n))&&(delete s[a],r=!0)}}return u.isArray(t)?t.forEach(i):i(t),r}clear(t){const n=Object.keys(this);let s=n.length,r=!1;for(;s--;){const i=n[s];(!t||Ae(this,this[i],i,t,!0))&&(delete this[i],r=!0)}return r}normalize(t){const n=this,s={};return u.forEach(this,(r,i)=>{const o=u.findKey(s,i);if(o){n[o]=pe(r),delete n[i];return}const a=t?Es(i):String(i).trim();a!==i&&delete n[i],n[a]=pe(r),s[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return u.forEach(this,(s,r)=>{s!=null&&s!==!1&&(n[r]=t&&u.isArray(s)?s.join(", "):s)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
3
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const s=new this(t);return n.forEach(r=>s.set(r)),s}static accessor(t){const s=(this[Ke]=this[Ke]={accessors:{}}).accessors,r=this.prototype;function i(o){const a=se(o);s[a]||(ys(r,o),s[a]=!0)}return u.isArray(t)?t.forEach(i):i(t),this}};P.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);u.reduceDescriptors(P.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(s){this[n]=s}}});u.freezeMethods(P);function Oe(e,t){const n=this||ae,s=t||n,r=P.from(s.headers);let i=s.data;return u.forEach(e,function(a){i=a.call(n,i,r.normalize(),t?t.status:void 0)}),r.normalize(),i}function Ct(e){return!!(e&&e.__CANCEL__)}function te(e,t,n){g.call(this,e??"canceled",g.ERR_CANCELED,t,n),this.name="CanceledError"}u.inherits(te,g,{__CANCEL__:!0});function vt(e,t,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?e(n):t(new g("Request failed with status code "+n.status,[g.ERR_BAD_REQUEST,g.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Ts(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function gs(e,t){e=e||10;const n=new Array(e),s=new Array(e);let r=0,i=0,o;return t=t!==void 0?t:1e3,function(f){const l=Date.now(),c=s[i];o||(o=l),n[r]=f,s[r]=l;let p=i,T=0;for(;p!==r;)T+=n[p++],p=p%e;if(r=(r+1)%e,r===i&&(i=(i+1)%e),l-o<t)return;const R=c&&l-c;return R?Math.round(T*1e3/R):void 0}}function Ss(e,t){let n=0,s=1e3/t,r,i;const o=(l,c=Date.now())=>{n=c,r=null,i&&(clearTimeout(i),i=null),e(...l)};return[(...l)=>{const c=Date.now(),p=c-n;p>=s?o(l,c):(r=l,i||(i=setTimeout(()=>{i=null,o(r)},s-p)))},()=>r&&o(r)]}const Ee=(e,t,n=3)=>{let s=0;const r=gs(50,250);return Ss(i=>{const o=i.loaded,a=i.lengthComputable?i.total:void 0,f=o-s,l=r(f),c=o<=a;s=o;const p={loaded:o,total:a,progress:a?o/a:void 0,bytes:f,rate:l||void 0,estimated:l&&a&&c?(a-o)/l:void 0,event:i,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(p)},n)},Je=(e,t)=>{const n=e!=null;return[s=>t[0]({lengthComputable:n,total:e,loaded:s}),t[1]]},We=e=>(...t)=>u.asap(()=>e(...t)),ws=D.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,D.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(D.origin),D.navigator&&/(msie|trident)/i.test(D.navigator.userAgent)):()=>!0,Rs=D.hasStandardBrowserEnv?{write(e,t,n,s,r,i){const o=[e+"="+encodeURIComponent(t)];u.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),u.isString(s)&&o.push("path="+s),u.isString(r)&&o.push("domain="+r),i===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function bs(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function As(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Nt(e,t,n){let s=!bs(t);return e&&(s||n==!1)?As(e,t):t}const Xe=e=>e instanceof P?{...e}:e;function X(e,t){t=t||{};const n={};function s(l,c,p,T){return u.isPlainObject(l)&&u.isPlainObject(c)?u.merge.call({caseless:T},l,c):u.isPlainObject(c)?u.merge({},c):u.isArray(c)?c.slice():c}function r(l,c,p,T){if(u.isUndefined(c)){if(!u.isUndefined(l))return s(void 0,l,p,T)}else return s(l,c,p,T)}function i(l,c){if(!u.isUndefined(c))return s(void 0,c)}function o(l,c){if(u.isUndefined(c)){if(!u.isUndefined(l))return s(void 0,l)}else return s(void 0,c)}function a(l,c,p){if(p in t)return s(l,c);if(p in e)return s(void 0,l)}const f={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(l,c,p)=>r(Xe(l),Xe(c),p,!0)};return u.forEach(Object.keys({...e,...t}),function(c){const p=f[c]||r,T=p(e[c],t[c],c);u.isUndefined(T)&&p!==a||(n[c]=T)}),n}const Dt=e=>{const t=X({},e);let{data:n,withXSRFToken:s,xsrfHeaderName:r,xsrfCookieName:i,headers:o,auth:a}=t;if(t.headers=o=P.from(o),t.url=Ot(Nt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),u.isFormData(n)){if(D.hasStandardBrowserEnv||D.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(u.isFunction(n.getHeaders)){const f=n.getHeaders(),l=["content-type","content-length"];Object.entries(f).forEach(([c,p])=>{l.includes(c.toLowerCase())&&o.set(c,p)})}}if(D.hasStandardBrowserEnv&&(s&&u.isFunction(s)&&(s=s(t)),s||s!==!1&&ws(t.url))){const f=r&&i&&Rs.read(i);f&&o.set(r,f)}return t},Os=typeof XMLHttpRequest<"u",_s=Os&&function(e){return new Promise(function(n,s){const r=Dt(e);let i=r.data;const o=P.from(r.headers).normalize();let{responseType:a,onUploadProgress:f,onDownloadProgress:l}=r,c,p,T,R,d;function y(){R&&R(),d&&d(),r.cancelToken&&r.cancelToken.unsubscribe(c),r.signal&&r.signal.removeEventListener("abort",c)}let h=new XMLHttpRequest;h.open(r.method.toUpperCase(),r.url,!0),h.timeout=r.timeout;function b(){if(!h)return;const S=P.from("getAllResponseHeaders"in h&&h.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:S,config:e,request:h};vt(function(L){n(L),y()},function(L){s(L),y()},C),h=null}"onloadend"in h?h.onloadend=b:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf("file:")===0)||setTimeout(b)},h.onabort=function(){h&&(s(new g("Request aborted",g.ECONNABORTED,e,h)),h=null)},h.onerror=function(v){const C=v&&v.message?v.message:"Network Error",G=new g(C,g.ERR_NETWORK,e,h);G.event=v||null,s(G),h=null},h.ontimeout=function(){let v=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const C=r.transitional||_t;r.timeoutErrorMessage&&(v=r.timeoutErrorMessage),s(new g(v,C.clarifyTimeoutError?g.ETIMEDOUT:g.ECONNABORTED,e,h)),h=null},i===void 0&&o.setContentType(null),"setRequestHeader"in h&&u.forEach(o.toJSON(),function(v,C){h.setRequestHeader(C,v)}),u.isUndefined(r.withCredentials)||(h.withCredentials=!!r.withCredentials),a&&a!=="json"&&(h.responseType=r.responseType),l&&([T,d]=Ee(l,!0),h.addEventListener("progress",T)),f&&h.upload&&([p,R]=Ee(f),h.upload.addEventListener("progress",p),h.upload.addEventListener("loadend",R)),(r.cancelToken||r.signal)&&(c=S=>{h&&(s(!S||S.type?new te(null,e,h):S),h.abort(),h=null)},r.cancelToken&&r.cancelToken.subscribe(c),r.signal&&(r.signal.aborted?c():r.signal.addEventListener("abort",c)));const O=Ts(r.url);if(O&&D.protocols.indexOf(O)===-1){s(new g("Unsupported protocol "+O+":",g.ERR_BAD_REQUEST,e));return}h.send(i||null)})},ks=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let s=new AbortController,r;const i=function(l){if(!r){r=!0,a();const c=l instanceof Error?l:this.reason;s.abort(c instanceof g?c:new te(c instanceof Error?c.message:c))}};let o=t&&setTimeout(()=>{o=null,i(new g(`timeout ${t} of ms exceeded`,g.ETIMEDOUT))},t);const a=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(l=>{l.unsubscribe?l.unsubscribe(i):l.removeEventListener("abort",i)}),e=null)};e.forEach(l=>l.addEventListener("abort",i));const{signal:f}=s;return f.unsubscribe=()=>u.asap(a),f}},Cs=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let s=0,r;for(;s<n;)r=s+t,yield e.slice(s,r),s=r},vs=async function*(e,t){for await(const n of Ns(e))yield*Cs(n,t)},Ns=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:s}=await t.read();if(n)break;yield s}}finally{await t.cancel()}},Qe=(e,t,n,s)=>{const r=vs(e,t);let i=0,o,a=f=>{o||(o=!0,s&&s(f))};return new ReadableStream({async pull(f){try{const{done:l,value:c}=await r.next();if(l){a(),f.close();return}let p=c.byteLength;if(n){let T=i+=p;n(T)}f.enqueue(new Uint8Array(c))}catch(l){throw a(l),l}},cancel(f){return a(f),r.return()}},{highWaterMark:2})},Ye=64*1024,{isFunction:de}=u,Ds=(({Request:e,Response:t})=>({Request:e,Response:t}))(u.global),{ReadableStream:Ze,TextEncoder:et}=u.global,tt=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Ls=e=>{e=u.merge.call({skipUndefined:!0},Ds,e);const{fetch:t,Request:n,Response:s}=e,r=t?de(t):typeof fetch=="function",i=de(n),o=de(s);if(!r)return!1;const a=r&&de(Ze),f=r&&(typeof et=="function"?(d=>y=>d.encode(y))(new et):async d=>new Uint8Array(await new n(d).arrayBuffer())),l=i&&a&&tt(()=>{let d=!1;const y=new n(D.origin,{body:new Ze,method:"POST",get duplex(){return d=!0,"half"}}).headers.has("Content-Type");return d&&!y}),c=o&&a&&tt(()=>u.isReadableStream(new s("").body)),p={stream:c&&(d=>d.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(d=>{!p[d]&&(p[d]=(y,h)=>{let b=y&&y[d];if(b)return b.call(y);throw new g(`Response type '${d}' is not supported`,g.ERR_NOT_SUPPORT,h)})});const T=async d=>{if(d==null)return 0;if(u.isBlob(d))return d.size;if(u.isSpecCompliantForm(d))return(await new n(D.origin,{method:"POST",body:d}).arrayBuffer()).byteLength;if(u.isArrayBufferView(d)||u.isArrayBuffer(d))return d.byteLength;if(u.isURLSearchParams(d)&&(d=d+""),u.isString(d))return(await f(d)).byteLength},R=async(d,y)=>{const h=u.toFiniteNumber(d.getContentLength());return h??T(y)};return async d=>{let{url:y,method:h,data:b,signal:O,cancelToken:S,timeout:v,onDownloadProgress:C,onUploadProgress:G,responseType:L,headers:ne,withCredentials:Q="same-origin",fetchOptions:ce}=Dt(d),ue=t||fetch;L=L?(L+"").toLowerCase():"text";let Y=ks([O,S&&S.toAbortSignal()],v),V=null;const z=Y&&Y.unsubscribe&&(()=>{Y.unsubscribe()});let le;try{if(G&&l&&h!=="get"&&h!=="head"&&(le=await R(ne,b))!==0){let H=new n(y,{method:"POST",body:b,duplex:"half"}),m;if(u.isFormData(b)&&(m=H.headers.get("content-type"))&&ne.setContentType(m),H.body){const[E,w]=Je(le,Ee(We(G)));b=Qe(H.body,Ye,E,w)}}u.isString(Q)||(Q=Q?"include":"omit");const F=i&&"credentials"in n.prototype,fe={...ce,signal:Y,method:h.toUpperCase(),headers:ne.normalize().toJSON(),body:b,duplex:"half",credentials:F?Q:void 0};V=i&&new n(y,fe);let M=await(i?ue(V,ce):ue(y,fe));const $=c&&(L==="stream"||L==="response");if(c&&(C||$&&z)){const H={};["status","statusText","headers"].forEach(j=>{H[j]=M[j]});const m=u.toFiniteNumber(M.headers.get("content-length")),[E,w]=C&&Je(m,Ee(We(C),!0))||[];M=new s(Qe(M.body,Ye,E,()=>{w&&w(),z&&z()}),H)}L=L||"text";let Re=await p[u.findKey(p,L)||"text"](M,d);return!$&&z&&z(),await new Promise((H,m)=>{vt(H,m,{data:Re,headers:P.from(M.headers),status:M.status,statusText:M.statusText,config:d,request:V})})}catch(F){throw z&&z(),F&&F.name==="TypeError"&&/Load failed|fetch/i.test(F.message)?Object.assign(new g("Network Error",g.ERR_NETWORK,d,V),{cause:F.cause||F}):g.from(F,F&&F.code,d,V)}}},Is=new Map,Lt=e=>{let t=e?e.env:{};const{fetch:n,Request:s,Response:r}=t,i=[s,r,n];let o=i.length,a=o,f,l,c=Is;for(;a--;)f=i[a],l=c.get(f),l===void 0&&c.set(f,l=a?new Map:Ls(t)),c=l;return l};Lt();const De={http:Xn,xhr:_s,fetch:{get:Lt}};u.forEach(De,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const nt=e=>`- ${e}`,Ps=e=>u.isFunction(e)||e===null||e===!1,It={getAdapter:(e,t)=>{e=u.isArray(e)?e:[e];const{length:n}=e;let s,r;const i={};for(let o=0;o<n;o++){s=e[o];let a;if(r=s,!Ps(s)&&(r=De[(a=String(s)).toLowerCase()],r===void 0))throw new g(`Unknown adapter '${a}'`);if(r&&(u.isFunction(r)||(r=r.get(t))))break;i[a||"#"+o]=r}if(!r){const o=Object.entries(i).map(([f,l])=>`adapter ${f} `+(l===!1?"is not supported by the environment":"is not available in the build"));let a=n?o.length>1?`since :
4
- `+o.map(nt).join(`
5
- `):" "+nt(o[0]):"as no adapter specified";throw new g("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return r},adapters:De};function _e(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new te(null,e)}function st(e){return _e(e),e.headers=P.from(e.headers),e.data=Oe.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),It.getAdapter(e.adapter||ae.adapter,e)(e).then(function(s){return _e(e),s.data=Oe.call(e,e.transformResponse,s),s.headers=P.from(s.headers),s},function(s){return Ct(s)||(_e(e),s&&s.response&&(s.response.data=Oe.call(e,e.transformResponse,s.response),s.response.headers=P.from(s.response.headers))),Promise.reject(s)})}const Pt="1.12.2",we={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{we[e]=function(s){return typeof s===e||"a"+(t<1?"n ":" ")+e}});const rt={};we.transitional=function(t,n,s){function r(i,o){return"[Axios v"+Pt+"] Transitional option '"+i+"'"+o+(s?". "+s:"")}return(i,o,a)=>{if(t===!1)throw new g(r(o," has been removed"+(n?" in "+n:"")),g.ERR_DEPRECATED);return n&&!rt[o]&&(rt[o]=!0,console.warn(r(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,o,a):!0}};we.spelling=function(t){return(n,s)=>(console.warn(`${s} is likely a misspelling of ${t}`),!0)};function Us(e,t,n){if(typeof e!="object")throw new g("options must be an object",g.ERR_BAD_OPTION_VALUE);const s=Object.keys(e);let r=s.length;for(;r-- >0;){const i=s[r],o=t[i];if(o){const a=e[i],f=a===void 0||o(a,i,e);if(f!==!0)throw new g("option "+i+" must be "+f,g.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new g("Unknown option "+i,g.ERR_BAD_OPTION)}}const me={assertOptions:Us,validators:we},q=me.validators;let J=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ve,response:new Ve}}async request(t,n){try{return await this._request(t,n)}catch(s){if(s instanceof Error){let r={};Error.captureStackTrace?Error.captureStackTrace(r):r=new Error;const i=r.stack?r.stack.replace(/^.+\n/,""):"";try{s.stack?i&&!String(s.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(s.stack+=`
6
- `+i):s.stack=i}catch{}}throw s}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=X(this.defaults,n);const{transitional:s,paramsSerializer:r,headers:i}=n;s!==void 0&&me.assertOptions(s,{silentJSONParsing:q.transitional(q.boolean),forcedJSONParsing:q.transitional(q.boolean),clarifyTimeoutError:q.transitional(q.boolean)},!1),r!=null&&(u.isFunction(r)?n.paramsSerializer={serialize:r}:me.assertOptions(r,{encode:q.function,serialize:q.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),me.assertOptions(n,{baseUrl:q.spelling("baseURL"),withXsrfToken:q.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=i&&u.merge(i.common,i[n.method]);i&&u.forEach(["delete","get","head","post","put","patch","common"],d=>{delete i[d]}),n.headers=P.concat(o,i);const a=[];let f=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(n)===!1||(f=f&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const l=[];this.interceptors.response.forEach(function(y){l.push(y.fulfilled,y.rejected)});let c,p=0,T;if(!f){const d=[st.bind(this),void 0];for(d.unshift(...a),d.push(...l),T=d.length,c=Promise.resolve(n);p<T;)c=c.then(d[p++],d[p++]);return c}T=a.length;let R=n;for(;p<T;){const d=a[p++],y=a[p++];try{R=d(R)}catch(h){y.call(this,h);break}}try{c=st.call(this,R)}catch(d){return Promise.reject(d)}for(p=0,T=l.length;p<T;)c=c.then(l[p++],l[p++]);return c}getUri(t){t=X(this.defaults,t);const n=Nt(t.baseURL,t.url,t.allowAbsoluteUrls);return Ot(n,t.params,t.paramsSerializer)}};u.forEach(["delete","get","head","options"],function(t){J.prototype[t]=function(n,s){return this.request(X(s||{},{method:t,url:n,data:(s||{}).data}))}});u.forEach(["post","put","patch"],function(t){function n(s){return function(i,o,a){return this.request(X(a||{},{method:t,headers:s?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}J.prototype[t]=n(),J.prototype[t+"Form"]=n(!0)});let xs=class Ut{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});const s=this;this.promise.then(r=>{if(!s._listeners)return;let i=s._listeners.length;for(;i-- >0;)s._listeners[i](r);s._listeners=null}),this.promise.then=r=>{let i;const o=new Promise(a=>{s.subscribe(a),i=a}).then(r);return o.cancel=function(){s.unsubscribe(i)},o},t(function(i,o,a){s.reason||(s.reason=new te(i,o,a),n(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=s=>{t.abort(s)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Ut(function(r){t=r}),cancel:t}}};function Fs(e){return function(n){return e.apply(null,n)}}function Ms(e){return u.isObject(e)&&e.isAxiosError===!0}const Le={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Le).forEach(([e,t])=>{Le[t]=e});function xt(e){const t=new J(e),n=ht(J.prototype.request,t);return u.extend(n,J.prototype,t,{allOwnKeys:!0}),u.extend(n,t,null,{allOwnKeys:!0}),n.create=function(r){return xt(X(e,r))},n}const k=xt(ae);k.Axios=J;k.CanceledError=te;k.CancelToken=xs;k.isCancel=Ct;k.VERSION=Pt;k.toFormData=Se;k.AxiosError=g;k.Cancel=k.CanceledError;k.all=function(t){return Promise.all(t)};k.spread=Fs;k.isAxiosError=Ms;k.mergeConfig=X;k.AxiosHeaders=P;k.formToJSON=e=>kt(u.isHTMLForm(e)?new FormData(e):e);k.getAdapter=It.getAdapter;k.HttpStatusCode=Le;k.default=k;const{Axios:zs,AxiosError:$s,CanceledError:Vs,isCancel:Ks,CancelToken:Js,VERSION:Ws,all:Xs,Cancel:Qs,isAxiosError:Ys,spread:Zs,toFormData:er,AxiosHeaders:tr,HttpStatusCode:nr,formToJSON:sr,getAdapter:rr,mergeConfig:or}=k;class Ft{instance;getAccessToken;constructor(t){this.getAccessToken=t.getAccessToken,this.instance=k.create({baseURL:t.baseUrl,headers:{"Content-Type":"application/json",...t.defaultHeaders}}),this.instance.interceptors.request.use(n=>{const s=this.getAccessToken();return s?n.headers.Authorization=`Bearer ${s}`:delete n.headers.Authorization,n},n=>Promise.reject(n)),this.instance.interceptors.response.use(n=>n,async n=>(n.response?.status===401&&console.warn("[AuthApiService] Unauthorized request - token may be expired"),Promise.reject(n)))}async get(t,n){return(await this.instance.get(t,n)).data}async post(t,n,s){return(await this.instance.post(t,n,s)).data}async patch(t,n,s){return(await this.instance.patch(t,n,s)).data}async put(t,n,s){return(await this.instance.put(t,n,s)).data}async delete(t,n){return(await this.instance.delete(t,n)).data}async getUser(){return this.get("/auth/user")}async updateUser(t){return this.patch("/auth/user",t)}getInstance(){return this.instance}}const Bs={providers:{email:{enabled:!1},phone:{enabled:!1}},emailAuth:{enabled:!1},phoneAuth:{enabled:!1},registration:{enabled:!1},mfa:{enabled:!1,methods:[]},tenants:{mode:W.SINGLE,defaultTenantId:null,options:[]},sso:{enabled:!1,providers:[]},ui:void 0},Hs=()=>{const e=Kt(),t=A.useMemo(()=>e.status===x.AUTHENTICATED,[e.status]),n=A.useMemo(()=>e.status===x.UNAUTHENTICATED,[e.status]),s=A.useMemo(()=>e.backendConfig??Bs,[e.backendConfig]),r=A.useMemo(()=>e.backendConfig!==null&&e.backendConfig!==void 0,[e.backendConfig]),i=A.useMemo(()=>!r&&e.isLoading,[r,e.isLoading]),o=A.useMemo(()=>!!e.session?.id,[e.session]),a=A.useMemo(()=>e.backendConfig?.tenants?.options??[],[e.backendConfig?.tenants?.options]),f=A.useMemo(()=>e.backendConfig?.tenants?.mode??W.SINGLE,[e.backendConfig?.tenants?.mode]),l=A.useMemo(()=>f===W.MULTI,[f]),c=A.useMemo(()=>!e.tokens?.accessToken||!e.baseUrl?null:new Ft({baseUrl:e.baseUrl,getAccessToken:()=>e.tokens?.accessToken||null}),[e.tokens?.accessToken,e.baseUrl]);return{...e,isAuthenticated:t,isUnauthenticated:n,config:s,isConfigLoaded:r,isConfigLoading:i,hasSession:o,tenantOptions:a,tenantMode:f,isMultiTenant:l,api:c}},js=()=>{const e=Jt(),t=A.useSyncExternalStore(T=>e.subscribe(T),()=>e.getSnapshot(),()=>e.getSnapshot()),n=A.useCallback(T=>e.getStatus(T),[e]),s=A.useCallback(()=>e.refreshStatus(),[e]),r=A.useCallback(()=>e.ensureStatusLoaded(),[e]),i=A.useCallback(T=>e.toggleMfa(T),[e]),o=A.useCallback(()=>e.setupTotp(),[e]),a=A.useCallback(T=>e.verifyTotpSetup(T),[e]),f=A.useCallback(()=>e.generateRecoveryCode(),[e]),l=A.useCallback(T=>e.resetTotp(T),[e]),c=A.useCallback(T=>e.removeDevice(T),[e]),p=A.useCallback(()=>e.getAvailableMethods(),[e]);return A.useMemo(()=>({...t,getStatus:n,refreshStatus:s,ensureStatusLoaded:r,toggleMfa:i,setupTotp:o,verifyTotpSetup:a,generateRecoveryCode:f,resetTotp:l,removeDevice:c,getAvailableMethods:p}),[t,n,s,r,i,o,a,f,l,c,p])};exports.APPLE_AUTH_PROVIDER=Gt;exports.AuthApiService=Ft;exports.AuthEventType=_;exports.AuthProvider=ot;exports.AuthStatus=x;exports.EMAIL_AUTH_PROVIDER=Bt;exports.FACEBOOK_AUTH_PROVIDER=qt;exports.GOOGLE_AUTH_PROVIDER=jt;exports.MFAMethodEnum=Mt;exports.MfaMethod=Ie;exports.MfaService=dt;exports.NestAuthProvider=ln;exports.PHONE_AUTH_PROVIDER=Ht;exports.TenantMode=W;exports.createAuthClient=ut;exports.createTokenStorage=ft;exports.useAuth=Hs;exports.useMfa=js;
package/index.d.ts DELETED
@@ -1,13 +0,0 @@
1
- export * from './types';
2
- export { MFAMethodEnum, MfaMethod } from './types';
3
- export { NestAuthProvider } from './provider/nest-auth-provider';
4
- export { useAuth } from './hooks/use-auth';
5
- export type { UseAuthReturn } from './hooks/use-auth';
6
- export { useMfa } from './hooks/use-mfa';
7
- export type { UseMfaReturn } from './hooks/use-mfa';
8
- export * from './hooks/use-mfa';
9
- export { createAuthClient } from './client/create-client';
10
- export { createTokenStorage } from './storage/token-storage';
11
- export { AuthApiService } from './services/auth-api-service';
12
- export { MfaService, type MfaServiceState } from './services/mfa-service';
13
- //# sourceMappingURL=index.d.ts.map