import t,{useEffect as e,useCallback as o,createElement as n,Fragment as r}from"react";import{useService as a}from"@xstate/react";import{addSeconds as i,isAfter as s,differenceInSeconds as u}from"date-fns";import{Machine as c,assign as l,interpret as g}from"xstate";import{choose as h}from"xstate/lib/actions";const d=({children:o,auth0_params:n={}})=>(e(()=>{console.error("The AuthProvider root component no longer works. Please take 5min to migrate to AuthConfig. 👉 https://useauth.dev/docs/upgrading")},[]),t.createElement(t.Fragment,null,o));function p(){return(p=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var o=arguments[e];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(t[n]=o[n])}return t}).apply(this,arguments)}const f=g(c({id:"useAuth",initial:"unauthenticated",context:{user:{},expiresAt:null,authResult:null,isAuthenticating:!1,error:void 0,errorType:void 0,config:{navigate:()=>console.error("Please specify a navigation method that works with your router"),callbackDomain:"http://localhost:8000"}},states:{unauthenticated:{on:{LOGIN:"authenticating",CHECK_SESSION:"verifying",SET_CONFIG:{actions:["setConfig"]}}},authenticating:{on:{ERROR:"error",AUTHENTICATED:"authenticated",SET_CONFIG:{actions:["setConfig"]}},entry:["startAuthenticating"],exit:["stopAuthenticating"]},verifying:{invoke:{id:"checkSession",src:(t,e)=>t.config.authProvider.checkSession(),onDone:{target:"authenticated"},onError:{target:"unauthenticated",actions:["clearUserFromContext","clearLocalStorage"]}},entry:["startAuthenticating"],exit:["stopAuthenticating"]},authenticated:{on:{LOGOUT:"unauthenticated",SET_CONFIG:{actions:["setConfig"]},CHECK_SESSION:"verifying"},entry:["saveUserToContext","saveToLocalStorage"],exit:h([{cond:(t,e)=>"CHECK_SESSION"!==e.type,actions:["clearUserFromContext","clearLocalStorage"]}])},error:{entry:["saveErrorToContext","clearUserFromContext","clearLocalStorage"]}}},{actions:{startAuthenticating:l(t=>({isAuthenticating:!0})),stopAuthenticating:l(t=>({isAuthenticating:!1})),saveUserToContext:l((t,e)=>{const{authResult:o,user:n}=e.data?e.data:e;return{user:n,authResult:o,expiresAt:i(new Date,o.expiresIn)}}),clearUserFromContext:l(t=>({user:{},expiresAt:null,authResult:null})),saveToLocalStorage:(t,e)=>{const{expiresAt:o,user:n}=t;"undefined"!=typeof localStorage&&(localStorage.setItem("useAuth:expires_at",o?o.toISOString():"0"),localStorage.setItem("useAuth:user",JSON.stringify(n)))},clearLocalStorage:()=>{"undefined"!=typeof localStorage&&(localStorage.removeItem("useAuth:expires_at"),localStorage.removeItem("useAuth:user"))},saveErrorToContext:l((t,e)=>({errorType:e.errorType,error:e.error})),setConfig:l((t,e)=>({config:p({},t.config,e)}))}}));f.start(),function(t){if("undefined"!=typeof localStorage){const e=new Date(localStorage.getItem("useAuth:expires_at")||"0"),o=new Date;if(s(e,o)){const n=JSON.parse(localStorage.getItem("useAuth:user")||"{}");t("LOGIN"),t("AUTHENTICATED",{user:n,authResult:{expiresIn:u(e,o)}})}}}(f.send);const S=()=>{const[t,e]=a(f),{authProvider:n,navigate:r,callbackDomain:i}=t.context.config,u=o(async({postLoginRoute:t="/"}={})=>{n&&r?"undefined"!=typeof window&&(e("LOGIN"),await n.handleLoginCallback(e)&&r(t)):console.warn("authProvider not configured yet")},[n,r]),c=()=>!(!t.context.expiresAt||!s(t.context.expiresAt,new Date));return{isAuthenticating:t.context.isAuthenticating,isAuthenticated:c,isAuthorized:e=>{const o=Array.isArray(e)?e:[e],r=null==n?void 0:n.userRoles(t.context.user);return!(!c()||!r)&&o.some(t=>r.includes(t))},user:t.context.user,userId:null==n?void 0:n.userId(t.context.user),authResult:t.context.authResult,login:()=>{null==n||n.authorize()},signup:()=>{null==n||n.signup()},logout:t=>{"string"==typeof t?null==n||n.logout(`${i}${t}`):null==n||n.logout(),e("LOGOUT"),r("string"==typeof t?t:"/")},handleAuthentication:u,dispatch:e}},m=({authProvider:t,params:o,navigate:a,children:i})=>{const{dispatch:s}=S(),u="undefined"!=typeof window?`${window.location.protocol}//${window.location.host}`:"http://localhost:8000";return e(()=>{const e=new t(p({dispatch:s},t.addDefaultParams(o,u)));s("SET_CONFIG",{authProvider:e,navigate:a,callbackDomain:u}),s("CHECK_SESSION")},[s,t,o,a]),n(r,null,i)};export{m as AuthConfig,d as AuthProvider,S as useAuth};
//# sourceMappingURL=react-use-auth.modern.js.map
