@azure/msal-react
Advanced tools
Comparing version 1.3.0 to 1.3.1
@@ -88,3 +88,3 @@ 'use strict'; | ||
const name = "@azure/msal-react"; | ||
const version = "1.3.0"; | ||
const version = "1.3.1"; | ||
@@ -95,2 +95,66 @@ /* | ||
*/ | ||
var MsalProviderActionType; | ||
(function (MsalProviderActionType) { | ||
MsalProviderActionType["UNBLOCK_INPROGRESS"] = "UNBLOCK_INPROGRESS"; | ||
MsalProviderActionType["EVENT"] = "EVENT"; | ||
})(MsalProviderActionType || (MsalProviderActionType = {})); | ||
/** | ||
* Returns the next inProgress and accounts state based on event message | ||
* @param previousState | ||
* @param action | ||
*/ | ||
const reducer = (previousState, action) => { | ||
const { | ||
type, | ||
payload | ||
} = action; | ||
let newAccounts = previousState.accounts; | ||
let newInProgress = previousState.inProgress; | ||
switch (type) { | ||
case MsalProviderActionType.UNBLOCK_INPROGRESS: | ||
if (previousState.inProgress === msalBrowser.InteractionStatus.Startup) { | ||
newInProgress = msalBrowser.InteractionStatus.None; | ||
payload.logger.info("MsalProvider - handleRedirectPromise resolved, setting inProgress to 'none'"); | ||
} | ||
break; | ||
case MsalProviderActionType.EVENT: | ||
const message = payload.message; | ||
const status = msalBrowser.EventMessageUtils.getInteractionStatusFromEvent(message, previousState.inProgress); | ||
if (status) { | ||
payload.logger.info(`MsalProvider - ${message.eventType} results in setting inProgress from ${previousState.inProgress} to ${status}`); | ||
newInProgress = status; | ||
} | ||
break; | ||
default: | ||
throw new Error(`Unknown action type: ${type}`); | ||
} | ||
const currentAccounts = payload.instance.getAllAccounts(); | ||
if (!accountArraysAreEqual(currentAccounts, previousState.accounts)) { | ||
payload.logger.info("MsalProvider - updating account state"); | ||
newAccounts = currentAccounts; | ||
} else { | ||
payload.logger.verbose("MsalProvider - no account changes"); | ||
} | ||
return { ...previousState, | ||
inProgress: newInProgress, | ||
accounts: newAccounts | ||
}; | ||
}; | ||
/** | ||
* MSAL context provider component. This must be rendered above any other components that use MSAL. | ||
*/ | ||
function MsalProvider({ | ||
@@ -106,52 +170,20 @@ instance, | ||
return instance.getLogger().clone(name, version); | ||
}, [instance]); // State hook to store accounts | ||
const [accounts, setAccounts] = React.useState(() => instance.getAllAccounts()); // State hook to store in progress value | ||
const [inProgress, setInProgress] = React.useState(msalBrowser.InteractionStatus.Startup); // Mutable object used in the event callback | ||
const inProgressRef = React.useRef(inProgress); | ||
React.useEffect(() => { | ||
const callbackId = instance.addEventCallback(message => { | ||
switch (message.eventType) { | ||
case msalBrowser.EventType.ACCOUNT_ADDED: | ||
case msalBrowser.EventType.ACCOUNT_REMOVED: | ||
case msalBrowser.EventType.LOGIN_SUCCESS: | ||
case msalBrowser.EventType.SSO_SILENT_SUCCESS: | ||
case msalBrowser.EventType.HANDLE_REDIRECT_END: | ||
case msalBrowser.EventType.LOGIN_FAILURE: | ||
case msalBrowser.EventType.SSO_SILENT_FAILURE: | ||
case msalBrowser.EventType.LOGOUT_END: | ||
case msalBrowser.EventType.ACQUIRE_TOKEN_SUCCESS: | ||
case msalBrowser.EventType.ACQUIRE_TOKEN_FAILURE: | ||
const currentAccounts = instance.getAllAccounts(); | ||
if (!accountArraysAreEqual(currentAccounts, accounts)) { | ||
logger.info("MsalProvider - updating account state"); | ||
setAccounts(currentAccounts); | ||
} else { | ||
logger.info("MsalProvider - no account changes"); | ||
} | ||
break; | ||
} | ||
}); | ||
logger.verbose(`MsalProvider - Registered event callback with id: ${callbackId}`); | ||
return () => { | ||
// Remove callback when component unmounts or accounts change | ||
if (callbackId) { | ||
logger.verbose(`MsalProvider - Removing event callback ${callbackId}`); | ||
instance.removeEventCallback(callbackId); | ||
} | ||
}, [instance]); | ||
const [state, updateState] = React.useReducer(reducer, undefined, () => { | ||
// Lazy initialization of the initial state | ||
return { | ||
inProgress: msalBrowser.InteractionStatus.Startup, | ||
accounts: instance.getAllAccounts() | ||
}; | ||
}, [instance, accounts, logger]); | ||
}); | ||
React.useEffect(() => { | ||
const callbackId = instance.addEventCallback(message => { | ||
const status = msalBrowser.EventMessageUtils.getInteractionStatusFromEvent(message, inProgressRef.current); | ||
if (status !== null) { | ||
logger.info(`MsalProvider - ${message.eventType} results in setting inProgress from ${inProgressRef.current} to ${status}`); | ||
inProgressRef.current = status; | ||
setInProgress(status); | ||
} | ||
updateState({ | ||
payload: { | ||
instance, | ||
logger, | ||
message | ||
}, | ||
type: MsalProviderActionType.EVENT | ||
}); | ||
}); | ||
@@ -167,8 +199,12 @@ logger.verbose(`MsalProvider - Registered event callback with id: ${callbackId}`); | ||
*/ | ||
if (inProgressRef.current === msalBrowser.InteractionStatus.Startup) { | ||
inProgressRef.current = msalBrowser.InteractionStatus.None; | ||
setInProgress(msalBrowser.InteractionStatus.None); | ||
} | ||
updateState({ | ||
payload: { | ||
instance, | ||
logger | ||
}, | ||
type: MsalProviderActionType.UNBLOCK_INPROGRESS | ||
}); | ||
}); | ||
return () => { | ||
// Remove callback when component unmounts or accounts change | ||
if (callbackId) { | ||
@@ -182,4 +218,4 @@ logger.verbose(`MsalProvider - Removing event callback ${callbackId}`); | ||
instance, | ||
inProgress, | ||
accounts, | ||
inProgress: state.inProgress, | ||
accounts: state.accounts, | ||
logger | ||
@@ -186,0 +222,0 @@ }; |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("react"),n=(e=t)&&"object"==typeof e&&"default"in e?e.default:e,r=require("@azure/msal-browser");const o=t.createContext({instance:r.stubbedPublicClientApplication,inProgress:r.InteractionStatus.None,accounts:[],logger:new r.Logger({})}),c=o.Consumer;function a(e,t){return"function"==typeof e?e(t):e}function s(e,t){return e.length>0&&(t.homeAccountId||t.localAccountId||t.username)&&e.filter(e=>!(t.username&&t.username.toLowerCase()!==e.username.toLowerCase()||t.homeAccountId&&t.homeAccountId.toLowerCase()!==e.homeAccountId.toLowerCase()||t.localAccountId&&t.localAccountId.toLowerCase()!==e.localAccountId.toLowerCase()))[0]||null}const u=()=>t.useContext(o);function i(e,t){return t&&(t.username||t.homeAccountId||t.localAccountId)?!!s(e,t):e.length>0}function l(e){const{accounts:n}=u(),[r,o]=t.useState(()=>i(n,e));return t.useEffect(()=>{o(i(n,e))},[n,e]),r}function d(e,t){return t&&(t.homeAccountId||t.localAccountId||t.username)?s(e.getAllAccounts(),t):e.getActiveAccount()}function p(e){const{instance:n,inProgress:o,logger:c}=u(),[a,s]=t.useState(()=>d(n,e));return t.useEffect(()=>{s(t=>{const o=d(n,e);return r.AccountEntity.accountInfoIsEqual(t,o,!0)?t:(c.info("useAccount - Updating account"),o)})},[o,e,n,c]),a}class h extends r.AuthError{constructor(e,t){super(e,t),Object.setPrototypeOf(this,h.prototype),this.name="ReactAuthError"}static createInvalidInteractionTypeError(){return new h("invalid_interaction_type","The provided interaction type is invalid.")}static createUnableToFallbackToInteractionError(){return new h("unable_to_fallback_to_interaction","Interaction is required but another interaction is already in progress. Please try again when the current interaction is complete.")}}function E(e,n,o){const{instance:c,inProgress:a,logger:s}=u(),i=l(o),d=p(o),[[E,I],A]=t.useState([null,null]),g=t.useRef(a!==r.InteractionStatus.None);t.useEffect(()=>{g.current=a!==r.InteractionStatus.None},[a]);const m=t.useRef(!0);t.useEffect(()=>{(I||E)&&(m.current=!1)},[I,E]);const v=t.useCallback(async(t,o)=>{const a=o||n;switch(t||e){case r.InteractionType.Popup:return s.verbose("useMsalAuthentication - Calling loginPopup"),c.loginPopup(a);case r.InteractionType.Redirect:return s.verbose("useMsalAuthentication - Calling loginRedirect"),c.loginRedirect(a).then(null);case r.InteractionType.Silent:return s.verbose("useMsalAuthentication - Calling ssoSilent"),c.ssoSilent(a);default:throw h.createInvalidInteractionTypeError()}},[c,e,n,s]),f=t.useCallback(async(t,o)=>{const a=t||e;let u;return o?(s.trace("useMsalAuthentication - acquireToken - Using request provided in the callback"),u={...o}):n?(s.trace("useMsalAuthentication - acquireToken - Using request provided in the hook"),u={...n,scopes:n.scopes||r.OIDC_DEFAULT_SCOPES}):(s.trace("useMsalAuthentication - acquireToken - No request object provided, using default request."),u={scopes:r.OIDC_DEFAULT_SCOPES}),!u.account&&d&&(s.trace("useMsalAuthentication - acquireToken - Attaching account to request"),u.account=d),(async()=>(s.verbose("useMsalAuthentication - Calling acquireTokenSilent"),c.acquireTokenSilent(u).catch(async e=>{if(e instanceof r.InteractionRequiredAuthError){if(g.current)throw s.error("useMsalAuthentication - Interaction required but is already in progress. Please try again, if needed, after interaction completes."),h.createUnableToFallbackToInteractionError();return s.error("useMsalAuthentication - Interaction required, falling back to interaction"),v(a,u)}throw e})))().then(e=>(A([e,null]),e)).catch(e=>{throw A([null,e]),e})},[c,e,n,s,d,v]);return t.useEffect(()=>{const e=c.addEventCallback(e=>{switch(e.eventType){case r.EventType.LOGIN_SUCCESS:case r.EventType.SSO_SILENT_SUCCESS:e.payload&&A([e.payload,null]);break;case r.EventType.LOGIN_FAILURE:case r.EventType.SSO_SILENT_FAILURE:e.error&&A([null,e.error])}});return s.verbose("useMsalAuthentication - Registered event callback with id: "+e),()=>{e&&(s.verbose("useMsalAuthentication - Removing event callback "+e),c.removeEventCallback(e))}},[c,s]),t.useEffect(()=>{m.current&&a===r.InteractionStatus.None&&(m.current=!1,i?d&&(s.info("useMsalAuthentication - User is authenticated, attempting to acquire token"),f().catch(()=>{})):(s.info("useMsalAuthentication - No user is authenticated, attempting to login"),v().catch(()=>{})))},[i,d,a,v,f,s]),{login:v,acquireToken:f,result:E,error:I}}exports.AuthenticatedTemplate=function({username:e,homeAccountId:o,localAccountId:c,children:s}){const i=u();return l(t.useMemo(()=>({username:e,homeAccountId:o,localAccountId:c}),[e,o,c]))&&i.inProgress!==r.InteractionStatus.Startup?n.createElement(n.Fragment,null,a(s,i)):null},exports.MsalAuthenticationTemplate=function({interactionType:e,username:o,homeAccountId:c,localAccountId:s,authenticationRequest:i,loadingComponent:d,errorComponent:p,children:h}){const I=t.useMemo(()=>({username:o,homeAccountId:c,localAccountId:s}),[o,c,s]),A=u(),g=E(e,i,I),m=l(I);if(g.error&&A.inProgress===r.InteractionStatus.None){if(p)return n.createElement(p,Object.assign({},g));throw g.error}return m?n.createElement(n.Fragment,null,a(h,g)):d&&A.inProgress!==r.InteractionStatus.None?n.createElement(d,Object.assign({},A)):null},exports.MsalConsumer=c,exports.MsalContext=o,exports.MsalProvider=function({instance:e,children:c}){t.useEffect(()=>{e.initializeWrapperLibrary(r.WrapperSKU.React,"1.3.0")},[e]);const a=t.useMemo(()=>e.getLogger().clone("@azure/msal-react","1.3.0"),[e]),[s,u]=t.useState(()=>e.getAllAccounts()),[i,l]=t.useState(r.InteractionStatus.Startup),d=t.useRef(i);return t.useEffect(()=>{const t=e.addEventCallback(t=>{switch(t.eventType){case r.EventType.ACCOUNT_ADDED:case r.EventType.ACCOUNT_REMOVED:case r.EventType.LOGIN_SUCCESS:case r.EventType.SSO_SILENT_SUCCESS:case r.EventType.HANDLE_REDIRECT_END:case r.EventType.LOGIN_FAILURE:case r.EventType.SSO_SILENT_FAILURE:case r.EventType.LOGOUT_END:case r.EventType.ACQUIRE_TOKEN_SUCCESS:case r.EventType.ACQUIRE_TOKEN_FAILURE:const t=e.getAllAccounts();!function(e,t){if(e.length!==t.length)return!1;const n=[...t];return e.every(e=>{const t=n.shift();return!(!e||!t)&&e.homeAccountId===t.homeAccountId&&e.localAccountId===t.localAccountId&&e.username===t.username})}(t,s)?(a.info("MsalProvider - updating account state"),u(t)):a.info("MsalProvider - no account changes")}});return a.verbose("MsalProvider - Registered event callback with id: "+t),()=>{t&&(a.verbose("MsalProvider - Removing event callback "+t),e.removeEventCallback(t))}},[e,s,a]),t.useEffect(()=>{const t=e.addEventCallback(e=>{const t=r.EventMessageUtils.getInteractionStatusFromEvent(e,d.current);null!==t&&(a.info(`MsalProvider - ${e.eventType} results in setting inProgress from ${d.current} to ${t}`),d.current=t,l(t))});return a.verbose("MsalProvider - Registered event callback with id: "+t),e.handleRedirectPromise().catch(()=>{}).finally(()=>{d.current===r.InteractionStatus.Startup&&(d.current=r.InteractionStatus.None,l(r.InteractionStatus.None))}),()=>{t&&(a.verbose("MsalProvider - Removing event callback "+t),e.removeEventCallback(t))}},[e,a]),n.createElement(o.Provider,{value:{instance:e,inProgress:i,accounts:s,logger:a}},c)},exports.UnauthenticatedTemplate=function({username:e,homeAccountId:o,localAccountId:c,children:s}){const i=u();return l(t.useMemo(()=>({username:e,homeAccountId:o,localAccountId:c}),[e,o,c]))||i.inProgress===r.InteractionStatus.Startup||i.inProgress===r.InteractionStatus.HandleRedirect?null:n.createElement(n.Fragment,null,a(s,i))},exports.useAccount=p,exports.useIsAuthenticated=l,exports.useMsal=u,exports.useMsalAuthentication=E,exports.version="1.3.0",exports.withMsal=e=>{const t=t=>{const r=u();return n.createElement(e,Object.assign({},t,{msalContext:r}))};return t.displayName=`withMsal(${e.displayName||e.name||"Component"})`,t}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("react"),n=(e=t)&&"object"==typeof e&&"default"in e?e.default:e,r=require("@azure/msal-browser");const o=t.createContext({instance:r.stubbedPublicClientApplication,inProgress:r.InteractionStatus.None,accounts:[],logger:new r.Logger({})}),c=o.Consumer;function a(e,t){return"function"==typeof e?e(t):e}function s(e,t){return e.length>0&&(t.homeAccountId||t.localAccountId||t.username)&&e.filter(e=>!(t.username&&t.username.toLowerCase()!==e.username.toLowerCase()||t.homeAccountId&&t.homeAccountId.toLowerCase()!==e.homeAccountId.toLowerCase()||t.localAccountId&&t.localAccountId.toLowerCase()!==e.localAccountId.toLowerCase()))[0]||null}var i;!function(e){e.UNBLOCK_INPROGRESS="UNBLOCK_INPROGRESS",e.EVENT="EVENT"}(i||(i={}));const u=(e,t)=>{const{type:n,payload:o}=t;let c=e.accounts,a=e.inProgress;switch(n){case i.UNBLOCK_INPROGRESS:e.inProgress===r.InteractionStatus.Startup&&(a=r.InteractionStatus.None,o.logger.info("MsalProvider - handleRedirectPromise resolved, setting inProgress to 'none'"));break;case i.EVENT:const t=o.message,c=r.EventMessageUtils.getInteractionStatusFromEvent(t,e.inProgress);c&&(o.logger.info(`MsalProvider - ${t.eventType} results in setting inProgress from ${e.inProgress} to ${c}`),a=c);break;default:throw new Error("Unknown action type: "+n)}const s=o.instance.getAllAccounts();return function(e,t){if(e.length!==t.length)return!1;const n=[...t];return e.every(e=>{const t=n.shift();return!(!e||!t)&&e.homeAccountId===t.homeAccountId&&e.localAccountId===t.localAccountId&&e.username===t.username})}(s,e.accounts)?o.logger.verbose("MsalProvider - no account changes"):(o.logger.info("MsalProvider - updating account state"),c=s),{...e,inProgress:a,accounts:c}},l=()=>t.useContext(o);function d(e,t){return t&&(t.username||t.homeAccountId||t.localAccountId)?!!s(e,t):e.length>0}function g(e){const{accounts:n}=l(),[r,o]=t.useState(()=>d(n,e));return t.useEffect(()=>{o(d(n,e))},[n,e]),r}function p(e,t){return t&&(t.homeAccountId||t.localAccountId||t.username)?s(e.getAllAccounts(),t):e.getActiveAccount()}function h(e){const{instance:n,inProgress:o,logger:c}=l(),[a,s]=t.useState(()=>p(n,e));return t.useEffect(()=>{s(t=>{const o=p(n,e);return r.AccountEntity.accountInfoIsEqual(t,o,!0)?t:(c.info("useAccount - Updating account"),o)})},[o,e,n,c]),a}class m extends r.AuthError{constructor(e,t){super(e,t),Object.setPrototypeOf(this,m.prototype),this.name="ReactAuthError"}static createInvalidInteractionTypeError(){return new m("invalid_interaction_type","The provided interaction type is invalid.")}static createUnableToFallbackToInteractionError(){return new m("unable_to_fallback_to_interaction","Interaction is required but another interaction is already in progress. Please try again when the current interaction is complete.")}}function I(e,n,o){const{instance:c,inProgress:a,logger:s}=l(),i=g(o),u=h(o),[[d,p],I]=t.useState([null,null]),A=t.useRef(a!==r.InteractionStatus.None);t.useEffect(()=>{A.current=a!==r.InteractionStatus.None},[a]);const f=t.useRef(!0);t.useEffect(()=>{(p||d)&&(f.current=!1)},[p,d]);const E=t.useCallback(async(t,o)=>{const a=o||n;switch(t||e){case r.InteractionType.Popup:return s.verbose("useMsalAuthentication - Calling loginPopup"),c.loginPopup(a);case r.InteractionType.Redirect:return s.verbose("useMsalAuthentication - Calling loginRedirect"),c.loginRedirect(a).then(null);case r.InteractionType.Silent:return s.verbose("useMsalAuthentication - Calling ssoSilent"),c.ssoSilent(a);default:throw m.createInvalidInteractionTypeError()}},[c,e,n,s]),v=t.useCallback(async(t,o)=>{const a=t||e;let i;return o?(s.trace("useMsalAuthentication - acquireToken - Using request provided in the callback"),i={...o}):n?(s.trace("useMsalAuthentication - acquireToken - Using request provided in the hook"),i={...n,scopes:n.scopes||r.OIDC_DEFAULT_SCOPES}):(s.trace("useMsalAuthentication - acquireToken - No request object provided, using default request."),i={scopes:r.OIDC_DEFAULT_SCOPES}),!i.account&&u&&(s.trace("useMsalAuthentication - acquireToken - Attaching account to request"),i.account=u),(async()=>(s.verbose("useMsalAuthentication - Calling acquireTokenSilent"),c.acquireTokenSilent(i).catch(async e=>{if(e instanceof r.InteractionRequiredAuthError){if(A.current)throw s.error("useMsalAuthentication - Interaction required but is already in progress. Please try again, if needed, after interaction completes."),m.createUnableToFallbackToInteractionError();return s.error("useMsalAuthentication - Interaction required, falling back to interaction"),E(a,i)}throw e})))().then(e=>(I([e,null]),e)).catch(e=>{throw I([null,e]),e})},[c,e,n,s,u,E]);return t.useEffect(()=>{const e=c.addEventCallback(e=>{switch(e.eventType){case r.EventType.LOGIN_SUCCESS:case r.EventType.SSO_SILENT_SUCCESS:e.payload&&I([e.payload,null]);break;case r.EventType.LOGIN_FAILURE:case r.EventType.SSO_SILENT_FAILURE:e.error&&I([null,e.error])}});return s.verbose("useMsalAuthentication - Registered event callback with id: "+e),()=>{e&&(s.verbose("useMsalAuthentication - Removing event callback "+e),c.removeEventCallback(e))}},[c,s]),t.useEffect(()=>{f.current&&a===r.InteractionStatus.None&&(f.current=!1,i?u&&(s.info("useMsalAuthentication - User is authenticated, attempting to acquire token"),v().catch(()=>{})):(s.info("useMsalAuthentication - No user is authenticated, attempting to login"),E().catch(()=>{})))},[i,u,a,E,v,s]),{login:E,acquireToken:v,result:d,error:p}}exports.AuthenticatedTemplate=function({username:e,homeAccountId:o,localAccountId:c,children:s}){const i=l();return g(t.useMemo(()=>({username:e,homeAccountId:o,localAccountId:c}),[e,o,c]))&&i.inProgress!==r.InteractionStatus.Startup?n.createElement(n.Fragment,null,a(s,i)):null},exports.MsalAuthenticationTemplate=function({interactionType:e,username:o,homeAccountId:c,localAccountId:s,authenticationRequest:i,loadingComponent:u,errorComponent:d,children:p}){const h=t.useMemo(()=>({username:o,homeAccountId:c,localAccountId:s}),[o,c,s]),m=l(),A=I(e,i,h),f=g(h);if(A.error&&m.inProgress===r.InteractionStatus.None){if(d)return n.createElement(d,Object.assign({},A));throw A.error}return f?n.createElement(n.Fragment,null,a(p,A)):u&&m.inProgress!==r.InteractionStatus.None?n.createElement(u,Object.assign({},m)):null},exports.MsalConsumer=c,exports.MsalContext=o,exports.MsalProvider=function({instance:e,children:c}){t.useEffect(()=>{e.initializeWrapperLibrary(r.WrapperSKU.React,"1.3.1")},[e]);const a=t.useMemo(()=>e.getLogger().clone("@azure/msal-react","1.3.1"),[e]),[s,l]=t.useReducer(u,void 0,()=>({inProgress:r.InteractionStatus.Startup,accounts:e.getAllAccounts()}));return t.useEffect(()=>{const t=e.addEventCallback(t=>{l({payload:{instance:e,logger:a,message:t},type:i.EVENT})});return a.verbose("MsalProvider - Registered event callback with id: "+t),e.handleRedirectPromise().catch(()=>{}).finally(()=>{l({payload:{instance:e,logger:a},type:i.UNBLOCK_INPROGRESS})}),()=>{t&&(a.verbose("MsalProvider - Removing event callback "+t),e.removeEventCallback(t))}},[e,a]),n.createElement(o.Provider,{value:{instance:e,inProgress:s.inProgress,accounts:s.accounts,logger:a}},c)},exports.UnauthenticatedTemplate=function({username:e,homeAccountId:o,localAccountId:c,children:s}){const i=l();return g(t.useMemo(()=>({username:e,homeAccountId:o,localAccountId:c}),[e,o,c]))||i.inProgress===r.InteractionStatus.Startup||i.inProgress===r.InteractionStatus.HandleRedirect?null:n.createElement(n.Fragment,null,a(s,i))},exports.useAccount=h,exports.useIsAuthenticated=g,exports.useMsal=l,exports.useMsalAuthentication=I,exports.version="1.3.1",exports.withMsal=e=>{const t=t=>{const r=l();return n.createElement(e,Object.assign({},t,{msalContext:r}))};return t.displayName=`withMsal(${e.displayName||e.name||"Component"})`,t}; | ||
//# sourceMappingURL=msal-react.cjs.production.min.js.map |
@@ -1,3 +0,3 @@ | ||
import React__default, { createContext, useEffect, useMemo, useState, useRef, useContext, useCallback } from 'react'; | ||
import { stubbedPublicClientApplication, InteractionStatus, Logger, WrapperSKU, EventType, EventMessageUtils, AccountEntity, AuthError, InteractionType, InteractionRequiredAuthError, OIDC_DEFAULT_SCOPES } from '@azure/msal-browser'; | ||
import React__default, { createContext, useEffect, useMemo, useReducer, useContext, useState, useRef, useCallback } from 'react'; | ||
import { stubbedPublicClientApplication, InteractionStatus, Logger, WrapperSKU, EventMessageUtils, AccountEntity, AuthError, InteractionType, InteractionRequiredAuthError, EventType, OIDC_DEFAULT_SCOPES } from '@azure/msal-browser'; | ||
@@ -81,3 +81,3 @@ /* | ||
const name = "@azure/msal-react"; | ||
const version = "1.3.0"; | ||
const version = "1.3.1"; | ||
@@ -88,2 +88,66 @@ /* | ||
*/ | ||
var MsalProviderActionType; | ||
(function (MsalProviderActionType) { | ||
MsalProviderActionType["UNBLOCK_INPROGRESS"] = "UNBLOCK_INPROGRESS"; | ||
MsalProviderActionType["EVENT"] = "EVENT"; | ||
})(MsalProviderActionType || (MsalProviderActionType = {})); | ||
/** | ||
* Returns the next inProgress and accounts state based on event message | ||
* @param previousState | ||
* @param action | ||
*/ | ||
const reducer = (previousState, action) => { | ||
const { | ||
type, | ||
payload | ||
} = action; | ||
let newAccounts = previousState.accounts; | ||
let newInProgress = previousState.inProgress; | ||
switch (type) { | ||
case MsalProviderActionType.UNBLOCK_INPROGRESS: | ||
if (previousState.inProgress === InteractionStatus.Startup) { | ||
newInProgress = InteractionStatus.None; | ||
payload.logger.info("MsalProvider - handleRedirectPromise resolved, setting inProgress to 'none'"); | ||
} | ||
break; | ||
case MsalProviderActionType.EVENT: | ||
const message = payload.message; | ||
const status = EventMessageUtils.getInteractionStatusFromEvent(message, previousState.inProgress); | ||
if (status) { | ||
payload.logger.info(`MsalProvider - ${message.eventType} results in setting inProgress from ${previousState.inProgress} to ${status}`); | ||
newInProgress = status; | ||
} | ||
break; | ||
default: | ||
throw new Error(`Unknown action type: ${type}`); | ||
} | ||
const currentAccounts = payload.instance.getAllAccounts(); | ||
if (!accountArraysAreEqual(currentAccounts, previousState.accounts)) { | ||
payload.logger.info("MsalProvider - updating account state"); | ||
newAccounts = currentAccounts; | ||
} else { | ||
payload.logger.verbose("MsalProvider - no account changes"); | ||
} | ||
return { ...previousState, | ||
inProgress: newInProgress, | ||
accounts: newAccounts | ||
}; | ||
}; | ||
/** | ||
* MSAL context provider component. This must be rendered above any other components that use MSAL. | ||
*/ | ||
function MsalProvider({ | ||
@@ -99,52 +163,20 @@ instance, | ||
return instance.getLogger().clone(name, version); | ||
}, [instance]); // State hook to store accounts | ||
const [accounts, setAccounts] = useState(() => instance.getAllAccounts()); // State hook to store in progress value | ||
const [inProgress, setInProgress] = useState(InteractionStatus.Startup); // Mutable object used in the event callback | ||
const inProgressRef = useRef(inProgress); | ||
useEffect(() => { | ||
const callbackId = instance.addEventCallback(message => { | ||
switch (message.eventType) { | ||
case EventType.ACCOUNT_ADDED: | ||
case EventType.ACCOUNT_REMOVED: | ||
case EventType.LOGIN_SUCCESS: | ||
case EventType.SSO_SILENT_SUCCESS: | ||
case EventType.HANDLE_REDIRECT_END: | ||
case EventType.LOGIN_FAILURE: | ||
case EventType.SSO_SILENT_FAILURE: | ||
case EventType.LOGOUT_END: | ||
case EventType.ACQUIRE_TOKEN_SUCCESS: | ||
case EventType.ACQUIRE_TOKEN_FAILURE: | ||
const currentAccounts = instance.getAllAccounts(); | ||
if (!accountArraysAreEqual(currentAccounts, accounts)) { | ||
logger.info("MsalProvider - updating account state"); | ||
setAccounts(currentAccounts); | ||
} else { | ||
logger.info("MsalProvider - no account changes"); | ||
} | ||
break; | ||
} | ||
}); | ||
logger.verbose(`MsalProvider - Registered event callback with id: ${callbackId}`); | ||
return () => { | ||
// Remove callback when component unmounts or accounts change | ||
if (callbackId) { | ||
logger.verbose(`MsalProvider - Removing event callback ${callbackId}`); | ||
instance.removeEventCallback(callbackId); | ||
} | ||
}, [instance]); | ||
const [state, updateState] = useReducer(reducer, undefined, () => { | ||
// Lazy initialization of the initial state | ||
return { | ||
inProgress: InteractionStatus.Startup, | ||
accounts: instance.getAllAccounts() | ||
}; | ||
}, [instance, accounts, logger]); | ||
}); | ||
useEffect(() => { | ||
const callbackId = instance.addEventCallback(message => { | ||
const status = EventMessageUtils.getInteractionStatusFromEvent(message, inProgressRef.current); | ||
if (status !== null) { | ||
logger.info(`MsalProvider - ${message.eventType} results in setting inProgress from ${inProgressRef.current} to ${status}`); | ||
inProgressRef.current = status; | ||
setInProgress(status); | ||
} | ||
updateState({ | ||
payload: { | ||
instance, | ||
logger, | ||
message | ||
}, | ||
type: MsalProviderActionType.EVENT | ||
}); | ||
}); | ||
@@ -160,8 +192,12 @@ logger.verbose(`MsalProvider - Registered event callback with id: ${callbackId}`); | ||
*/ | ||
if (inProgressRef.current === InteractionStatus.Startup) { | ||
inProgressRef.current = InteractionStatus.None; | ||
setInProgress(InteractionStatus.None); | ||
} | ||
updateState({ | ||
payload: { | ||
instance, | ||
logger | ||
}, | ||
type: MsalProviderActionType.UNBLOCK_INPROGRESS | ||
}); | ||
}); | ||
return () => { | ||
// Remove callback when component unmounts or accounts change | ||
if (callbackId) { | ||
@@ -175,4 +211,4 @@ logger.verbose(`MsalProvider - Removing event callback ${callbackId}`); | ||
instance, | ||
inProgress, | ||
accounts, | ||
inProgress: state.inProgress, | ||
accounts: state.accounts, | ||
logger | ||
@@ -179,0 +215,0 @@ }; |
@@ -6,2 +6,5 @@ import React, { PropsWithChildren } from "react"; | ||
}>; | ||
/** | ||
* MSAL context provider component. This must be rendered above any other components that use MSAL. | ||
*/ | ||
export declare function MsalProvider({ instance, children }: MsalProviderProps): React.ReactElement; |
export declare const name = "@azure/msal-react"; | ||
export declare const version = "1.3.0"; | ||
export declare const version = "1.3.1"; |
{ | ||
"name": "@azure/msal-react", | ||
"version": "1.3.0", | ||
"version": "1.3.1", | ||
"author": { | ||
@@ -44,8 +44,8 @@ "name": "Microsoft", | ||
"peerDependencies": { | ||
"@azure/msal-browser": "^2.22.0", | ||
"react": "^16.8.0 || ^17" | ||
"@azure/msal-browser": "^2.22.1", | ||
"react": "^16.8.0 || ^17 || ^18" | ||
}, | ||
"module": "dist/msal-react.esm.js", | ||
"devDependencies": { | ||
"@azure/msal-browser": "^2.22.0", | ||
"@azure/msal-browser": "^2.22.1", | ||
"@testing-library/jest-dom": "^5.11.5", | ||
@@ -52,0 +52,0 @@ "@testing-library/react": "^11.2.3", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
201867
25
1310