import t,{useEffect as e,useCallback as n,createElement as r,Fragment as o}from"react";import{useService as a}from"@xstate/react";import{addSeconds as i,isAfter as u,differenceInSeconds as c}from"date-fns";import{Machine as s,assign as l,interpret as h}from"xstate";import{choose as f}from"xstate/lib/actions";var g=function(n){var r=n.children;return e(function(){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,r)};function d(){return(d=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}var p=h(s({id:"useAuth",initial:"unauthenticated",context:{user:{},expiresAt:null,authResult:null,isAuthenticating:!1,error:void 0,errorType:void 0,config:{navigate:function(){return 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:function(t,e){return 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:f([{cond:function(t,e){return"CHECK_SESSION"!==e.type},actions:["clearUserFromContext","clearLocalStorage"]}])},error:{entry:["saveErrorToContext","clearUserFromContext","clearLocalStorage"]}}},{actions:{startAuthenticating:l(function(t){return{isAuthenticating:!0}}),stopAuthenticating:l(function(t){return{isAuthenticating:!1}}),saveUserToContext:l(function(t,e){var n=e.data?e.data:e,r=n.authResult;return{user:n.user,authResult:r,expiresAt:i(new Date,r.expiresIn)}}),clearUserFromContext:l(function(t){return{user:{},expiresAt:null,authResult:null}}),saveToLocalStorage:function(t,e){var n=t.expiresAt,r=t.user;"undefined"!=typeof localStorage&&(localStorage.setItem("useAuth:expires_at",n?n.toISOString():"0"),localStorage.setItem("useAuth:user",JSON.stringify(r)))},clearLocalStorage:function(){"undefined"!=typeof localStorage&&(localStorage.removeItem("useAuth:expires_at"),localStorage.removeItem("useAuth:user"))},saveErrorToContext:l(function(t,e){return{errorType:e.errorType,error:e.error}}),setConfig:l(function(t,e){return{config:d({},t.config,e)}})}}));p.start(),function(t){if("undefined"!=typeof localStorage){var e=new Date(localStorage.getItem("useAuth:expires_at")||"0"),n=new Date;if(u(e,n)){var r=JSON.parse(localStorage.getItem("useAuth:user")||"{}");t("LOGIN"),t("AUTHENTICATED",{user:r,authResult:{expiresIn:c(e,n)}})}}}(p.send);var v=function(){var t=a(p),e=t[0],r=t[1],o=e.context.config,i=o.authProvider,c=o.navigate,s=o.callbackDomain,l=n(function(t){var e=(void 0===t?{}:t).postLoginRoute,n=void 0===e?"/":e;try{if(!i||!c)return console.warn("authProvider not configured yet"),Promise.resolve();var o=function(){if("undefined"!=typeof window)return r("LOGIN"),Promise.resolve(i.handleLoginCallback(r)).then(function(t){t&&c(n)})}();return Promise.resolve(o&&o.then?o.then(function(){}):void 0)}catch(t){return Promise.reject(t)}},[i,c]),h=function(){return!(!e.context.expiresAt||!u(e.context.expiresAt,new Date))};return{isAuthenticating:e.context.isAuthenticating,isAuthenticated:h,isAuthorized:function(t){var n=Array.isArray(t)?t:[t],r=null==i?void 0:i.userRoles(e.context.user);return!(!h()||!r)&&n.some(function(t){return r.includes(t)})},user:e.context.user,userId:null==i?void 0:i.userId(e.context.user),authResult:e.context.authResult,login:function(){null==i||i.authorize()},signup:function(){null==i||i.signup()},logout:function(t){"string"==typeof t?null==i||i.logout(""+s+t):null==i||i.logout(),r("LOGOUT"),c("string"==typeof t?t:"/")},handleAuthentication:l,dispatch:r}},m=function(t){var n=t.authProvider,a=t.params,i=t.navigate,u=t.children,c=v().dispatch,s="undefined"!=typeof window?window.location.protocol+"//"+window.location.host:"http://localhost:8000";return e(function(){var t=new n(d({dispatch:c},n.addDefaultParams(a,s)));c("SET_CONFIG",{authProvider:t,navigate:i,callbackDomain:s}),c("CHECK_SESSION")},[c,n,a,i]),r(o,null,u)};export{m as AuthConfig,g as AuthProvider,v as useAuth};
//# sourceMappingURL=react-use-auth.esm.js.map
