PageSourceSearch

https://www.superabile.it/etc.clientlibs/superabile/clientlibs/cli…-df920f02b081bac097dfa85cbddabff2-lc.min.js

js superabile.it collected 2026-10-02 04:29:31 UTC 282,289 bytes, 2 lines download raw bytes

1/*! For license information please see login.js.LICENSE.txt */
2!function(){"use strict";var e,t,r,n,o={16125:function(e,t,r){r.a(e,(async function(e,n){try{r.d(t,{DT:function(){return a}});var o=r(68537),i=r(33697),s=e([o]);async function a(e){try{const t={"Content-Type":"application/json"},r=await o.A.post(i.Sn,e,{},t);return{error:r.statusText,status:r.status}}catch(e){console.error("Error in interestService.postInterest: ",e)}}o=(s.then?(await s)():s)[0],n()}catch(c){n(c)}}))},33697:function(e,t,r){r.d(t,{JX:function(){return o},Sn:function(){return n}});const n="/api/Interest",o="/api/UserLocation"},40036:function(e){e.exports=Pinia},44081:function(e,t,r){r.d(t,{vq:function(){return jl}});var n=r(55438),o=r(81140);const i="AAD",s="OIDC",a="EAR",c="none",l="unexpected_error",h="post_request_failed",d={[l]:"Unexpected error in authentication.",[h]:"Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details."};class u extends Error{constructor(e,t,r){super(t?`${e}: ${t}`:e),Object.setPrototypeOf(this,u.prototype),this.errorCode=e||o.YM.EMPTY_STRING,this.errorMessage=t||o.YM.EMPTY_STRING,this.subError=r||o.YM.EMPTY_STRING,this.name="AuthError"}setCorrelationId(e){this.correlationId=e}}function g(e,t){return new u(e,t?`${d[e]} ${t}`:d[e])}const p="client_info_decoding_error",m="client_info_empty_error",f="token_parsing_error",y="null_or_empty_token",C="endpoints_resolution_error",I="network_error",w="openid_config_error",A="hash_not_deserialized",v="invalid_state",T="state_mismatch",_="state_not_found",E="nonce_mismatch",b="auth_time_not_found",k="max_age_transpired",S="multiple_matching_tokens",R="multiple_matching_accounts",O="multiple_matching_appMetadata",P="request_cannot_be_made",M="cannot_remove_empty_scope",N="cannot_append_scopeset",L="empty_input_scopeset",D="device_code_polling_cancelled",U="device_code_expired",q="device_code_unknown_error",H="no_account_in_silent_request",x="invalid_cache_record",F="invalid_cache_environment",B="no_account_found",K="no_crypto_object",G="unexpected_credential_type",z="invalid_assertion",Y="invalid_client_credential",$="token_refresh_required",j="user_timeout_reached",V="token_claims_cnf_required_for_signedjwt",W="authorization_code_missing_from_server_response",Q="binding_key_not_removed",J="end_session_endpoint_not_supported",X="key_id_missing",Z="no_network_connectivity",ee="user_canceled",te="missing_tenant_id_error",re="method_not_implemented",ne="nested_app_auth_bridge_disabled",oe="platform_broker_error",ie={[p]:"The client info could not be parsed/decoded correctly",[m]:"The client info was empty",[f]:"Token cannot be parsed",[y]:"The token is null or empty",[C]:"Endpoints cannot be resolved",[I]:"Network request failed",[w]:"Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",[A]:"The hash parameters could not be deserialized",[v]:"State was not the expected format",[T]:"State mismatch error",[_]:"State not found",[E]:"Nonce mismatch error",[b]:"Max Age was requested and the ID token is missing the auth_time variable. auth_time is an optional claim and is not enabled by default - it must be enabled. See https://aka.ms/msaljs/optional-claims for more information.",[k]:"Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",[S]:"The cache contains multiple tokens satisfying the requirements. Call AcquireToken again providing more requirements such as authority or account.",[R]:"The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",[O]:"The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",[P]:"Token request cannot be made without authorization code or refresh token.",[M]:"Cannot remove null or empty scope from ScopeSet",[N]:"Cannot append ScopeSet",[L]:"Empty input ScopeSet cannot be processed",[D]:"Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",[U]:"Device code is expired.",[q]:"Device code stopped polling for unknown reasons.",[H]:"Please pass an account object, silent flow is not supported without account information",[x]:"Cache record object was null or undefined.",[F]:"Invalid environment when attempting to create cache entry",[B]:"No account found in cache for given key.",[K]:"No crypto object detected.",[G]:"Unexpected credential type.",[z]:"Client assertion must meet requirements described 
2in https://tools.ietf.org/html/rfc7515",[Y]:"Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",[$]:"Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.",[j]:"User defined timeout for device code polling reached",[V]:"Cannot generate a POP jwt if the token_claims are not populated",[W]:"Server response does not contain an authorization code to proceed",[Q]:"Could not remove the credential's binding key from storage.",[J]:"The provided authority does not support logout",[X]:"A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.",[Z]:"No network connectivity. Check your internet connection.",[ee]:"User cancelled the flow.",[te]:"A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",[re]:"This method has not been implemented",[ne]:"The nested app auth bridge is disabled",[oe]:"An error occurred in the native broker. See the platformBrokerError property for details."};class se extends u{constructor(e,t){super(e,t?`${ie[e]}: ${t}`:ie[e]),this.name="ClientAuthError",Object.setPrototypeOf(this,se.prototype)}}function ae(e,t){return new se(e,t)}const ce={createNewGuid:()=>{throw ae(re)},base64Decode:()=>{throw ae(re)},base64Encode:()=>{throw ae(re)},base64UrlEncode:()=>{throw ae(re)},encodeKid:()=>{throw ae(re)},async getPublicKeyThumbprint(){throw ae(re)},async removeTokenBindingKey(){throw ae(re)},async clearKeystore(){throw ae(re)},async signJwt(){throw ae(re)},async hashString(){throw ae(re)}},le="@azure/msal-common",he="15.13.3",de="redirect_uri_empty",ue="claims_request_parsing_error",ge="authority_uri_insecure",pe="url_parse_error",me="empty_url_error",fe="empty_input_scopes_error",ye="invalid_claims",Ce="token_request_empty",Ie="logout_request_empty",we="invalid_code_challenge_method",Ae="pkce_params_missing",ve="invalid_cloud_discovery_metadata",Te="invalid_authority_metadata",_e="untrusted_authority",Ee="missing_ssh_jwk",be="missing_ssh_kid",ke="missing_nonce_authentication_header",Se="invalid_authentication_header",Re="cannot_set_OIDCOptions",Oe="cannot_allow_platform_broker",Pe="authority_mismatch",Me="invalid_request_method_for_EAR",Ne="invalid_authorize_post_body_parameters",Le="invalid_platform_broker_configuration",De={[de]:"A redirect URI is required for all calls, and none has been set.",[ue]:"Could not parse the given claims request object.",[ge]:"Authority URIs must use https.  Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options",[pe]:"URL could not be parsed into appropriate segments.",[me]:"URL was empty or null.",[fe]:"Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",[ye]:"Given claims parameter must be a stringified JSON object.",[Ce]:"Token request was empty and not found in cache.",[Ie]:"The logout request was null or undefined.",[we]:'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',[Ae]:"Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",[ve]:"Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",[Te]:"Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",[_e]:"The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",[Ee]:"Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",[be]:"Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",[ke]:"Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.",[Se]:"Invalid authentication header provided",[Re]:"Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",[Oe]:"Cannot set allowPlatformBroker parameter to true when not in AAD protocol mode.",[Pe]:"Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority.",[Ne]:"Invalid authorize post body parameters provided. If you are using authorizePostBodyParameters, the request method must be POST. Please check the request method and parameters.",[Me]:"Invalid request method for EAR protocol mode. The request method cannot be GET when using EAR protocol mode. Please change the request method to POST.",[Le]:"Invalid platform broker configuration. `allowPlatformBrokerWithDOM` can only be enabled when `allowPlatformBroker` is enabled."};class Ue extends u{constructor(e){super(e,De[e]),this.name="ClientConfigurationError",Object.setPrototypeOf(this,Ue.prototype)}}function qe(e){return new Ue(e)}class He{static isEmptyObj(e){if(e)try{const t=JSON.parse(e);return 0===Object.keys(t).length}catch(e){}return!0}static startsWith(e,t){return 0===e.indexOf(t)}static endsWith(e,t){return e.length>=t.length&&e.lastIndexOf(t)===e.length-t.length}static queryStringToObject(e){const t={},r=e.split("&"),n=e=>decodeURIComponent(e.replace(/\+/g," "));return r.forEach((e=>{if(e.trim()){const[r,o]=e.split(/=(.+)/g,2);r&&o&&(t[n(r)]=n(o))}})),t}static trimArrayEntries(e){return e.map((e=>e.trim()))}static removeEmptyStringsFromArray(e){return e.filter((e=>!!e))}static jsonParseHelper(e){try{return JSON.parse(e)}catch(e){return null}}static matchPattern(e,t){return new RegExp(e.replace(/\\/g,"\\\\").replace(/\*/g,"[^ ]*").replace(/\?/g,"\\?")).test(t)}}class xe{constructor(e){const t=e?He.trimArrayEntries([...e]):[],r=t?He.removeEmptyStringsFromArray(t):[];if(!r||!r.length)throw qe(fe);this.scopes=new Set,r.forEach((e=>this.scopes.add(e)))}static fromString(e){const t=(e||o.YM.EMPTY_STRING).split(" ");return new xe(t)}static createSearchScopes(e){const t=e&&e.length>0?e:[...o.aZ],r=new xe(t);return r.containsOnlyOIDCScopes()?r.removeScope(o.YM.OFFLINE_ACCESS_SCOPE):r.removeOIDCScopes(),r}containsScope(e){const t=this.printScopesLowerCase().split(" "),r=new xe(t);return!!e&&r.scopes.has(e.toLowerCase())}containsScopeSet(e){return!(!e||e.scopes.size<=0)&&(this.scopes.size>=e.scopes.size&&e.asArray().every((e=>this.containsScope(e))))}containsOnlyOIDCScopes(){let e=0;return o._A.forEach((t=>{this.containsScope(t)&&(e+=1)})),this.scopes.size===e}appendScope(e){e&&this.scopes.add(e.trim())}appendScopes(e){try{e.forEach((e=>this.appendScope(e)))}catch(e){throw ae(N)}}removeScope(e){if(!e)throw ae(M);this.scopes.delete(e.trim())}removeOIDCScopes(){o._A.forEach((e=>{this.scopes.delete(e)}))}unionScopeSets(e){if(!e)throw ae(L);const t=new Set;
2return e.scopes.forEach((e=>t.add(e.toLowerCase()))),this.scopes.forEach((e=>t.add(e.toLowerCase()))),t}intersectingScopeSets(e){if(!e)throw ae(L);e.containsOnlyOIDCScopes()||e.removeOIDCScopes();const t=this.unionScopeSets(e),r=e.getScopeCount(),n=this.getScopeCount();return t.size<n+r}getScopeCount(){return this.scopes.size}asArray(){const e=[];return this.scopes.forEach((t=>e.push(t))),e}printScopes(){if(this.scopes){return this.asArray().join(" ")}return o.YM.EMPTY_STRING}printScopesLowerCase(){return this.printScopes().toLowerCase()}}function Fe(e,t){if(!e)throw ae(m);try{const r=t(e);return JSON.parse(r)}catch(e){throw ae(p)}}function Be(e){if(!e)throw ae(p);const t=e.split(o.LR.CLIENT_INFO_SEPARATOR,2);return{uid:t[0],utid:t.length<2?o.YM.EMPTY_STRING:t[1]}}function Ke(e,t){return!!e&&!!t&&e===t.split(".")[1]}function Ge(e,t,r,n){if(n){const{oid:t,sub:r,tid:o,name:i,tfp:s,acr:a,preferred_username:c,upn:l,login_hint:h}=n,d=o||s||a||"";return{tenantId:d,localAccountId:t||r||"",name:i,username:c||l||"",loginHint:h,isHomeTenant:Ke(d,e)}}return{tenantId:r,localAccountId:t,username:"",isHomeTenant:Ke(r,e)}}function ze(e,t,r,n){let o=e;if(t){const{isHomeTenant:r,...n}=t;o={...e,...n}}if(r){const{isHomeTenant:t,...i}=Ge(e.homeAccountId,e.localAccountId,e.tenantId,r);return o={...o,...i,idTokenClaims:r,idToken:n},o}return o}const Ye=0,$e=1,je=2,Ve=3;function We(e){if(e){return e.tid||e.tfp||e.acr||null}return null}class Qe{static getAccountInfo(e){return{homeAccountId:e.homeAccountId,environment:e.environment,tenantId:e.realm,username:e.username,localAccountId:e.localAccountId,loginHint:e.loginHint,name:e.name,nativeAccountId:e.nativeAccountId,authorityType:e.authorityType,tenantProfiles:new Map((e.tenantProfiles||[]).map((e=>[e.tenantId,e]))),dataBoundary:e.dataBoundary}}isSingleTenant(){return!this.tenantProfiles}static createAccount(e,t,r){const n=new Qe;let i;t.authorityType===$e?n.authorityType=o.Qd.ADFS_ACCOUNT_TYPE:t.protocolMode===s?n.authorityType=o.Qd.GENERIC_ACCOUNT_TYPE:n.authorityType=o.Qd.MSSTS_ACCOUNT_TYPE,e.clientInfo&&r&&(i=Fe(e.clientInfo,r),i.xms_tdbr&&(n.dataBoundary="EU"===i.xms_tdbr?"EU":"None")),n.clientInfo=e.clientInfo,n.homeAccountId=e.homeAccountId,n.nativeAccountId=e.nativeAccountId;const a=e.environment||t&&t.getPreferredCache();if(!a)throw ae(F);n.environment=a,n.realm=i?.utid||We(e.idTokenClaims)||"",n.localAccountId=i?.uid||e.idTokenClaims?.oid||e.idTokenClaims?.sub||"";const c=e.idTokenClaims?.preferred_username||e.idTokenClaims?.upn,l=e.idTokenClaims?.emails?e.idTokenClaims.emails[0]:null;if(n.username=c||l||"",n.loginHint=e.idTokenClaims?.login_hint,n.name=e.idTokenClaims?.name||"",n.cloudGraphHostName=e.cloudGraphHostName,n.msGraphHost=e.msGraphHost,e.tenantProfiles)n.tenantProfiles=e.tenantProfiles;else{const t=Ge(e.homeAccountId,n.localAccountId,n.realm,e.idTokenClaims);n.tenantProfiles=[t]}return n}static createFromAccountInfo(e,t,r){const n=new Qe;return n.authorityType=e.authorityType||o.Qd.GENERIC_ACCOUNT_TYPE,n.homeAccountId=e.homeAccountId,n.localAccountId=e.localAccountId,n.nativeAccountId=e.nativeAccountId,n.realm=e.tenantId,n.environment=e.environment,n.username=e.username,n.name=e.name,n.loginHint=e.loginHint,n.cloudGraphHostName=t,n.msGraphHost=r,n.tenantProfiles=Array.from(e.tenantProfiles?.values()||[]),n.dataBoundary=e.dataBoundary,n}static generateHomeAccountId(e,t,r,n,o){if(t!==$e&&t!==je){if(e)try{const t=Fe(e,n.base64Decode);if(t.uid&&t.utid)return`${t.uid}.${t.utid}`}catch(e){}r.warning("No client info in response")}return o?.sub||""}static isAccountEntity(e){return!!e&&(e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("realm")&&e.hasOwnProperty("localAccountId")&&e.hasOwnProperty("username")&&e.hasOwnProperty("authorityType"))}static accountInfoIsEqual(e,t,r){if(!e||!t)return!1;let n=!0;if(r){const r=e.idTokenClaims||{},o=t.idTokenClaims||{};n=r.iat===o.iat&&r.nonce===o.nonce}return e.homeAccountId===t.homeAccountId&&e.localAccountId===t.localAccountId&&e.username===t.username&&e.tenantId===t.tenantId&&e.loginHint===t.loginHint&&e.environment===t.environment&&e.nativeAccountId===t.nativeAccountId&&n}}function Je(e,t){const r=function(e){if(!e)throw ae(y);const t=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(e);if(!t||t.length<4)throw ae(f);return t[2]}(e);try{const e=t(r);return JSON.parse(e)}catch(e){throw ae(f)}}function Xe(e){if(!e.signin_state)return!1;const t=["kmsi","dvc_dmjd"];return e.signin_state.some((e=>t.includes(e.trim().toLowerCase())))}function Ze(e,t){if(0===t||Date.now()-3e5>e+t)throw ae(k)}function et(e){if(!e)return e;let t=e.toLowerCase();return He.endsWith(t,"?")?t=t.slice(0,-1):He.endsWith(t,"?/")&&(t=t.
2slice(0,-2)),He.endsWith(t,"/")||(t+="/"),t}function tt(e){return e.startsWith("#/")?e.substring(2):e.startsWith("#")||e.startsWith("?")?e.substring(1):e}function rt(e){if(!e||e.indexOf("=")<0)return null;try{const t=tt(e),r=Object.fromEntries(new URLSearchParams(t));if(r.code||r.ear_jwe||r.error||r.error_description||r.state)return r}catch(e){throw ae(A)}return null}function nt(e,t=!0,r){const n=new Array;return e.forEach(((e,o)=>{!t&&r&&o in r?n.push(`${o}=${e}`):n.push(`${o}=${encodeURIComponent(e)}`)})),n.join("&")}function ot(e){if(!e)return e;const t=e.split("#")[0];try{const e=new URL(t);return et(e.origin+e.pathname+e.search)}catch(e){return et(t)}}class it{get urlString(){return this._urlString}constructor(e){if(this._urlString=e,!this._urlString)throw qe(me);e.includes("#")||(this._urlString=it.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return He.endsWith(t,"?")?t=t.slice(0,-1):He.endsWith(t,"?/")&&(t=t.slice(0,-2)),He.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch(e){throw qe(pe)}if(!e.HostNameAndPort||!e.PathSegments)throw qe(pe);if(!e.Protocol||"https:"!==e.Protocol.toLowerCase())throw qe(ge)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return it.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),r=t.PathSegments;return!e||0===r.length||r[0]!==o.v2.COMMON&&r[0]!==o.v2.ORGANIZATIONS||(r[0]=e),it.constructAuthorityUriFromObject(t)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw qe(pe);const r={Protocol:t[1],HostNameAndPort:t[4],AbsolutePath:t[5],QueryString:t[7]};let n=r.AbsolutePath.split("/");return n=n.filter((e=>e&&e.length>0)),r.PathSegments=n,r.QueryString&&r.QueryString.endsWith("/")&&(r.QueryString=r.QueryString.substring(0,r.QueryString.length-1)),r}static getDomainFromUrl(e){const t=RegExp("^([^:/?#]+://)?([^/?#]*)"),r=e.match(t);if(!r)throw qe(pe);return r[2]}static getAbsoluteUrl(e,t){if(e[0]===o.YM.FORWARD_SLASH){const r=new it(t).getUrlComponents();return r.Protocol+"//"+r.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e){return new it(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"))}static hashContainsKnownProperties(e){return!!rt(e)}}const st={"login.microsoftonline.com":{token_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys",issuer:"https://login.microsoftonline.com/{tenantid}/v2.0",authorization_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/logout"},"login.chinacloudapi.cn":{token_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.chinacloudapi.cn/{tenantid}/discovery/v2.0/keys",issuer:"https://login.partner.microsoftonline.cn/{tenantid}/v2.0",authorization_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/logout"},"login.microsoftonline.us":{token_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.microsoftonline.us/{tenantid}/discovery/v2.0/keys",issuer:"https://login.microsoftonline.us/{tenantid}/v2.0",authorization_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/logout"}},at={metadata:[{preferred_network:"login.microsoftonline.com",preferred_cache:"login.windows.net",aliases:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"]},{preferred_network:"login.partner.microsoftonline.cn",preferred_cache:"login.partner.microsoftonline.cn",aliases:["login.partner.microsoftonline.cn","login.chinacloudapi.cn"]},{preferred_network:"login.microsoftonline.de",preferred_cache:"login.microsoftonline.de",aliases:["login.microsoftonline.de"]},{preferred_network:"login.microsoftonline.us",preferred_cache:"login.microsoftonline.us",aliases:["login.microsoftonline.us","login.usgovcloudapi.net"]},{preferred_network:"login-us.microsoftonline.com",preferred_cache:"login-us.microsoftonline.com",aliases:["login-us.microsoftonline.com"]}]},ct=new Set;function lt(e,t,r,n){if(n?.trace(`getAliasesFromMetadata called with source: ${r}`),e&&t){const o=ht(t,e);
2if(o)return n?.trace(`getAliasesFromMetadata: found cloud discovery metadata in ${r}, returning aliases`),o.aliases;n?.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in ${r}`)}return null}function ht(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.aliases.includes(t))return n}return null}at.metadata.forEach((e=>{e.aliases.forEach((e=>{ct.add(e)}))}));const dt="cache_quota_exceeded",ut="cache_error_unknown",gt={[dt]:"Exceeded cache storage capacity.",[ut]:"Unexpected error occurred when using cache storage."};class pt extends u{constructor(e,t){const r=t||(gt[e]?gt[e]:gt[ut]);super(`${e}: ${r}`),Object.setPrototypeOf(this,pt.prototype),this.name="CacheError",this.errorCode=e,this.errorMessage=r}}function mt(e){return e instanceof Error?"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||e.message.includes("exceeded the quota")?new pt(dt):new pt(e.name,e.message):new pt(ut)}class ft{constructor(e,t,r,n,o){this.clientId=e,this.cryptoImpl=t,this.commonLogger=r.clone(le,he),this.staticAuthorityOptions=o,this.performanceClient=n}getAllAccounts(e,t){return this.buildTenantProfiles(this.getAccountsFilteredBy(e,t),t,e)}getAccountInfoFilteredBy(e,t){if(0===Object.keys(e).length||Object.values(e).every((e=>!e)))return this.commonLogger.warning("getAccountInfoFilteredBy: Account filter is empty or invalid, returning null"),null;const r=this.getAllAccounts(e,t);if(r.length>1){return r.sort((e=>e.idTokenClaims?-1:1))[0]}return 1===r.length?r[0]:null}getBaseAccountInfo(e,t){const r=this.getAccountsFilteredBy(e,t);return r.length>0?Qe.getAccountInfo(r[0]):null}buildTenantProfiles(e,t,r){return e.flatMap((e=>this.getTenantProfilesFromAccountEntity(e,t,r?.tenantId,r)))}getTenantedAccountInfoByFilter(e,t,r,n,o){let i,s=null;if(o&&!this.tenantProfileMatchesFilter(r,o))return null;const a=this.getIdToken(e,n,t,r.tenantId);return a&&(i=Je(a.secret,this.cryptoImpl.base64Decode),!this.idTokenClaimsMatchTenantProfileFilter(i,o))?null:(s=ze(e,r,i,a?.secret),s)}getTenantProfilesFromAccountEntity(e,t,r,n){const o=Qe.getAccountInfo(e);let i=o.tenantProfiles||new Map;const s=this.getTokenKeys();if(r){const e=i.get(r);if(!e)return[];i=new Map([[r,e]])}const a=[];return i.forEach((e=>{const r=this.getTenantedAccountInfoByFilter(o,s,e,t,n);r&&a.push(r)})),a}tenantProfileMatchesFilter(e,t){return!(t.localAccountId&&!this.matchLocalAccountIdFromTenantProfile(e,t.localAccountId))&&((!t.name||e.name===t.name)&&(void 0===t.isHomeTenant||e.isHomeTenant===t.isHomeTenant))}idTokenClaimsMatchTenantProfileFilter(e,t){if(t){if(t.localAccountId&&!this.matchLocalAccountIdFromTokenClaims(e,t.localAccountId))return!1;if(t.loginHint&&!this.matchLoginHintFromTokenClaims(e,t.loginHint))return!1;if(t.username&&!this.matchUsername(e.preferred_username,t.username))return!1;if(t.name&&!this.matchName(e,t.name))return!1;if(t.sid&&!this.matchSid(e,t.sid))return!1}return!0}async saveCacheRecord(e,t,r,n){if(!e)throw ae(x);try{e.account&&await this.setAccount(e.account,t,r),e.idToken&&!1!==n?.idToken&&await this.setIdTokenCredential(e.idToken,t,r),e.accessToken&&!1!==n?.accessToken&&await this.saveAccessToken(e.accessToken,t,r),e.refreshToken&&!1!==n?.refreshToken&&await this.setRefreshTokenCredential(e.refreshToken,t,r),e.appMetadata&&this.setAppMetadata(e.appMetadata,t)}catch(e){throw this.commonLogger?.error("CacheManager.saveCacheRecord: failed"),e instanceof u?e:mt(e)}}async saveAccessToken(e,t,r){const n={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType,requestedClaimsHash:e.requestedClaimsHash},o=this.getTokenKeys(),i=xe.fromString(e.target);o.accessToken.forEach((e=>{if(!this.accessTokenKeyMatchesFilter(e,n,!1))return;const r=this.getAccessTokenCredential(e,t);if(r&&this.credentialMatchesFilter(r,n)){xe.fromString(r.target).intersectingScopeSets(i)&&this.removeAccessToken(e,t)}})),await this.setAccessTokenCredential(e,t,r)}getAccountsFilteredBy(e,t){const r=this.getAccountKeys(),n=[];return r.forEach((r=>{const o=this.getAccount(r,t);if(!o)return;if(e.homeAccountId&&!this.matchHomeAccountId(o,e.homeAccountId))return;if(e.username&&!this.matchUsername(o.username,e.username))return;if(e.environment&&!this.matchEnvironment(o,e.environment))return;if(e.realm&&!this.matchRealm(o,e.realm))return;if(e.nativeAccountId&&!this.matchNativeAccountId(o,e.nativeAccountId))return;if(e.authorityType&&!this.matchAuthorityType(o,e.authorityType))return;const i={localAccountId:e?.localAccountId,name:e?.name},s=o.tenantProfiles?.filter((e=>this.tenantProfileMatchesFilter(e,i)));s&&0===s.length||n.push(o)})),n}credentialMatchesFilter(e,t){if(t.clientId&&!this.matchClientId(e,t.clientId))return!1;if(t.userAssertionHash&&!this.matchUserAssertionHash(e,t.userAssertionHash))return!1;if("string"==typeof t.homeAccountId&&!this.matchHomeAccountId(e,t.homeAccountId))return!1;if(t.environment&&!this.matchEnvironment(e,t.environment))return!1;if(t.realm&&!this.matchRealm(e,t.realm))return!1;if(t.credentialType&&!this.matchCredentialType(e,t.credentialType))return!1;if(t.familyId&&!this.matchFamilyId(e,t.familyId))return!1;if(t.target&&!this.matchTarget(e,t.target))return!1;if((t.requestedClaimsHash||e.requestedClaimsHash)&&e.requestedClaimsHash!==t.requestedClaimsHash)return!1;if(e.credentialType===o.aG.ACCESS_TOKEN_WITH_AUTH_SCHEME){if(t.tokenType&&!this.matchTokenType(e,t.tokenType))return!1;if(t.tokenType===o.IO.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId))return!1}return!0}getAppMetadataFilteredBy(e){const t=this.getKeys(),r={};return t.forEach((t=>{if(!this.isAppMetadata(t))return;const n=this.getAppMetadata(t);
2n&&(e.environment&&!this.matchEnvironment(n,e.environment)||e.clientId&&!this.matchClientId(n,e.clientId)||(r[t]=n))})),r}getAuthorityMetadataByAlias(e){const t=this.getAuthorityMetadataKeys();let r=null;return t.forEach((t=>{if(!this.isAuthorityMetadata(t)||-1===t.indexOf(this.clientId))return;const n=this.getAuthorityMetadata(t);n&&-1!==n.aliases.indexOf(e)&&(r=n)})),r}removeAllAccounts(e){this.getAllAccounts({},e).forEach((t=>{this.removeAccount(t,e)}))}removeAccount(e,t){this.removeAccountContext(e,t);this.getAccountKeys().filter((t=>t.includes(e.homeAccountId)&&t.includes(e.environment))).forEach((e=>{this.removeItem(e,t),this.performanceClient.incrementFields({accountsRemoved:1},t)}))}removeAccountContext(e,t){const r=this.getTokenKeys(),n=t=>t.includes(e.homeAccountId)&&t.includes(e.environment);r.idToken.filter(n).forEach((e=>{this.removeIdToken(e,t)})),r.accessToken.filter(n).forEach((e=>{this.removeAccessToken(e,t)})),r.refreshToken.filter(n).forEach((e=>{this.removeRefreshToken(e,t)}))}removeAccessToken(e,t){const r=this.getAccessTokenCredential(e,t);if(this.removeItem(e,t),this.performanceClient.incrementFields({accessTokensRemoved:1},t),!r||r.credentialType.toLowerCase()!==o.aG.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()||r.tokenType!==o.IO.POP)return;const n=r.keyId;n&&this.cryptoImpl.removeTokenBindingKey(n).catch((()=>{this.commonLogger.error(`Failed to remove token binding key ${n}`,t),this.performanceClient?.incrementFields({removeTokenBindingKeyFailure:1},t)}))}removeAppMetadata(e){return this.getKeys().forEach((t=>{this.isAppMetadata(t)&&this.removeItem(t,e)})),!0}getIdToken(e,t,r,n,i){this.commonLogger.trace("CacheManager - getIdToken called");const s={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:o.aG.ID_TOKEN,clientId:this.clientId,realm:n},a=this.getIdTokensByFilter(s,t,r),c=a.size;if(c<1)return this.commonLogger.info("CacheManager:getIdToken - No token found"),null;if(c>1){let r=a;if(!n){const t=new Map;a.forEach(((r,n)=>{r.realm===e.tenantId&&t.set(n,r)}));const n=t.size;if(n<1)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result"),a.values().next().value;if(1===n)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile"),t.values().next().value;r=t}return this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them"),r.forEach(((e,r)=>{this.removeIdToken(r,t)})),i&&t&&i.addFields({multiMatchedID:a.size},t),null}return this.commonLogger.info("CacheManager:getIdToken - Returning ID token"),a.values().next().value}getIdTokensByFilter(e,t,r){const n=r&&r.idToken||this.getTokenKeys().idToken,o=new Map;return n.forEach((r=>{if(!this.idTokenKeyMatchesFilter(r,{clientId:this.clientId,...e}))return;const n=this.getIdTokenCredential(r,t);n&&this.credentialMatchesFilter(n,e)&&o.set(r,n)})),o}idTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.clientId||-1!==r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase()))}removeIdToken(e,t){this.removeItem(e,t)}removeRefreshToken(e,t){this.removeItem(e,t)}getAccessToken(e,t,r,n){const i=t.correlationId;this.commonLogger.trace("CacheManager - getAccessToken called",i);const s=xe.createSearchScopes(t.scopes),a=t.authenticationScheme||o.IO.BEARER,c=a&&a.toLowerCase()!==o.IO.BEARER.toLowerCase()?o.aG.ACCESS_TOKEN_WITH_AUTH_SCHEME:o.aG.ACCESS_TOKEN,l={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:c,clientId:this.clientId,realm:n||e.tenantId,target:s,tokenType:a,keyId:t.sshKid,requestedClaimsHash:t.requestedClaimsHash},h=r&&r.accessToken||this.getTokenKeys().accessToken,d=[];h.forEach((e=>{if(this.accessTokenKeyMatchesFilter(e,l,!0)){const t=this.getAccessTokenCredential(e,i);t&&this.credentialMatchesFilter(t,l)&&d.push(t)}}));const u=d.length;return u<1?(this.commonLogger.info("CacheManager:getAccessToken - No token found",i),null):u>1?(this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them",i),d.forEach((e=>{this.removeAccessToken(this.generateCredentialKey(e),i)})),this.performanceClient.addFields({multiMatchedAT:d.length},i),null):(this.commonLogger.info("CacheManager:getAccessToken - Returning access token",i),d[0])}accessTokenKeyMatchesFilter(e,t,r){const n=e.toLowerCase();if(t.clientId&&-1===n.indexOf(t.clientId.toLowerCase()))return!1;if(t.homeAccountId&&-1===n.indexOf(t.homeAccountId.toLowerCase()))return!1;if(t.realm&&-1===n.indexOf(t.realm.toLowerCase()))return!1;if(t.requestedClaimsHash&&-1===n.indexOf(t.requestedClaimsHash.toLowerCase()))return!1;if(t.target){const e=t.target.asArray();for(let t=0;t<e.length;t++){if(r&&!n.includes(e[t].toLowerCase()))return!1;if(!r&&n.includes(e[t].toLowerCase()))return!0}}return!0}getAccessTokensByFilter(e,t){const r=this.getTokenKeys(),n=[];
2return r.accessToken.forEach((r=>{if(!this.accessTokenKeyMatchesFilter(r,e,!0))return;const o=this.getAccessTokenCredential(r,t);o&&this.credentialMatchesFilter(o,e)&&n.push(o)})),n}getRefreshToken(e,t,r,n,i){this.commonLogger.trace("CacheManager - getRefreshToken called");const s=t?o.hB:void 0,a={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:o.aG.REFRESH_TOKEN,clientId:this.clientId,familyId:s},c=n&&n.refreshToken||this.getTokenKeys().refreshToken,l=[];c.forEach((e=>{if(this.refreshTokenKeyMatchesFilter(e,a)){const t=this.getRefreshTokenCredential(e,r);t&&this.credentialMatchesFilter(t,a)&&l.push(t)}}));const h=l.length;return h<1?(this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found."),null):(h>1&&i&&r&&i.addFields({multiMatchedRT:h},r),this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token"),l[0])}refreshTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.familyId||-1!==r.indexOf(t.familyId.toLowerCase()))&&(!(!t.familyId&&t.clientId&&-1===r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase())))}readAppMetadataFromCache(e){const t={environment:e,clientId:this.clientId},r=this.getAppMetadataFilteredBy(t),n=Object.keys(r).map((e=>r[e])),o=n.length;if(o<1)return null;if(o>1)throw ae(O);return n[0]}isAppMetadataFOCI(e){const t=this.readAppMetadataFromCache(e);return!(!t||t.familyId!==o.hB)}matchHomeAccountId(e,t){return!("string"!=typeof e.homeAccountId||t!==e.homeAccountId)}matchLocalAccountIdFromTokenClaims(e,t){return t===(e.oid||e.sub)}matchLocalAccountIdFromTenantProfile(e,t){return e.localAccountId===t}matchName(e,t){return!(t.toLowerCase()!==e.name?.toLowerCase())}matchUsername(e,t){return!(!e||"string"!=typeof e||t?.toLowerCase()!==e.toLowerCase())}matchUserAssertionHash(e,t){return!(!e.userAssertionHash||t!==e.userAssertionHash)}matchEnvironment(e,t){if(this.staticAuthorityOptions){const r=function(e,t){let r;const n=e.canonicalAuthority;if(n){const i=new it(n).getUrlComponents().HostNameAndPort;r=lt(i,e.cloudDiscoveryMetadata?.metadata,o.E_.CONFIG,t)||lt(i,at.metadata,o.E_.HARDCODED_VALUES,t)||e.knownAuthorities}return r||[]}(this.staticAuthorityOptions,this.commonLogger);if(r.includes(t)&&r.includes(e.environment))return!0}const r=this.getAuthorityMetadataByAlias(t);return!!(r&&r.aliases.indexOf(e.environment)>-1)}matchCredentialType(e,t){return e.credentialType&&t.toLowerCase()===e.credentialType.toLowerCase()}matchClientId(e,t){return!(!e.clientId||t!==e.clientId)}matchFamilyId(e,t){return!(!e.familyId||t!==e.familyId)}matchRealm(e,t){return!(e.realm?.toLowerCase()!==t.toLowerCase())}matchNativeAccountId(e,t){return!(!e.nativeAccountId||t!==e.nativeAccountId)}matchLoginHintFromTokenClaims(e,t){return e.login_hint===t||(e.preferred_username===t||e.upn===t)}matchSid(e,t){return e.sid===t}matchAuthorityType(e,t){return!(!e.authorityType||t.toLowerCase()!==e.authorityType.toLowerCase())}matchTarget(e,t){if(e.credentialType!==o.aG.ACCESS_TOKEN&&e.credentialType!==o.aG.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target)return!1;return xe.fromString(e.target).containsScopeSet(t)}matchTokenType(e,t){return!(!e.tokenType||e.tokenType!==t)}matchKeyId(e,t){return!(!e.keyId||e.keyId!==t)}isAppMetadata(e){return-1!==e.indexOf(o.GU)}isAuthorityMetadata(e){return-1!==e.indexOf(o.u0.CACHE_KEY)}generateAuthorityMetadataCacheKey(e){return`${o.u0.CACHE_KEY}-${this.clientId}-${e}`}static toObject(e,t){for(const r in t)e[r]=t[r];return e}}class yt extends ft{async setAccount(){throw ae(re)}getAccount(){throw ae(re)}async setIdTokenCredential(){throw ae(re)}getIdTokenCredential(){throw ae(re)}async setAccessTokenCredential(){throw ae(re)}getAccessTokenCredential(){throw ae(re)}async setRefreshTokenCredential(){throw ae(re)}getRefreshTokenCredential(){throw ae(re)}setAppMetadata(){throw ae(re)}getAppMetadata(){throw ae(re)}setServerTelemetry(){throw ae(re)}getServerTelemetry(){throw ae(re)}setAuthorityMetadata(){throw ae(re)}getAuthorityMetadata(){throw ae(re)}getAuthorityMetadataKeys(){throw ae(re)}setThrottlingCache(){throw ae(re)}getThrottlingCache(){throw ae(re)}removeItem(){throw ae(re)}getKeys(){throw ae(re)}getAccountKeys(){throw ae(re)}getTokenKeys(){throw ae(re)}generateCredentialKey(){throw ae(re)}generateAccountKey(){throw ae(re)}}const Ct="acquireTokenByCode",It="acquireTokenByRefreshToken",wt="acquireTokenSilent",At="acquireTokenSilentAsync",vt="acquireTokenPopup",Tt="acquireTokenPreRedirect",_t="acquireTokenRedirect",Et="cryptoOptsGetPublicKeyThumbprint",bt="cryptoOptsSignJwt",kt="silentCacheClientAcquireToken",St="silentIframeClientAcquireToken",Rt="awaitConcurrentIframe",Ot="silentRefreshClientAcquireToken",Pt="ssoSilent",Mt="standardInteractionClientGetDiscoveredAuthority",Nt="nativeInteractionClientAcquireToken",Lt="networkClientSendPostRequestAsync",Dt="refreshTokenClientExecutePostToTokenEndpoint",Ut="authorizationCodeClientExecutePostToTokenEndpoint",qt="refreshTokenClientExecuteTokenRequest",Ht="refreshTokenClientAcquireToken",xt="refreshTokenClientAcquireTokenWithCachedRefreshToken",Ft="refreshTokenClientAcquireTokenByRefreshToken",Bt="refreshTokenClientCreateTokenRequestBody",Kt="acquireTokenFromCache",Gt="silentFlowClientAcquireCachedToken",zt="silentFlowClientGenerateResultFromCacheRecord",Yt="acquireTokenBySilentIframe",$t="initializeBaseRequest",jt="initializeSilentRequest",Vt="initializeClientApplication",Wt="initializeCache",Qt="silentIframeClientTokenHelper",Jt="silentHandlerInitiateAuthRequest",Xt="silentHandlerMonitorIframeForHash",Zt="silentHandlerLoadFrame",er="silentHandlerLoadFrameSync",tr="standardInteractionClientCreateAuthCodeClient",rr="standardInteractionClientGetClientConfiguration",nr="standardInteractionClientInitializeAuthorizationRequest",or="getAuthCodeUrl",ir="getStandardParams",sr="handleCodeResponseFromServer",ar="handleCodeResponse",cr="handleResponseEar",lr="handleResponsePlatformBroker",hr="handleResponseCode",dr="updateTokenEndpointAuthority",ur="authClientAcquireToken",gr="authClientExecuteTokenRequest",pr="authClientCreateTokenRequestBody",mr="popTokenGenerateCnf",fr="popTokenGenerateKid",yr="handleServerTokenResponse",Cr="deserializeResponse",Ir="authorityFactoryCreateDiscoveredInstance",wr="authorityResolveEndpointsAsync",Ar="authorityGetCloudDiscoveryMetadataFromNetwork",vr="authorityUpdateCloudDiscoveryMetadata",Tr="authorityGetEndpointMetadataFromNetwork",_r="authorityUpdateEndpointMetadata",Er="authorityUpdateMetadataWithRegionalInformation",br="regionDiscoveryDetectRegion",kr="regionDiscoveryGetRegionFromIMDS",Sr="regionDiscoveryGetCurrentVersion",Rr="acquireTokenByCodeAsync",Or="handleRedirectPromise",Pr="handleNativeRedirectPromise",Mr="nativeMessageHandlerHandshake",Nr="removeHiddenIframe",Lr="clearTokensAndKeysWithClaims",Dr="cacheManagerGetRefreshToken",Ur="importExistingCache",qr="setUserData",Hr="localStorageUpdated",xr="generatePkceCodes",Fr="generateCodeVerifier",Br="generateCodeChallengeFromVerifier",Kr="sha256Digest",Gr="getRandomValues",zr="generateHKDF",Yr="generateBaseKey",$r="base64Decode",jr="urlEncodeArr",Vr="encrypt",Wr="decrypt",Qr="generateEarKey",Jr="decryptEarResponse",Xr=(new Map([[Ct,"ATByCode"],[It,"ATByRT"],[wt,"ATS"],[At,"ATSAsync"],[vt,"ATPopup"],[_t,"ATRedirect"],[Et,"CryptoGetPKThumb"],[bt,"CryptoSignJwt"],[kt,"SltCacheClientAT"],[St,"SltIframeClientAT"],[Ot,"SltRClientAT"],[Pt,"SsoSlt"],[Mt,"StdIntClientGetDiscAuth"],["fetchAccountIdWithNativeBroker","FetchAccIdWithNtvBroker"],[Nt,"NtvIntClientAT"],["baseClientCreateTokenRequestHeaders","BaseClientCreateTReqHead"],[Lt,"NetClientSendPost"],[Dt,"RTClientExecPost"],[Ut,"AuthCodeClientExecPost"],["brokerHandshake","BrokerHandshake"],["acquireTokenByRefreshTokenInBroker","ATByRTInBroker"],["acquireTokenByBroker","ATByBroker"],[qt,"RTClientExecTReq"],[Ht,"RTClientAT"],[xt,"RTClientATWithCachedRT"],[Ft,"RTClientATByRT"],[Bt,"RTClientCreateTReqBody"],[Kt,"ATFromCache"],[Gt,"SltFlowClientATCached"],[zt,"SltFlowClientGenResFromCache"],[Yt,"ATBySltIframe"],[$t,"InitBaseReq"],[jt,"InitSltReq"],[Vt,"InitClientApplication"],[Wt,"InitCache"],[Ur,"importCache"],[qr,"setUserData"],[Hr,"localStorageUpdated"],[Qt,"SIClientTHelper"],[Jt,"SHandlerInitAuthReq"],[Xt,"SltHandlerMonitorIframeForHash"],[Zt,"SHandlerLoadFrame"],[er,"SHandlerLoadFrameSync"],[tr,"StdIntClientCreateAuthCodeClient"],[rr,"StdIntClientGetClientConf"],[nr,"StdIntClientInitAuthReq"],[or,"GetAuthCodeUrl"],[sr,"HandleCodeResFromServer"],[ar,"HandleCodeResp"],[cr,"HandleRespEar"],[hr,"HandleRespCode"],[lr,"HandleRespPlatBroker"],[dr,"UpdTEndpointAuth"],[ur,"AuthClientAT"],[gr,"AuthClientExecTReq"],[pr,"AuthClientCreateTReqBody"],[mr,"PopTGenCnf"],[fr,"PopTGenKid"],[yr,"HandleServerTRes"],[Cr,"DeserializeRes"],[Ir,"AuthFactCreateDiscInst"],[wr,"AuthResolveEndpointsAsync"],["authorityResolveEndpointsFromLocalSources","AuthResolveEndpointsFromLocal"],[Ar,"AuthGetCDMetaFromNet"],[vr,"AuthUpdCDMeta"],[Tr,"AuthUpdCDMetaFromNet"],[_r,"AuthUpdEndpointMeta"],[Er,"AuthUpdMetaWithRegInfo"],[br,"RegDiscDetectReg"],[kr,"RegDiscGetRegFromIMDS"],[Sr,"RegDiscGetCurrentVer"],[Rr,"ATByCodeAsync"],["getEndpointMetadataFromNetwork","GetEndpointMetaFromNet"],["getCloudDiscoveryMetadataFromNetworkMeasurement","GetCDMetaFromNet"],[Or,"HandleRedirectPromise"],[Pr,"HandleNtvRedirectPromise"],["updateCloudDiscoveryMetadataMeasurement","UpdateCDMeta"],["usernamePasswordCl
2ientAcquireToken","UserPassClientAT"],[Mr,"NtvMsgHandlerHandshake"],["nativeGenerateAuthResult","NtvGenAuthRes"],[Nr,"RemoveHiddenIframe"],[Lr,"ClearTAndKeysWithClaims"],[Dr,"CacheManagerGetRT"],[xr,"GenPkceCodes"],[Fr,"GenCodeVerifier"],[Br,"GenCodeChallengeFromVerifier"],[Kr,"Sha256Digest"],[Gr,"GetRandomValues"],[zr,"genHKDF"],[Yr,"genBaseKey"],[$r,"b64Decode"],[jr,"urlEncArr"],[Vr,"encrypt"],[Wr,"decrypt"],[Qr,"genEarKey"],[Jr,"decryptEarResp"]]),1);new Set(["accessTokenSize","durationMs","idTokenSize","matsSilentStatus","matsHttpStatus","refreshTokenSize","queuedTimeMs","startTimeMs","status","multiMatchedAT","multiMatchedID","multiMatchedRT","unencryptedCacheCount","encryptedCacheExpiredCount","oldAccountCount","oldAccessCount","oldIdCount","oldRefreshCount","currAccountCount","currAccessCount","currIdCount","currRefreshCount","expiredCacheRemovedCount","upgradedCacheCount"]);class Zr{startMeasurement(){}endMeasurement(){}flushMeasurement(){return null}}class en{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:Xr,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""},measurement:new Zr}}startPerformanceMeasurement(){return new Zr}calculateQueuedTime(){return 0}addQueueMeasurement(){}setPreQueueTime(){}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}incrementFields(){}cacheEventByCorrelationId(){}}const tn={tokenRenewalOffsetSeconds:o.F0,preventCorsPreflight:!1},rn={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:n.$.Info,correlationId:o.YM.EMPTY_STRING},nn={claimsBasedCachingEnabled:!1},on={async sendGetRequestAsync(){throw ae(re)},async sendPostRequestAsync(){throw ae(re)}},sn={sku:o.YM.SKU,version:he,cpu:o.YM.EMPTY_STRING,os:o.YM.EMPTY_STRING},an={clientSecret:o.YM.EMPTY_STRING,clientAssertion:void 0},cn={azureCloudInstance:c,tenant:`${o.YM.DEFAULT_COMMON_TENANT}`},ln={application:{appName:"",appVersion:""}};function hn(e){return e.authOptions.authority.options.protocolMode===s}const dn={sendGetRequestAsync:()=>Promise.reject(ae(re)),sendPostRequestAsync:()=>Promise.reject(ae(re))},un="invalid_grant",gn=483,pn=600,mn="msal",fn=30,yn="msal.js.browser",Cn="53ee284d-920a-4b59-9d30-a60315b26836",In="ppnbnpeolgkicgegkbkbjmhlideopiji",wn="MATS",An="MicrosoftEntra",vn="DOM API",Tn="get-token-and-sign-out",_n="PlatformAuthDOMHandler",En="PlatformAuthExtensionHandler",bn="Handshake",kn="HandshakeResponse",Sn="GetToken",Rn="Response",On="localStorage",Pn="sessionStorage",Mn="memoryStorage",Nn="GET",Ln="POST",Dn="signin",Un="signout",qn="request.origin",Hn="urlHash",xn="request.params",Fn="code.verifier",Bn="interaction.status",Kn="request.native",Gn="wrapper.sku",zn="wrapper.version",Yn=861,$n=862,jn=863,Vn=865,Wn=866,Qn=61,Jn=961,Xn=962;var Zn;!function(e){e.Redirect="redirect",e.Popup="popup",e.Silent="silent",e.None="none"}(Zn||(Zn={}));const eo={scopes:o.aZ},to="msal.db",ro=`${to}.keys`,no=0,oo=1,io=2,so=3,ao=4,co=5,lo=[no,co,ao],ho="pkce_not_created",uo="ear_jwk_empty",go="ear_jwe_empty",po="crypto_nonexistent",mo="empty_navigate_uri",fo="hash_empty_error",yo="no_state_in_hash",Co="hash_does_not_contain_known_properties",Io="unable_to_parse_state",wo="state_interaction_type_mismatch",Ao="interaction_in_progress",vo="popup_window_error",To="empty_window_error",_o="user_cancelled",Eo="monitor_popup_timeout",bo="monitor_window_timeout",ko="redirect_in_iframe",So="block_iframe_reload",Ro="block_nested_popups",Oo="iframe_closed_prematurely",Po="silent_logout_unsupported",Mo="no_account_error",No="silent_prompt_value_error",Lo="no_token_request_cache_error",Do="unable_to_parse_token_request_cache_error",Uo="auth_request_not_set_error",qo="invalid_cache_type",Ho="non_browser_environment",xo="database_not_open",Fo="no_network_connectivity",Bo="post_request_failed",Ko="get_request_failed",Go="failed_to_parse_response",zo="unable_to_load_token",Yo="crypto_key_not_found",$o="auth_code_required",jo="auth_code_or_nativeAccountId_required",Vo="spa_code_and_nativeAccountId_present",Wo="database_unavailable",Qo="unable_to_acquire_token_from_native_platform",Jo="native_handshake_timeout",Xo="native_extension_not_installed",Zo="native_connection_not_established",ei="uninitialized_public_client_application",ti="native_prompt_not_supported",ri="invalid_base64_string",ni="invalid_pop_token_request",oi="failed_to_build_headers",ii="failed_to_parse_headers",si="failed_to_decrypt_ear_response",ai="timed_out",ci="For more visit: aka.ms/msaljs/browser-errors",li={[ho]:"The PKCE code challenge and verifier could not be generated.",[uo]:"No EAR encryption key provided. This is unexpected.",[go]:"Server response does not contain ear_jwe property. This is unexpected.",[po]:"The crypto object or function is not available.",[mo]:"Navigation URI is empty. Please check stack trace for more info.",[fo]:`Hash value cannot be processed because it is empty. Please verify that your redirectUri is not clearing the hash. ${ci}`,[yo]:"Hash does not contain state. Please verify that the request originated from msal.",[Co]:`Hash does not contain known properites. Please verify that your redirectUri is not changing the hash.  ${ci}`,[Io]:"Unable to parse state. Please verify that the request originated from msal.",[wo]:"Hash contains state but the interaction type does not match the caller.",[Ao]:`Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API.   ${ci}`,[vo]:"Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser.",[To]:"window.open returned null or undefined window object.",[_o]:"User cancelled the flow.",[Eo]:`Token acquisition in popup failed due to timeout.  ${ci}`,[bo]:`Token acquisition in iframe failed due to timeout.  ${ci}
2`,[ko]:"Redirects are not supported for iframed or brokered applications. Please ensure you are using MSAL.js in a top frame of the window if using the redirect APIs, or use the popup APIs.",[So]:`Request was blocked inside an iframe because MSAL detected an authentication response.  ${ci}`,[Ro]:"Request was blocked inside a popup because MSAL detected it was running in a popup.",[Oo]:"The iframe being monitored was closed prematurely.",[Po]:"Silent logout not supported. Please call logoutRedirect or logoutPopup instead.",[Mo]:"No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the request.",[No]:"The value given for the prompt value is not valid for silent requests - must be set to 'none' or 'no_session'.",[Lo]:"No token request found in cache.",[Do]:"The cached token request could not be parsed.",[Uo]:"Auth Request not set. Please ensure initiateAuthRequest was called from the InteractionHandler",[qo]:"Invalid cache type",[Ho]:"Login and token requests are not supported in non-browser environments.",[xo]:"Database is not open!",[Fo]:"No network connectivity. Check your internet connection.",[Bo]:"Network request failed: If the browser threw a CORS error, check that the redirectUri is registered in the Azure App Portal as type 'SPA'",[Ko]:"Network request failed. Please check the network trace to determine root cause.",[Go]:"Failed to parse network response. Check network trace.",[zo]:"Error loading token to cache.",[Yo]:"Cryptographic Key or Keypair not found in browser storage.",[$o]:"An authorization code must be provided (as the `code` property on the request) to this flow.",[jo]:"An authorization code or nativeAccountId must be provided to this flow.",[Vo]:"Request cannot contain both spa code and native account id.",[Wo]:"IndexedDB, which is required for persistent cryptographic key storage, is unavailable. This may be caused by browser privacy features which block persistent storage in third-party contexts.",[Qo]:`Unable to acquire token from native platform.  ${ci}`,[Jo]:"Timed out while attempting to establish connection to browser extension",[Xo]:"Native extension is not installed. If you think this is a mistake call the initialize function.",[Zo]:`Connection to native platform has not been established. Please install a compatible browser extension and run initialize().  ${ci}`,[ei]:`You must call and await the initialize function before attempting to call any other MSAL API.  ${ci}`,[ti]:"The provided prompt is not supported by the native platform. This request should be routed to the web based flow.",[ri]:"Invalid base64 encoded string.",[ni]:"Invalid PoP token request. The request should not have both a popKid value and signPopToken set to true.",[oi]:"Failed to build request headers object.",[ii]:"Failed to parse response headers",[si]:"Failed to decrypt ear response",[ai]:"The request timed out."};class hi extends u{constructor(e,t){super(e,li[e],t),Object.setPrototypeOf(this,hi.prototype),this.name="BrowserAuthError"}}function di(e,t){return new hi(e,t)}class ui{navigateInternal(e,t){return ui.defaultNavigateWindow(e,t)}navigateExternal(e,t){return ui.defaultNavigateWindow(e,t)}static defaultNavigateWindow(e,t){return t.noHistory?window.location.replace(e):window.location.assign(e),new Promise(((e,r)=>{setTimeout((()=>{r(di(ai,"failed_to_redirect"))}),t.timeout)}))}}class gi extends u{constructor(e,t,r){super(e.errorCode,e.errorMessage,e.subError),Object.setPrototypeOf(this,gi.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=r}}function pi(e,t,r,n){return e.errorMessage=`${e.errorMessage}, additionalErrorInfo: error.name:${n?.name}, error.message:${n?.message}`,new gi(e,t,r)}class mi{async sendGetRequestAsync(e,t){let r,n={},o=0;const i=fi(t);try{r=await fetch(e,{method:Nn,headers:i})}catch(e){throw pi(di(window.navigator.onLine?Ko:Fo),void 0,void 0,e)}n=yi(r.headers);try{return o=r.status,{headers:n,body:await r.json(),status:o}}catch(e){throw pi(di(Go),o,n,e)}}async sendPostRequestAsync(e,t){const r=t&&t.body||"",n=fi(t);let o,i=0,s={};try{o=await fetch(e,{method:Ln,headers:n,body:r})}catch(e){throw pi(di(window.navigator.onLine?Bo:Fo),void 0,void 0,e)}s=yi(o.headers);try{return i=o.status,{headers:s,body:await o.json(),status:i}}catch(e){throw pi(di(Go),i,s,e)}}}function fi(e){try{const t=new Headers;if(!e||!e.headers)return t;const r=e.headers;return Object.entries(r).forEach((([e,r])=>{t.append(e,r)})),t}catch(e){throw pi(di(oi),void 0,void 0,e)}}function yi(e){try{const t={};return e.forEach(((e,r)=>{t[r]=e})),t}catch(e){throw di(ii)}}const Ci="client_id",Ii="redirect_uri",wi="token_type",Ai="req_cnf",vi="return_spa_code",Ti="x-client-xtra-sku",_i="brk_client_id",Ei="brk_redirect_uri",bi="instance_aware";function ki(e,t,r){if(!t)return;const n=e.get(Ci);n&&e.has(_i)&&r?.addFields({embeddedClientId:n,embeddedRedirectUri:e.get(Ii)},t)}function Si(e,t){e.set("response_type",t)}function Ri(e,t,r=!0,n=o.aZ){!r||n.includes("openid")||t.includes("openid")||n.push("openid");const i=r?[...t||[],...n]:t||[],s=new xe(i);e.set("scope",s.printScopes())}function Oi(e,t){e.set(Ci,t)}function Pi(e,t){e.set(Ii,t)}function Mi(e,t){e.set("login_hint",t)}function Ni(e,t){e.set(o.OK.CCS_HEADER,`UPN:${t}`)}function Li(e,t){e.set(o.OK.CCS_HEADER,`Oid:${t.uid}@${t.utid}`)}function Di(e,t){e.set("sid",t)}function Ui(e,t,r){const n=Wi(t,r);try{JSON.parse(n)}catch(e){throw qe(ye)}e.set("claims",n)}function qi(e,t){e.set("client-request-id",t)}function Hi(e,t){e.set("x-client-SKU",t.sku),e.set("x-client-VER",t.version),t.os&&e.set("x-client-OS",t.os),t.cpu&&e.set("x-client-CPU",t.cpu)}function xi(e,t){t?.appName&&e.set("x-app-name",t.appName),t?.appVersion&&e.set("x-app-ver",t.appVersion)}function Fi(e,t){t&&e.set("state",t)}function Bi(e,t,r){if(!t||!r)throw qe(Ae);e.set("code_challenge",t),e.set("code_challenge_method",r)}function Ki(e,t){e.set("client_secret",t)}function Gi(e,t){t&&e.set("client_assertion",t)}function zi(e,t){t&&e.set("client_assertion_type",t)}function Yi(e,t){e.set("grant_type",t)}function $i(e){e.set(o.JR,"1")}function ji(e){e.has(bi)||e.set(bi,"true")}function Vi(e,t){Object.entries(t).forEach((([t,r])=>{!e.has(t)&&r&&e.set(t,r)}))}function Wi(e,t){let r;if(e)try{r=JSON.parse(e)}catch(e){throw qe(ye)}else r={};return t&&t.length>0&&(r.hasOwnProperty(o.Fq.ACCESS_TOKEN)||(r[o.Fq.ACCESS_TOKEN]={}),r[o.Fq.ACCESS_TOKEN][o.Fq.XMS_CC]={values:t}),JSON.stringify(r)}function Qi(e,t){t&&(e.set(wi,o.IO.POP),e.set(Ai,t))}function Ji(e,t){t&&(e.set(wi,o.IO.SSH),e.set(Ai,t))}function Xi(e,t){e.set("x-client-current-telemetry",t.generateCurrentRequestHeaderValue()),e.set("x-client-last-telemetry",t.generateLastRequestHeaderValue())}function Zi(e){e.set("x-ms-lib-capability",o.Xw.X_MS_LIB_CAPABILITY_VALUE)}function es(e,t,r){e.has(_i)||e.set(_i,t),e.has(Ei)||e.set(Ei,r)}function ts(e){return encodeURIComponent(ns(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"))}function rs(e){return os(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function ns(e){return os((new TextEncoder).encode(e))}function os(e){const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return btoa(t)}function is(e){return(new TextDecoder).decode(ss(e))}function ss(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw di(ri)}const r=atob(t);return Uint8Array.from(r,(e=>e.codePointAt(0)||0))}const as="AES-GCM",cs="HKDF",ls="SHA-256",hs=new Uint8Array([1,0,1]),ds="0123456789abcdef",us=new Uint32Array(1),gs="raw",ps="encrypt",ms="decrypt",fs={name:"RSASSA-PKCS1-v1_5",hash:ls,modulusLength:2048,publicExponent:hs};async function ys(e,t,r){t?.addQueueMeasurement(Kr,r);const n=(new TextEncoder).encode(e);return window.crypto.subtle.digest(ls,n)}function Cs(e){return window.crypto.getRandomValues(e)}function Is(){return window.crypto.getRandomValues(us),us[0]}
2function ws(){const e=Date.now(),t=1024*Is()+(1023&Is()),r=new Uint8Array(16),n=Math.trunc(t/2**30),o=t&2**30-1,i=Is();r[0]=e/2**40,r[1]=e/2**32,r[2]=e/2**24,r[3]=e/65536,r[4]=e/256,r[5]=e,r[6]=112|n>>>8,r[7]=n,r[8]=128|o>>>24,r[9]=o>>>16,r[10]=o>>>8,r[11]=o,r[12]=i>>>24,r[13]=i>>>16,r[14]=i>>>8,r[15]=i;let s="";for(let e=0;e<r.length;e++)s+=ds.charAt(r[e]>>>4),s+=ds.charAt(15&r[e]),3!==e&&5!==e&&7!==e&&9!==e||(s+="-");return s}async function As(e){return window.crypto.subtle.exportKey("jwk",e)}async function vs(){const e=await _s(),t={alg:"dir",kty:"oct",k:rs(new Uint8Array(e))};return ns(JSON.stringify(t))}async function Ts(e,t){const r=t.split(".");if(5!==r.length)throw di(si,"jwe_length");const n=await async function(e){const t=is(e),r=ss(JSON.parse(t).k);return window.crypto.subtle.importKey(gs,r,as,!1,[ms])}(e).catch((()=>{throw di(si,"import_key")}));try{const e=(new TextEncoder).encode(r[0]),t=ss(r[2]),o=ss(r[3]),i=ss(r[4]),s=8*i.byteLength,a=new Uint8Array(o.length+i.length);a.set(o),a.set(i,o.length);const c=await window.crypto.subtle.decrypt({name:as,iv:t,tagLength:s,additionalData:e},n,a);return(new TextDecoder).decode(c)}catch(e){throw di(si,"decrypt")}}async function _s(){const e=await window.crypto.subtle.generateKey({name:as,length:256},!0,[ps,ms]);return window.crypto.subtle.exportKey(gs,e)}async function Es(e){return window.crypto.subtle.importKey(gs,e,cs,!1,["deriveKey"])}async function bs(e,t,r){return window.crypto.subtle.deriveKey({name:cs,salt:t,hash:ls,info:(new TextEncoder).encode(r)},e,{name:as,length:256},!1,[ps,ms])}async function ks(e,t,r){const n=(new TextEncoder).encode(t),o=window.crypto.getRandomValues(new Uint8Array(16)),i=await bs(e,o,r),s=await window.crypto.subtle.encrypt({name:as,iv:new Uint8Array(12)},i,n);return{data:rs(new Uint8Array(s)),nonce:rs(o)}}async function Ss(e,t,r,n){const o=ss(n),i=await bs(e,ss(t),r),s=await window.crypto.subtle.decrypt({name:as,iv:new Uint8Array(12)},i,o);return(new TextDecoder).decode(s)}async function Rs(e){const t=await ys(e);return rs(new Uint8Array(t))}const Os="storage_not_supported",Ps="stubbed_public_client_application_called",Ms="in_mem_redirect_unavailable",Ns={[Os]:"Given storage configuration option was not supported.",[Ps]:"Stub instance of Public Client Application was called. If using msal-react, please ensure context is not used without a provider. For more visit: aka.ms/msaljs/browser-errors",[Ms]:"Redirect cannot be supported. In-memory storage was selected and storeAuthStateInCookie=false, which would cause the library to be unable to handle the incoming hash. If you would like to use the redirect API, please use session/localStorage or set storeAuthStateInCookie=true."};class Ls extends u{constructor(e,t){super(e,t),this.name="BrowserConfigurationAuthError",Object.setPrototypeOf(this,Ls.prototype)}}function Ds(e){return new Ls(e,Ns[e])}function Us(e){e.location.hash="","function"==typeof e.history.replaceState&&e.history.replaceState(null,"",`${e.location.origin}${e.location.pathname}${e.location.search}`)}function qs(){return window.parent!==window}function Hs(){return"undefined"!=typeof window&&window.location?window.location.href.split("?")[0].split("#")[0]:""}function xs(){if("undefined"!=typeof window&&window.opener&&window.opener!==window&&"string"==typeof window.name&&0===window.name.indexOf(`${mn}.`))throw di(Ro)}function Fs(){if("undefined"==typeof window)throw di(Ho)}function Bs(e){if(!e)throw di(ei)}function Ks(e){Fs(),function(){if(it.hashContainsKnownProperties(window.location.hash)&&qs())throw di(So)}(),xs(),Bs(e)}function Gs(e,t){if(Ks(e),function(e){if(qs()&&!e)throw di(ko)}(t.system.allowRedirectInIframe),t.cache.cacheLocation===Mn&&!t.cache.storeAuthStateInCookie)throw Ds(Ms)}function zs(e){const t=document.createElement("link");t.rel="preconnect",t.href=new URL(e).origin,t.crossOrigin="anonymous",document.head.appendChild(t),window.setTimeout((()=>{try{document.head.removeChild(t)}catch{}}),1e4)}const Ys=1e4;const $s="4.27.0",js="msal",Vs="browser",Ws=`${js}.${Vs}.log.level`,Qs=`${js}.${Vs}.log.pii`,Js=`${js}.version`,Xs="account.keys",Zs="token.keys";function ea(e=2){return e<1?`${js}.${Xs}`:`${js}.${e}.${Xs}`}function ta(e,t=2){return t<1?`${js}.${Zs}.${e}`:`${js}.${t}.${Zs}.${e}`}class ra{static loggerCallback(e,t){switch(e){case n.$.Error:return void console.error(t);case n.$.Info:return void console.info(t);case n.$.Verbose:return void console.debug(t);case n.$.Warning:return void console.warn(t);default:return void console.log(t)}}constructor(e){let t;this.browserEnvironment="undefined"!=typeof window,this.config=function({auth:e,cache:t,system:r,telemetry:a},l){const h={clientId:o.YM.EMPTY_STRING,authority:`${o.YM.DEFAULT_AUTHORITY}`,knownAuthorities:[],cloudDiscoveryMetadata:o.YM.EMPTY_STRING,authorityMetadata:o.YM.EMPTY_STRING,redirectUri:"undefined"!=typeof window?Hs():"",postLogoutRedirectUri:o.YM.EMPTY_STRING,navigateToLoginRequestUrl:!0,clientCapabilities:[],protocolMode:i,OIDCOptions:{serverResponseType:o.zL.FRAGMENT,defaultScopes:[o.YM.OPENID_SCOPE,o.YM.PROFILE_SCOPE,o.YM.OFFLINE_ACCESS_SCOPE]},azureCloudOptions:{azureCloudInstance:c,tenant:o.YM.EMPTY_STRING},skipAuthorityMetadataCache:!1,supportsNestedAppAuth:!1,instanceAware:!1,encodeExtraQueryParams:!1},d={cacheLocation:Pn,cacheRetentionDays:5,temporaryCacheLocation:Pn,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!(!t||t.cacheLocation!==On),claimsBasedCachingEnabled:!1},u={loggerCallback:()=>{},logLevel:n.$.Info,piiLoggingEnabled:!1},g={...{...tn,loggerOptions:u,networkClient:l?new mi:dn,navigationClient:new ui,loadFrameTimeout:0,windowHashTimeout:r?.loadFrameTimeout||6e4,iframeHashTimeout:r?.loadFrameTimeout||Ys,navigateFrameWait:0,redirectNavigationTimeout:3e4,asyncPopups:!1,allowRedirectInIframe:!1,allowPlatformBroker:!1,allowPlatformBrokerWithDOM:!1,nativeBrokerHandshakeTimeout:r?.nativeBrokerHandshakeTimeout||2e3,pollIntervalMilliseconds:fn},...r,loggerOptions:r?.loggerOptions||u},p={application:{appName:o.YM.EMPTY_STRING,appVersion:o.YM.EMPTY_STRING},client:new en};e?.protocolMode!==s&&e?.OIDCOptions&&new n.V(g.loggerOptions).warning(JSON.stringify(qe(Re)));if(e?.protocolMode&&e.protocolMode===s&&g?.allowPlatformBroker)throw qe(Oe);return{auth:{...h,...e,OIDCOptions:{...h.OIDCOptions,...e?.OIDCOptions}},cache:{...d,...t},system:g,telemetry:{...p,...a}}}(e,this.browserEnvironment);try{t=window[Pn]}catch(e){}const r=t?.getItem(Ws),a=t?.getItem(Qs)?.toLowerCase(),l="true"===a||"false"!==a&&void 0,h={...this.config.system.loggerOptions},d=r&&Object.keys(n.$).includes(r)?n.$[r]:void 0;d&&(h.loggerCallback=ra.loggerCallback,h.logLevel=d),void 0!==l&&(h.piiLoggingEnabled=l),this.logger=new n.V(h,"@azure/msal-browser",$s),this.available=!1}getConfig(){return this.config}getLogger(){return this.logger}isAvailable(){return this.available}isBrowserEnvironment(){return this.browserEnvironment}}class na extends ra{getModuleName(){return na.MODULE_NAME}getId(){return na.ID}async initialize(){return this.available="undefined"!=typeof window,this.available}}na.MODULE_NAME="",na.ID="StandardOperatingContext";const oa="missing_kid_error",ia="missing_alg_error",sa={[oa]:"The JOSE Header for the requested JWT, JWS or JWK object requires a keyId to be configured as the 'kid' header claim. No 'kid' value was provided.",[ia]:"The JOSE Header for the requested JWT, JWS or JWK object requires an algorithm to be specified as the 'alg' header claim. No 'alg' value was provided."};class aa extends u{constructor(e,t){super(e,t),this.name="JoseHeaderError",Object.setPrototypeOf(this,aa.prototype)}}function ca(e){return new aa(e,sa[e])}class la{constructor(e){this.typ=e.typ,this.alg=e.alg,this.kid=e.kid}static getShrHeaderString(e){if(!e.kid)throw ca(oa);if(!e.alg)throw ca(ia);const t=new la({typ:e.typ||o.Lz.Pop,kid:e.kid,alg:e.alg});return JSON.stringify(t)}}class ha{constructor(){this.dbName=to,this.version=1,this.tableName=ro,this.dbOpen=!1}async open(){return new Promise(((e,t)=>{const r=window.indexedDB.open(this.dbName,this.version);r.addEventListener("upgradeneeded",(e=>{e.target.result.createObjectStore(this.tableName)})),r.addEventListener("success",(t=>{const r=t;
2this.db=r.target.result,this.dbOpen=!0,e()})),r.addEventListener("error",(()=>t(di(Wo))))}))}closeConnection(){const e=this.db;e&&this.dbOpen&&(e.close(),this.dbOpen=!1)}async validateDbIsOpen(){if(!this.dbOpen)return this.open()}async getItem(e){return await this.validateDbIsOpen(),new Promise(((t,r)=>{if(!this.db)return r(di(xo));const n=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).get(e);n.addEventListener("success",(e=>{const r=e;this.closeConnection(),t(r.target.result)})),n.addEventListener("error",(e=>{this.closeConnection(),r(e)}))}))}async setItem(e,t){return await this.validateDbIsOpen(),new Promise(((r,n)=>{if(!this.db)return n(di(xo));const o=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).put(t,e);o.addEventListener("success",(()=>{this.closeConnection(),r()})),o.addEventListener("error",(e=>{this.closeConnection(),n(e)}))}))}async removeItem(e){return await this.validateDbIsOpen(),new Promise(((t,r)=>{if(!this.db)return r(di(xo));const n=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).delete(e);n.addEventListener("success",(()=>{this.closeConnection(),t()})),n.addEventListener("error",(e=>{this.closeConnection(),r(e)}))}))}async getKeys(){return await this.validateDbIsOpen(),new Promise(((e,t)=>{if(!this.db)return t(di(xo));const r=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).getAllKeys();r.addEventListener("success",(t=>{const r=t;this.closeConnection(),e(r.target.result)})),r.addEventListener("error",(e=>{this.closeConnection(),t(e)}))}))}async containsKey(e){return await this.validateDbIsOpen(),new Promise(((t,r)=>{if(!this.db)return r(di(xo));const n=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).count(e);n.addEventListener("success",(e=>{const r=e;this.closeConnection(),t(1===r.target.result)})),n.addEventListener("error",(e=>{this.closeConnection(),r(e)}))}))}async deleteDatabase(){return this.db&&this.dbOpen&&this.closeConnection(),new Promise(((e,t)=>{const r=window.indexedDB.deleteDatabase(to),n=setTimeout((()=>t(!1)),200);r.addEventListener("success",(()=>(clearTimeout(n),e(!0)))),r.addEventListener("blocked",(()=>(clearTimeout(n),e(!0)))),r.addEventListener("error",(()=>(clearTimeout(n),t(!1))))}))}}class da{constructor(){this.cache=new Map}async initialize(){}getItem(e){return this.cache.get(e)||null}getUserData(e){return this.getItem(e)}setItem(e,t){this.cache.set(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){this.cache.delete(e)}getKeys(){const e=[];return this.cache.forEach(((t,r)=>{e.push(r)})),e}containsKey(e){return this.cache.has(e)}clear(){this.cache.clear()}decryptData(){return Promise.resolve(null)}}class ua{constructor(e){this.inMemoryCache=new da,this.indexedDBCache=new ha,this.logger=e}handleDatabaseAccessError(e){if(!(e instanceof hi&&e.errorCode===Wo))throw e;this.logger.error("Could not access persistent storage. This may be caused by browser privacy features which block persistent storage in third-party contexts.")}async getItem(e){const t=this.inMemoryCache.getItem(e);if(!t)try{return this.logger.verbose("Queried item not found in in-memory cache, now querying persistent storage."),await this.indexedDBCache.getItem(e)}catch(e){this.handleDatabaseAccessError(e)}return t}async setItem(e,t){this.inMemoryCache.setItem(e,t);try{await this.indexedDBCache.setItem(e,t)}catch(e){this.handleDatabaseAccessError(e)}}async removeItem(e){this.inMemoryCache.removeItem(e);try{await this.indexedDBCache.removeItem(e)}catch(e){this.handleDatabaseAccessError(e)}}async getKeys(){const e=this.inMemoryCache.getKeys();if(0===e.length)try{return this.logger.verbose("In-memory cache is empty, now querying persistent storage."),await this.indexedDBCache.getKeys()}catch(e){this.handleDatabaseAccessError(e)}return e}async containsKey(e){const t=this.inMemoryCache.containsKey(e);if(!t)try{return this.logger.verbose("Key not found in in-memory cache, now querying persistent storage."),await this.indexedDBCache.containsKey(e)}catch(e){this.handleDatabaseAccessError(e)}return t}clearInMemory(){this.logger.verbose("Deleting in-memory keystore"),this.inMemoryCache.clear(),this.logger.verbose("In-memory keystore deleted")}
2async clearPersistent(){try{this.logger.verbose("Deleting persistent keystore");const e=await this.indexedDBCache.deleteDatabase();return e&&this.logger.verbose("Persistent keystore deleted"),e}catch(e){return this.handleDatabaseAccessError(e),!1}}}class ga{constructor(e,t,r){this.logger=e,function(e){if(!window)throw di(Ho);if(!window.crypto)throw di(po);if(!e&&!window.crypto.subtle)throw di(po,"crypto_subtle_undefined")}(r??!1),this.cache=new ua(this.logger),this.performanceClient=t}createNewGuid(){return ws()}base64Encode(e){return ns(e)}base64Decode(e){return is(e)}base64UrlEncode(e){return ts(e)}encodeKid(e){return this.base64UrlEncode(JSON.stringify({kid:e}))}async getPublicKeyThumbprint(e){const t=this.performanceClient?.startMeasurement(Et,e.correlationId),r=await async function(e,t){return window.crypto.subtle.generateKey(fs,e,t)}(ga.EXTRACTABLE,ga.POP_KEY_USAGES),n=await As(r.publicKey),o=pa({e:n.e,kty:n.kty,n:n.n}),i=await this.hashString(o),s=await As(r.privateKey),a=await async function(e,t,r){return window.crypto.subtle.importKey("jwk",e,fs,t,r)}(s,!1,["sign"]);return await this.cache.setItem(i,{privateKey:a,publicKey:r.publicKey,requestMethod:e.resourceRequestMethod,requestUri:e.resourceRequestUri}),t&&t.end({success:!0}),i}async removeTokenBindingKey(e){await this.cache.removeItem(e);if(await this.cache.containsKey(e))throw ae(Q)}async clearKeystore(){this.cache.clearInMemory();try{return await this.cache.clearPersistent(),!0}catch(e){return e instanceof Error?this.logger.error(`Clearing keystore failed with error: ${e.message}`):this.logger.error("Clearing keystore failed with unknown error"),!1}}async signJwt(e,t,r,n){const o=this.performanceClient?.startMeasurement(bt,n),i=await this.cache.getItem(t);if(!i)throw di(Yo);const s=await As(i.publicKey),a=pa(s),c=ts(JSON.stringify({kid:t})),l=ts(la.getShrHeaderString({...r?.header,alg:s.alg,kid:c}));e.cnf={jwk:JSON.parse(a)};const h=`${l}.${ts(JSON.stringify(e))}`,d=(new TextEncoder).encode(h),u=await async function(e,t){return window.crypto.subtle.sign(fs,e,t)}(i.privateKey,d),g=`${h}.${rs(new Uint8Array(u))}`;return o&&o.end({success:!0}),g}async hashString(e){return Rs(e)}}function pa(e){return JSON.stringify(e,Object.keys(e).sort())}ga.POP_KEY_USAGES=["sign","verify"],ga.EXTRACTABLE=!0;const ma=(e,t,r,n,o)=>(...i)=>{r.trace(`Executing function ${t}`);const s=n?.startMeasurement(t,o);if(o){const e=t+"CallCount";n?.incrementFields({[e]:1},o)}try{const n=e(...i);return s?.end({success:!0}),r.trace(`Returning result from ${t}`),n}catch(e){r.trace(`Error occurred in ${t}`);try{r.trace(JSON.stringify(e))}catch(e){r.trace("Unable to print error message.")}throw s?.end({success:!1},e),e}},fa=(e,t,r,n,o)=>(...i)=>{r.trace(`Executing function ${t}`);const s=n?.startMeasurement(t,o);if(o){const e=t+"CallCount";n?.incrementFields({[e]:1},o)}return n?.setPreQueueTime(t,o),e(...i).then((e=>(r.trace(`Returning result from ${t}`),s?.end({success:!0}),e))).catch((e=>{r.trace(`Error occurred in ${t}`);try{r.trace(JSON.stringify(e))}catch(e){r.trace("Unable to print error message.")}throw s?.end({success:!1},e),e}))};class ya{constructor(e,t,r,n){this.networkInterface=e,this.logger=t,this.performanceClient=r,this.correlationId=n}async detectRegion(e,t){this.performanceClient?.addQueueMeasurement(br,this.correlationId);let r=e;if(r)t.region_source=o.jZ.ENVIRONMENT_VARIABLE;else{const e=ya.IMDS_OPTIONS;try{const n=await fa(this.getRegionFromIMDS.bind(this),kr,this.logger,this.performanceClient,this.correlationId)(o.YM.IMDS_VERSION,e);if(n.status===o.t3.SUCCESS&&(r=n.body,t.region_source=o.jZ.IMDS),n.status===o.t3.BAD_REQUEST){const n=await fa(this.getCurrentVersion.bind(this),Sr,this.logger,this.performanceClient,this.correlationId)(e);if(!n)return t.region_source=o.jZ.FAILED_AUTO_DETECTION,null;const i=await fa(this.getRegionFromIMDS.bind(this),kr,this.logger,this.performanceClient,this.correlationId)(n,e);i.status===o.t3.SUCCESS&&(r=i.body,t.region_source=o.jZ.IMDS)}}catch(e){return t.region_source=o.jZ.FAILED_AUTO_DETECTION,null}}return r||(t.region_source=o.jZ.FAILED_AUTO_DETECTION),r||null}async getRegionFromIMDS(e,t){return this.performanceClient?.addQueueMeasurement(kr,this.correlationId),this.networkInterface.sendGetRequestAsync(`${o.YM.IMDS_ENDPOINT}?api-version=${e}&format=text`,t,o.YM.IMDS_TIMEOUT)}async getCurrentVersion(e){this.performanceClient?.addQueueMeasurement(Sr,this.correlationId);try{const t=await this.networkInterface.sendGetRequestAsync(`${o.YM.IMDS_ENDPOINT}?format=json`,e);return t.status===o.t3.BAD_REQUEST&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch(e){return null}}}function Ca(){return Math.round((new Date).getTime()/1e3)}function Ia(e){return e.getTime()/1e3}function wa(e){return e?new Date(1e3*Number(e)):new Date}function Aa(e,t){const r=Number(e)||0;return Ca()+t>r}function va(e,t){const r=Number(e)+24*t*60*60*1e3;return Date.now()>r}function Ta(e,t,r,n,i){return{credentialType:o.aG.ID_TOKEN,homeAccountId:e,environment:t,clientId:n,secret:r,realm:i,lastUpdatedAt:Date.now().toString()}}function _a(e,t,r,n,i,s,a,c,l,h,d,u,g,p,m){const f={homeAccountId:e,credentialType:o.aG.ACCESS_TOKEN,secret:r,cachedAt:Ca().toString(),expiresOn:a.toString(),extendedExpiresOn:c.toString(),environment:t,clientId:n,realm:i,target:s,tokenType:d||o.IO.BEARER,lastUpdatedAt:Date.now().toString()};if(u&&(f.userAssertionHash=u),h&&(f.refreshOn=h.toString()),p&&(f.requestedClaims=p,f.requestedClaimsHash=m),f.tokenType?.toLowerCase()!==o.IO.BEARER.toLowerCase())switch(f.credentialType=o.aG.ACCESS_TOKEN_WITH_AUTH_SCHEME,f.tokenType){case o.IO.POP:const e=Je(r,l);if(!e?.cnf?.kid)throw ae(V);f.keyId=e.cnf.kid;break;case o.IO.SSH:f.keyId=g}return f}function Ea(e,t,r,n,i,s,a){const c={credentialType:o.aG.REFRESH_TOKEN,homeAccountId:e,environment:t,clientId:n,secret:r,lastUpdatedAt:Date.now().toString()};return s&&(c.userAssertionHash=s),i&&(c.familyId=i),a&&(c.expiresOn=a.toString()),c}function ba(e){return e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("credentialType")&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("secret")}function ka(e){return!!e&&(ba(e)&&e.hasOwnProperty("realm")&&e.hasOwnProperty("target")&&(e.credentialType===o.aG.ACCESS_TOKEN||e.credentialType===o.aG.ACCESS_TOKEN_WITH_AUTH_SCHEME))}function Sa(e){return!!e&&(ba(e)&&e.credentialType===o.aG.REFRESH_TOKEN)}function Ra(){return Ca()+o.u0.REFRESH_TIME_SECONDS}function Oa(e,t,r){e.authorization_endpoint=t.authorization_endpoint,e.token_endpoint=t.token_endpoint,e.end_session_endpoint=t.end_session_endpoint,e.issuer=t.issuer,e.endpointsFromNetwork=r,e.jwks_uri=t.jwks_uri}function Pa(e,t,r){e.aliases=t.aliases,e.preferred_cache=t.preferred_cache,e.preferred_network=t.preferred_network,e.aliasesFromNetwork=r}function Ma(e){return e.expiresAt<=Ca()}ya.IMDS_OPTIONS={headers:{Metadata:"true"}};class Na{constructor(e,t,r,n,o,i,s,a){this.canonicalAuthority=e,this._canonicalAuthority.val
2idateAsUri(),this.networkInterface=t,this.cacheManager=r,this.authorityOptions=n,this.regionDiscoveryMetadata={region_used:void 0,region_source:void 0,region_outcome:void 0},this.logger=o,this.performanceClient=s,this.correlationId=i,this.managedIdentity=a||!1,this.regionDiscovery=new ya(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(o.YM.CIAM_AUTH_URL))return Ve;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case o.YM.ADFS:return $e;case o.YM.DSTS:return je}return Ye}get authorityType(){return this.getAuthorityType(this.canonicalAuthorityUrlComponents)}get protocolMode(){return this.authorityOptions.protocolMode}get options(){return this.authorityOptions}get canonicalAuthority(){return this._canonicalAuthority.urlString}set canonicalAuthority(e){this._canonicalAuthority=new it(e),this._canonicalAuthority.validateAsUri(),this._canonicalAuthorityUrlComponents=null}get canonicalAuthorityUrlComponents(){return this._canonicalAuthorityUrlComponents||(this._canonicalAuthorityUrlComponents=this._canonicalAuthority.getUrlComponents()),this._canonicalAuthorityUrlComponents}get hostnameAndPort(){return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase()}get tenant(){return this.canonicalAuthorityUrlComponents.PathSegments[0]}get authorizationEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.authorization_endpoint);throw ae(C)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw ae(C)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw ae(C)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw ae(J);return this.replacePath(this.metadata.end_session_endpoint)}throw ae(C)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw ae(C)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw ae(C)}canReplaceTenant(e){return 1===e.PathSegments.length&&!Na.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===Ye&&this.protocolMode!==s}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const r=new it(this.metadata.canonical_authority).getUrlComponents(),n=r.PathSegments;return this.canonicalAuthorityUrlComponents.PathSegments.forEach(((e,o)=>{let i=n[o];if(0===o&&this.canReplaceTenant(r)){const e=new it(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];i!==e&&(this.logger.verbose(`Replacing tenant domain name ${i} with id ${e}`),i=e)}e!==i&&(t=t.replace(`/${i}/`,`/${e}/`))})),this.replaceTenant(t)}get defaultOpenIdConfigurationEndpoint(){const e=this.hostnameAndPort;return this.canonicalAuthority.endsWith("v2.0/")||this.authorityType===$e||this.protocolMode===s&&!this.isAliasOfKnownMicrosoftAuthority(e)?`${this.canonicalAuthority}.well-known/openid-configuration`:`${this.canonicalAuthority}v2.0/.well-known/openid-configuration`}discoveryComplete(){return!!this.metadata}async resolveEndpointsAsync(){this.performanceClient?.addQueueMeasurement(wr,this.correlationId);const e=this.getCurrentMetadataEntity(),t=await fa(this.updateCloudDiscoveryMetadata.bind(this),vr,this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const r=await fa(this.updateEndpointMetadata.bind(this),_r,this.logger,this.performanceClient,this.correlationId)(e);this.updateCachedMetadata(e,t,{source:r}),this.performanceClient?.addFields({cloudDiscoverySource:t,authorityEndpointSource:r},this.correlationId)}getCurrentMetadataEntity(){let e=this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort);return e||(e={aliases:[],preferred_cache:this.hostnameAndPort,preferred_network:this.hostnameAndPort,canonical_authority:this.canonicalAuthority,authorization_endpoint:"",token_endpoint:"",end_session_endpoint:"",issuer:"",aliasesFromNetwork:!1,endpointsFromNetwork:!1,expiresAt:Ra(),jwks_uri:""}),e}updateCachedMetadata(e,t,r){t!==o.E_.CACHE&&r?.source!==o.E_.CACHE&&(e.expiresAt=Ra(),e.canonical_authority=this.canonicalAuthority);const n=this.cacheManager.generateAuthorityMetadataCacheKey(e.preferred_cache);this.cacheManager.setAuthorityMetadata(n,e),this.metadata=e}async updateEndpointMetadata(e){this.performanceClient?.addQueueMeasurement(_r,this.correlationId);const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===o.E_.HARDCODED_VALUES&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){Oa(e,await fa(this.updateMetadataWithRegionalInformation.bind(this),Er,this.logger,this.performanceClient,this.correlationId)(t.metadata),!1),e.canonical_authority=this.canonicalAuthority}return t.source}let r=await fa(this.getEndpointMetadataFromNetwork.bind(this),Tr,this.logger,this.performanceClient,this.correlationId)();if(r)return this.authorityOptions.azureRegionConfiguration?.azureRegion&&(r=await fa(this.updateMetadataWithRegionalInformation.bind(this),Er,this.logger,this.performanceClient,this.correlationId)(r)),Oa(e,r,!0),o.E_.NETWORK;throw ae(w,this.defaultOpenIdConfigurationEndpoint)}updateEndpointMetadataFromLocalSources(e){this.logger.verbose("Attempting to get endpoint metadata from authority configuration");const t=this.getEndpointMetadataFromConfig();if(t)return this.logger.verbose("Found endpoint metadata in authority configuration"),Oa(e,t,!1),{source:o.E_.CONFIG};if(this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values."),this.authorityOptions.skipAuthorityMetadataCache)this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache.");else{const t=this.getEndpointMetadataFromHardcodedValues();if(t)return Oa(e,t,!1),{source:o.E_.HARDCODED_VALUES,metadata:t};this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.")}const r=Ma(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!r?(this.logger.verbose("Found endpoint metadata in the cache."),{source:o.E_.CACHE}):(r&&this.logger.verbose("The metadata entity is expired."),null)}isAuthoritySameType(e){return new it(e.canonical_authority).getUrlComponents().PathSegments.length===this.canonicalAuthorityUrlComponents.PathSegments.length}getEndpointMetadataFromConfig(){if(this.authorityOptions.authorityMetadata)try{return JSON.parse(this.authorityOptions.authorityMetadata)}catch(e){throw qe(Te)}
2return null}async getEndpointMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(Tr,this.correlationId);const e={},t=this.defaultOpenIdConfigurationEndpoint;this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${t}`);try{const r=await this.networkInterface.sendGetRequestAsync(t,e),n=function(e){return e.hasOwnProperty("authorization_endpoint")&&e.hasOwnProperty("token_endpoint")&&e.hasOwnProperty("issuer")&&e.hasOwnProperty("jwks_uri")}(r.body);return n?r.body:(this.logger.verbose("Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration"),null)}catch(e){return this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`),null}}getEndpointMetadataFromHardcodedValues(){return this.hostnameAndPort in st?st[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){this.performanceClient?.addQueueMeasurement(Er,this.correlationId);const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if(t!==o.YM.AZURE_REGION_AUTO_DISCOVER_FLAG)return this.regionDiscoveryMetadata.region_outcome=o._2.CONFIGURED_NO_AUTO_DETECTION,this.regionDiscoveryMetadata.region_used=t,Na.replaceWithRegionalInformation(e,t);const r=await fa(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),br,this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(r)return this.regionDiscoveryMetadata.region_outcome=o._2.AUTO_DETECTION_REQUESTED_SUCCESSFUL,this.regionDiscoveryMetadata.region_used=r,Na.replaceWithRegionalInformation(e,r);this.regionDiscoveryMetadata.region_outcome=o._2.AUTO_DETECTION_REQUESTED_FAILED}return e}async updateCloudDiscoveryMetadata(e){this.performanceClient?.addQueueMeasurement(vr,this.correlationId);const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const r=await fa(this.getCloudDiscoveryMetadataFromNetwork.bind(this),Ar,this.logger,this.performanceClient,this.correlationId)();if(r)return Pa(e,r,!0),o.E_.NETWORK;throw qe(_e)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("Attempting to get cloud discovery metadata  from authority configuration"),this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities||o.YM.NOT_APPLICABLE}`),this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata||o.YM.NOT_APPLICABLE}`),this.logger.verbosePii(`Canonical Authority: ${e.canonical_authority||o.YM.NOT_APPLICABLE}`);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("Found cloud discovery metadata in authority configuration"),Pa(e,t,!1),o.E_.CONFIG;if(this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values."),this.options.skipAuthorityMetadataCache)this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache.");else{const t=(r=this.hostnameAndPort,ht(at.metadata,r));if(t)return this.logger.verbose("Found cloud discovery metadata from hardcoded values."),Pa(e,t,!1),o.E_.HARDCODED_VALUES;this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.")}var r;const n=Ma(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!n?(this.logger.verbose("Found cloud discovery metadata in the cache."),o.E_.CACHE):(n&&this.logger.verbose("The metadata entity is expired."),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===Ve)return this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host."),Na.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);if(this.authorityOptions.cloudDiscoveryMetadata){this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.");try{this.logger.verbose("Attempting to parse the cloud discovery metadata.");const e=ht(JSON.parse(this.authorityOptions.cloudDiscoveryMetadata).metadata,this.hostnameAndPort);if(this.logger.verbose("Parsed the cloud discovery metadata."),e)return this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata."),e;this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.")}catch(e){throw this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error."),qe(ve)}}return this.isInKnownAuthorities()?(this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host."),Na.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(Ar,this.correlationId);const e=`${o.YM.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let r=null;try{const n=await this.networkInterface.sendGetRequestAsync(e,t);let i,s;if(function(e){return e.hasOwnProperty("tenant_discovery_endpoint")&&e.hasOwnProperty("metadata")}(n.body))i=n.body,s=i.metadata,this.logger.verbosePii(`tenant_discovery_endpoint is: ${i.tenant_discovery_endpoint}`);else{if(!function(e){return e.hasOwnProperty("error")&&e.hasOwnProperty("error_description")}(n.body))return this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse"),null;if(this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${n.status}`),i=n.body,i.error===o.YM.INVALID_INSTANCE)return this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invali
2d_instance."),null;this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${i.error}`),this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${i.error_description}`),this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []"),s=[]}this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request."),r=ht(s,this.hostnameAndPort)}catch(e){if(e instanceof u)this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: ${e.errorCode}\nError Description: ${e.errorMessage}`);else{const t=e;this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: ${t.name}\nError Description: ${t.message}`)}return null}return r||(this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request."),this.logger.verbose("Creating custom Authority for custom domain scenario."),r=Na.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),r}isInKnownAuthorities(){return this.authorityOptions.knownAuthorities.filter((e=>e&&it.getDomainFromUrl(e).toLowerCase()===this.hostnameAndPort)).length>0}static generateAuthority(e,t){let r;if(t&&t.azureCloudInstance!==c){const e=t.tenant?t.tenant:o.YM.DEFAULT_COMMON_TENANT;r=`${t.azureCloudInstance}/${e}/`}return r||e}static createCloudDiscoveryMetadataFromHost(e){return{preferred_network:e,preferred_cache:e,aliases:[e]}}getPreferredCache(){if(this.managedIdentity)return o.YM.DEFAULT_AUTHORITY_HOST;if(this.discoveryComplete())return this.metadata.preferred_cache;throw ae(C)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return ct.has(e)}static isPublicCloudAuthority(e){return o.YM.KNOWN_PUBLIC_CLOUDS.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,r){const n=new it(e);n.validateAsUri();const i=n.getUrlComponents();let s=`${t}.${i.HostNameAndPort}`;this.isPublicCloudAuthority(i.HostNameAndPort)&&(s=`${t}.${o.YM.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`);const a=it.constructAuthorityUriFromObject({...n.getUrlComponents(),HostNameAndPort:s}).urlString;return r?`${a}?${r}`:a}static replaceWithRegionalInformation(e,t){const r={...e};return r.authorization_endpoint=Na.buildRegionalAuthorityString(r.authorization_endpoint,t),r.token_endpoint=Na.buildRegionalAuthorityString(r.token_endpoint,t),r.end_session_endpoint&&(r.end_session_endpoint=Na.buildRegionalAuthorityString(r.end_session_endpoint,t)),r}static transformCIAMAuthority(e){let t=e;const r=new it(e).getUrlComponents();if(0===r.PathSegments.length&&r.HostNameAndPort.endsWith(o.YM.CIAM_AUTH_URL)){t=`${t}${r.HostNameAndPort.split(".")[0]}${o.YM.AAD_TENANT_DOMAIN_SUFFIX}`}return t}}function La(e){return e.endsWith(o.YM.FORWARD_SLASH)?e:`${e}${o.YM.FORWARD_SLASH}`}Na.reservedTenantDomains=new Set(["{tenant}","{tenantid}",o.v2.COMMON,o.v2.CONSUMERS,o.v2.ORGANIZATIONS]);const Da="no_tokens_found",Ua="native_account_unavailable",qa="refresh_token_expired",Ha="ux_not_allowed",xa="bad_token",Fa=["interaction_required","consent_required","login_required",xa,Ha],Ba=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token"],Ka={[Da]:"No refresh token found in the cache. Please sign-in.",[Ua]:"The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API.",[qa]:"Refresh token has expired.",[xa]:"Identity provider returned bad_token due to an expired or invalid refresh token. Please invoke an interactive API to resolve.",[Ha]:"`canShowUI` flag in Edge was set to false. User interaction required on web page. Please invoke an interactive API to resolve."};class Ga extends u{constructor(e,t,r,n,i,s,a,c){super(e,t,r),Object.setPrototypeOf(this,Ga.prototype),this.timestamp=n||o.YM.EMPTY_STRING,this.traceId=i||o.YM.EMPTY_STRING,this.correlationId=s||o.YM.EMPTY_STRING,this.claims=a||o.YM.EMPTY_STRING,this.name="InteractionRequiredAuthError",this.errorNo=c}}function za(e,t,r){const n=!!e&&Fa.indexOf(e)>-1,o=!!r&&Ba.indexOf(r)>-1,i=!!t&&Fa.some((e=>t.indexOf(e)>-1));return n||i||o}function Ya(e){return new Ga(e,Ka[e])}function $a(e,t,r){return{clientId:e,authority:t.authority,scopes:t.scopes,homeAccountIdentifier:r,claims:t.claims,authenticationScheme:t.authenticationScheme,resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,sshKid:t.sshKid,embeddedClientId:t.embeddedClientId||t.tokenBodyParameters?.clientId}}const ja=864e5,Va="Lax",Wa="None";class Qa{initialize(){return Promise.resolve()}getItem(e){const t=`${encodeURIComponent(e)}`,r=document.cookie.split(";");for(let e=0;e<r.length;e++){const n=r[e],[o,...i]=decodeURIComponent(n).trim().split("="),s=i.join("=");if(o===t)return s}return""}getUserData(){throw ae(re)}setItem(e,t,r,n=!0,o=Va){let i=`${encodeURIComponent(e)}=${encodeURIComponent(t)};path=/;SameSite=${o};`;if(r){const e=function(e){const t=new Date,r=new Date(t.getTime()+e*ja);return r.toUTCString()}(r);i+=`expires=${e};`}(n||o===Wa)&&(i+="Secure;"),document.cookie=i}async setUserData(){return Promise.reject(ae(re))}removeItem(e){this.setItem(e,"",-1)}getKeys(){const e=document.cookie.split(";"),t=[];return e.forEach((e=>{const r=decodeURIComponent(e).trim().split("=");t.push(r[0])})),t}containsKey(e){return this.getKeys().includes(e)}decryptData(){return Promise.resolve(null)}}function Ja(e,t){const r=e.getItem(ea(t));return r?JSON.parse(r):[]}function Xa(e,t,r){const n=t.getItem(ta(e,r));if(n){const e=JSON.parse(n);if(e&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("accessToken")&&e.hasOwnProperty("refreshToken"))return e}return{idToken:[],accessToken:[],refreshToken:[]}}function Za(e){return e.hasOwnProperty("id")&&e.hasOwnProperty("nonce")&&e.hasOwnProperty("data")}const ec="msal.cache.encryption";class tc{constructor(e,t,r){if(!window.localStorage)throw Ds(Os);this.memoryStorage=new da,this.initialized=!1,this.clientId=e,this.logger=t,this.performanceClient=r,this.broadcast=new BroadcastChannel("msal.broadcast.cache")}async initialize(e){const t=new Qa,r=t.getItem(ec);let n={key:"",id:""};if(r)try{n=JSON.parse(r)}catch(e){}if(n.key&&n.id){const t=ma(ss,$r,this.logger,this.performanceClient,e)(n.key);this.encryptionCookie={id:n.id,key:await fa(Es,zr,this.logger,this.performanceClient,e)(t)}}else{const r=ws(),n=await fa(_s,Yr,this.logger,this.performanceClient,e)(),o=ma(rs,jr,this.logger,this.performanceClient,e)(new Uint8Array(n));this.encryptionCookie={id:r,key:await fa(Es,zr,this.logger,this.performanceClient,e)(n)};const i={id:r,key:o};t.setItem(ec,JSON.stringify(i),0,!0,Wa)}await fa(this.importExistingCache.bind(this),Ur,this.logger,this.performanceClient,e)(e),this.broadcast.addEventListener("message",this.updateCache.bind(this)),this.initialized=!0}getItem(e){return window.localStorage.getItem(e)}getUserData(e){if(!this.initialized)throw di(ei);return this.memoryStorage.getItem(e)}async decryptData(e,t,r){if(!this.initialized||!this.encryptionCookie)throw di(ei);if(t.id!==this.encryptionCookie.id)return this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},r),null;const n=await fa(Ss,Wr,this.logger,this.performanceClient,r)(this.encryptionCookie.ke
2y,t.nonce,this.getContext(e),t.data);if(!n)return null;try{return{...JSON.parse(n),lastUpdatedAt:t.lastUpdatedAt}}catch(e){return this.performanceClient.incrementFields({encryptedCacheCorruptionCount:1},r),null}}setItem(e,t){window.localStorage.setItem(e,t)}async setUserData(e,t,r,n,o){if(!this.initialized||!this.encryptionCookie)throw di(ei);if(o)this.setItem(e,t);else{const{data:o,nonce:i}=await fa(ks,Vr,this.logger,this.performanceClient,r)(this.encryptionCookie.key,t,this.getContext(e)),s={id:this.encryptionCookie.id,nonce:i,data:o,lastUpdatedAt:n};this.setItem(e,JSON.stringify(s))}this.memoryStorage.setItem(e,t),this.broadcast.postMessage({key:e,value:t,context:this.getContext(e)})}removeItem(e){this.memoryStorage.containsKey(e)&&(this.memoryStorage.removeItem(e),this.broadcast.postMessage({key:e,value:null,context:this.getContext(e)})),window.localStorage.removeItem(e)}getKeys(){return Object.keys(window.localStorage)}containsKey(e){return window.localStorage.hasOwnProperty(e)}clear(){this.memoryStorage.clear();Ja(this).forEach((e=>this.removeItem(e)));const e=Xa(this.clientId,this);e.idToken.forEach((e=>this.removeItem(e))),e.accessToken.forEach((e=>this.removeItem(e))),e.refreshToken.forEach((e=>this.removeItem(e))),this.getKeys().forEach((e=>{(e.startsWith(js)||-1!==e.indexOf(this.clientId))&&this.removeItem(e)}))}async importExistingCache(e){if(!this.encryptionCookie)return;let t=Ja(this);t=await this.importArray(t,e),t.length?this.setItem(ea(),JSON.stringify(t)):this.removeItem(ea());const r=Xa(this.clientId,this);r.idToken=await this.importArray(r.idToken,e),r.accessToken=await this.importArray(r.accessToken,e),r.refreshToken=await this.importArray(r.refreshToken,e),r.idToken.length||r.accessToken.length||r.refreshToken.length?this.setItem(ta(this.clientId),JSON.stringify(r)):this.removeItem(ta(this.clientId))}async getItemFromEncryptedCache(e,t){if(!this.encryptionCookie)return null;const r=this.getItem(e);if(!r)return null;let n;try{n=JSON.parse(r)}catch(e){return null}return Za(n)?n.id!==this.encryptionCookie.id?(this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},t),null):(this.performanceClient.incrementFields({encryptedCacheCount:1},t),fa(Ss,Wr,this.logger,this.performanceClient,t)(this.encryptionCookie.key,n.nonce,this.getContext(e),n.data)):(this.performanceClient.incrementFields({unencryptedCacheCount:1},t),r)}async importArray(e,t){const r=[],n=[];return e.forEach((e=>{const o=this.getItemFromEncryptedCache(e,t).then((t=>{t?(this.memoryStorage.setItem(e,t),r.push(e)):this.removeItem(e)}));n.push(o)})),await Promise.all(n),r}getContext(e){let t="";return e.includes(this.clientId)&&(t=this.clientId),t}updateCache(e){this.logger.trace("Updating internal cache from broadcast event");const t=this.performanceClient.startMeasurement(Hr);t.add({isBackground:!0});const{key:r,value:n,context:o}=e.data;return r?o&&o!==this.clientId?(this.logger.trace(`Ignoring broadcast event from clientId: ${o}`),void t.end({success:!1,errorCode:"contextMismatch"})):(n?(this.memoryStorage.setItem(r,n),this.logger.verbose("Updated 
2item in internal cache")):(this.memoryStorage.removeItem(r),this.logger.verbose("Removed item from internal cache")),void t.end({success:!0})):(this.logger.error("Broadcast event missing key"),void t.end({success:!1,errorCode:"noKey"}))}}class rc{constructor(){if(!window.sessionStorage)throw Ds(Os)}async initialize(){}getItem(e){return window.sessionStorage.getItem(e)}getUserData(e){return this.getItem(e)}setItem(e,t){window.sessionStorage.setItem(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){window.sessionStorage.removeItem(e)}getKeys(){return Object.keys(window.sessionStorage)}containsKey(e){return window.sessionStorage.hasOwnProperty(e)}decryptData(){return Promise.resolve(null)}}const nc="msal:initializeStart",oc="msal:initializeEnd",ic="msal:accountAdded",sc="msal:accountRemoved",ac="msal:activeAccountChanged",cc="msal:loginStart",lc="msal:loginSuccess",hc="msal:loginFailure",dc="msal:acquireTokenStart",uc="msal:acquireTokenSuccess",gc="msal:acquireTokenFailure",pc="msal:acquireTokenFromNetworkStart",mc="msal:ssoSilentStart",fc="msal:ssoSilentSuccess",yc="msal:ssoSilentFailure",Cc="msal:acquireTokenByCodeStart",Ic="msal:acquireTokenByCodeSuccess",wc="msal:acquireTokenByCodeFailure",Ac="msal:handleRedirectStart",vc="msal:handleRedirectEnd",Tc="msal:popupOpened",_c="msal:logoutStart",Ec="msal:logoutSuccess",bc="msal:logoutFailure",kc="msal:logoutEnd",Sc="msal:restoreFromBFCache";function Rc(e,t){const r=e.indexOf(t);r>-1&&e.splice(r,1)}class Oc extends ft{constructor(e,t,r,n,o,i,s){super(e,r,n,o,s),this.cacheConfig=t,this.logger=n,this.internalStorage=new da,this.browserStorage=Pc(e,t.cacheLocation,n,o),this.temporaryCacheStorage=Pc(e,t.temporaryCacheLocation,n,o),this.cookieStorage=new Qa,this.eventHandler=i}async initialize(e){this.performanceClient.addFields({cacheLocation:this.cacheConfig.cacheLocation,cacheRetentionDays:this.cacheConfig.cacheRetentionDays},e),await this.browserStorage.initialize(e),await this.migrateExistingCache(e),this.trackVersionChanges(e)}async migrateExistingCache(e){let t=Ja(this.browserStorage),r=Xa(this.clientId,this.browserStorage);this.performanceClient.addFields({preMigrateAcntCount:t.length,preMigrateATCount:r.accessToken.length,preMigrateITCount:r.idToken.length,preMigrateRTCount:r.refreshToken.length},e);for(let t=0;t<2;t++){const r=t;await this.removeStaleAccounts(t,r,e)}for(let t=0;t<2;t++){const r=t;await this.migrateIdTokens(t,r,e)}const n=this.getKMSIValues();for(let t=0;t<2;t++)await this.migrateAccessTokens(t,n,e),await this.migrateRefreshTokens(t,n,e);t=Ja(this.browserStorage),r=Xa(this.clientId,this.browserStorage),this.performanceClient.addFields({postMigrateAcntCount:t.length,postMigrateATCount:r.accessToken.length,postMigrateITCount:r.idToken.length,postMigrateRTCount:r.refreshToken.length},e)}async updateOldEntry(e,t){const r=this.browserStorage.getItem(e),n=this.validateAndParseJson(r||"");if(!n)return this.browserStorage.removeItem(e),null;if(n.lastUpdatedAt){if(va(n.lastUpdatedAt,this.cacheConfig.cacheRetentionDays))return this.browserStorage.removeItem(e),this.performanceClient.incrementFields({expiredCacheRemovedCount:1},t),null}else n.lastUpdatedAt=Date.now().toString(),this.setItem(e,JSON.stringify(n),t);const i=Za(n)?await this.browserStorage.decryptData(e,n,t):n;return i&&ba(i)?(ka(i)||Sa(i))&&i.expiresOn&&Aa(i.expiresOn,o.F0)?(this.browserStorage.removeItem(e),this.performanceClient.incrementFields({expiredCacheRemovedCount:1},t),null):i:(this.performanceClient.incrementFields({invalidCacheCount:1},t),null)}async removeStaleAccounts(e,t,r){const n=Ja(this.browserStorage,e);if(0!==n.length){for(const e of[...n]){this.performanceClient.incrementFields({oldAcntCount:1},r);const o=this.browserStorage.getItem(e),i=this.validateAndParseJson(o||"");i?i.lastUpdatedAt?va(i.lastUpdatedAt,this.cacheConfig.cacheRetentionDays)&&(await this.removeAccountOldSchema(e,i,t,r),Rc(n,e)):(i.lastUpdatedAt=Date.now().toString(),this.setItem(e,JSON.stringify(i),r)):Rc(n,e)}this.setAccountKeys(n,r,e)}}async removeAccountOldSchema(e,t,r,n){const o=Za(t)?await this.browserStorage.decryptData(e,t,n):t,i=o?.homeAccountId;if(i){const e=this.getTokenKeys(r);[...e.idToken].filter((e=>
2e.includes(i))).forEach((t=>{this.browserStorage.removeItem(t),Rc(e.idToken,t)})),[...e.accessToken].filter((e=>e.includes(i))).forEach((t=>{this.browserStorage.removeItem(t),Rc(e.accessToken,t)})),[...e.refreshToken].filter((e=>e.includes(i))).forEach((t=>{this.browserStorage.removeItem(t),Rc(e.refreshToken,t)})),this.setTokenKeys(e,n,r)}this.performanceClient.incrementFields({expiredAcntRemovedCount:1},n),this.browserStorage.removeItem(e)}getKMSIValues(){const e={},t=this.getTokenKeys().idToken;for(const r of t){const t=this.browserStorage.getUserData(r);if(t){const r=JSON.parse(t),n=Je(r.secret,is);n&&(e[r.homeAccountId]=Xe(n))}}return e}async migrateIdTokens(e,t,r){const n=Xa(this.clientId,this.browserStorage,e);if(0===n.idToken.length)return;const o=Xa(this.clientId,this.browserStorage,2),i=Ja(this.browserStorage),s=Ja(this.browserStorage,t);for(const e of[...n.idToken]){this.performanceClient.incrementFields({oldITCount:1},r);const t=await this.updateOldEntry(e,r);if(!t){Rc(n.idToken,e);continue}const a=i.find((e=>e.includes(t.homeAccountId))),c=s.find((e=>e.includes(t.homeAccountId)));let l=null;if(a)l=this.getAccount(a,r);else if(c){const e=this.browserStorage.getItem(c),t=this.validateAndParseJson(e||"");l=t&&Za(t)?await this.browserStorage.decryptData(c,t,r):t}if(!l){this.performanceClient.incrementFields({skipITMigrateCount:1},r);continue}const h=Je(t.secret,is),d=this.generateCredentialKey(t),u=this.getIdTokenCredential(d,r),g=Object.keys(h).includes("signin_state"),p=u&&Object.keys(Je(u.secret,is)||{}).includes("signin_state");if(!u||t.lastUpdatedAt>u.lastUpdatedAt&&(g||!p)){const e=l.tenantProfiles||[],n=We(h)||l.realm;if(n&&!e.find((e=>e.tenantId===n))){const t=Ge(l.homeAccountId,l.localAccountId,n,h);e.push(t)}l.tenantProfiles=e;const s=this.generateAccountKey(Qe.getAccountInfo(l)),a=Xe(h);await this.setUserData(s,JSON.stringify(l),r,l.lastUpdatedAt,a),i.includes(s)||i.push(s),await this.setUserData(d,JSON.stringify(t),r,t.lastUpdatedAt,a),this.performanceClient.incrementFields({migratedITCount:1},r),o.idToken.push(d)}}this.setTokenKeys(n,r,e),this.setTokenKeys(o,r),this.setAccountKeys(i,r)}async migrateAccessTokens(e,t,r){const n=Xa(this.clientId,this.browserStorage,e);if(0===n.accessToken.length)return;const o=Xa(this.clientId,this.browserStorage,2);for(const e of[...n.accessToken]){this.performanceClient.incrementFields({oldATCount:1},r);const i=await this.updateOldEntry(e,r);if(!i){Rc(n.accessToken,e);continue}if(!Object.keys(t).includes(i.homeAccountId)){this.performanceClient.incrementFields({skipATMigrateCount:1},r);continue}const s=this.generateCredentialKey(i),a=t[i.homeAccountId];if(o.accessToken.includes(s)){const e=this.getAccessTokenCredential(s,r);(!e||i.lastUpdatedAt>e.lastUpdatedAt)&&(await this.setUserData(s,JSON.stringify(i),r,i.lastUpdatedAt,a),this.performanceClient.incrementFields({migratedATCount:1},r))}else await this.setUserData(s,JSON.stringify(i),r,i.lastUpdatedAt,a),this.performanceClient.incrementFields({migratedATCount:1},r),o.accessToken.push(s)}this.setTokenKeys(n,r,e),this.setTokenKeys(o,r)}async migrateRefreshTokens(e,t,r){const n=Xa(this.clientId,this.browserStorage,e);if(0===n.refreshToken.length)return;const o=Xa(this.clientId,this.browserStorage,2);for(const e of[...n.refreshToken]){this.performanceClient.incrementFields({oldRTCount:1},r);const i=await this.updateOldEntry(e,r);if(!i){Rc(n.refreshToken,e);continue}if(!Object.keys(t).includes(i.homeAccountId)){this.performanceClient.incrementFields({skipRTMigrateCount:1},r);continue}const s=this.generateCredentialKey(i),a=t[i.homeAccountId];if(o.refreshToken.includes(s)){const e=this.getRefreshTokenCredential(s,r);(!e||i.lastUpdatedAt>e.lastUpdatedAt)&&(await this.setUserData(s,JSON.stringify(i),r,i.lastUpdatedAt,a),this.performanceClient.incrementFields({migratedRTCount:1},r))}else await this.setUserData(s,JSON.stringify(i),r,i.lastUpdatedAt,a),this.performanceClient.incrementFields({migratedRTCount:1},r),o.refreshToken.push(s)}this.setTokenKeys(n,r,e),this.setTokenKeys(o,r)}trackVersionChanges(e){const t=this.browserStorage.getItem(Js);t&&(this.logger.info(`MSAL.js was last initialized by version: ${t}`),this.performanceClient.addFields({previousLibraryVersion:t},e)),t!==$s&&this.setItem(Js,$s,e)}validateAndParseJson(e){if(!e)return null;try{const t=JSON.parse(e);return t&&"object"==typeof t?t:null}catch(e){return null}}setItem(e,t,r){const n=new Array(3).fill(0),o=[];for(let i=0;i<=20;i++)try{if(this.browserStorage.setItem(e,t),i>0)for(let e=0;e<=2;e++){const t=n.slice(0,e).reduce(((e,t)=>e+t),0);if(t>=i)break;const s=i>t+n[e]?t+n[e]:i;i>t&&n[e]>0&&this.removeAccessTokenKeys(o.slice(t,s),r,e)}break}catch(s){const a=mt(s);if(!(a.errorCode===dt&&i<20))throw a;if(!o.length)for(let r=0;r<=2;r++)if(e===ta(this.clientId,r)){const e=JSON.parse(t).accessToken;o.push(...e),n[r]=e.length}else{const e=this.getTokenKeys(r).accessToken;o.push(...e),n[r]=e.length}if(o.length<=i)throw a;this.removeAccessToken(o[i],r,!1)}}async setUserData(e,t,r,n,o){const i=new Array(3).fill(0),s=[];for(let a=0;a<=20;a++)try{if(await fa(this.browserStorage.setUserData.bind(this.browserStorage),qr,this.logger,this.performanceClient)(e,t,r,n,o),a>0)for(let e=0;e<=2;e++){const t=i.slice(0,e).reduce(((e,t)=>e+t),0);if(t>=a)break;const n=a>t+i[e]?t+i[e]:a;a>t&&i[e]>0&&this.removeAccessTokenKeys(s.slice(t,n),r,e)}break}catch(e){const t=mt(e);if(!(t.errorCode===dt&&a<20))throw t;if(!s.length)for(let e=0;e<=2;e++){const t=this.getTokenKeys(e).accessToken;s.push(...t),i[e]=t.length}if(s.length<=a)throw t;this.removeAccessToken(s[a],r,!1)}}getAccount(e,t){this.logger.trace("BrowserCacheManager.getAccount called");const r=this.browserStorage.getUserData(e);if(!r)return this.removeAccountKeyFromMap(e,t),null;const n=this.validateAndParseJson(r);return n&&Qe.isAccountEntity(n)?ft.toObject(new Qe,n):null}async setAccount(e,t,r){this.logger.trace("BrowserCacheManager.setAccount called");const n=this.generateAccountKey(Qe.getAccountInfo(e)),o=Date.now().toString();e.lastUpdatedAt=o,await this.setUserData(n,JSON.stringify(e),t,o,r);const i=this.addAccountKeyToMap(n,t);this.performanceClient.addFields({kmsi:r},t),this.cacheConfig.cacheLocation===On&&i&&this.eventHandler.emitEvent(ic,void 0,Qe.getAccountInfo(e))}getAccountKeys(){return Ja(this.browserStorage)}setAccountKeys(e,t,r=2){0===e.length?this.removeItem(ea(r)):this.setItem(ea(r),JSON.stringify(e),t)}addAccountKeyToMap(e,t){this.logger.trace("BrowserCacheManager.addAccountKeyToMap called"),this.logger.tracePii(`BrowserCacheManager.addAccountKeyToMap called with key: ${e}`);const r=this.getAccountKeys();return-1===r.indexOf(e)?(r.push(e),this.setItem(ea(),JSON.stringify(r),t),this.logger.verbose("BrowserCacheManager.addAccountKeyToMap account key added"),!0):(this.logger.verbose("BrowserCacheManager.addAccountKeyToMap account key already exists in map"),!1)}removeAccountKeyFromMap(e,t){this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap called"),this.logger.tracePii(`BrowserCacheManager.removeAccountKeyFromMap called with key: ${e}`);const r=this.getAccountKeys(),n=r.indexOf(e);n>-1?(r.splice(n,1),this.setAccountKeys(r,t),this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap account key removed")):this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap ke
2y not found in existing map")}removeAccount(e,t){const r=this.getActiveAccount(t);r?.homeAccountId===e.homeAccountId&&r?.environment===e.environment&&this.setActiveAccount(null,t),super.removeAccount(e,t),this.removeAccountKeyFromMap(this.generateAccountKey(e),t),this.browserStorage.getKeys().forEach((t=>{t.includes(e.homeAccountId)&&t.includes(e.environment)&&this.browserStorage.removeItem(t)})),this.cacheConfig.cacheLocation===On&&this.eventHandler.emitEvent(sc,void 0,e)}removeIdToken(e,t){super.removeIdToken(e,t);const r=this.getTokenKeys(),n=r.idToken.indexOf(e);n>-1&&(this.logger.info("idToken removed from tokenKeys map"),r.idToken.splice(n,1),this.setTokenKeys(r,t))}removeAccessToken(e,t,r=!0){super.removeAccessToken(e,t),r&&this.removeAccessTokenKeys([e],t)}removeAccessTokenKeys(e,t,r=2){this.logger.trace("removeAccessTokenKey called");const n=this.getTokenKeys(r);let o=0;if(e.forEach((e=>{const t=n.accessToken.indexOf(e);t>-1&&(n.accessToken.splice(t,1),o++)})),o>0)return this.logger.info(`removed ${o} accessToken keys from tokenKeys map`),void this.setTokenKeys(n,t,r)}removeRefreshToken(e,t){super.removeRefreshToken(e,t);const r=this.getTokenKeys(),n=r.refreshToken.indexOf(e);n>-1&&(this.logger.info("refreshToken removed from tokenKeys map"),r.refreshToken.splice(n,1),this.setTokenKeys(r,t))}getTokenKeys(e=2){return Xa(this.clientId,this.browserStorage,e)}setTokenKeys(e,t,r=2){0!==e.idToken.length||0!==e.accessToken.length||0!==e.refreshToken.length?this.setItem(ta(this.clientId,r),JSON.stringify(e),t):this.removeItem(ta(this.clientId,r))}getIdTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit"),this.removeIdToken(e,t),null;const n=this.validateAndParseJson(r);return n&&((i=n)&&ba(i)&&i.hasOwnProperty("realm")&&i.credentialType===o.aG.ID_TOKEN)?(this.logger.trace("BrowserCacheManager.getIdTokenCredential: cache hit"),n):(this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit"),null);var i}async setIdTokenCredential(e,t,r){this.logger.trace("BrowserCacheManager.setIdTokenCredential called");const n=this.generateCredentialKey(e),o=Date.now().toString();e.lastUpdatedAt=o,await this.setUserData(n,JSON.stringify(e),t,o,r);const i=this.getTokenKeys();-1===i.idToken.indexOf(n)&&(this.logger.info("BrowserCacheManager: addTokenKey - idToken added to map"),i.idToken.push(n),this.setTokenKeys(i,t))}getAccessTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit"),this.removeAccessTokenKeys([e],t),null;const n=this.validateAndParseJson(r);return n&&ka(n)?(this.logger.trace("BrowserCacheManager.getAccessTokenCredential: cache hit"),n):(this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit"),null)}async setAccessTokenCredential(e,t,r){this.logger.trace("BrowserCacheManager.setAccessTokenCredential called");const n=this.generateCredentialKey(e),o=Date.now().toString();e.lastUpdatedAt=o,await this.setUserData(n,JSON.stringify(e),t,o,r);const i=this.getTokenKeys(),s=i.accessToken.indexOf(n);-1!==s&&i.accessToken.splice(s,1),this.logger.trace(`access token ${-1===s?"added to":"updated in"} map`),i.accessToken.push(n),this.setTokenKeys(i,t)}getRefreshTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit"),this.removeRefreshToken(e,t),null;const n=this.validateAndParseJson(r);return n&&Sa(n)?(this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: cache hit"),n):(this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit"),null)}async setRefreshTokenCredential(e,t,r){this.logger.trace("BrowserCacheManager.setRefreshTokenCredential called");const n=this.generateCredentialKey(e),o=Date.now().toString();e.lastUpdatedAt=o,await this.setUserData(n,JSON.stringify(e),t,o,r);const i=this.getTokenKeys();-1===i.refreshToken.indexOf(n)&&(this.logger.info("BrowserCacheManager: addTokenKey - refreshToken added to map"),i.refreshToken.push(n),this.setTokenKeys(i,t))}getAppMetadata(e){const t=this.browserStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit"),null;const r=this.validateAndParseJson(t);return r&&(n=e,(i=r)&&0===n.indexOf(o.GU)&&i.hasOwnProperty("clientId")&&i.hasOwnProperty("environment"))?(this.logger.trace("BrowserCacheManager.getAppMetadata: cache hit"),r):(this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit"),null);var n,i}setAppMetadata(e,t){this.logger.trace("BrowserCacheManager.setAppMetadata called");const r=function({environment:e,clientId:t}){return[o.GU,e,t].join(o.LR.CACHE_KEY_SEPARATOR).toLowerCase()}(e);this.setItem(r,JSON.stringify(e),t)}getServerTelemetry(e){const t=this.browserStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit"),null;const r=this.validateAndParseJson(t);return r&&function(e,t){const r=0===e.indexOf(o.gT.CACHE_KEY);let n=!0;return t&&(n=t.hasOwnProperty("failedRequests")&&t.hasOwnProperty("errors")&&t.hasOwnProperty("cacheHits")),r&&n}(e,r)?(this.logger.trace("BrowserCacheManager.getServerTelemetry: cache hit"),r):(this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit"),null)}setServerTelemetry(e,t,r){this.logger.trace("BrowserCacheManager.setServerTelemetry called"),this.setItem(e,JSON.stringify(t),r)}getAuthorityMetadata(e){const t=this.internalStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getAuthorityMetadata: called, no cache hit"),null;const r=this.validateAndParseJson(t);return r&&function(e,t){return!!t&&0===e.indexOf(o.u0.CACHE_KEY)&&t.hasOwnProperty("aliases")&&t.hasOwnProperty("preferred_cache")&&t.hasOwnProperty("preferred_network")&&t.hasOwnProperty("canonical_authority")&&t.hasOwnProperty("authorization_endpoint")&&t.hasOwnProperty("token_endpoint")&&t.hasOwnProperty("issuer")&&t.hasOwnProperty("aliasesFromNetwork")&&t.hasOwnProperty("endpointsFromNetwork")&&t.hasOwnProperty("expiresAt")&&t.hasOwnProperty("jwks_uri")}(e,r)?(this.logger.trace("BrowserCacheManager.getAuthorityMetadata: cache hit"),r):null}getAuthorityMetadataKeys(){return this.internalStorage.getKeys().filter((e=>this.isAuthorityMetadata(e)))}setWrapperMetadata(e,t){this.internalStorage.setItem(Gn,e),this.internalStorage.setItem(zn,t)}getWrapperMetadata(){return[this.internalStorage.getItem(Gn)||o.YM.EMPTY_STRING,this.internalStorage.getItem(zn)||o.YM.EMPTY_STRING]}setAuthorityMetadata(e,t){this.logger.trace("BrowserCacheManager.setAuthorityMetadata called"),this.internalStorage.setItem(e,JSON.stringify(t))}getActiveAccount(e){const t=this.generateCacheKey(o.Gd.ACTIVE_ACCOUNT_FILTERS),r=this.browserStorage.getItem(t);if(!r)return this.logger.trace("BrowserCacheManager.getActiveAccount: No active account filters found"),null;const n=this.validateAndParseJson(r);return n?(this.logger.trace("BrowserCacheManager.getActiveAccount: Active account filters schema found"),this.getAccountInfoFilteredBy({homeAccountId:n.homeAccountId,localAccountId:n.localAccountId,tenantId:n.tenantId},e)):(this.logger.trace("BrowserCacheManager.getActiveAccount: No active account found"),null)}setActiveAccount(e,t){const r=this.generateCacheKey(o.Gd.ACTIVE_ACCOUNT_FILTERS);if(e){this.logger.verbose("setActiveAccount: Active account set");const n={homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,tenantId:e.tenantId,lastUpdatedAt:Ca().toString()};this.setItem(r,JSON.stringify(n),t)}else this.logger.verbose("setActiveAccount: No account passed, active account not set"),this.browserStorage.removeItem(r);this.eventHandler.emitEvent(ac)}getThrottlingCache(e){const t=this.browserStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit"),null;const r=this.validateAndParseJson(t);return r&&function(e,t){let r=!1;
2e&&(r=0===e.indexOf(o.Xw.THROTTLING_PREFIX));let n=!0;return t&&(n=t.hasOwnProperty("throttleTime")),r&&n}(e,r)?(this.logger.trace("BrowserCacheManager.getThrottlingCache: cache hit"),r):(this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit"),null)}setThrottlingCache(e,t,r){this.logger.trace("BrowserCacheManager.setThrottlingCache called"),this.setItem(e,JSON.stringify(t),r)}getTemporaryCache(e,t){const r=t?this.generateCacheKey(e):e;if(this.cacheConfig.storeAuthStateInCookie){const e=this.cookieStorage.getItem(r);if(e)return this.logger.trace("BrowserCacheManager.getTemporaryCache: storeAuthStateInCookies set to true, retrieving from cookies"),e}const n=this.temporaryCacheStorage.getItem(r);if(!n){if(this.cacheConfig.cacheLocation===On){const e=this.browserStorage.getItem(r);if(e)return this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item found in local storage"),e}return this.logger.trace("BrowserCacheManager.getTemporaryCache: No cache item found in local storage"),null}return this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item returned"),n}setTemporaryCache(e,t,r){const n=r?this.generateCacheKey(e):e;this.temporaryCacheStorage.setItem(n,t),this.cacheConfig.storeAuthStateInCookie&&(this.logger.trace("BrowserCacheManager.setTemporaryCache: storeAuthStateInCookie set to true, setting item cookie"),this.cookieStorage.setItem(n,t,void 0,this.cacheConfig.secureCookies))}removeItem(e){this.browserStorage.removeItem(e)}removeTemporaryItem(e){this.temporaryCacheStorage.removeItem(e),this.cacheConfig.storeAuthStateInCookie&&(this.logger.trace("BrowserCacheManager.removeItem: storeAuthStateInCookie is true, clearing item cookie"),this.cookieStorage.removeItem(e))}getKeys(){return this.browserStorage.getKeys()}clear(e){this.removeAllAccounts(e),this.removeAppMetadata(e),this.temporaryCacheStorage.getKeys().forEach((e=>{-1===e.indexOf(js)&&-1===e.indexOf(this.clientId)||this.removeTemporaryItem(e)})),this.browserStorage.getKeys().forEach((e=>{-1===e.indexOf(js)&&-1===e.indexOf(this.clientId)||this.browserStorage.removeItem(e)})),this.internalStorage.clear()}clearTokensAndKeysWithClaims(e){this.performanceClient.addQueueMeasurement(Lr,e);const t=this.getTokenKeys();let r=0;t.accessToken.forEach((t=>{const n=this.getAccessTokenCredential(t,e);n?.requestedClaimsHash&&t.includes(n.requestedClaimsHash.toLowerCase())&&(this.removeAccessToken(t,e),r++)})),r>0&&this.logger.warning(`${r} access tokens with claims in the cache keys have been removed from the cache.`)}generateCacheKey(e){return He.startsWith(e,js)?e:`${js}.${this.clientId}.${e}`}generateCredentialKey(e){const t=e.credentialType===o.aG.REFRESH_TOKEN&&e.familyId||e.clientId,r=e.tokenType&&e.tokenType.toLowerCase()!==o.IO.BEARER.toLowerCase()?e.tokenType.toLowerCase():"";return[`${js}.2`,e.homeAccountId,e.environment,e.credentialType,t,e.realm||"",e.target||"",e.requestedClaimsHash||"",r].join("|").toLowerCase()}generateAccountKey(e){const t=e.homeAccountId.split(".")[1];return[`${js}.2`,e.homeAccountId,e.environment,t||e.tenantId||""].join("|").toLowerCase()}resetRequestCache(){this.logger.trace("BrowserCacheManager.resetRequestCache called"),this.removeTemporaryItem(this.generateCacheKey(xn)),this.removeTemporaryItem(this.generateCacheKey(Fn)),this.removeTemporaryItem(this.generateCacheKey(qn)),this.removeTemporaryItem(this.generateCacheKey(Hn)),this.removeTemporaryItem(this.generateCacheKey(Kn)),this.setInteractionInProgress(!1)}cacheAuthorizeRequest(e,t){this.logger.trace("BrowserCacheManager.cacheAuthorizeRequest called");const r=ns(JSON.stringify(e));if(this.setTemporaryCache(xn,r,!0),t){const e=ns(t);this.setTemporaryCache(Fn,e,!0)}}getCachedRequest(){this.logger.trace("BrowserCacheManager.getCachedRequest called");const e=this.getTemporaryCache(xn,!0);if(!e)throw di(Lo);const t=this.getTemporaryCache(Fn,!0);let r,n="";try{r=JSON.parse(is(e)),t&&(n=is(t))}catch(t){throw this.logger.errorPii(`Attempted to parse: ${e}`),this.logger.error(`Parsing cached token request threw with error: ${t}`),di(Do)}return[r,n]}getCachedNativeRequest(){this.logger.trace("BrowserCacheManager.getCachedNativeRequest called");const e=this.getTemporaryCache(Kn,!0);if(!e)return this.logger.trace("BrowserCacheManager.getCachedNativeRequest: No cached native request found"),null;const t=this.validateAndParseJson(e);return t||(this.logger.error("BrowserCacheManager.getCachedNativeRequest: Unable to parse native request"),null)}isInteractionInProgress(e){const t=this.getInteractionInProgress()?.clientId;return e?t===this.clientId:!!t}getInteractionInProgress(){const e=`${js}.${Bn}
2`,t=this.getTemporaryCache(e,!1);try{return t?JSON.parse(t):null}catch(t){return this.logger.error("Cannot parse interaction status. Removing temporary cache items and clearing url hash. Retrying interaction should fix the error"),this.removeTemporaryItem(e),this.resetRequestCache(),Us(window),null}}setInteractionInProgress(e,t=Dn){const r=`${js}.${Bn}`;if(e){if(this.getInteractionInProgress())throw di(Ao);this.setTemporaryCache(r,JSON.stringify({clientId:this.clientId,type:t}),!1)}else e||this.getInteractionInProgress()?.clientId!==this.clientId||this.removeTemporaryItem(r)}async hydrateCache(e,t){const r=Ta(e.account?.homeAccountId,e.account?.environment,e.idToken,this.clientId,e.tenantId);let n;t.claims&&(n=await this.cryptoImpl.hashString(t.claims));const o={idToken:r,accessToken:_a(e.account?.homeAccountId,e.account.environment,e.accessToken,this.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?Ia(e.expiresOn):0,e.extExpiresOn?Ia(e.extExpiresOn):0,is,void 0,e.tokenType,void 0,t.sshKid,t.claims,n)};return this.saveCacheRecord(o,e.correlationId,Xe(Je(e.idToken,is)))}async saveCacheRecord(e,t,r,n){try{await super.saveCacheRecord(e,t,r,n)}catch(e){if(e instanceof pt&&this.performanceClient&&t)try{const e=this.getTokenKeys();this.performanceClient.addFields({cacheRtCount:e.refreshToken.length,cacheIdCount:e.idToken.length,cacheAtCount:e.accessToken.length},t)}catch(e){}throw e}}}function Pc(e,t,r,n){try{switch(t){case On:return new tc(e,r,n);case Pn:return new rc}}catch(e){r.error(e)}return new da}class Mc{constructor(e){this.eventCallbacks=new Map,this.logger=e||new n.V({}),"undefined"!=typeof BroadcastChannel&&(this.broadcastChannel=new BroadcastChannel("msal.broadcast.event")),this.invokeCrossTabCallbacks=this.invokeCrossTabCallbacks.bind(this)}addEventCallback(e,t,r){if("undefined"!=typeof window){const n=r||ws();return this.eventCallbacks.has(n)?(this.logger.error(`Event callback with id: ${n} is already registered. Please provide a unique id or remove the existing callback and try again.`),null):(this.eventCallbacks.set(n,[e,t||[]]),this.logger.verbose(`Event callback registered with id: ${n}`),n)}return null}removeEventCallback(e){this.eventCallbacks.delete(e),this.logger.verbose(`Event callback ${e} removed.`)}emitEvent(e,t,r,n){const o={eventType:e,interactionType:t||null,payload:r||null,error:n||null,timestamp:Date.now()};switch(e){case ic:case sc:case ac:this.broadcastChannel?.postMessage(o);break;default:this.invokeCallbacks(o)}}invokeCallbacks(e){this.eventCallbacks.forEach((([t,r],n)=>{(0===r.length||r.includes(e.eventType))&&(this.logger.verbose(`Emitting event to callback ${n}: ${e.eventType}`),t.apply(null,[e]))}))}invokeCrossTabCallbacks(e){const t=e.data;this.invokeCallbacks(t)}subscribeCrossTab(){this.broadcastChannel?.addEventListener("message",this.invokeCrossTabCallbacks)}unsubscribeCrossTab(){this.broadcastChannel?.removeEventListener("message",this.invokeCrossTabCallbacks)}}const Nc="home_account_id",Lc="UPN";async function Dc(e,t,r,n,o,i,s){s?.addQueueMeasurement(Ir,i);const a=Na.transformCIAMAuthority(La(e)),c=new Na(a,t,r,n,o,i,s);try{return await fa(c.resolveEndpointsAsync.bind(c),wr,o,s,i)(),c}catch(e){throw ae(C)}}class Uc extends u{constructor(e,t,r,n,o){super(e,t,r),this.name="ServerError",this.errorNo=n,this.status=o,Object.setPrototypeOf(this,Uc.prototype)}}class qc{static generateThrottlingStorageKey(e){return`${o.Xw.THROTTLING_PREFIX}.${JSON.stringify(e)}`}static preProcess(e,t,r){const n=qc.generateThrottlingStorageKey(t),i=e.getThrottlingCache(n);if(i){if(i.throttleTime<Date.now())return void e.removeItem(n,r);throw new Uc(i.errorCodes?.join(" ")||o.YM.EMPTY_STRING,i.errorMessage,i.subError)}}static postProcess(e,t,r,n){if(qc.checkResponseStatus(r)||qc.checkResponseForRetryAfter(r)){const i={throttleTime:qc.calculateThrottleTime(parseInt(r.headers[o.OK.RETRY_AFTER])),error:r.body.error,errorCodes:r.body.error_codes,errorMessage:r.body.error_description,subError:r.body.suberror};e.setThrottlingCache(qc.generateThrottlingStorageKey(t),i,n)}}static checkResponseStatus(e){return 429===e.status||e.status>=500&&e.status<600}static checkResponseForRetryAfter(e){return!!e.headers&&(e.headers.hasOwnProperty(o.OK.RETRY_AFTER)&&(e.status<200||e.status>=300))}static calculateThrottleTime(e){const t=e<=0?0:e,r=Date.now()/1e3;return Math.floor(1e3*Math.min(r+(t||o.Xw.DEFAULT_THROTTLE_TIME_SECONDS),r+o.Xw.DEFAULT_MAX_THROTTLE_TIME_SECONDS))}static removeThrottle(e,t,r,n){const o=$a(t,r,n),i=this.generateThrottlingStorageKey(o);e.removeItem(i,r.correlationId)}}class Hc{constructor(e,t){this.config=function({authOptions:e,systemOptions:t,loggerOptions:r,cacheOptions:o,storageInterface:i,networkInterface:s,cryptoInterface:a,clientCredentials:c,library
2Info:l,telemetry:h,serverTelemetryManager:d,persistencePlugin:u,serializableCache:g}){const p={...rn,...r};return{authOptions:(m=e,{clientCapabilities:[],azureCloudOptions:cn,skipAuthorityMetadataCache:!1,instanceAware:!1,encodeExtraQueryParams:!1,...m}),systemOptions:{...tn,...t},loggerOptions:p,cacheOptions:{...nn,...o},storageInterface:i||new yt(e.clientId,ce,new n.V(p),new en),networkInterface:s||on,cryptoInterface:a||ce,clientCredentials:c||an,libraryInfo:{...sn,...l},telemetry:{...ln,...h},serverTelemetryManager:d||null,persistencePlugin:u||null,serializableCache:g||null};var m}(e),this.logger=new n.V(this.config.loggerOptions,le,he),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}createTokenRequestHeaders(e){const t={};if(t[o.OK.CONTENT_TYPE]=o.YM.URL_FORM_CONTENT_TYPE,!this.config.systemOptions.preventCorsPreflight&&e)switch(e.type){case Nc:try{const r=Be(e.credential);t[o.OK.CCS_HEADER]=`Oid:${r.uid}@${r.utid}`}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case Lc:t[o.OK.CCS_HEADER]=`UPN: ${e.credential}`}return t}async executePostToTokenEndpoint(e,t,r,n,o,i){i&&this.performanceClient?.addQueueMeasurement(i,o);const s=await this.sendPostRequest(n,e,{body:t,headers:r},o);return this.config.serverTelemetryManager&&s.status<500&&429!==s.status&&this.config.serverTelemetryManager.clearTelemetryCache(),s}async sendPostRequest(e,t,r,n){let i;qc.preProcess(this.cacheManager,e,n);try{i=await fa(this.networkClient.sendPostRequestAsync.bind(this.networkClient),Lt,this.logger,this.performanceClient,n)(t,r);const e=i.headers||{};this.performanceClient?.addFields({refreshTokenSize:i.body.refresh_token?.length||0,httpVerToken:e[o.OK.X_MS_HTTP_VERSION]||"",requestId:e[o.OK.X_MS_REQUEST_ID]||""},n)}catch(e){if(e instanceof gi){const t=e.responseHeaders;throw t&&this.performanceClient?.addFields({httpVerToken:t[o.OK.X_MS_HTTP_VERSION]||"",requestId:t[o.OK.X_MS_REQUEST_ID]||"",contentTypeHeader:t[o.OK.CONTENT_TYPE]||void 0,contentLengthHeader:t[o.OK.CONTENT_LENGTH]||void 0,httpStatus:e.httpStatus},n),e.error}throw e instanceof u?e:ae(I)}return qc.postProcess(this.cacheManager,e,i,n),i}async updateAuthority(e,t){this.performanceClient?.addQueueMeasurement(dr,t);const r=`https://${e}/${this.authority.tenant}/`,n=await Dc(r,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=n}createTokenQueryParameters(e){const t=new Map;return e.embeddedClientId&&es(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenQueryParameters&&Vi(t,e.tokenQueryParameters),qi(t,e.correlationId),ki(t,e.correlationId,this.performanceClient),nt(t)}}class xc{static setRequestState(e,t,r){const n=xc.generateLibraryState(e,r);return t?`${n}${o.YM.RESOURCE_DELIM}${t}`:n}static generateLibraryState(e,t){if(!e)throw ae(K);const r={id:e.createNewGuid()};t&&(r.meta=t);const n=JSON.stringify(r);return e.base64Encode(n)}static parseRequestState(e,t){if(!e)throw ae(K);if(!t)throw ae(v);try{const r=t.split(o.YM.RESOURCE_DELIM),n=r[0],i=r.length>1?r.slice(1).join(o.YM.RESOURCE_DELIM):o.YM.EMPTY_STRING,s=e.base64Decode(n),a=JSON.parse(s);return{userRequestState:i||o.YM.EMPTY_STRING,libraryState:a}}catch(e){throw ae(v)}}}const Fc="sw";class Bc{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){this.performanceClient?.addQueueMeasurement(mr,e.correlationId);const r=await fa(this.generateKid.bind(this),mr,t,this.performanceClient,e.correlationId)(e),n=this.cryptoUtils.base64UrlEncode(JSON.stringify(r));return{kid:r.kid,reqCnfString:n}}async generateKid(e){this.performanceClient?.addQueueMeasurement(fr,e.correlationId);return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:Fc}}async signPopToken(e,t,r){return this.signPayload(e,t,r)}async signPayload(e,t,r,n){const{resourceRequestMethod:o,resourceRequestUri:i,shrClaims:s,shrNonce:a,shrOptions:c}=r,l=i?new it(i):void 0,h=l?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:Ca(),m:o?.toUpperCase(),u:h?.HostNameAndPort,nonce:a||this.cryptoUtils.createNewGuid(),p:h?.AbsolutePath,q:h?.QueryString?[[],h.QueryString]:void 0,client_claims:s||void 0,...n},t,c,r.correlationId)}}class Kc{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}class Gc{constructor(e,t,r,n,o,i,s){this.clientId=e,this.cacheStorage=t,this.cryptoObj=r,this.logger=n,this.serializableCache=o,this.persistencePlugin=i,this.performanceClient=s}validateTokenResponse(e,t){if(e.error||e.error_description||e.suberror){const r=`Error(s): ${e.error_codes||o.YM.NOT_AVAILABLE} - Timestamp: ${e.timestamp||o.YM.NOT_AVAILABLE} - Description: ${e.error_description||o.YM.NOT_AVAILABLE} - Correlation ID: ${e.correlation_id||o.YM.NOT_AVAILABLE} - Trace ID: ${e.trace_id||o.YM.NOT_AVAILABLE}`,n=e.error_codes?.length?e.error_codes[0]:void 0,i=new Uc(e.error,r,e.suberror,n,e.status);if(t&&e.status&&e.status>=o.t3.SERVER_ERROR_RANGE_START&&e.status<=o.t3.SERVER_ERROR_RANGE_END)return void this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.\n${i}`);if(t&&e.status&&e.status>=o.t3.CLIENT_ERROR_RANGE_START&&e.status<=o.t3.CLIENT_ERROR_RANGE_END)return void this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.\n${i}`);if(za(e.error,e.error_description,e.suberror))throw new Ga(e.error,e.error_description,e.suberror,e.timestamp||o.YM.EMPTY_STRING,e.trace_id||o.YM.EMPTY_STRING,e.correlation_id||o.YM.EMPTY_STRING,e.claims||o.YM.EMPTY_STRING,n);throw i}}async handleServerTokenResponse(e,t,r,n,i,s,a,c,l){let h,d;if(this.performanceClient?.addQueueMeasurement(yr,e.correlation_id),e.id_token){if(h=Je(e.id_token||o.YM.EMPTY_STRING,this.cryptoObj.base64Decode),i&&i.nonce&&h.nonce!==i.nonce)throw ae(E);if(n.maxAge||0===n.maxAge){const e=h.auth_time;if(!e)throw ae(b);Ze(e,n.maxAge)}}this.homeAccountIdentifier=Qe.generateHomeAccountId(e.client_info||o.YM.EMPTY_STRING,t.authorityType,this.logger,this.cryptoObj,h),i&&i.state&&(d=xc.parseRequestState(this.cryptoObj,i.state)),e.key_id=e.key_id||n.sshKid||void 0;const u=this.generateCacheRecord(e,t,r,n,h,s,i);let g;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("Persistence enabled, calling beforeCacheAccess"),g=new Kc(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(g)),a&&!c&&u.account){const e=this.cacheStorage.generateAccountKey(Qe.getAccountInfo(u.account));if(!this.cacheStorage.getAccount(e,n.correlationId))return this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache"),await Gc.generateAuthenticationResult(this.cryptoObj,t,u,!1,n,h,d,void 0,l)}await this.cacheStorage.saveCacheRecord(u,n.correlationId,Xe(h||{}),n.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&g&&(this.logger.verbose("Persistence enabled, calling afterCacheAccess"),await this.persistencePlugin.afterCacheAccess(g))}return Gc.generateAuthenticationResult(this.cryptoObj,t,u,!1,n,h,d,e,l)}generateCacheRecord(e,t,r,n,o,i,s){const a=t.getPreferredCache();if(!a)throw ae(F);const c=We(o);let l,h;e.id_token&&o&&(l=Ta(this.homeAccountIdentifier,a,e.id_token,this.clientId,c||""),h=zc(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,n.correlationId,o,e.client_info,a,c,s,void 0,this.logger));let d=null;if(e.access_token){const o=e.scope?xe.fromString(e.scope):new xe(n.scopes||[]),s=("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0,l=("string"==typeof e.ext_expires_in?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,h=("string"==typeof e.refresh_in?parseInt(e.refresh_in,10):e.refresh_in)||void 0,u=r+s,g=u+l,p=h&&h>0?r+h:void 0;d=_a(this.homeAccountIdentifier,a,e.access_token,this.clientId,c||t.tenant||"",o.printScopes(),u,g,this.cryptoObj.base64Decode,p,e.token_type,i,e.key_id,n.claims,n.requestedClaimsHash)}let u=null;if(e.refresh_token){let t;if(e.refresh_token_expires_in){t=r+("string"==typeof e.refresh_token_expires_in?parseInt(e.refresh_token_expires_in,10):e.refresh_token_expires_in)}u=Ea(this.homeAccountIdentifier,a,e.refresh_token,this.clientId,e.foci,i,t)}let g=null;return e.foci&&(g={clientId:this.clientId,environment:a,familyId:e.foci}),{account:h,idToken:l,accessToken:d,refreshToken:u,appMetadata:g}}static async generateAuthenticationResult(e,t,r,n,i,s,a,c,l){let h,d,u=o.YM.EMPTY_STRING,g=[],p=null,m=o.YM.EMPTY_STRING;if(r.accessToken){if(r.accessToken.tokenType!==o.IO.POP||i.popKid)u=r.accessToken.secret;else{const t=new Bc(e),{secret:n,keyId:o}=r.accessToken;if(!o)throw ae(X);u=await t.signPopToken(n,o,i)}g=xe.fromString(r.accessToken.target).asArray(),p=wa(r.accessToken.expiresOn),h=wa(r.accessToken.extendedExpiresOn),r.accessToken.refreshOn&&(d=wa(r.accessToken.refreshOn))}r.appMetadata&&(m=r.appMetadata.familyId===o.hB?o.hB:"");const f=s?.oid||s?.sub||"",y=s?.tid||"";c?.spa_accountid&&r.account&&(r.account.nativeAccountId=c?.spa_accountid);const C=r.account?ze(Qe.getAccountInfo(r.account),void 0,s,r.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:f,tenantId:y,scopes:g,account:C,idToken:r?.idToken?.secret||"",idTokenClaims:s||{},accessToken:u,fromCache:n,expiresOn:p,extExpiresOn:h,refreshOn:d,correlationId:i.correlationId,requestId:l||o.YM.EMPTY_STRING,familyId:m,tokenType:r.accessToken?.tokenType||o.YM.EMPTY_STRING,state:a?a.userRequestState:o.YM.EMPTY_STRING,cloudGraphHostName:r.account?.cloudGraphHostName||o.YM.EMPTY_STRING,msGraphHost:r.account?.msGraphHost||o.YM.EMPTY_STRING,code:c?.spa_code,fromNativeBroker:!1}}}function zc(e,t,r,n,o,i,s,a,c,l,h,d){d?.verbose("setCachedAccount called");const u=e.getAccountKeys().find((e=>e.startsWith(r)));let g=null;u&&(g=e.getAccount(u,o));const p=g||Qe.createAccount({homeAccountId:r,idTokenClaims:i,clientInfo:s,environment:a,cloudGraphHostName:l?.cloud_graph_host_name,msGraphHost:l?.msgraph_host,nativeAccountId:h},t,n),m=p.tenantProfiles||[],f=c||p.realm;if(f&&!m.find((e=>
2e.tenantId===f))){const e=Ge(r,p.localAccountId,f,i);m.push(e)}return p.tenantProfiles=m,p}async function Yc(e,t,r){if("string"==typeof e)return e;return e({clientId:t,tokenEndpoint:r})}class $c extends Hc{constructor(e,t){super(e,t),this.includeRedirectUri=!0,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async acquireToken(e,t){if(this.performanceClient?.addQueueMeasurement(ur,e.correlationId),!e.code)throw ae(P);const r=Ca(),n=await fa(this.executeTokenRequest.bind(this),gr,this.logger,this.performanceClient,e.correlationId)(this.authority,e),i=n.headers?.[o.OK.X_MS_REQUEST_ID],s=new Gc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin,this.performanceClient);return s.validateTokenResponse(n.body),fa(s.handleServerTokenResponse.bind(s),yr,this.logger,this.performanceClient,e.correlationId)(n.body,this.authority,r,e,t,void 0,void 0,void 0,i)}getLogoutUri(e){if(!e)throw qe(Ie);const t=this.createLogoutUrlQueryString(e);return it.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(gr,t.correlationId);const r=this.createTokenQueryParameters(t),n=it.appendQueryString(e.tokenEndpoint,r),i=await fa(this.createTokenRequestBody.bind(this),pr,this.logger,this.performanceClient,t.correlationId)(t);let s;if(t.clientInfo)try{const e=Fe(t.clientInfo,this.cryptoUtils.base64Decode);s={credential:`${e.uid}${o.LR.CLIENT_INFO_SEPARATOR}${e.utid}`,type:Nc}}catch(e){this.logger.verbose("Could not parse client info for CCS Header: "+e)}const a=this.createTokenRequestHeaders(s||t.ccsCredential),c=$a(this.config.authOptions.clientId,t);return fa(this.executePostToTokenEndpoint.bind(this),Ut,this.logger,this.performanceClient,t.correlationId)(n,i,a,c,t.correlationId,Ut)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(pr,e.correlationId);const t=new Map;if(Oi(t,e.embeddedClientId||e.tokenBodyParameters?.[Ci]||this.config.authOptions.clientId),this.includeRedirectUri)Pi(t,e.redirectUri);else if(!e.redirectUri)throw qe(de);if(Ri(t,e.scopes,!0,this.oidcDefaultScopes),function(e,t){e.set("code",t)}(t,e.code),Hi(t,this.config.libraryInfo),xi(t,this.config.telemetry.application),Zi(t),this.serverTelemetryManager&&!hn(this.config)&&Xi(t,this.serverTelemetryManager),e.codeVerifier&&function(e,t){e.set("code_verifier",t)}(t,e.codeVerifier),this.config.clientCredentials.clientSecret&&Ki(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;Gi(t,await Yc(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),zi(t,r.assertionType)}if(Yi(t,o.$x.AUTHORIZATION_CODE_GRANT),$i(t),e.authenticationScheme===o.IO.POP){const r=new Bc(this.cryptoUtils,this.performanceClient);let n;if(e.popKid)n=this.cryptoUtils.encodeKid(e.popKid);else{n=(await fa(r.generateCnf.bind(r),mr,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}Qi(t,n)}else if(e.authenticationScheme===o.IO.SSH){if(!e.sshJwk)throw qe(Ee);Ji(t,e.sshJwk)}let r;if((!He.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ui(t,e.claims,this.config.authOptions.clientCapabilities),e.clientInfo)try{const t=Fe(e.clientInfo,this.cryptoUtils.base64Decode);r={credential:`${t.uid}${o.LR.CLIENT_INFO_SEPARATOR}${t.utid}`,type:Nc}}catch(e){this.logger.verbose("Could not parse client info for CCS Header: "+e)}else r=e.ccsCredential;if(this.config.systemOptions.preventCorsPreflight&&r)switch(r.type){case Nc:try{Li(t,Be(r.credential))}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case Lc:Ni(t,r.credential)}return e.embeddedClientId&&es(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenBodyParameters&&Vi(t,e.tokenBodyParameters),!e.enableSpaAuthorizationCode||e.tokenBodyParameters&&e.tokenBodyParameters[vi]||Vi(t,{[vi]:"1"}),ki(t,e.correlationId,this.performanceClient),nt(t)}createLogoutUrlQueryString(e){const t=new Map;return e.postLogoutRedirectUri&&function(e,t){e.set("post_logout_redirect_uri",t)}(t,e.postLogoutRedirectUri),e.correlationId&&qi(t,e.correlationId),e.idTokenHint&&function(e,t){e.set("id_token_hint",t)}(t,e.idTokenHint),e.state&&Fi(t,e.state),e.logoutHint&&function(e,t){e.set("logout_hint",t)}(t,e.logoutHint),e.extraQueryParameters&&Vi(t,e.extraQueryParameters),this.config.authOptions.instanceAware&&ji(t),nt(t,this.config.authOptions.encodeExtraQueryParams,e.extraQueryParameters)}}function jc(e){const{skus:t,libraryName:r,libraryVersion:n,extensionName:o,extensionVersion:i}=e,s=new Map([[0,[r,n]],[2,[o,i]]]);let a=[];if(t?.length){if(a=t.split(","),a.length<4)return t}else a=Array.from({length:4},(()=>"|"));
2return s.forEach(((e,t)=>{2===e.length&&e[0]?.length&&e[1]?.length&&function(e){const{skuArr:t,index:r,skuName:n,skuVersion:o}=e;if(r>=t.length)return;t[r]=[n,o].join("|")}({skuArr:a,index:t,skuName:e[0],skuVersion:e[1]})})),a.join(",")}class Vc{constructor(e,t){this.cacheOutcome=o.Rv.NOT_APPLICABLE,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||o.YM.EMPTY_STRING,this.wrapperVer=e.wrapperVer||o.YM.EMPTY_STRING,this.telemetryCacheKey=o.gT.CACHE_KEY+o.LR.CACHE_KEY_SEPARATOR+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${o.gT.VALUE_SEPARATOR}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],r=this.getNativeBrokerErrorCode();r?.length&&t.push(`broker_error=${r}`);const n=t.join(o.gT.VALUE_SEPARATOR),i=[e,this.getRegionDiscoveryFields()].join(o.gT.VALUE_SEPARATOR);return[o.gT.SCHEMA_VERSION,i,n].join(o.gT.CATEGORY_SEPARATOR)}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=Vc.maxErrorsToSend(e),r=e.failedRequests.slice(0,2*t).join(o.gT.VALUE_SEPARATOR),n=e.errors.slice(0,t).join(o.gT.VALUE_SEPARATOR),i=e.errors.length,s=[i,t<i?o.gT.OVERFLOW_TRUE:o.gT.OVERFLOW_FALSE].join(o.gT.VALUE_SEPARATOR);return[o.gT.SCHEMA_VERSION,e.cacheHits,r,n,s].join(o.gT.CATEGORY_SEPARATOR)}cacheFailedRequest(e){const t=this.getLastRequests();t.errors.length>=o.gT.MAX_CACHED_ERRORS&&(t.failedRequests.shift(),t.failedRequests.shift(),t.errors.shift()),t.failedRequests.push(this.apiId,this.correlationId),e instanceof Error&&e&&e.toString()?e instanceof u?e.subError?t.errors.push(e.subError):e.errorCode?t.errors.push(e.errorCode):t.errors.push(e.toString()):t.errors.push(e.toString()):t.errors.push(o.gT.UNKNOWN_ERROR),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId),e.cacheHits}getLastRequests(){return this.cacheManager.getServerTelemetry(this.telemetryCacheKey)||{failedRequests:[],errors:[],cacheHits:0}}clearTelemetryCache(){const e=this.getLastRequests(),t=Vc.maxErrorsToSend(e);if(t===e.errors.length)this.cacheManager.removeItem(this.telemetryCacheKey,this.correlationId);else{const r={failedRequests:e.failedRequests.slice(2*t),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,r,this.correlationId)}}static maxErrorsToSend(e){let t,r=0,n=0;const i=e.errors.length;for(t=0;t<i;t++){const i=e.failedRequests[2*t]||o.YM.EMPTY_STRING,s=e.failedRequests[2*t+1]||o.YM.EMPTY_STRING,a=e.errors[t]||o.YM.EMPTY_STRING;if(n+=i.toString().length+s.toString().length+a.length+3,!(n<o.gT.MAX_LAST_HEADER_BYTES))break;r+=1}return r}getRegionDiscoveryFields(){const e=[];return e.push(this.regionUsed||o.YM.EMPTY_STRING),e.push(this.regionSource||o.YM.EMPTY_STRING),e.push(this.regionOutcome||o.YM.EMPTY_STRING),e.join(",")}updateRegionDiscoveryMetadata(e){this.regionUsed=e.region_used,this.regionSource=e.region_source,this.regionOutcome=e.region_outcome}setCacheOutcome(e){this.cacheOutcome=e}setNativeBrokerErrorCode(e){const t=this.getLastRequests();t.nativeBrokerErrorCode=e,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}getNativeBrokerErrorCode(){return this.getLastRequests().nativeBrokerErrorCode}clearNativeBrokerErrorCode(){const e=this.getLastRequests();delete e.nativeBrokerErrorCode,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId)}static makeExtraSkuString(e){return jc(e)}}class Wc{constructor(e,t,r,n,o,i,s,a,c){this.config=e,this.browserStorage=t,this.browserCrypto=r,this.networkClient=this.config.system.networkClient,this.eventHandler=o,this.navigationClient=i,this.platformAuthProvider=a,this.correlationId=c||ws(),this.logger=n.clone(yn,$s,this.correlationId),this.performanceClient=s}async clearCacheOnLogout(e,t){if(t)try{this.browserStorage.removeAccount(t,e),this.logger.verbose("Cleared cache items belonging to the account provided in the logout request.")}catch(e){this.logger.error("Account provided in logout request was not found. Local cache unchanged.")}else try{this.logger.verbose("No account provided in logout request, clearing all cache items.",this.correlationId),this.browserStorage.clear(e),await this.browserCrypto.clearKeystore()}catch(e){this.logger.error("Attempted to clear all MSAL cache items and failed. Local cache unchanged.")}}getRedirectUri(e){this.logger.verbose("getRedirectUri called");const t=e||this.config.auth.redirectUri;return it.getAbsoluteUrl(t,Hs())}initializeServerTelemetryManager(e,t){this.logger.verbose("initializeServerTelemetryManager called");const r={clientId:this.config.auth.clientId,correlationId:this.correlationId,apiId:e,forceRefresh:t||!1,wrapperSKU:this.browserStorage.getWrapperMetadata()[0],wrapperVer:this.browserStorage.getWrapperMetadata()[1]};return new Vc(r,this.browserStorage)}async getDiscoveredAuthority(e){const{account:t}=e,r=e.requestExtraQueryParameters&&e.requestExtraQueryParameters.hasOwnProperty("instance_aware")?e.requestExtraQueryParameters.instance_aware:void 0;this.performanceClient.addQueueMeasurement(Mt,this.correlationId);const n={protocolMode:this.config.auth.protocolMode,OIDCOptions:this.config.auth.OIDCOptions,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache},o=e.requestAuthority||this.config.auth.authority,i=r?.length?"true"===r:this.config.auth.instanceAware,s=t&&i?this.config.auth.authority.replace(it.getDomainFromUrl(o),t.environment):o,a=Na.generateAuthority(s,e.requestAzureCloudOptions||this.config.auth.azureCloudOptions),c=await fa(Dc,Ir,this.logger,this.performanceClient,this.correlationId)(a,this.config.system.networkClient,this.browserStorage,n,this.logger,this.correlationId,this.performanceClient);if(t&&!c.isAlias(t.environment))throw qe(Pe);return c}}async function Qc(e,t,r,n){r.addQueueMeasurement($t,e.correlationId);const i=e.authority||t.auth.authority,s=[...e&&e.scopes||[]],a={...e,correlationId:e.correlationId,authority:i,scopes:s};if(a.authenticationScheme){if(a.authenticationScheme===o.IO.SSH){if(!e.sshJwk)throw qe(Ee);if(!e.sshKid)throw qe(be)}n.verbose(`Authentication Scheme set to "${a.authenticationScheme}" as configured in Auth request`)}else a.authenticationScheme=o.IO.BEARER,n.verbose('Authentication Scheme wasn\'t explicitly set in request, defaulting to "Bearer" request');return t.cache.claimsBasedCachingEnabled&&e.claims&&!He.isEmptyObj(e.claims)&&(a.requestedClaimsHash=await Rs(e.claims)),a}
2async function Jc(e,t,r,n,o){n.addQueueMeasurement(jt,e.correlationId);const i=await fa(Qc,$t,o,n,e.correlationId)(e,r,n,o);return{...e,...i,account:t,forceRefresh:e.forceRefresh||!1}}function Xc(e,t){let r;const n=e.httpMethod;if(t===a){if(r=n||o.ym.POST,r!==o.ym.POST)throw qe(Me)}else r=n||o.ym.GET;if(e.authorizePostBodyParameters&&r!==o.ym.POST)throw qe(Ne);return r}class Zc extends Wc{initializeLogoutRequest(e){this.logger.verbose("initializeLogoutRequest called",e?.correlationId);const t={correlationId:this.correlationId||ws(),...e};if(e)if(e.logoutHint)this.logger.verbose("logoutHint has already been set in logoutRequest");else if(e.account){const r=this.getLogoutHintFromIdTokenClaims(e.account);r&&(this.logger.verbose("Setting logoutHint to login_hint ID Token Claim value for the account provided"),t.logoutHint=r)}else this.logger.verbose("logoutHint was not set and account was not passed into logout request, logoutHint will not be set");else this.logger.verbose("logoutHint will not be set since no logout request was configured");return e&&null===e.postLogoutRedirectUri?this.logger.verbose("postLogoutRedirectUri passed as null, not setting post logout redirect uri",t.correlationId):e&&e.postLogoutRedirectUri?(this.logger.verbose("Setting postLogoutRedirectUri to uri set on logout request",t.correlationId),t.postLogoutRedirectUri=it.getAbsoluteUrl(e.postLogoutRedirectUri,Hs())):null===this.config.auth.postLogoutRedirectUri?this.logger.verbose("postLogoutRedirectUri configured as null and no uri set on request, not passing post logout redirect",t.correlationId):this.config.auth.postLogoutRedirectUri?(this.logger.verbose("Setting postLogoutRedirectUri to configured uri",t.correlationId),t.postLogoutRedirectUri=it.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri,Hs())):(this.logger.verbose("Setting postLogoutRedirectUri to current page",t.correlationId),t.postLogoutRedirectUri=it.getAbsoluteUrl(Hs(),Hs())),t}getLogoutHintFromIdTokenClaims(e){const t=e.idTokenClaims;if(t){if(t.login_hint)return t.login_hint;this.logger.verbose("The ID Token Claims tied to the provided account do not contain a login_hint claim, logoutHint will not be added to logout request")}else this.logger.verbose("The provided account does not contain ID Token Claims, logoutHint will not be added to logout request");return null}async createAuthCodeClient(e){this.performanceClient.addQueueMeasurement(tr,this.correlationId);const t=await fa(this.getClientConfiguration.bind(this),rr,this.logger,this.performanceClient,this.correlationId)(e);return new $c(t,this.performanceClient)}async getClientConfiguration(e){const{serverTelemetryManager:t,requestAuthority:r,requestAzureCloudOptions:n,requestExtraQueryParameters:i,account:s}=e;this.performanceClient.addQueueMeasurement(rr,this.correlationId);const a=e.authority||await fa(this.getDiscoveredAuthority.bind(this),Mt,this.logger,this.performanceClient,this.correlationId)({requestAuthority:r,requestAzureCloudOptions:n,requestExtraQueryParameters:i,account:s}),c=this.config.system.loggerOptions;return{authOptions:{clientId:this.config.auth.clientId,authority:a,clientCapabilities:this.config.auth.clientCapabilities,redirectUri:this.config.auth.redirectUri},systemOptions:{tokenRenewalOffsetSeconds:this.config.system.tokenRenewalOffsetSeconds,preventCorsPreflight:!0},loggerOptions:{loggerCallback:c.loggerCallback,piiLoggingEnabled:c.piiLoggingEnabled,logLevel:c.logLevel,correlationId:this.correlationId},cacheOptions:{claimsBasedCachingEnabled:this.config.cache.claimsBasedCachingEnabled},cryptoInterface:this.browserCrypto,networkInterface:this.networkClient,storageInterface:this.browserStorage,serverTelemetryManager:t,libraryInfo:{sku:yn,version:$s,cpu:o.YM.EMPTY_STRING,os:o.YM.EMPTY_STRING},telemetry:this.config.telemetry}}async initializeAuthorizationRequest(e,t){this.performanceClient.addQueueMeasurement(nr,this.correlationId);const r=this.getRedirectUri(e.redirectUri),n={interactionType:t},i=xc.setRequestState(this.browserCrypto,e&&e.state||o.YM.EMPTY_STRING,n),s={...await fa(Qc,$t,this.logger,this.performanceClient,this.correlationId)({...e,correlationId:this.correlationId},this.config,this.performanceClient,this.logger),redirectUri:r,state:i,nonce:e.nonce||ws(),responseMode:this.config.auth.OIDCOptions.serverResponseType},a={...s,httpMethod:Xc(s,this.config.auth.protocolMode)};if(e.loginHint||e.sid)return a;const c=e.account||this.browserStorage.getActiveAccount(this.correlationId);return c&&(this.logger.verbose("Setting validated request account",this.correlationId),this.logger.verbosePii(`Setting validated request account: ${c.homeAccountId}`,this.correlationId),a.account=c),a}}function el(e,t,r){const n=rt(e);if(!n)throw tt(e)?(r.error(`A ${t} is present in the iframe but it does not contain known properties. It's likely that the ${t} has been replaced by code running on the redirectUri page.`),r.errorPii(`The ${t} detected is: ${e}`),di(Co)):(r.error(`The request has returned to the redirectUri but a ${t} is not present. It's likely that the ${t} has been removed or the page has been redirected by code running on the redirectUri page.`),di(fo));return n}function tl(e,t,r){if(!e.state)throw di(yo);const n=function(e,t){if(!t)return null;try{return xc.parseRequestState(e,t).libraryState.meta}catch(e){throw ae(v)}}(t,e.state);if(!n)throw di(Io);if(n.interactionType!==r)throw di(wo)}function rl(e,t,r,n){const i=t.correlationId,s=new Map;Oi(s,t.embeddedClientId||t.extraQueryParameters?.[Ci]||e.clientId);if(Ri(s,[...t.scopes||[],...t.extraScopesToConsent||[]],!0,e.authority.options.OIDCOptions?.defaultScopes),Pi(s,t.redirectUri),qi(s,i),function(e,t){e.set("response_mode",t||o.p.QUERY)}(s,t.responseMode),$i(s),t.prompt&&(!function(e,t){e.set("prompt",t)}(s,t.prompt),n?.addFields({prompt:t.prompt},i)),t.domainHint&&(!function(e,t){e.set("domain_hint",t)}(s,t.domainHint),n?.addFields({domainHintFromRequest:!0},i)),t.prompt!==o._M.SELECT_ACCOUNT)if(t.sid&&t.prompt===o._M.NONE)r.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request"),Di(s,t.sid),n?.addFields({sidFromRequest:!0},i);else if(t.account){const e=(a=t.account,a.idTokenClaims?.sid||null);let c=function(e){return e.loginHint||e.idTokenClaims?.login_hint||null}(t.account);if(c&&t.domainHint&&(r.warning('AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint'),c=null),c){r.verbose("createAuthCodeUrlQueryString: login_hint claim present on account"),Mi(s,c),n?.addFields({loginHintFromClaim:!0},i);try{Li(s,Be(t.account.homeAccountId))}catch(e){r.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(e&&t.prompt===o._M.NONE){r.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account"),Di(s,e),n?.addFields({sidFromClaim:!0},i);try{Li(s,Be(t.account.homeAccountId))}catch(e){r.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(t.loginHint)r.verbose("createAuthCodeUrlQueryString: Adding login_hint from request"),Mi(s,t.loginHint),Ni(s,t.loginHint),n?.addFields({loginHintFromRequest:!0},i);else if(t.account.username){r.verbose("createAuthCodeUrlQueryString: Adding login_hint from account"),Mi(s,t.account.username),n?.addFields({loginHintFromUpn:!0},i);try{Li(s,Be(t.account.homeAccountId))}catch(e){r.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}}else t.loginHint&&(r.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request"),Mi(s,t.loginHint),Ni(s,t.loginHint),n?.addFields({loginHintFromRequest:!0},i));else r.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints");var a;return t.nonce&&function(e,t){e.set("nonce",t)}(s,t.nonce),t.state&&Fi(s,t.state),(t.claims||e.clientCapabilities&&e.clientCapabilities.length>0)&&Ui(s,t.claims,e.clientCapabilities),t.embeddedClientId&&es(s,e.clientId,e.redirectUri),!e.instanceAware||t.extraQueryParameters&&Object.keys(t.extraQueryParameters).includes(bi)||ji(s),s}function nl(e,t,r,n){const o=nt(t,r,n);return it.appendQueryString(e.authorizationEndpoint,o)}function ol(e,t){if(!e.state||!t)throw e.state?ae(_,"Cached State"):ae(_,"Server State");let r,n;try{r=decodeURIComponent(e.state)}catch(t){throw ae(v,e.state)}try{n=decodeURIComponent(t)}catch(t){throw ae(v,e.state)}if(r!==n)throw ae(T);
2if(e.error||e.error_description||e.suberror){const t=function(e){const t="code=",r=e.error_uri?.lastIndexOf(t);return r&&r>=0?e.error_uri?.substring(r+t.length):void 0}(e);if(za(e.error,e.error_description,e.suberror))throw new Ga(e.error||"",e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.correlation_id||"",e.claims||"",t);throw new Uc(e.error||"",e.error_description,e.suberror,t)}}class il{constructor(e,t,r,n,o){this.authModule=e,this.browserStorage=t,this.authCodeRequest=r,this.logger=n,this.performanceClient=o}async handleCodeResponse(e,t){let r;this.performanceClient.addQueueMeasurement(ar,t.correlationId);try{r=function(e,t){if(ol(e,t),!e.code)throw ae(W);return e}(e,t.state)}catch(e){throw e instanceof Uc&&e.subError===_o?di(_o):e}return fa(this.handleCodeResponseFromServer.bind(this),sr,this.logger,this.performanceClient,t.correlationId)(r,t)}async handleCodeResponseFromServer(e,t,r=!0){if(this.performanceClient.addQueueMeasurement(sr,t.correlationId),this.logger.trace("InteractionHandler.handleCodeResponseFromServer called"),this.authCodeRequest.code=e.code,e.cloud_instance_host_name&&await fa(this.authModule.updateAuthority.bind(this.authModule),dr,this.logger,this.performanceClient,t.correlationId)(e.cloud_instance_host_name,t.correlationId),r&&(e.nonce=t.nonce||void 0),e.state=t.state,e.client_info)this.authCodeRequest.clientInfo=e.client_info;else{const e=this.createCcsCredentials(t);e&&(this.authCodeRequest.ccsCredential=e)}return await fa(this.authModule.acquireToken.bind(this.authModule),ur,this.logger,this.performanceClient,t.correlationId)(this.authCodeRequest,e)}createCcsCredentials(e){return e.account?{credential:e.account.homeAccountId,type:Nc}:e.loginHint?{credential:e.loginHint,type:Lc}:null}}const sl="user_switch",al={[sl]:"User attempted to switch accounts in the native broker, which is not allowed. All new accounts must sign-in through the standard web flow first, please try again."};class cl extends u{constructor(e,t,r){super(e,t),Object.setPrototypeOf(this,cl.prototype),this.name="NativeAuthError",this.ext=r}}function ll(e){if(e.ext&&e.ext.status&&"DISABLED"===e.ext.status)return!0;if(e.ext&&e.ext.error&&-2147186943===e.ext.error)return!0;switch(e.errorCode){case"ContentError":case"PageException":return!0;default:return!1}}function hl(e,t,r){if(r&&r.status)switch(r.status){case"ACCOUNT_UNAVAILABLE":return Ya(Ua);case"USER_INTERACTION_REQUIRED":return new Ga(e,t);case"USER_CANCEL":return di(_o);case"NO_NETWORK":return di(Fo);case"UX_NOT_ALLOWED":return Ya(Ha)}return new cl(e,al[e]||t,r)}class dl extends Hc{constructor(e,t){super(e,t)}async acquireCachedToken(e){this.performanceClient?.addQueueMeasurement(Gt,e.correlationId);let t=o.Rv.NOT_APPLICABLE;if(e.forceRefresh||!this.config.cacheOptions.claimsBasedCachingEnabled&&!He.isEmptyObj(e.claims))throw this.setCacheOutcome(o.Rv.FORCE_REFRESH_OR_CLAIMS,e.correlationId),ae($);if(!e.account)throw ae(H);const r=e.account.tenantId||function(e){const t=new it(e).getUrlComponents(),r=t.PathSegments.slice(-1)[0]?.toLowerCase();switch(r){case o.v2.COMMON:case o.v2.ORGANIZATIONS:case o.v2.CONSUMERS:return;default:return r}}(e.authority),n=this.cacheManager.getTokenKeys(),i=this.cacheManager.getAccessToken(e.account,e,n,r);if(!i)throw this.setCacheOutcome(o.Rv.NO_CACHED_ACCESS_TOKEN,e.correlationId),ae($);if(s=i.cachedAt,Number(s)>Ca()||Aa(i.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(o.Rv.CACHED_ACCESS_TOKEN_EXPIRED,e.correlationId),ae($);var s;i.refreshOn&&Aa(i.refreshOn,0)&&(t=o.Rv.PROACTIVELY_REFRESHED);const a=e.authority||this.authority.getPreferredCache(),c={account:this.cacheManager.getAccount(this.cacheManager.generateAccountKey(e.account),e.correlationId),accessToken:i,idToken:this.cacheManager.getIdToken(e.account,e.correlationId,n,r,this.performanceClient),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(a)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await fa(this.generateResultFromCacheRecord.bind(this),zt,this.logger,this.performanceClient,e.correlationId)(c,e),t]}
2setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==o.Rv.NOT_APPLICABLE&&this.logger.info(`Token refresh is required due to cache outcome: ${e}`)}async generateResultFromCacheRecord(e,t){let r;if(this.performanceClient?.addQueueMeasurement(zt,t.correlationId),e.idToken&&(r=Je(e.idToken.secret,this.config.cryptoInterface.base64Decode)),t.maxAge||0===t.maxAge){const e=r?.auth_time;if(!e)throw ae(b);Ze(e,t.maxAge)}return Gc.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,r)}}class ul extends Zc{async acquireToken(e){this.performanceClient.addQueueMeasurement(kt,e.correlationId);const t=this.initializeServerTelemetryManager(Qn),r=await fa(this.getClientConfiguration.bind(this),rr,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,account:e.account}),n=new dl(r,this.performanceClient);this.logger.verbose("Silent auth client created");try{const t=(await fa(n.acquireCachedToken.bind(n),Gt,this.logger,this.performanceClient,e.correlationId)(e))[0];return this.performanceClient.addFields({fromCache:!0},e.correlationId),t}catch(e){throw e instanceof hi&&e.errorCode===Yo&&this.logger.verbose("Signing keypair for bound access token not found. Refreshing bound access token and generating a new crypto keypair."),e}}logout(e){this.logger.verbose("logoutRedirect called");const t=this.initializeLogoutRequest(e);return this.clearCacheOnLogout(t.correlationId,t?.account)}}class gl extends Wc{constructor(e,t,r,n,o,i,s,a,c,l,h,d){super(e,t,r,n,o,i,a,c,d),this.apiId=s,this.accountId=l,this.platformAuthProvider=c,this.nativeStorageManager=h,this.silentCacheClient=new ul(e,this.nativeStorageManager,r,n,o,i,a,c,d);const u=this.platformAuthProvider.getExtensionName();this.skus=Vc.makeExtraSkuString({libraryName:yn,libraryVersion:$s,extensionName:u,extensionVersion:this.platformAuthProvider.getExtensionVersion()})}addRequestSKUs(e){e.extraParameters={...e.extraParameters,[Ti]:this.skus}}async acquireToken(e,t){this.performanceClient.addQueueMeasurement(Nt,this.correlationId),this.logger.trace("NativeInteractionClient - acquireToken called.");const r=this.performanceClient.startMeasurement(Nt,this.correlationId),n=Ca(),o=this.initializeServerTelemetryManager(this.apiId);try{const i=await this.initializeNativeRequest(e);try{const e=await this.acquireTokensFromCache(this.accountId,i);return r.end({success:!0,isNativeBroker:!1,fromCache:!0}),e}catch(e){if(t===oo)throw this.logger.info("MSAL internal Cache does not contain tokens, return error as per cache policy"),r.end({success:!1,brokerErrorCode:"cache_request_failed"}),e;this.logger.info("MSAL internal Cache does not contain tokens, proceed to make a native call")}const s=await this.platformAuthProvider.sendMessage(i);return await this.handleNativeResponse(s,i,n).then((e=>(r.end({success:!0,isNativeBroker:!0,requestId:e.requestId}),o.clearNativeBrokerErrorCode(),e))).catch((e=>{throw r.end({success:!1,errorCode:e.errorCode,subErrorCode:e.subError}),e}))}catch(e){throw e instanceof cl&&o.setNativeBrokerErrorCode(e.errorCode),r.end({success:!1}),e}}createSilentCacheRequest(e,t){return{authority:e.authority,correlationId:this.correlationId,scopes:xe.fromString(e.scope).asArray(),account:t,forceRefresh:!1}}async acquireTokensFromCache(e,t){if(!e)throw this.logger.warning("NativeInteractionClient:acquireTokensFromCache - No nativeAccountId provided"),ae(B);const r=this.browserStorage.getBaseAccountInfo({nativeAccountId:e},this.correlationId);if(!r)throw ae(B);try{const e=this.createSilentCacheRequest(t,r),n=await this.silentCacheClient.acquireToken(e),o={...r,idTokenClaims:n?.idTokenClaims,idToken:n?.idToken};return{...n,account:o}}catch(e){throw e}}async acquireTokenRedirect(e,t){this.logger.trace("NativeInteractionClient - acquireTokenRedirect called.");const{...r}=e;delete r.onRedirectNavigate;const n=await this.initializeNativeRequest(r);try{await this.platformAuthProvider.sendMessage(n)}catch(e){if(e instanceof cl){if(this.initializeServerTelemetryManager(this.apiId).setNativeBrokerErrorCode(e.errorCode),ll(e))throw e}}this.browserStorage.setTemporaryCache(Kn,JSON.stringify(n),!0);const o={apiId:Yn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},i=this.config.auth.navigateToLoginRequestUrl?window.location.href:this.getRedirectUri(e.redirectUri);t.end({success:!0}),await this.navigationClient.navigateExternal(i,o)}async handleRedirectPromise(e,t){if(this.logger.trace("NativeInteractionClient - handleRedirectPromise called."),!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null."),null;const r=this.browserStorage.getCachedNativeRequest();if(!r)return this.logger.verbose("NativeInteractionClient - handleRedirectPromise called but there is no cached request, returning null."),e&&t&&e?.addFields({errorCode:"no_cached_request"},t),null;const{prompt:n,...o}=r;n&&this.logger.verbose("NativeInteractionClient - handleRedirectPromise called and prompt was included in the original request, remov
2ing prompt from cached request to prevent second interaction with native broker window."),this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Kn));const i=Ca();try{this.logger.verbose("NativeInteractionClient - handleRedirectPromise sending message to native broker.");const t=await this.platformAuthProvider.sendMessage(o),r=await this.handleNativeResponse(t,o,i);return this.initializeServerTelemetryManager(this.apiId).clearNativeBrokerErrorCode(),e&&this.correlationId&&this.performanceClient.addFields({isNativeBroker:!0},this.correlationId),r}catch(e){throw e}}logout(){return this.logger.trace("NativeInteractionClient - logout called."),Promise.reject("Logout not implemented yet")}async handleNativeResponse(e,t,r){this.logger.trace("NativeInteractionClient - handleNativeResponse called.");const n=Je(e.id_token,is),o=this.createHomeAccountIdentifier(e,n),i=this.browserStorage.getAccountInfoFilteredBy({nativeAccountId:t.accountId},this.correlationId)?.homeAccountId;if(t.extraParameters?.child_client_id&&e.account.id!==t.accountId)this.logger.info("handleNativeServerResponse: Double broker flow detected, ignoring accountId mismatch");else if(o!==i&&e.account.id!==t.accountId)throw hl(sl);const s=await this.getDiscoveredAuthority({requestAuthority:t.authority}),a=zc(this.browserStorage,s,o,is,this.correlationId,n,e.client_info,void 0,n.tid,void 0,e.account.id,this.logger);e.expires_in=Number(e.expires_in);const c=await this.generateAuthenticationResult(e,t,n,a,s.canonicalAuthority,r);return await this.cacheAccount(a,this.correlationId,Xe(n)),await this.cacheNativeTokens(e,t,o,n,e.access_token,c.tenantId,r),c}createHomeAccountIdentifier(e,t){return Qe.generateHomeAccountId(e.client_info||o.YM.EMPTY_STRING,Ye,this.logger,this.browserCrypto,t)}generateScopes(e,t){return t?xe.fromString(t):xe.fromString(e)}async generatePopAccessToken(e,t){if(t.tokenType===o.IO.POP&&t.signPopToken){if(e.shr)return this.logger.trace("handleNativeServerResponse: SHR is enabled in native layer"),e.shr;const r=new Bc(this.browserCrypto),n={resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,shrNonce:t.shrNonce};if(!t.keyId)throw ae(X);return r.signPopToken(e.access_token,t.keyId,n)}return e.access_token}async generateAuthenticationResult(e,t,r,n,i,s){const a=this.addTelemetryFromNativeResponse(e.properties.MATS),c=this.generateScopes(t.scope,e.scope),l=e.account.properties||{},h=l.UID||r.oid||r.sub||o.YM.EMPTY_STRING,d=l.TenantId||r.tid||o.YM.EMPTY_STRING,u=ze(Qe.getAccountInfo(n),void 0,r,e.id_token);
2u.nativeAccountId!==e.account.id&&(u.nativeAccountId=e.account.id);const g=await this.generatePopAccessToken(e,t),p=t.tokenType===o.IO.POP?o.IO.POP:o.IO.BEARER;return{authority:i,uniqueId:h,tenantId:d,scopes:c.asArray(),account:u,idToken:e.id_token,idTokenClaims:r,accessToken:g,fromCache:!!a&&this.isResponseFromCache(a),expiresOn:wa(s+e.expires_in),tokenType:p,correlationId:this.correlationId,state:e.state,fromNativeBroker:!0}}async cacheAccount(e,t,r){await this.browserStorage.setAccount(e,this.correlationId,r),this.browserStorage.removeAccountContext(Qe.getAccountInfo(e),t)}cacheNativeTokens(e,t,r,n,i,s,a){const c=Ta(r,t.authority,e.id_token||"",t.clientId,n.tid||""),l=a+(t.tokenType===o.IO.POP?o.YM.SHR_NONCE_VALIDITY:("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0),h=this.generateScopes(e.scope,t.scope),d={idToken:c,accessToken:_a(r,t.authority,i,t.clientId,n.tid||s,h.printScopes(),l,0,is,void 0,t.tokenType,void 0,t.keyId)};return this.nativeStorageManager.saveCacheRecord(d,this.correlationId,Xe(n),t.storeInCache)}getExpiresInValue(e,t){return e===o.IO.POP?o.YM.SHR_NONCE_VALIDITY:("string"==typeof t?parseInt(t,10):t)||0}addTelemetryFromNativeResponse(e){const t=this.getMATSFromResponse(e);return t?(this.performanceClient.addFields({extensionId:this.platformAuthProvider.getExtensionId(),extensionVersion:this.platformAuthProvider.getExtensionVersion(),matsBrokerVersion:t.broker_version,matsAccountJoinOnStart:t.account_join_on_start,matsAccountJoinOnEnd:t.account_join_on_end,matsDeviceJoin:t.device_join,matsPromptBehavior:t.prompt_behavior,matsApiErrorCode:t.api_error_code,matsUiVisible:t.ui_visible,matsSilentCode:t.silent_code,matsSilentBiSubCode:t.silent_bi_sub_code,matsSilentMessage:t.silent_message,matsSilentStatus:t.silent_status,matsHttpStatus:t.http_status,matsHttpEventCount:t.http_event_count},this.correlationId),t):null}getMATSFromResponse(e){if(e)try{return JSON.parse(e)}catch(e){this.logger.error("NativeInteractionClient - Error parsing MATS telemetry, returning null instead")}return null}isResponseFromCache(e){return void 0===e.is_cached?(this.logger.verbose("NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false."),!1):!!e.is_cached}async initializeNativeRequest(e){this.logger.trace("NativeInteractionClient - initializeNativeRequest called");const t=await this.getCanonicalAuthority(e),{scopes:r,...n}=e,i=new xe(r||[]);i.appendScopes(o.aZ);const s={...n,accountId:this.accountId,clientId:this.config.auth.clientId,authority:t.urlString,scope:i.printScopes(),redirectUri:this.getRedirectUri(e.redirectUri),prompt:this.getPrompt(e.prompt),correlationId:this.correlationId,tokenType:e.authenticationScheme,windowTitleSubstring:document.title,extraParameters:{...e.extraQueryParameters,...e.tokenQueryParameters},extendedExpiryToken:!1,keyId:e.popKid};if(s.signPopToken&&e.popKid)throw di(ni);if(this.handleExtraBrokerParams(s),s.extraParameters=s.extraParameters||{},s.extraParameters.telemetry=wn,e.authenticationScheme===o.IO.POP){const t={resourceRequestUri:e.resourceRequestUri,resourceRequestMethod:e.resourceRequestMethod,shrClaims:e.shrClaims,shrNonce:e.shrNonce},r=new Bc(this.browserCrypto);let n;if(s.keyId)n=this.browserCrypto.base64UrlEncode(JSON.stringify({kid:s.keyId})),s.signPopToken=!1;else{const e=await fa(r.generateCnf.bind(r),mr,this.logger,this.performanceClient,this.correlationId)(t,this.logger);
2n=e.reqCnfString,s.keyId=e.kid,s.signPopToken=!0}s.reqCnf=n}return this.addRequestSKUs(s),s}async getCanonicalAuthority(e){const t=e.authority||this.config.auth.authority;e.account&&await this.getDiscoveredAuthority({requestAuthority:t,requestAzureCloudOptions:e.azureCloudOptions,account:e.account});const r=new it(t);return r.validateAsUri(),r}getPrompt(e){switch(this.apiId){case jn:case Qn:return this.logger.trace("initializeNativeRequest: silent request sets prompt to none"),o._M.NONE}if(e)switch(e){case o._M.NONE:case o._M.CONSENT:case o._M.LOGIN:case o._M.SELECT_ACCOUNT:return this.logger.trace("initializeNativeRequest: prompt is compatible with native flow"),e;default:throw this.logger.trace(`initializeNativeRequest: prompt = ${e} is not compatible with native flow`),di(ti)}else this.logger.trace("initializeNativeRequest: prompt was not provided")}handleExtraBrokerParams(e){const t=e.extraParameters&&e.extraParameters.hasOwnProperty(_i)&&e.extraParameters.hasOwnProperty(Ei)&&e.extraParameters.hasOwnProperty(Ci);if(!e.embeddedClientId&&!t)return;let r="";const n=e.redirectUri;e.embeddedClientId?(e.redirectUri=this.config.auth.redirectUri,r=e.embeddedClientId):e.extraParameters&&(e.redirectUri=e.extraParameters[Ei],r=e.extraParameters[Ci]),e.extraParameters={child_client_id:r,child_redirect_uri:n},this.performanceClient?.addFields({embeddedClientId:r,embeddedRedirectUri:n},this.correlationId)}}async function pl(e,t,r,n,i){const a=rl({...e.auth,authority:t},r,n,i);if(Hi(a,{sku:yn,version:$s,os:"",cpu:""}),e.auth.protocolMode!==s&&xi(a,e.telemetry.application),r.platformBroker&&(function(e){e.set("nativebroker","1")}(a),i.addFields({isPlatformAuthorizeRequest:!0},r.correlationId),r.authenticationScheme===o.IO.POP)){const e=new ga(n,i),t=new Bc(e);let o;if(r.popKid)o=e.encodeKid(r.popKid);else{o=(await fa(t.generateCnf.bind(t),mr,n,i,r.correlationId)(r,n)).reqCnfString}Qi(a,o)}return ki(a,r.correlationId,i),a}async function ml(e,t,r,n,i){if(!r.codeChallenge)throw qe(Ae);const s=await fa(pl,ir,n,i,r.correlationId)(e,t,r,n,i);return Si(s,o.RX.CODE),Bi(s,r.codeChallenge,o.YM.S256_CODE_CHALLENGE_METHOD),Vi(s,r.extraQueryParameters||{}),nl(t,s,e.auth.encodeExtraQueryParams,r.extraQueryParameters)}async function fl(e,t,r,n,i,s){if(!n.earJwk)throw di(uo);const a=await pl(t,r,n,i,s);Si(a,o.RX.IDTOKEN_TOKEN_REFRESHTOKEN),function(e,t){e.set("ear_jwk",encodeURIComponent(t)),e.set("ear_jwe_crypto","eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0")}(a,n.earJwk),Bi(a,n.codeChallenge,o.YM.S256_CODE_CHALLENGE_METHOD);const c=new Map;Vi(c,n.extraQueryParameters||{});return Cl(e,nl(r,c,t.auth.encodeExtraQueryParams,n.extraQueryParameters),a)}async function yl(e,t,r,n,i,s){const a=await pl(t,r,n,i,s);Si(a,o.RX.CODE),Bi(a,n.codeChallenge,n.codeChallengeMethod||o.YM.S256_CODE_CHALLENGE_METHOD),function(e,t){Object.entries(t).forEach((([t,r])=>{r&&e.set(t,r)}))}(a,n.authorizePostBodyParameters||{});const c=new Map;Vi(c,n.extraQueryParameters||{});return Cl(e,nl(r,c,t.auth.encodeExtraQueryParams,n.extraQueryParameters),a)}function Cl(e,t,r){const n=e.createElement("form");return n.method="post",n.action=t,r.forEach(((t,r)=>{const o=e.createElement("input");o.hidden=!0,o.name=r,o.value=t,n.appendChild(o)})),e.body.appendChild(n),n}async function Il(e,t,r,n,o,i,s,a,c,l){if(a.verbose("Account id found, calling WAM for token"),!l)throw di(Zo);const h=new ga(a,c),d=new gl(n,o,h,a,s,n.system.navigationClient,r,c,l,t,i,e.correlationId),{userRequestState:u}=xc.parseRequestState(h,e.state);return fa(d.acquireToken.bind(d),Nt,a,c,e.correlationId)({...e,state:u,prompt:void 0})}async function wl(e,t,r,n,o,i,s,a,c,l,h,d){if(qc.removeThrottle(s,o.auth.clientId,e),t.accountId)return fa(Il,lr,l,h,e.correlationId)(e,t.accountId,n,o,s,a,c,l,h,d);const u={...e,code:t.code||"",codeVerifier:r},g=new il(i,s,u,l,h);return await fa(g.handleCodeResponse.bind(g),ar,l,h,e.correlationId)(t,e)}async function Al(e,t,r,n,o,i,s,a,c,l,h){if(qc.removeThrottle(i,n.auth.clientId,e),ol(t,e.state),!t.ear_jwe)throw di(go);if(!e.earJwk)throw di(uo);const d=JSON.parse(await fa(Ts,Jr,c,l,e.correlationId)(e.earJwk,t.ear_jwe));if(d.accountId)return fa(Il,lr,c,l,e.correlationId)(e,d.accountId,r,n,i,s,a,c,l,h);const u=new Gc(n.auth.clientId,i,new ga(c,l),c,null,null,l);u.validateTokenResponse(d);const g={code:"",state:e.state,nonce:e.nonce,client_info:d.client_info,cloud_graph_host_name:d.cloud_graph_host_name,cloud_instance_host_name:d.cloud_instance_host_name,cloud_instance_name:d.cloud_instance_name,msgra
2ph_host:d.msgraph_host};return await fa(u.handleServerTokenResponse.bind(u),yr,c,l,e.correlationId)(d,o,Ca(),e,g,void 0,void 0,void 0,void 0)}async function vl(e,t,r){e.addQueueMeasurement(xr,r);const n=ma(Tl,Fr,t,e,r)(e,t,r);return{verifier:n,challenge:await fa(_l,Br,t,e,r)(n,e,t,r)}}function Tl(e,t,r){try{const n=new Uint8Array(32);ma(Cs,Gr,t,e,r)(n);return rs(n)}catch(e){throw di(ho)}}async function _l(e,t,r,n){t.addQueueMeasurement(Br,n);try{const o=await fa(ys,Kr,r,t,n)(e,t,n);return rs(new Uint8Array(o))}catch(e){throw di(ho)}}class El{constructor(e,t,r,n){this.logger=e,this.handshakeTimeoutMs=t,this.extensionId=n,this.resolvers=new Map,this.handshakeResolvers=new Map,this.messageChannel=new MessageChannel,this.windowListener=this.onWindowMessage.bind(this),this.performanceClient=r,this.handshakeEvent=r.startMeasurement(Mr),this.platformAuthType=En}async sendMessage(e){this.logger.trace(this.platformAuthType+" - sendMessage called.");const t={method:Sn,request:e},r={channel:Cn,extensionId:this.extensionId,responseId:ws(),body:t};this.logger.trace(this.platformAuthType+" - Sending request to browser extension"),this.logger.tracePii(this.platformAuthType+` - Sending request to browser extension: ${JSON.stringify(r)}`),this.messageChannel.port1.postMessage(r);const n=await new Promise(((e,t)=>{this.resolvers.set(r.responseId,{resolve:e,reject:t})}));return this.validatePlatformBrokerResponse(n)}static async createProvider(e,t,r){e.trace("PlatformAuthExtensionHandler - createProvider called.");try{const n=new El(e,t,r,In);return await n.sendHandshakeRequest(),n}catch(n){const o=new El(e,t,r);return await o.sendHandshakeRequest(),o}}async sendHandshakeRequest(){this.logger.trace(this.platformAuthType+" - sendHandshakeRequest called."),window.addEventListener("message",this.windowListener,!1);const e={channel:Cn,extensionId:this.extensionId,responseId:ws(),body:{method:bn}};return this.handshakeEvent.add({extensionId:this.extensionId,extensionHandshakeTimeoutMs:this.handshakeTimeoutMs}),this.messageChannel.port1.onmessage=e=>{this.onChannelMessage(e)},window.postMessage(e,window.origin,[this.messageChannel.port2]),new Promise(((t,r)=>{this.handshakeResolvers.set(e.responseId,{resolve:t,reject:r}),this.timeoutId=window.setTimeout((()=>{window.removeEventListener("message",this.windowListener,!1),this.messageChannel.port1.close(),this.messageChannel.port2.close(),this.handshakeEvent.end({extensionHandshakeTimedOut:!0,success:!1}),r(di(Jo)),this.handshakeResolvers.delete(e.responseId)}),this.handshakeTimeoutMs)}))}onWindowMessage(e){if(this.logger.trace(this.platformAuthType+" - onWindowMessage called"),e.source!==window)return;const t=e.data;if(t.channel&&t.channel===Cn&&(!t.extensionId||t.extensionId===this.extensionId)&&t.body.method===bn){const e=this.handshakeResolvers.get(t.responseId);if(!e)return void this.logger.trace(this.platformAuthType+`.onWindowMessage - resolver can't be found for request ${t.responseId}`);this.logger.verbose(t.extensionId?`Extension with id: ${t.extensionId} not installed`:"No extension installed"),clearTimeout(this.timeoutId),this.messageChannel.port1.close(),this.messageChannel.port2.close(),window.removeEventListener("message",this.windowListener,!1),this.handshakeEvent.end({success:!1,extensionInstalled:!1}),e.reject(di(Xo))}}onChannelMessage(e){this.logger.trace(this.platformAuthType+" - onChannelMessage called.");const t=e.data,r=this.resolvers.get(t.responseId),n=this.handshakeResolvers.get(t.responseId);try{const e=t.body.method;if(e===Rn){if(!r)return;const e=t.body.response;if(this.logger.trace(this.platformAuthType+" - Received response from browser extension"),this.logger.tracePii(this.platformAuthType+` - Received response from browser extension: ${JSON.stringify(e)}`),"Success"!==e.status)r.reject(hl(e.code,e.description,e.ext));else{if(!e.result)throw g(l,"Event does not contain result.");e.result.code&&e.result.description?r.reject(hl(e.result.code,e.result.description,e.result.ext)):r.resolve(e.result)}this.resolvers.delete(t.responseId)}else if(e===kn){if(!n)return void this.logger.trace(this.platformAuthType+`.onChannelMessage - resolver can't be found for request ${t.responseId}`);clearTimeout(this.timeoutId),window.removeEventListener("message",this.windowListener,!1),this.extensionId=t.extensionId,this.extensionVersion=t.body.version,this.logger.verbose(this.platformAuthType+` - Received HandshakeResponse from extension: ${this.extensionId}`),this.handshakeEvent.end({extensionInstalled:!0,success:!0}),n.resolve(),this.handshakeResolvers.delete(t.responseId)}}catch(t){this.logger.error("Error parsing response from WAM Extension"),this.logger.errorPii(`Error parsing response from WAM Extension: ${t}`),this.logger.errorPii(`Unable to parse ${e}`),r?r.reject(t):n&&n.reject(t)}}validatePlatformBrokerResponse(e){if(e.hasOwnProperty("access_token")&&e.hasOwnProperty("id_token")&&e.hasOwnProperty("client_info")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scope")&&e.hasOwnProperty("expires_in"))return e;throw g(l,"Response missing expected properties.")}getExtensionId(){return this.extensionId}getExtensionVersion(){return this.extensionVersion}getExtensionName(){return this.getExtensionId()===In?"chrome":this.getExtensionId()?.length?"unknown":void 0}}class bl{constructor(e,t,r){this.logger=e,this.performanceClient=t,this.correlationId=r,this.platformAuthType=_n}static async createProvider(e,t,r){if(e.trace("PlatformAuthDOMHandler: createProvider called"),window.navigator?.platformAuthentication){const n=await window.navigator.platformAuthentication.getSupportedContracts(An);if(n?.includes(Tn))return e.trace("Platform auth api available in DOM"),new bl(e,t,r)}}getExtensionId(){return An}getExtensionVersion(){return""}getExtensionName(){return vn}async sendMessage(e){this.logger.trace(this.platformAuthType+" - Sending request to browser DOM API");try{const t=this.initializePlatformDOMRequest(e),r=await window.navigator.platformAuthentication.executeGetToken(t);return this.validatePlatformBrokerResponse(r)}catch(e){throw this.logger.error(this.platformAuthType+" - executeGetToken DOM API error"),e}}initializePlatformDOMRequest(e){this.logger.trace(this.platformAuthType+" - initializeNativeDOMRequest called");const{accountId:t,clientId:r,authority:n,scope:o,redirectUri:i,correlationId:s,state:a,storeInCache:c,embeddedClientId:l,extraParameters:h,...d}=e,u=this.getDOMExtraParams(d);return{accountId:t,brokerId:this.getExtensionId(),authority:n,clientId:r,correlationId:s||this.correlationId,extraParameters:{...h,...u},isSecurityTokenService:!1,redirectUri:i,scope:o,state:a,storeInCache:c,embeddedClientId:l}}validatePlatformBrokerResponse(e){if(e.hasOwnProperty("isSuccess")){if(e.hasOwnProperty("accessToken")&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("clientInfo")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scopes")&&e.hasOwnProperty("expiresIn"))return this.logger.trace(this.platformAuthType+" - platform broker returned successful and valid response"),this.convertToPlatformBrokerResponse(e);if(e.hasOwnProperty("error")){const t=e;if(!1===t.isSuccess&&t.error&&t.error.code)throw this.logger.trace(this.platformAuthType+" - platform broker returned error response"),hl(t.error.code,t.error.description,{error:parseInt(t.error.errorCode),protocol_error:t.error.protocolError,status:t.error.status,properties:t.error.properties})}}throw g(l,"Response missing expected properties.")}convertToPlatformBrokerResponse(e){this.logger.trace(this.platformAuthType+" - convertToNativeResponse called");return{access_token:e.accessToken,id_token:e.idToken,client_info:e.clientInfo,account:e.account,expires_in:e.expires
2In,scope:e.scopes,state:e.state||"",properties:e.properties||{},extendedLifetimeToken:e.extendedLifetimeToken??!1,shr:e.proofOfPossessionPayload}}getDOMExtraParams(e){return{...Object.entries(e).reduce(((e,[t,r])=>(e[t]=String(r),e)),{})}}}async function kl(e,t,r,n,o){let i;e.trace("getPlatformAuthProvider called",r),e.trace("Has client allowed platform auth via DOM API: "+o);try{o&&(i=await bl.createProvider(e,t,r)),i||(e.trace("Platform auth via DOM API not available, checking for extension"),i=await El.createProvider(e,n||2e3,t))}catch(t){e.trace("Platform auth not available",t)}return i}function Sl(e,t,r,n){if(t.trace("isPlatformAuthAllowed called"),!e.system.allowPlatformBroker&&e.system.allowPlatformBrokerWithDOM)throw qe(Le);if(!e.system.allowPlatformBroker)return t.trace("isPlatformAuthAllowed: allowPlatformBroker is not enabled, returning false"),!1;if(!r)return t.trace("isPlatformAuthAllowed: Platform auth provider is not initialized, returning false"),!1;if(n)switch(n){case o.IO.BEARER:case o.IO.POP:return t.trace("isPlatformAuthAllowed: authenticationScheme is supported, returning true"),!0;default:return t.trace("isPlatformAuthAllowed: authenticationScheme is not supported, returning false"),!1}return!0}class Rl extends Zc{constructor(e,t,r,n,o,i,s,a,c,l){super(e,t,r,n,o,i,s,c,l),this.unloadWindow=this.unloadWindow.bind(this),this.nativeStorage=a,this.eventHandler=o}acquireToken(e,t){let r;try{if(r={popupName:this.generatePopupName(e.scopes||o.aZ,e.authority||this.config.auth.authority),popupWindowAttributes:e.popupWindowAttributes||{},popupWindowParent:e.popupWindowParent??window},this.performanceClient.addFields({isAsyncPopup:this.config.system.asyncPopups},this.correlationId),this.config.system.asyncPopups)return this.logger.verbose("asyncPopups set to true, acquiring token"),this.acquireTokenPopupAsync(e,r,t);{const n={...e,httpMethod:Xc(e,this.config.auth.protocolMode)};return this.logger.verbose("asyncPopup set to false, opening popup before acquiring token"),r.popup=this.openSizedPopup("about:blank",r),this.acquireTokenPopupAsync(n,r,t)}}catch(e){return Promise.reject(e)}}logout(e){try{this.logger.verbose("logoutPopup called");const t=this.initializeLogoutRequest(e),r={popupName:this.generateLogoutPopupName(t),popupWindowAttributes:e?.popupWindowAttributes||{},popupWindowParent:e?.popupWindowParent??window},n=e&&e.authority,o=e&&e.mainWindowRedirectUri;return this.config.system.asyncPopups?(this.logger.verbose("asyncPopups set to true"),this.logoutPopupAsync(t,r,n,o)):(this.logger.verbose("asyncPopup set to false, opening popup"),r.popup=this.openSizedPopup("about:blank",r),this.logoutPopupAsync(t,r,n,o))}catch(e){return Promise.reject(e)}}async acquireTokenPopupAsync(e,t,r){this.logger.verbose("acquireTokenPopupAsync called");const n=await fa(this.initializeAuthorizationRequest.bind(this),nr,this.logger,this.performanceClient,this.correlationId)(e,Zn.Popup);t.popup&&zs(n.authority);const o=Sl(this.config,this.logger,this.platformAuthProvider,e.authenticationScheme);return n.platformBroker=o,this.config.auth.protocolMode===a?this.executeEarFlow(n,t,r):this.executeCodeFlow(n,t,r)}async executeCodeFlow(e,t,r){const n=e.correlationId,i=this.initializeServerTelemetryManager($n),s=r||await fa(vl,xr,this.logger,this.performanceClient,n)(this.performanceClient,this.logger,n),a={...e,codeChallenge:s.challenge};try{const r=await fa(this.createAuthCodeClient.bind(this),tr,this.logger,this.performanceClient,n)({serverTelemetryManager:i,requestAuthority:a.authority,requestAzureCloudOptions:a.azureCloudOptions,requestExtraQueryParameters:a.extraQueryParameters,account:a.account});if(a.httpMethod===o.ym.POST)return await this.executeCodeFlowWithPost(a,t,r,s.verifier);{const o=await fa(ml,or,this.logger,this.performanceClient,n)(this.config,r.authority,a,this.logger,this.performanceClient),i=this.initiateAuthRequest(o,t);this.eventHandler.emitEvent(Tc,Zn.Popup,{popupWindow:i},null);const c=await this.monitorPopupForHash(i,t.popupWindowParent),l=ma(el,Cr,this.logger,this.performanceClient,this.correlationId)(c,this.config.auth.OIDCOptions.serverResponseType,this.logger);return await fa(wl,hr,this.logger,this.performanceClient,n)(e,l,s.verifier,$n,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}catch(e){throw t.popup?.close(),e instanceof u&&(e.setCorrelationId(this.correlationId),i.cacheFailedRequest(e)),e}}async executeEarFlow(e,t,r){const n=e.correlationId,o=await fa(this.getDiscoveredAuthority.bind(this),Mt,this.logger,this.performanceClient,n)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),i=await fa(vs,Qr,this.logger,this.performanceClient,n)(),s=r||await fa(vl,xr,this.logger,this.performanceClient,n)(this.performanceClient,this.logger,n),a={...e,earJwk:i,codeChallenge:s.challenge},c=t.popup||this.openPopup("about:blank",t);(await fl(c.document,this.config,o,a,this.logger,this.performanceClient)).submit();const l=await fa(this.monitorPopupForHash.bind(this),Xt,this.logger,this.performanceClient,n)(c,t.popupWindowParent),h=ma(el,Cr,this.logger,this.performanceClient,this.correlationId)(l,this.config.auth.OIDCOptions.serverResponseType,this.logger);if(!h.ear_jwe&&h.code){const t=await fa(this.createAuthCodeClient.bind(this),tr,this.logger,this.performanceClient,n)({serverTelemetryManager:this.initializeServerTelemetryManager($n),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:o});return fa(wl,hr,this.logger,this.performanceClient,n)(a,h,s.verifier,$n,this.config,t,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}return fa(Al,cr,this.logger,this.performanceClient,n)(a,h,$n,this.config,o,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async executeCodeFlowWithPost(e,t,r,n){const o=e.correlationId,i=await fa(this.getDiscoveredAuthority.bind(this),Mt,this.logger,this.performanceClient,o)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),s=t.popup||this.openPopup("about:blank",t);(await yl(s.document,this.config,i,e,this.logger,this.performanceClient)).submit();const a=await fa(this.monitorPopupForHash.bind(this),Xt,this.logger,this.performanceClient,o)(s,t.popupWindowParent),c=ma(el,Cr,this.logger,this.performanceClient,this.correlationId)(a,this.config.auth.OIDCOptions.serverResponseType,this.logger);return fa(wl,hr,this.logger,this.performanceClient,o)(e,c,n,$n,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async logoutPopupAsync(e,t,r,n){this.logger.verbose("logoutPopupAsync called"),this.eventHandler.emitEvent(_c,Zn.Popup,e);const o=this.initializeServerTelemetryManager(Xn);try{await this.clearCacheOnLogout(this.correlationId,e.account);const i=await fa(this.createAuthCodeClient.bind(this),tr,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:o,requestAuthority:r,account:e.account||void 0});try{i.authority.endSessionEndpoint}catch{if(e.account?.homeAccountId&&e.postLogoutRedirectUri&&i.authority.protocolMode===s){if(this.eventHandler.emitEvent(Ec,Zn.Popup,e),n){const e={apiId:Xn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=it.getAbsoluteUrl(n,Hs());await this.navigationClient.navigateInternal(t,e)}return void t.popup?.close()}}const a=i.getLogoutUri(e);this.eventHandler.emitEvent(Ec,Zn.Popup,e);const c=this.openPopup(a,t);
2if(this.eventHandler.emitEvent(Tc,Zn.Popup,{popupWindow:c},null),await this.monitorPopupForHash(c,t.popupWindowParent).catch((()=>{})),n){const e={apiId:Xn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=it.getAbsoluteUrl(n,Hs());this.logger.verbose("Redirecting main window to url specified in the request"),this.logger.verbosePii(`Redirecting main window to: ${t}`),await this.navigationClient.navigateInternal(t,e)}else this.logger.verbose("No main window navigation requested")}catch(e){throw t.popup?.close(),e instanceof u&&(e.setCorrelationId(this.correlationId),o.cacheFailedRequest(e)),this.eventHandler.emitEvent(bc,Zn.Popup,null,e),this.eventHandler.emitEvent(kc,Zn.Popup),e}this.eventHandler.emitEvent(kc,Zn.Popup)}initiateAuthRequest(e,t){if(e)return this.logger.infoPii(`Navigate to: ${e}`),this.openPopup(e,t);throw this.logger.error("Navigate url is empty"),di(mo)}monitorPopupForHash(e,t){return new Promise(((t,r)=>{this.logger.verbose("PopupHandler.monitorPopupForHash - polling started");const n=setInterval((()=>{if(e.closed)return this.logger.error("PopupHandler.monitorPopupForHash - window closed"),clearInterval(n),void r(di(_o));let i="";try{i=e.location.href}catch(e){}if(!i||"about:blank"===i)return;clearInterval(n);let s="";const a=this.config.auth.OIDCOptions.serverResponseType;e&&(s=a===o.zL.QUERY?e.location.search:e.location.hash),this.logger.verbose("PopupHandler.monitorPopupForHash - popup window is on same origin as caller"),t(s)}),this.config.system.pollIntervalMilliseconds)})).finally((()=>{this.cleanPopup(e,t)}))}openPopup(e,t){try{let r;if(t.popup?(r=t.popup,this.logger.verbosePii(`Navigating popup window to: ${e}`),r.location.assign(e)):void 0===t.popup&&(this.logger.verbosePii(`Opening popup window to: ${e}`),r=this.openSizedPopup(e,t)),!r)throw di(To);return r.focus&&r.focus(),this.currentWindow=r,t.popupWindowParent.addEventListener("beforeunload",this.unloadWindow),r}catch(e){throw this.logger.error("error opening popup "+e.message),di(vo)}}openSizedPopup(e,{popupName:t,popupWindowAttributes:r,popupWindowParent:n}){const o=n.screenLeft?n.screenLeft:n.screenX,i=n.screenTop?n.screenTop:n.screenY,s=n.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=n.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;let c=r.popupSize?.width,l=r.popupSize?.height,h=r.popupPosition?.top,d=r.popupPosition?.left;return(!c||c<0||c>s)&&(this.logger.verbose("Default popup window width used. Window width not configured or invalid."),c=gn),(!l||l<0||l>a)&&(this.logger.verbose("Default popup window height used. Window height not configured or invalid."),l=pn),(!h||h<0||h>a)&&(this.logger.verbose("Default popup window top position used. Window top not configured or invalid."),h=Math.max(0,a/2-pn/2+i)),(!d||d<0||d>s)&&(this.logger.verbose("Default popup window left position used. Window left not configured or invalid."),d=Math.max(0,s/2-gn/2+o)),n.open(e,t,`width=${c}, height=${l}, top=${h}, left=${d}, scrollbars=yes`)}unloadWindow(e){this.currentWindow&&this.currentWindow.close(),e.preventDefault()}cleanPopup(e,t){e.close(),t.removeEventListener("beforeunload",this.unloadWindow)}generatePopupName(e,t){return`${mn}.${this.config.auth.clientId}.${e.join("-")}.${t}.${this.correlationId}`}generateLogoutPopupName(e){const t=e.account&&e.account.homeAccountId;return`${mn}.${this.config.auth.clientId}.${t}.${this.correlationId}`}}class Ol extends Zc{constructor(e,t,r,n,o,i,s,a,c,l){super(e,t,r,n,o,i,s,c,l),this.nativeStorage=a}async acquireToken(e){const t=await fa(this.initializeAuthorizationRequest.bind(this),nr,this.logger,this.performanceClient,this.correlationId)(e,Zn.Redirect);t.platformBroker=Sl(this.config,this.logger,this.platformAuthProvider,e.authenticationScheme);const r=e=>{e.persisted&&(this.logger.verbose("Page was restored from back/forward cache. Clearing temporary cache."),this.browserStorage.resetRequestCache(),this.eventHandler.emitEvent(Sc,Zn.Redirect))},n=this.getRedirectStartPage(e.redirectStartPage);this.logger.verbosePii(`Redirect start page: ${n}`),this.browserStorage.setTemporaryCache(qn,n,!0),window.addEventListener("pageshow",r);try{this.config.auth.protocolMode===a?await this.executeEarFlow(t):await this.executeCodeFlow(t,e.onRedirectNavigate)}catch(e){throw e instanceof u&&e.setCorrelationId(this.correlationId),window.removeEventListener("pageshow",r),e}}async executeCodeFlow(e,t){const r=e.correlationId,n=this.initializeServerTelemetryManager(Yn),i=await fa(vl,xr,this.logger,this.performanceClient,r)(this.performanceClient,this.logger,r),s={...e,codeChallenge:i.challenge};this.browserStorage.cacheAuthorizeRequest(s,i.verifier);try{if(s.httpMethod===o.ym.POST)return await this.executeCodeFlowWithPost(s);{const r=await fa(this.createAuthCodeClient.bind(this),tr,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:s.authority,requestAzureCloudOptions:s.azureCloudOptions,requestExtraQueryParameters:s.extraQueryParameters,account:s.account}),o=await fa(ml,or,this.logger,this.performanceClient,e.correlationId)(this.config,r.authority,s,this.logger,this.performanceClient);return await this.initiateAuthRequest(o,t)}}catch(e){throw e instanceof u&&(e.setCorrelationId(this.correlationId),n.cacheFailedRequest(e)),e}}async executeEarFlow(e){const t=e.correlationId,r=await fa(this.getDiscoveredAuthority.bind(this),Mt,this.logger,this.performanceClient,t)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),n=await fa(vs,Qr,this.logger,this.performanceClient,t)(),o=await fa(vl,xr,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),i={...e,earJwk:n,codeChallenge:o.challenge};this.browserStorage.cacheAuthorizeRequest(i,o.verifier);return(await fl(document,this.config,r,i,this.logger,this.performanceClient)).submit(),new Promise(((e,t)=>{setTimeout((()=>{t(di(ai,"failed_to_redirect"))}),this.config.system.redirectNavigationTimeout)}))}async executeCodeFlowWithPost(e){const t=e.correlationId,r=await fa(this.getDiscoveredAuthority.bind(this),Mt,this.logger,this.performanceClient,t)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});this.browserStorage.cacheAuthorizeRequest(e);return(await yl(document,this.config,r,e,this.logger,this.performanceClient)).submit(),new Promise(((e,t)=>{setTimeout((()=>{t(di(ai,"failed_to_redirect"))}),this.config.system.redirectNavigationTimeout)}))}async handleRedirectPromise(e="",t,r,n){const i=this.initializeServerTelemetryManager(Vn);try{const[s,a]=this.getRedirectResponse(e||"");if(!s)return this.logger.info("handleRedirectPromise did not detect a response as a result of a redirect. Cleaning temporary cache."),this.browserStorage.resetRequestCache(),"back_forward"!==function(){if("undefined"==typeof window||void 0===window.performance||"function"!=typeof window.performance.getEntriesByType)return;const e=window.performance.getEntriesByType("navigation"),t=e.length?e[0]:void 0;return t?.type}()?n.event.errorCode="no_server_response":this.logger.verbose("Back navigation event detected. Muting no_server_response error"),null;const c=this.browserStorage.getTemporaryCache(qn,!0)||o.YM.EMPTY_STRING,l=ot(c);if(l===ot(window.location.href)&&this.config.auth.navigateToLoginRequestUrl){this.logger.verbose("Current page is loginRequestUrl, handling response"),c.indexOf("#")>-1&&function(e){const t=e.split("#");t.shift(),window.location.hash=t.length>0?t.join("#"):""}(c);return await this.handleResponse(s,t,r,i)}if(!this.config.auth.navigateToLoginRequestUrl)return this.logger.verbose("NavigateToLoginRequestUrl set to false, handling response"),await this.handleResponse(s,t,r,i);if(!qs()||this.config.system.allowRedirectInIframe){this.browserStorage.setTemporaryCache(Hn,a,!0);const e={apiId:Vn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!0};let n=!0;if(c&&"null"!==c)this.logger.verbose(`Navigating to loginRequestUrl: ${c}`),n=await this.navigationClient.navigateInternal(c,e);else{const t=function(){const e=new it(window.location.href).getUrlComponents();return`${e.Protocol}//${e.HostNameAndPort}/`}();this.browserStorage.setTemporaryCache(qn,t,!0),this.logger.warning("Unable to get valid login request url from cache, redirecting to home page"),n=await this.navigationClient.navigateInternal(t,e)}if(!n)return await this.handleResponse(s,t,r,i)}return null}catch(e){throw e instanceof u&&(e.setCorrelationId(this.correlationId),i.cacheFailedRequest(e)),e}}getRedirectResponse(e){this.logger.verbose("getRedirectResponseHash called");let t=e;t||(t=this.config.auth.OIDCOptions.serverResponseType===o.zL.QUERY?window.location.search:window.location.hash);let r=rt(t);if(r){try{tl(r,this.browserCrypto,Zn.Redirect)}catch(e){return e instanceof u&&this.logger.error(`Interaction type validation failed due to ${e.errorCode}: ${e.errorMessage}`),[null,""]}return Us(window),this.logger.verbose("Hash contains known properties, returning response hash"),[r,t]}const n=this.browserStorage.getTemporaryCache(Hn,!0);return this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Hn)),n&&(r=rt(n),r)?(this.logger.verbose("Hash does not contain known properties, returning c
2ached hash"),[r,n]):[null,""]}async handleResponse(e,t,r,n){if(!e.state)throw di(yo);if(e.ear_jwe){const r=await fa(this.getDiscoveredAuthority.bind(this),Mt,this.logger,this.performanceClient,t.correlationId)({requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account});return fa(Al,cr,this.logger,this.performanceClient,t.correlationId)(t,e,Yn,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}const o=await fa(this.createAuthCodeClient.bind(this),tr,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:t.authority});return fa(wl,hr,this.logger,this.performanceClient,t.correlationId)(t,e,r,Yn,this.config,o,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async initiateAuthRequest(e,t){if(this.logger.verbose("RedirectHandler.initiateAuthRequest called"),e){this.logger.infoPii(`RedirectHandler.initiateAuthRequest: Navigate to: ${e}`);const r={apiId:Yn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},n=t||this.config.auth.onRedirectNavigate;if("function"==typeof n){this.logger.verbose("RedirectHandler.initiateAuthRequest: Invoking onRedirectNavigate callback");return!1!==n(e)?(this.logger.verbose("RedirectHandler.initiateAuthRequest: onRedirectNavigate did not return false, navigating"),void await this.navigationClient.navigateExternal(e,r)):void this.logger.verbose("RedirectHandler.initiateAuthRequest: onRedirectNavigate returned false, stopping navigation")}return this.logger.verbose("RedirectHandler.initiateAuthRequest: Navigating window to navigate url"),void await this.navigationClient.navigateExternal(e,r)}throw this.logger.info("RedirectHandler.initiateAuthRequest: Navigate url is empty"),di(mo)}async logout(e){this.logger.verbose("logoutRedirect called");const t=this.initializeLogoutRequest(e),r=this.initializeServerTelemetryManager(Jn);try{this.eventHandler.emitEvent(_c,Zn.Redirect,e),await this.clearCacheOnLogout(this.correlationId,t.account);const n={apiId:Jn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},o=await fa(this.createAuthCodeClient.bind(this),tr,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:e&&e.authority,requestExtraQueryParameters:e?.extraQueryParameters,account:e&&e.account||void 0});if(o.authority.protocolMode===s)try{o.authority.endSessionEndpoint}catch{if(t.account?.homeAccountId)return void this.eventHandler.emitEvent(Ec,Zn.Redirect,t)}const i=o.getLogoutUri(t);if(this.eventHandler.emitEvent(Ec,Zn.Redirect,t),!e||"function"!=typeof e.onRedirectNavigate)return this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,Un),void await this.navigationClient.navigateExternal(i,n);if(!1!==e.onRedirectNavigate(i))return this.logger.verbose("Logout onRedirectNavigate did not return false, navigating"),this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,Un),void await this.navigationClient.navigateExternal(i,n);this.browserStorage.setInteractionInProgress(!1),this.logger.verbose("Logout onRedirectNavigate returned false, stopping navigation")}catch(e){throw e instanceof u&&(e.setCorrelationId(this.correlationId),r.cacheFailedRequest(e)),this.eventHandler.emitEvent(bc,Zn.Redirect,null,e),this.eventHandler.emitEvent(kc,Zn.Redirect),e}this.eventHandler.emitEvent(kc,Zn.Redirect)}getRedirectStartPage(e){const t=e||window.location.href;return it.getAbsoluteUrl(t,Hs())}}async function Pl(e,t,r,n,o){if(t.addQueueMeasurement(Jt,n),!e)throw r.info("Navigate url is empty"),di(mo);return o?fa(Dl,Zt,r,t,n)(e,o,t,n):ma(Ul,er,r,t,n)(e)}async function Ml(e,t,r,n,o){const i=ql();if(!i.contentDocument)throw"No document associated with iframe!";return(await yl(i.contentDocument,e,t,r,n,o)).submit(),i}async function Nl(e,t,r,n,o){const i=ql();if(!i.contentDocument)throw"No document associated with iframe!";return(await fl(i.contentDocument,e,t,r,n,o)).submit(),i}async function Ll(e,t,r,n,i,s,a){return n.addQueueMeasurement(Xt,s),new Promise(((n,s)=>{t<Ys&&i.warning(`system.loadFrameTimeout or system.iframeHashTimeout set to lower (${t}ms) than the default (10000ms). This may result in timeouts.`);const c=window.setTimeout((()=>{window.clearInterval(l),s(di(bo))}),t),l=window.setInterval((()=>{let t="";const r=e.contentWindow;try{t=r?r.location.href:""}catch(e){}if(!t||"about:blank"===t)return;let i="";r&&(i=a===o.zL.QUERY?r.location.search:r.location.hash),window.clearTimeout(c),window.clearInterval(l),n(i)}),r)})).finally((()=>{ma(Hl,Nr,i,n,s)(e)}))}function Dl(e,t,r,n){return r.addQueueMeasurement(Zt,n),new Promise(((r,n)=>{const o=ql();window.setTimeout((()=>{o?(o.src=e,r(o)):n("Unable to load iframe")}),t)}))}
2function Ul(e){const t=ql();return t.src=e,t}function ql(){const e=document.createElement("iframe");return e.className="msalSilentIframe",e.style.visibility="hidden",e.style.position="absolute",e.style.width=e.style.height="0",e.style.border="0",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),e.setAttribute("allow","local-network-access *"),document.body.appendChild(e),e}function Hl(e){document.body===e.parentNode&&document.body.removeChild(e)}class xl extends Zc{constructor(e,t,r,n,o,i,s,a,c,l,h){super(e,t,r,n,o,i,a,l,h),this.apiId=s,this.nativeStorage=c}async acquireToken(e){this.performanceClient.addQueueMeasurement(St,e.correlationId),e.loginHint||e.sid||e.account&&e.account.username||this.logger.warning("No user hint provided. The authorization server may need more information to complete this request.");const t={...e};t.prompt?t.prompt!==o._M.NONE&&t.prompt!==o._M.NO_SESSION&&(this.logger.warning(`SilentIframeClient. Replacing invalid prompt ${t.prompt} with ${o._M.NONE}`),t.prompt=o._M.NONE):t.prompt=o._M.NONE;const r=await fa(this.initializeAuthorizationRequest.bind(this),nr,this.logger,this.performanceClient,e.correlationId)(t,Zn.Silent);return r.platformBroker=Sl(this.config,this.logger,this.platformAuthProvider,r.authenticationScheme),zs(r.authority),this.config.auth.protocolMode===a?this.executeEarFlow(r):this.executeCodeFlow(r)}async executeCodeFlow(e){let t;const r=this.initializeServerTelemetryManager(this.apiId);try{return t=await fa(this.createAuthCodeClient.bind(this),tr,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:r,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),await fa(this.silentTokenHelper.bind(this),Qt,this.logger,this.performanceClient,e.correlationId)(t,e)}catch(n){if(n instanceof u&&(n.setCorrelationId(this.correlationId),r.cacheFailedRequest(n)),!(t&&n instanceof u&&n.errorCode===un))throw n;return this.performanceClient.addFields({retryError:n.errorCode},this.correlationId),await fa(this.silentTokenHelper.bind(this),Qt,this.logger,this.performanceClient,this.correlationId)(t,e)}}async executeEarFlow(e){const t=e.correlationId,r=await fa(this.getDiscoveredAuthority.bind(this),Mt,this.logger,this.performanceClient,t)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),n=await fa(vs,Qr,this.logger,this.performanceClient,t)(),o=await fa(vl,xr,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),i={...e,earJwk:n,codeChallenge:o.challenge},s=await fa(Nl,Jt,this.logger,this.performanceClient,t)(this.config,r,i,this.logger,this.performanceClient),a=this.config.auth.OIDCOptions.serverResponseType,c=await fa(Ll,Xt,this.logger,this.performanceClient,t)(s,this.config.system.iframeHashTimeout,this.config.system.pollIntervalMilliseconds,this.performanceClient,this.logger,t,a),l=ma(el,Cr,this.logger,this.performanceClient,t)(c,a,this.logger);if(!l.ear_jwe&&l.code){const n=await fa(this.createAuthCodeClient.bind(this),tr,this.logger,this.performanceClient,t)({serverTelemetryManager:this.initializeServerTelemetryManager(this.apiId),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:r});return fa(wl,hr,this.logger,this.performanceClient,t)(i,l,o.verifier,this.apiId,this.config,n,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}return fa(Al,cr,this.logger,this.performanceClient,t)(i,l,this.apiId,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}logout(){return Promise.reject(di(Po))}async silentTokenHelper(e,t){const r=t.correlationId;this.performanceClient.addQueueMeasurement(Qt,r);const n=await fa(vl,xr,this.logger,this.performanceClient,r)(this.performanceClient,this.logger,r),i={...t,codeChallenge:n.challenge};let s;if(t.httpMethod===o.ym.POST)s=await fa(Ml,Jt,this.logger,this.performanceClient,r)(this.config,e.authority,i,this.logger,this.performanceClient);else{const t=await fa(ml,or,this.logger,this.performanceClient,r)(this.config,e.authority,i,this.logger,this.performanceClient);s=await fa(Pl,Jt,this.logger,this.performanceClient,r)(t,this.performanceClient,this.logger,r,this.config.system.navigateFrameWait)}const a=this.config.auth.OIDCOptions.serverResponseType,c=await fa(Ll,Xt,this.logger,this.performanceClient,r)(s,this.config.system.iframeHashTimeout,this.config.system.pollIntervalMilliseconds,this.performanceClient,this.logger,r,a),l=ma(el,Cr,this.logger,this.performanceClient,r)(c,a,this.logger);return fa(wl,hr,this.logger,this.performanceClient,r)(t,l,n.verifier,this.apiId,this.config,e,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}class Fl extends Hc{constructor(e,t){super(e,t)}async acquireToken(e){this.performanceClient?.addQueueMeasurement(Ht,e.correlationId);const t=Ca(),r=await fa(this.executeTokenRequest.bind(this),qt,this.logger,this.performanceClient,e.correlationId)(e,this.authority),n=r.headers?.[o.OK.X_MS_REQUEST_ID],i=new Gc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return i.validateTokenResponse(r.body),fa(i.handleServerTokenResponse.bind(i),yr,this.logger,this.performanceClient,e.correlationId)(r.body,this.authority,t,e,void 0,void 0,!0,e.forceCache,n)}async acquireTokenByRefreshToken(e){if(!e)throw qe(Ce);if(this.performanceClient?.addQueueMeasurement(Ft,e.correlationId),!e.account)throw ae(H);if(this.cacheManager.isAppMetadataFOCI(e.account.environment))try{return await fa(this.acquireTokenWithCachedRefreshToken.bind(this),xt,this.logger,this.performanceClient,e.correlationId)(e,!0)}catch(t){const r=t instanceof Ga&&t.errorCode===Da,n=t instanceof Uc&&t.errorCode===o.I.INVALID_GRANT_ERROR&&t.subError===o.I.CLIENT_MISMATCH_ERROR;if(r||n)return fa(this.acquireTokenWithCachedRefreshToken.bind(this),xt,this.logger,this.performanceClient,e.correlationId)(e,!1);throw t}return fa(this.acquireTokenWithCachedRefreshToken.bind(this),xt,this.logger,this.performanceClient,e.correlationId)(e,!1)}async acquireTokenWithCachedRefreshToken(e,t){this.performanceClient?.addQueueMeasurement(xt,e.correlationId);const r=ma(this.cacheManager.getRefreshToken.bind(this.cacheManager),Dr,this.logger,this.performanceClient,e.correlationId)(e.account,t,e.correlationId,void 0,this.performanceClient);if(!r)throw Ya(Da);if(r.expiresOn&&Aa(r.expiresOn,e.refreshTokenExpirationOffsetSeconds||300))throw this.performanceClient?.addFields({rtExpiresOnMs:Number(r.expiresOn)},e.correlationId),Ya(qa);const n={...e,refreshToken:r.secret,authenticationScheme:e.authenticationScheme||o.IO.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:Nc}};try{return await fa(this.acquireToken.bind(this),Ht,this.logger,this.performanceClient,e.correlationId)(n)}catch(t){if(t instanceof Ga&&(this.performanceClient?.addFields({rtExpiresOnMs:Number(r.expiresOn)},e.correlationId),t.subError===xa)){this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache");const t=this.cacheManager.generateCredentialKey(r);this.cacheManager.removeRefreshToken(t,e.correlationId)}throw t}}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(qt,e.correlationId);const r=this.createTokenQueryParameters(e),n=it.appendQueryString(t.tokenEndpoint,r),o=await fa(this.createTokenRequestBody.bind(this),Bt,this.logger,this.performanceClient,e.correlationId)(e),i=this.createTokenRequestHeaders(e.ccsCredential),s=$a(this.config.authOptions.clientId,e);return fa(this.executePostToTokenEndpoint.bind(this),Dt,this.logger,this.performanceClient,e.correlationId)(n,o,i,s,e.correlationId,Dt)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(Bt,e.correlationId);const t=new Map;if(Oi(t,e.embeddedClientId||e.tokenBodyParameters?.[Ci]||this.config.authOptions.clientId),e.redirectUri&&Pi(t,e.redirectUri),Ri(t,e.scopes,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),Yi(t,o.$x.REFRESH_TOKEN_GRANT),$i(t),Hi(t,this.config.libraryInfo),xi(t,this.config.telemetry.application),Zi(t),this.serverTelemetryManager&&!hn(this.config)&&Xi(t,this.serverTelemetryManager),function(e,t){e.set("refresh_token",t)}(t,e.refreshToken),this.config.clientCredentials.clientSecret&&Ki(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;Gi(t,await Yc(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),zi(t,r.assertionType)}if(e.authenticationScheme===o.IO.POP){const r=new Bc(this.cryptoUtils,this.performanceClient);let n;if(e.popKid)n=this.cryptoUtils.encodeKid(e.popKid);else{n=(await fa(r.generateCnf.bind(r),mr,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}Qi(t,n)}else if(e.authenticationScheme===o.IO.SSH){if(!e.sshJwk)throw qe(Ee);Ji(t,e.sshJwk)}if((!He.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ui(t,e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case Nc:try{Li(t,Be(e.ccsCredential.credential))}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case Lc:Ni(t,e.ccsCredential.credential)}return e.embeddedClientId&&es(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenBodyParameters&&Vi(t,e.tokenBodyParameters),ki(t,e.correlationId,this.performanceClient),nt(t)}}class Bl extends Zc{async acquireToken(e){this.performanceClient.addQueueMeasurement(Ot,e.correlationId);const t=await fa(Qc,$t,this.logger,this.performanceClient,e.correlationId)(e,this.config,this.performanceClient,this.logger),r={...e,...t};e.redirectUri&&(r.redirectUri=this.getRedirectUri(e.redirectUri));const n=this.initializeServerTelemetryManager(Qn),o=await this.createRefreshTokenClient({serverTelemetryManager:n,authorityUrl:r.authority,azureCloudOptions:r.azureCloudOptions,account:r.account});return fa(o.acquireTokenByRefreshToken.bind(o),Ft,this.logger,this.performanceClient,e.correlationId)(r).catch((e=>{throw e.setCorrelationId(this.correlationId),n.cacheFailedRequest(e),e}))}logout(){return Promise.reject(di(Po))}async createRefreshTokenClient(e){const t=await fa(this.getClientConfiguration.bind(this),rr,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:e.serverTelemetryManager,requestAuthority:e.authorityUrl,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return new Fl(t,this.performanceClient)}}class Kl{constructor(e,t,r,n){this.isBrowserEnvironment="undefined"!=typeof window,this.config=e,this.storage=t,this.logger=r,this.cryptoObj=n}async loadExternalTokens(e,t,r){if(!this.isBrowserEnvironment)throw di(Ho);const n=e.correlationId||ws(),o=t.id_token?Je(t.id_token,is):void 0,i=Xe(o||{}),s={protocolMode:this.config.auth.protocolMode,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache}
2,a=e.authority?new Na(Na.generateAuthority(e.authority,e.azureCloudOptions),this.config.system.networkClient,this.storage,s,this.logger,e.correlationId||ws()):void 0,c=await this.loadAccount(e,r.clientInfo||t.client_info||"",n,o,a),l=await this.loadIdToken(t,c.homeAccountId,c.environment,c.realm,n,i),h=await this.loadAccessToken(e,t,c.homeAccountId,c.environment,c.realm,r,n,i),d=await this.loadRefreshToken(t,c.homeAccountId,c.environment,n,i);return this.generateAuthenticationResult(e,{account:c,idToken:l,accessToken:h,refreshToken:d},o,a)}async loadAccount(e,t,r,n,o){if(this.logger.verbose("TokenCache - loading account"),e.account){const t=Qe.createFromAccountInfo(e.account);return await this.storage.setAccount(t,r,Xe(n||{})),t}if(!o||!t&&!n)throw this.logger.error("TokenCache - if an account is not provided on the request, authority and either clientInfo or idToken must be provided instead."),di(zo);const i=Qe.generateHomeAccountId(t,o.authorityType,this.logger,this.cryptoObj,n),s=n?.tid,a=zc(this.storage,o,i,is,r,n,t,o.hostnameAndPort,s,void 0,void 0,this.logger);return await this.storage.setAccount(a,r,Xe(n||{})),a}async loadIdToken(e,t,r,n,o,i){if(!e.id_token)return this.logger.verbose("TokenCache - no id token found in response"),null;this.logger.verbose("TokenCache - loading id token");const s=Ta(t,r,e.id_token,this.config.auth.clientId,n);return await this.storage.setIdTokenCredential(s,o,i),s}async loadAccessToken(e,t,r,n,o,i,s,a){if(!t.access_token)return this.logger.verbose("TokenCache - no access token found in response"),null;if(!t.expires_in)return this.logger.error("TokenCache - no expiration set on the access token. Cannot add it to the cache."),null;if(!(t.scope||e.scopes&&e.scopes.length))return this.logger.error("TokenCache - scopes not specified in the request or response. Cannot add token to the cache."),null;this.logger.verbose("TokenCache - loading access token");const c=t.scope?xe.fromString(t.scope):new xe(e.scopes),l=i.expiresOn||t.expires_in+Ca(),h=i.extendedExpiresOn||(t.ext_expires_in||t.expires_in)+Ca(),d=_a(r,n,t.access_token,this.config.auth.clientId,o,c.printScopes(),l,h,is);return await this.storage.setAccessTokenCredential(d,s,a),d}async loadRefreshToken(e,t,r,n,o){if(!e.refresh_token)return this.logger.verbose("TokenCache - no refresh token found in response"),null;this.logger.verbose("TokenCache - loading refresh token");const i=Ea(t,r,e.refresh_token,this.config.auth.clientId,e.foci,void 0,e.refresh_token_expires_in);return await this.storage.setRefreshTokenCredential(i,n,o),i}generateAuthenticationResult(e,t,r,n){let o,i="",s=[],a=null;t?.accessToken&&(i=t.accessToken.secret,s=xe.fromString(t.accessToken.target).asArray(),a=wa(t.accessToken.expiresOn),o=wa(t.accessToken.extendedExpiresOn));const c=t.account;return{authority:n?n.canonicalAuthority:"",uniqueId:t.account.localAccountId,tenantId:t.account.realm,scopes:s,account:Qe.getAccountInfo(c),idToken:t.idToken?.secret||"",idTokenClaims:r||{},accessToken:i,fromCache:!0,expiresOn:a,correlationId:e.correlationId||"",requestId:"",extExpiresOn:o,familyId:t.refreshToken?.familyId||"",tokenType:t?.accessToken?.tokenType||"",state:e.state||"",cloudGraphHostName:c.cloudGraphHostName||"",msGraphHost:c.msGraphHost||"",fromNativeBroker:!1}}}class Gl extends $c{constructor(e){super(e),this.includeRedirectUri=!1}}class zl extends Zc{constructor(e,t,r,n,o,i,s,a,c,l){super(e,t,r,n,o,i,a,c,l),this.apiId=s}async acquireToken(e){if(!e.code)throw di($o);const t=await fa(this.initializeAuthorizationRequest.bind(this),nr,this.logger,this.performanceClient,e.correlationId)(e,Zn.Silent),r=this.initializeServerTelemetryManager(this.apiId);try{const n={...t,code:e.code},o=await fa(this.getClientConfiguration.bind(this),rr,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:r,requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account}),i=new Gl(o);this.logger.verbose("Auth code client created");const s=new il(i,this.browserStorage,n,this.logger,this.performanceClient);return await fa(s.handleCodeResponseFromServer.bind(s),sr,this.logger,this.performanceClient,e.correlationId)({code:e.code,msgraph_host:e.msGraphHost,cloud_graph_host_name:e.cloudGraphHostName,cloud_instance_host_name:e.cloudInstanceHostName},t,!1)}catch(e){throw e instanceof u&&(e.setCorrelationId(this.correlationId),r.cacheFailedRequest(e)),e}}logout(){return Promise.reject(di(Po))}}function Yl(e,t,r){try{Ks(e)}catch(e){throw t.end({success:!1},e,r),e}}class $l{constructor(e){var t,r,n,o;this.operatingContext=e,this.isBrowserEnvironment=this.operatingContext.
2isBrowserEnvironment(),this.config=e.getConfig(),this.initialized=!1,this.logger=this.operatingContext.getLogger(),this.networkClient=this.config.system.networkClient,this.navigationClient=this.config.system.navigationClient,this.redirectResponse=new Map,this.hybridAuthCodeResponses=new Map,this.performanceClient=this.config.telemetry.client,this.browserCrypto=this.isBrowserEnvironment?new ga(this.logger,this.performanceClient):ce,this.eventHandler=new Mc(this.logger),this.browserStorage=this.isBrowserEnvironment?new Oc(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler,function(e){const t=e.cloudDiscoveryMetadata;let r;if(t)try{r=JSON.parse(t)}catch(e){throw qe(ve)}return{canonicalAuthority:e.authority?La(e.authority):void 0,knownAuthorities:e.knownAuthorities,cloudDiscoveryMetadata:r}}(this.config.auth)):(t=this.config.auth.clientId,r=this.logger,n=this.performanceClient,o=this.eventHandler,new Oc(t,{cacheLocation:Mn,cacheRetentionDays:5,temporaryCacheLocation:Mn,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!1,claimsBasedCachingEnabled:!1},ce,r,n,o));const i={cacheLocation:Mn,cacheRetentionDays:5,temporaryCacheLocation:Mn,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!1,claimsBasedCachingEnabled:!1};this.nativeInternalStorage=new Oc(this.config.auth.clientId,i,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler),this.tokenCache=new Kl(this.config,this.browserStorage,this.logger,this.browserCrypto),this.activeSilentTokenRequests=new Map,this.trackPageVisibility=this.trackPageVisibility.bind(this),this.trackPageVisibilityWithMeasurement=this.trackPageVisibilityWithMeasurement.bind(this)}static async createController(e,t){const r=new $l(e);return await r.initialize(t),r}trackPageVisibility(e){e&&(this.logger.info("Perf: Visibility change detected"),this.performanceClient.incrementFields({visibilityChangeCount:1},e))}async initialize(e,t){if(this.logger.trace("initialize called"),this.initialized)return void this.logger.info("initialize has already been called, exiting early.");if(!this.isBrowserEnvironment)return this.logger.info("in non-browser environment, exiting early."),this.initialized=!0,void this.eventHandler.emitEvent(oc);const r=e?.correlationId||this.getRequestCorrelationId(),n=this.config.system.allowPlatformBroker,o=this.performanceClient.startMeasurement(Vt,r);if(this.eventHandler.emitEvent(nc),!t)try{this.logMultipleInstances(o)}catch{}if(await fa(this.browserStorage.initialize.bind(this.browserStorage),Wt,this.logger,this.performanceClient,r)(r),n)try{this.platformAuthProvider=await kl(this.logger,this.performanceClient,r,this.config.system.nativeBrokerHandshakeTimeout,this.config.system.allowPlatformBrokerWithDOM)}catch(e){this.logger.verbose(e)}this.config.cache.claimsBasedCachingEnabled||(this.logger.verbose("Claims-based caching is disabled. Clearing the previous cache with claims"),ma(this.browserStorage.clearTokensAndKeysWithClaims.bind(this.browserStorage),Lr,this.logger,this.performanceClient,r)(r)),this.config.system.asyncPopups&&await this.preGeneratePkceCodes(r),this.initialized=!0,this.eventHandler.emitEvent(oc),o.end({allowPlatformBroker:n,success:!0})}async handleRedirectPromise(e){if(this.logger.verbose("handleRedirectPromise called"),Bs(this.initialized),this.isBrowserEnvironment){const t=e||"";let r=this.redirectResponse.get(t);return void 0===r?(r=this.handleRedirectPromiseInternal(e),this.redirectResponse.set(t,r),this.logger.verbose("handleRedirectPromise has been called for the first time, storing the promise")):this.logger.verbose("handleRedirectPromise has been called previously, returning the result from the first call"),r}return this.logger.verbose("handleRedirectPromise returns null, not browser environment"),null}async handleRedirectPromiseInternal(e){if(!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null."),null;const t=this.browserStorage.getInteractionInProgress()?.type;if(t===Un)return this.logger.verbose("handleRedirectPromise remov
2ing interaction_in_progress flag and returning null after sign-out"),this.browserStorage.setInteractionInProgress(!1),Promise.resolve(null);const r=this.getAllAccounts(),n=this.browserStorage.getCachedNativeRequest(),o=n&&this.platformAuthProvider&&!e;let i,s;this.eventHandler.emitEvent(Ac,Zn.Redirect);try{if(o&&this.platformAuthProvider){i=this.performanceClient.startMeasurement(_t,n?.correlationId||""),this.logger.trace("handleRedirectPromise - acquiring token from native platform"),i.add({isPlatformBrokerRequest:!0});const e=new gl(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Vn,this.performanceClient,this.platformAuthProvider,n.accountId,this.nativeInternalStorage,n.correlationId);s=fa(e.handleRedirectPromise.bind(e),Pr,this.logger,this.performanceClient,i.event.correlationId)(this.performanceClient,i.event.correlationId)}else{const[t,r]=this.browserStorage.getCachedRequest(),n=t.correlationId;i=this.performanceClient.startMeasurement(_t,n),this.logger.trace("handleRedirectPromise - acquiring token from web flow");const o=this.createRedirectClient(n);s=fa(o.handleRedirectPromise.bind(o),Or,this.logger,this.performanceClient,i.event.correlationId)(e,t,r,i)}}catch(e){throw this.browserStorage.resetRequestCache(),e}return s.then((e=>{if(e){this.browserStorage.resetRequestCache();r.length<this.getAllAccounts().length?(this.eventHandler.emitEvent(lc,Zn.Redirect,e),this.logger.verbose("handleRedirectResponse returned result, login success")):(this.eventHandler.emitEvent(uc,Zn.Redirect,e),this.logger.verbose("handleRedirectResponse returned result, acquire token success")),i.end({success:!0},void 0,e.account)}else i.event.errorCode?i.end({success:!1},void 0):i.discard();return this.eventHandler.emitEvent(vc,Zn.Redirect),e})).catch((e=>{this.browserStorage.resetRequestCache();const t=e;throw r.length>0?this.eventHandler.emitEvent(gc,Zn.Redirect,null,t):this.eventHandler.emitEvent(hc,Zn.Redirect,null,t),this.eventHandler.emitEvent(vc,Zn.Redirect),i.end({success:!1},t),e}))}async acquireTokenRedirect(e){const t=this.getRequestCorrelationId(e);this.logger.verbose("acquireTokenRedirect called",t);const r=this.performanceClient.startMeasurement(Tt,t);r.add({scenarioId:e.scenarioId});const n=e.onRedirectNavigate;if(n)e.onRedirectNavigate=t=>{const o="function"==typeof n?n(t):void 0;return r.add({navigateCallbackResult:!1!==o}),r.event=r.end({success:!0},void 0,e.account)||r.event,o};else{const t=this.config.auth.onRedirectNavigate;this.config.auth.onRedirectNavigate=n=>{const o="function"==typeof t?t(n):void 0;return r.add({navigateCallbackResult:!1!==o}),r.event=r.end({success:!0},void 0,e.account)||r.event,o}}const o=this.getAllAccounts().length>0;try{let n;if(Gs(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,Dn),o?this.eventHandler.emitEvent(dc,Zn.Redirect,e):this.eventHandler.emitEvent(cc,Zn.Redirect,e),this.platformAuthProvider&&this.canUsePlatformBroker(e)){n=new gl(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Yn,this.performanceClient,this.platformAuthProvider,this.getNativeAccountId(e),this.nativeInternalStorage,t).acquireTokenRedirect(e,r).catch((n=>{if(r.add({brokerErrorName:n.name,brokerErrorCode:n.errorCode}),n instanceof cl&&ll(n)){this.platformAuthProvider=void 0;return this.createRedirectClient(t).acquireToken(e)}if(n instanceof Ga){this.logger.verbose("acquireTokenRedirect - Resolving interaction required error thrown by native broker by falling back to web flow");return this.createRedirectClient(t).acquireToken(e)}throw n}))}else{n=this.createRedirectClient(t).acquireToken(e)}return await n}catch(n){throw this.browserStorage.resetRequestCache(),2===r.event.status?this.performanceClient.startMeasurement(_t,t).end({success:!1},n,e.account):r.end({success:!1},n,e.account),o?this.eventHandler.emitEvent(gc,Zn.Redirect,null,n):this.eventHandler.emitEvent(hc,Zn.Redirect,null,n),n}}acquireTokenPopup(e){const t=this.getRequestCorrelationId(e),r=this.performanceClient.startMeasurement(vt,t);r.add({scenarioId:e.scenarioId});try{this.logger.verbose("acquireTokenPopup called",t),Yl(this.initialized,r,e.account),this.browserStorage.setInteractionInProgress(!0,Dn)}catch(e){return Promise.reject(e)}const n=this.getAllAccounts();let o;n.length>0?this.eventHandler.emitEvent(dc,Zn.Popup,e):this.eventHandler.emitEvent(cc,Zn.Popup,e);const i=this.getPreGeneratedPkceCodes(t);if(this.canUsePlatformBroker(e))r.add({isPlatformBrokerRequest:!0}),o=this.acquireTokenNative({...e,correlationId:t},$n).then((e=>(r.end({success:!0},void 0,e.account),e))).catch((n=>{if(r.add({brokerErrorName:n.name,brokerErrorCode:n.errorCode}),n instanceof cl&&ll(n)){this.platformAuthProvider=void 0;return this.createPopupClient(t).acquireToken(e,i)}if(n instanceof Ga){this.logger.verbose("acquireTokenPopup - Resolving interaction required error thrown by native broker by falling back to web flow");return this.createPopupClient(t).acquireToken(e,i)}throw n}));else{o=this.createPopupClient(t).acquireToken(e,i)}return o.then((e=>(n.length<this.getAllAccounts().length?this.eventHandler.emitEvent(lc,Zn.Popup,e):this.eventHandler.emitEvent(uc,Zn.Popup,e),r.end({success:!0,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length},void 0,e.account),e))).catch((t=>(n.length>0?this.eventHandler.emitEvent(gc,Zn.Popup,null,t):this.eventHandler.emitEvent(hc,Zn.Popup,null,t),r.end({success:!1},t,e.account),Promise.reject(t)))).finally((async()=>{this.browserStorage.setInteractionInProgress(!1),this.config.system.asyncPopups&&await this.preGeneratePkceCodes(t)}))}trackPageVisibilityWithMeasurement(){const e=this.ssoSilentMeasurement||this.acquireTokenByCodeAsyncMeasurement;e&&(this.logger.info("Perf: Visibility change detected in ",e.event.name),e.increment({visibilityChangeCount:1}))}async ssoSilent(e){const t=this.getRequestCorrelationId(e),r={...e,prompt:e.prompt,correlationId:t};let n;if(this.ssoSilentMeasurement=this.performanceClient.startMeasurement(Pt,t),this.ssoSilentMeasurement?.add({scenarioId:e.scenarioId}),Yl(this.initialized,this.ssoSilentMeasurement,e.account),this.ssoSilentMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement),this.logger.verbose("ssoSilent called",t),this.eventHandler.emitEvent(mc,Zn.Silent,r),this.canUsePlatformBroker(r))this.ssoSilentMeasurement?.add({isPlatformBrokerRequest:!0}),n=this.acquireTokenNative(r,jn).catch((e=>{if(this.ssoSilentMeasurement?.add({brokerErrorName:e.name,brokerErrorCode:e.errorCode}),e instanceof cl&&ll(e)){this.platformAuthProvider=void 0;return this.createSilentIframeClient(r.correlationId).acquireToken(r)}throw e}));else{n=this.createSilentIframeClient(r.correlationId).acquireToken(r)}return n.then((e=>(this.eventHandler.emitEvent(fc,Zn.Silent,e),this.ssoSilentMeasurement?.end({success:!0,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length},void 0,e.account),e))).catch((t=>{throw this.eventHandler.emitEvent(yc,Zn.Silent,null,t),this.ssoSilentMeasurement?.end({success:!1},t,e.account),t})).finally((()=>{document.removeEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement)}))}async acquireTokenByCode(e){const t=this.getRequestCorrelationId(e);this.logger.trace("acquireTokenByCode called",t);const r=this.performanceClient.startMeasurement(Ct,t);Yl(this.initialized,r),this.eventHandler.emitEvent(Cc,Zn.Silent,e),r.add({scenarioId:e.scenarioId});try{if(e.code&&e.nativeAccountId)throw di(Vo);if(e.code){const n=e.code;let o=this.hybridAuthCodeResponses.get(n);return o?(this.logger.verbose("Existing acquireTokenByCode request found",t),r.discard()):(this.logger.verbose("Initiating new acquireTokenByCode request",t),o=this.acquireTokenByCodeAsync({...e,correlationId:t}).then((e=>(this.eventHandler.emitEvent(Ic,Zn.Silent,e),this.hybridAuthCodeResponses.delete(n),r.end({success:!0,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length},void 0,e.account),e))).catch((e=>{throw this.hybridAuthCodeResponses.delete(n),this.eventHandler.emitEvent(wc,Zn.Silent,null,e),r.end({success:!1},e),e})),this.hybridAuthCodeResponses.set(n,o)),await o}
2if(e.nativeAccountId){if(this.canUsePlatformBroker(e,e.nativeAccountId)){r.add({isPlatformBrokerRequest:!0});const n=await this.acquireTokenNative({...e,correlationId:t},Wn,e.nativeAccountId).catch((e=>{throw e instanceof cl&&ll(e)&&(this.platformAuthProvider=void 0),r.add({brokerErrorName:e.name,brokerErrorCode:e.errorCode}),e}));return r.end({success:!0},void 0,n.account),n}throw di(Qo)}throw di(jo)}catch(e){throw this.eventHandler.emitEvent(wc,Zn.Silent,null,e),r.end({success:!1},e),e}}async acquireTokenByCodeAsync(e){this.logger.trace("acquireTokenByCodeAsync called",e.correlationId),this.acquireTokenByCodeAsyncMeasurement=this.performanceClient.startMeasurement(Rr,e.correlationId),this.acquireTokenByCodeAsyncMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement);const t=this.createSilentAuthCodeClient(e.correlationId);return await t.acquireToken(e).then((e=>(this.acquireTokenByCodeAsyncMeasurement?.end({success:!0,fromCache:e.fromCache}),e))).catch((e=>{throw this.acquireTokenByCodeAsyncMeasurement?.end({success:!1},e),e})).finally((()=>{document.removeEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement)}))}async acquireTokenFromCache(e,t){switch(this.performanceClient.addQueueMeasurement(Kt,e.correlationId),t){case no:case oo:case io:const t=this.createSilentCacheClient(e.correlationId);return fa(t.acquireToken.bind(t),kt,this.logger,this.performanceClient,e.correlationId)(e);default:throw ae($)}}async acquireTokenByRefreshToken(e,t){switch(this.performanceClient.addQueueMeasurement(It,e.correlationId),t){case no:case io:case so:case ao:const t=this.createSilentRefreshClient(e.correlationId);return fa(t.acquireToken.bind(t),Ot,this.logger,this.performanceClient,e.correlationId)(e);default:throw ae($)}}async acquireTokenBySilentIframe(e){this.performanceClient.addQueueMeasurement(Yt,e.correlationId);const t=this.createSilentIframeClient(e.correlationId);return fa(t.acquireToken.bind(t),St,this.logger,this.performanceClient,e.correlationId)(e)}async logout(e){const t=this.getRequestCorrelationId(e);return this.logger.warning("logout API is deprecated and will be removed in msal-browser v3.0.0. Use logoutRedirect instead.",t),this.logoutRedirect({correlationId:t,...e})}async logoutRedirect(e){const t=this.getRequestCorrelationId(e);Gs(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,Un);return this.createRedirectClient(t).logout(e)}logoutPopup(e){try{const t=this.getRequestCorrelationId(e);Ks(this.initialized),this.browserStorage.setInteractionInProgress(!0,Un);return this.createPopupClient(t).logout(e).finally((()=>{this.browserStorage.setInteractionInProgress(!1)}))}catch(e){return Promise.reject(e)}}async clearCache(e){if(!this.isBrowserEnvironment)return void this.logger.info("in non-browser environment, returning early.");const t=this.getRequestCorrelationId(e);return this.createSilentCacheClient(t).logout(e)}getAllAccounts(e){const t=this.getRequestCorrelationId();return function(e,t,r,n,o){return e.verbose("getAllAccounts called"),r?t.getAllAccounts(o||{},n):[]}(this.logger,this.browserStorage,this.isBrowserEnvironment,t,e)}getAccount(e){const t=this.getRequestCorrelationId();return function(e,t,r,n){const o=r.getAccountInfoFilteredBy(e,n);return o?(t.verbose("getAccount: Account matching provided filter found, returning"),o):(t.verbose("getAccount: No matching account found, returning null"),null)}(e,this.logger,this.browserStorage,t)}getAccountByUsername(e){const t=this.getRequestCorrelationId();return function(e,t,r,n){if(t.trace("getAccountByUsername called"),!e)return t.warning("getAccountByUsername: No username provided"),null;const o=r.getAccountInfoFilteredBy({username:e},n);return o?(t.verbose("getAccountByUsername: Account matching username found, returning"),t.verbosePii(`getAccountByUsername: Returning signed-in accounts matching username: ${e}`),o):(t.verbose("getAccountByUsername: No matching account found, returning null"),null)}(e,this.logger,this.browserStorage,t)}getAccountByHomeId(e){const t=this.getRequestCorrelationId();return function(e,t,r,n){if(t.trace("getAccountByHomeId called"),!e)return t.warning("getAccountByHomeId: No homeAccountId provided"),null;const o=r.getAccountInfoFilteredBy({homeAccountId:e},n);return o?(t.verbose("getAccountByHomeId: Account matching homeAccountId found, returning"),t.verbosePii(`getAccountByHomeId: Returning signed-in accounts matching homeAccountId: ${e}`),o):(t.verbose("getAccountByHomeId: No matching account found, returning null"),null)}(e,this.logger,this.browserStorage,t)}getAccountByLocalId(e){const t=this.getRequestCorrelationId();return function(e,t,r,n){if(t.trace("getAccountByLocalId called"),!e)return t.warning("getAccountByLocalId: No localAccountId provided"),null;const o=r.getAccountInfoFilteredBy({localAccountId:e},n);return o?(t.verbose("getAccountByLocalId: Account matching localAccountId found, returning"),t.verbosePii(`getAccountByLocalId: Returning signed-in accounts matching localAccountId: ${e}`),o):(t.verbose("getAccountByLocalId: No matching account found, returning null"),null)}(e,this.logger,this.browserStorage,t)}setActiveAccount(e){const t=this.getRequestCorrelationId();!function(e,t,r){t.setActiveAccount(e,r)}(e,this.browserStorage,t)}getActiveAccount(){const e=this.getRequestCorrelationId();return function(e,t){return e.getActiveAccount(t)}(this.browserStorage,e)}async hydrateCache(e,t){this.logger.verbose("hydrateCache called");const r=Qe.createFromAccountInfo(e.account,e.cloudGraphHostName,e.msGraphHost);return await this.browserStorage.setAccount(r,e.correlationId,Xe(e.idTokenClaims)),e.fromNativeBroker?(this.logger.verbose("Response was from native broker, storing in-memory"),this.nativeInternalStorage.hydrateCache(e,t)):this.browserStorage.hydrateCache(e,t)}async acquireTokenNative(e,t,r,n){if(this.logger.trace("acquireTokenNative called"),!this.platformAuthProvider)throw di(Zo);return new gl(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,t,this.performanceClient,this.platformAuthProvider,r||this.getNativeAccountId(e),this.nativeInternalStorage,e.correlationId).acquireToken(e,n)}canUsePlatformBroker(e,t){if(this.logger.trace("canUsePlatformBroker called"),!this.platformAuthProvider)return this.logger.trace("canUsePlatformBroker: platform broker unavilable, returning false"),!1;if(!Sl(this.config,this.logger,this.platformAuthProvider,e.authenticationScheme))return this.logger.trace("canUsePlatformBroker: isBrokerAvailable returned false, returning false"),!1;if(e.prompt)switch(e.prompt){case o._M.NONE:case o._M.CONSENT:case o._M.LOGIN:case o._M.SELECT_ACCOUNT:this.logger.trace("canUsePlatformBroker: prompt is compatible with platform broker flow");break;default:return this.logger.trace(`canUsePlatformBroker: prompt = ${e.prompt} is not compatible with platform broker flow, returning false`),!1}return!(!t&&!this.getNativeAccountId(e))||(this.logger.trace("canUsePlatformBroker: nativeAccountId is not available, returning false"),!1)}getNativeAccountId(e){const t=e.account||this.getAccount({loginHint:e.loginHint,sid:e.sid})||this.getActiveAccount();return t&&t.nativeAccountId||""}createPopupClient(e){return new Rl(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,this.platformAuthProvider,e)}createRedirectClient(e){return new Ol(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,this.platformAuthProvider,e)}createSilentIframeClient(e){return new xl(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,jn,this.performanceClient,this.nativeInternalStorage,this.platformAuthProvider,e)}createSilentCacheClient(e){return new ul(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.platformAuthProvider,e)}createSilentRefreshClient(e){return new Bl(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.platformAuthProvider,e)}createSilentAuthCodeClient(e){return new zl(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Wn,this.performanceClient,this.platformAuthProvider,e)}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){return Fs(),this.performanceClient.addPerformanceCallback(e)}removePerformanceCallback(e){return this.performanceClient.removePerformanceCallback(e)}
2enableAccountStorageEvents(){this.config.cache.cacheLocation===On?this.eventHandler.subscribeCrossTab():this.logger.info("Account storage events are only available when cacheLocation is set to localStorage")}disableAccountStorageEvents(){this.config.cache.cacheLocation===On?this.eventHandler.unsubscribeCrossTab():this.logger.info("Account storage events are only available when cacheLocation is set to localStorage")}getTokenCache(){return this.tokenCache}getLogger(){return this.logger}setLogger(e){this.logger=e}initializeWrapperLibrary(e,t){this.browserStorage.setWrapperMetadata(e,t)}setNavigationClient(e){this.navigationClient=e}getConfiguration(){return this.config}getPerformanceClient(){return this.performanceClient}isBrowserEnv(){return this.isBrowserEnvironment}getRequestCorrelationId(e){return e?.correlationId?e.correlationId:this.isBrowserEnvironment?ws():o.YM.EMPTY_STRING}async loginRedirect(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("loginRedirect called",t),this.acquireTokenRedirect({correlationId:t,...e||eo})}loginPopup(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("loginPopup called",t),this.acquireTokenPopup({correlationId:t,...e||eo})}async acquireTokenSilent(e){const t=this.getRequestCorrelationId(e),r=this.performanceClient.startMeasurement(wt,t);r.add({cacheLookupPolicy:e.cacheLookupPolicy,scenarioId:e.scenarioId}),Yl(this.initialized,r,e.account),this.logger.verbose("acquireTokenSilent called",t);const n=e.account||this.getActiveAccount();if(!n)throw di(Mo);return this.acquireTokenSilentDeduped(e,n,t).then((n=>(r.end({success:!0,fromCache:n.fromCache,accessTokenSize:n.accessToken.length,idTokenSize:n.idToken.length},void 0,n.account),{...n,state:e.state,correlationId:t}))).catch((e=>{throw e instanceof u&&e.setCorrelationId(t),r.end({success:!1},e,n),e}))}async acquireTokenSilentDeduped(e,t,r){const n=$a(this.config.auth.clientId,{...e,authority:e.authority||this.config.auth.authority,correlationId:r},t.homeAccountId),o=JSON.stringify(n),i=this.activeSilentTokenRequests.get(o);if(void 0===i){this.logger.verbose("acquireTokenSilent called for the first time, storing active request",r),this.performanceClient.addFields({deduped:!1},r);const n=fa(this.acquireTokenSilentAsync.bind(this),At,this.logger,this.performanceClient,r)({...e,correlationId:r},t);return this.activeSilentTokenRequests.set(o,n),n.finally((()=>{this.activeSilentTokenRequests.delete(o)}))}return this.logger.verbose("acquireTokenSilent has been called previously, returning the result from the first call",r),this.performanceClient.addFields({deduped:!0},r),i}async acquireTokenSilentAsync(e,t){const r=()=>this.trackPageVisibility(e.correlationId);this.performanceClient.addQueueMeasurement(At,e.correlationId),this.eventHandler.emitEvent(dc,Zn.Silent,e),e.correlationId&&this.performanceClient.incrementFields({visibilityChangeCount:0},e.correlationId),document.addEventListener("visibilitychange",r);const n=await fa(Jc,jt,this.logger,this.performanceClient,e.correlationId)(e,t,this.config,this.performanceClient,this.logger),o=e.cacheLookupPolicy||no;return this.acquireTokenSilentNoIframe(n,o).catch((async e=>{const t=function(e,t){const r=!(e instanceof Ga&&e.subError!==xa),n=e.errorCode===un||e.errorCode===$,o=r&&n||e.errorCode===Da||e.errorCode===qa,i=lo.includes(t);return o&&i}(e,o);if(t){if(this.activeIframeRequest){if(o!==co){const[t,r]=this.activeIframeRequest;this.logger.verbose(`Iframe request is already in progress, awaiting resolution for request with correlationId: ${r}`,n.correlationId);const i=this.performanceClient.startMeasurement(Rt,n.correlationId);i.add({awaitIframeCorrelationId:r});const s=await t;if(i.end({success:s}),s)return this.logger.verbose(`Parallel iframe request with correlationId: ${r} succeeded. Retrying cache and/or RT redemption`,n.correlationId),this.acquireTokenSilentNoIframe(n,o);throw this.logger.info(`Iframe request with correlationId: ${r} failed. Interaction is required.`),e}return this.logger.warning("Another iframe request is currently in progress and CacheLookupPolicy is set to Skip. This may result in degraded performance and/or reliability for both calls. Please consider changing the CacheLookupPolicy to take advantage of request queuing and token cache.",n.correlationId),fa(this.acquireTokenBySilentIframe.bind(this),Yt,this.logger,this.performanceClient,n.correlationId)(n)}{let e;return this.activeIframeRequest=[new Promise((t=>{e=t})),n.correlationId],this.logger.verbose("Refresh token expired/invalid or CacheLookupPolicy is set to Skip, attempting acquire token by iframe.",n.correlationId),fa(this.acquireTokenBySilentIframe.bind(this),Yt,this.logger,this.performanceClient,n.correlationId)(n).then((t=>(e(!0),t))).catch((t=>{throw e(!1),t})).finally((()=>{this.activeIframeRequest=void 0}))}}throw e})).then((t=>(this.eventHandler.emitEvent(uc,Zn.Silent,t),this.performanceClient.addFields({fromCache:t.fromCache},e.correlationId),t))).catch((e=>{throw this.eventHandler.emitEvent(gc,Zn.Silent,null,e),e})).finally((()=>{document.removeEventListener("visibilitychange",r)}))}async acquireTokenSilentNoIframe(e,t){return Sl(this.config,this.logger,this.platformAuthProvider,e.authenticationScheme)&&e.account.nativeAccountId?(this.logger.verbose("acquireTokenSilent - attempting to acquire token from native platform"),this.performanceClient.addFields({isPlatformBrokerRequest:!0},e.correlationId),this.acquireTokenNative(e,Qn,e.account.nativeAccountId,t).catch((async t=>{if(this.performanceClient.addFields({brokerErrorName:t.name,brokerErrorCode:t.errorCode},e.correlationId),t instanceof cl&&ll(t))throw this.logger.verbose("acquireTokenSilent - native platform unavailable, falling back to web flow"),this.platformAuthProvider=void 0,ae($);throw t}))):(this.logger.verbose("acquireTokenSilent - attempting to acquire token from web flow"),t===oo&&this.logger.verbose("acquireTokenSilent - cache lookup policy set to AccessToken, attempting to acquire token from local cache"),fa(this.acquireTokenFromCache.bind(this),Kt,this.logger,this.performanceClient,e.correlationId)(e,t).catch((r=>{if(t===oo)throw r;return this.eventHandler.emitEvent(pc,Zn.Silent,e),fa(this.acquireTokenByRefreshToken.bind(this),It,this.logger,this.performanceClient,e.correlationId)(e,t)})))}async preGeneratePkceCodes(e){return this.logger.verbose("Generating new PKCE codes"),this.pkceCode=await fa(vl,xr,this.logger,this.performanceClient,e)(this.performanceClient,this.logger,e),Promise.resolve()}getPreGeneratedPkceCodes(e){this.logger.verbose("Attempting to pick up pre-generated PKCE codes");const t=this.pkceCode?{...this.pkceCode}:void 0;return this.pkceCode=void 0,this.logger.verbose((t?"Found":"Did not find")+" pre-generated PKCE codes"),this.performanceClient.addFields({usePreGeneratedPkce:!!t},e),t}logMultipleInstances(e){const t=this.config.auth.clientId;if(!window)return;window.msal=window.msal||{},window.msal.clientIds=window.msal.clientIds||[];window.msal.clientIds.length>0&&this.logger.verbose("There is already an instance of MSAL.js in the window."),window.msal.clientIds.push(t),function(e,t,r){const n=window.msal?.clientIds||[],o=n.length,i=n.filter((t=>t===e)).length;i>1&&r.warning("There is already an instance of MSAL.js in the window with the same client id."),t.add({msalInstanceCount:o,sameClientIdInstanceCount:i})}(t,e,this.logger)}}class jl{static async createPublicClientApplication(e){const t=await async function(e,t){const r=new na(e);return await r.initialize(),$l.createController(r,t)}(e);return new jl(e,t)}constructor(e,t){this.isBroker=!1,this.controller=t||new $l(new na(e))}async initialize(e){return this.controller.initialize(e,this.isBroker)}async acquireTokenPopup(e){return this.controller.acquireTokenPopup(e)}acquireTokenRedirect(e){return this.controller.acquireTokenRedirect(e)}acquireTokenSilent(e){return this.controller.acquireTokenSilent(e)}
2acquireTokenByCode(e){return this.controller.acquireTokenByCode(e)}addEventCallback(e,t){return this.controller.addEventCallback(e,t)}removeEventCallback(e){return this.controller.removeEventCallback(e)}addPerformanceCallback(e){return this.controller.addPerformanceCallback(e)}removePerformanceCallback(e){return this.controller.removePerformanceCallback(e)}enableAccountStorageEvents(){this.controller.enableAccountStorageEvents()}disableAccountStorageEvents(){this.controller.disableAccountStorageEvents()}getAccount(e){return this.controller.getAccount(e)}getAccountByHomeId(e){return this.controller.getAccountByHomeId(e)}getAccountByLocalId(e){return this.controller.getAccountByLocalId(e)}getAccountByUsername(e){return this.controller.getAccountByUsername(e)}getAllAccounts(e){return this.controller.getAllAccounts(e)}handleRedirectPromise(e){return this.controller.handleRedirectPromise(e)}loginPopup(e){return this.controller.loginPopup(e)}loginRedirect(e){return this.controller.loginRedirect(e)}logout(e){return this.controller.logout(e)}logoutRedirect(e){return this.controller.logoutRedirect(e)}logoutPopup(e){return this.controller.logoutPopup(e)}ssoSilent(e){return this.controller.ssoSilent(e)}getTokenCache(){return this.controller.getTokenCache()}getLogger(){return this.controller.getLogger()}setLogger(e){this.controller.setLogger(e)}setActiveAccount(e){this.controller.setActiveAccount(e)}getActiveAccount(){return this.controller.getActiveAccount()}initializeWrapperLibrary(e,t){return this.controller.initializeWrapperLibrary(e,t)}setNavigationClient(e){this.controller.setNavigationClient(e)}getConfiguration(){return this.controller.getConfiguration()}async hydrateCache(e,t){return this.controller.hydrateCache(e,t)}clearCache(e){return this.controller.clearCache(e)}}},49133:function(e,t,r){r.d(t,{r:function(){return f}});const n=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,o=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,i=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function s(e,t){if(!("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t))return t;!function(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}(e)}function a(e,t={}){if("string"!=typeof e)return e;const r=e.trim();if('"'===e[0]&&e.endsWith('"')&&!e.includes("\\"))return r.slice(1,-1);if(r.length<=9){const e=r.toLowerCase();if("true"===e)return!0;if("false"===e)return!1;if("undefined"===e)return;if("null"===e)return null;if("nan"===e)return Number.NaN;if("infinity"===e)return Number.POSITIVE_INFINITY;if("-infinity"===e)return Number.NEGATIVE_INFINITY}if(!i.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(n.test(e)||o.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,s)}return JSON.parse(e)}catch(r){if(t.strict)throw r;return e}}function c(e,t){if(null==e)return;let r=e;for(let e=0;e<t.length;e++){if(null==r||null==r[t[e]])return;r=r[t[e]]}return r}function l(e,t,r){if(0===r.length)return t;const n=r[0];return r.length>1&&(t=l("object"==typeof e&&null!==e&&Object.prototype.hasOwnProperty.call(e,n)?e[n]:Number.isInteger(Number(r[1]))?[]:{},t,Array.prototype.slice.call(r,1))),Number.isInteger(Number(n))&&Array.isArray(e)?e.slice()[n]:Object.assign({},e,{[n]:t})}function h(e,t){if(null==e||0===t.length)return e;if(1===t.length){if(null==e)return e;if(Number.isInteger(t[0])&&Array.isArray(e))return Array.prototype.slice.call(e,0).splice(t[0],1);const r={};for(const t in e)r[t]=e[t];return delete r[t[0]],r}if(null==e[t[0]]){if(Number.isInteger(t[0])&&Array.isArray(e))return Array.prototype.concat.call([],e);const r={};for(const t in e)r[t]=e[t];return r}return l(e,h(e[t[0]],Array.prototype.slice.call(t,1)),[t[0]])}function d(e,t){return t.map((e=>e.split("."))).map((t=>[t,c(e,t)])).filter((e=>void 0!==e[1])).reduce(((e,t)=>l(e,t[1],t[0])),{})}function u(e,t){return t.map((e=>e.split("."))).reduce(((e,t)=>h(e,t)),e)}function g(e,{storage:t,serializer:r,key:n,debug:o,pick:i,omit:s,beforeHydrate:a,afterHydrate:c},l,h=!0){try{h&&a?.(l);const o=t.getItem(n);if(o){const t=r.deserialize(o),n=i?d(t,i):t,a=s?u(n,s):n;e.$patch(a)}h&&c?.(l)}catch(e){o&&console.error("[pinia-plugin-persistedstate]",e)}}function p(e,{storage:t,serializer:r,key:n,debug:o,pick:i,omit:s}){try{const o=i?d(e,i):e,a=s?u(o,s):o,c=r.serialize(a);t.setItem(n,c)}catch(e){o&&console.error("[pinia-plugin-persistedstate]",e)}}var m=function(e={}){return function(t){!function(e,t,r){const{pinia:n,store:o,options:{persist:i=r}}=e;if(!i)return;if(!(o.$id in n.state.value)){const e=n._s.get(o.$id.replace("__hot:",""));return void(e&&Promise.resolve().then((()=>e.$persist())))}const s=(Array.isArray(i)?i:!0===i?[{}]:[i]).map(t);o.$hydrate=({runHooks:t=!0}={})=>
2{s.forEach((r=>{g(o,r,e,t)}))},o.$persist=()=>{s.forEach((e=>{p(o.$state,e)}))},s.forEach((t=>{g(o,t,e),o.$subscribe(((e,r)=>p(r,t)),{detached:!0})}))}(t,(r=>({key:(e.key?e.key:e=>e)(r.key??t.store.$id),debug:r.debug??e.debug??!1,serializer:r.serializer??e.serializer??{serialize:e=>JSON.stringify(e),deserialize:e=>a(e)},storage:r.storage??e.storage??window.localStorage,beforeHydrate:r.beforeHydrate,afterHydrate:r.afterHydrate,pick:r.pick,omit:r.omit})),e.auto??!1)}}();function f(){if(null==Pinia?.getActivePinia()){const e=Pinia.createPinia();e.use(m),Pinia?.setActivePinia(e)}return Pinia?.getActivePinia()}},52442:function(e,t,r){r.a(e,(async function(e,n){try{r.d(t,{GG:function(){return a}});var o=r(68537),i=r(33697),s=e([o]);async function a(e){try{const t={"Content-Type":"application/json"},r=await o.A.post(i.JX,e,{},t);return{error:r.statusText,status:r.status}}catch(e){console.error("Error in userLocationService.postLocation: ",e)}}o=(s.then?(await s)():s)[0],n()}catch(c){n(c)}}))},55438:function(e,t,r){r.d(t,{$:function(){return n},V:function(){return i}});var n,o=r(81140);!function(e){e[e.Error=0]="Error",e[e.Warning=1]="Warning",e[e.Info=2]="Info",e[e.Verbose=3]="Verbose",e[e.Trace=4]="Trace"}(n||(n={}));class i{constructor(e,t,r){this.level=n.Info;const s=e||i.createDefaultLoggerOptions();this.localCallback=s.loggerCallback||(()=>{}),this.piiLoggingEnabled=s.piiLoggingEnabled||!1,this.level="number"==typeof s.logLevel?s.logLevel:n.Info,this.correlationId=s.correlationId||o.YM.EMPTY_STRING,this.packageName=t||o.YM.EMPTY_STRING,this.packageVersion=r||o.YM.EMPTY_STRING}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:n.Info}}clone(e,t,r){return new i({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level,correlationId:r||this.correlationId},e,t)}logMessage(e,t){if(t.logLevel>this.level||!this.piiLoggingEnabled&&t.containsPii)return;const r=`${`[${(new Date).toUTCString()}] : [${t.correlationId||this.correlationId||""}]`} : ${this.packageName}@${this.packageVersion} : ${n[t.logLevel]} - ${e}`;this.executeCallback(t.logLevel,r,t.containsPii||!1)}executeCallback(e,t,r){this.localCallback&&this.localCallback(e,t,r)}error(e,t){this.logMessage(e,{logLevel:n.Error,containsPii:!1,correlationId:t||o.YM.EMPTY_STRING})}errorPii(e,t){this.logMessage(e,{logLevel:n.Error,containsPii:!0,correlationId:t||o.YM.EMPTY_STRING})}warning(e,t){this.logMessage(e,{logLevel:n.Warning,containsPii:!1,correlationId:t||o.YM.EMPTY_STRING})}warningPii(e,t){this.logMessage(e,{logLevel:n.Warning,containsPii:!0,correlationId:t||o.YM.EMPTY_STRING})}info(e,t){this.logMessage(e,{logLevel:n.Info,containsPii:!1,correlationId:t||o.YM.EMPTY_STRING})}infoPii(e,t){this.logMessage(e,{logLevel:n.Info,containsPii:!0,correlationId:t||o.YM.EMPTY_STRING})}verbose(e,t){this.logMessage(e,{logLevel:n.Verbose,containsPii:!1,correlationId:t||o.YM.EMPTY_STRING})}verbosePii(e,t){this.logMessage(e,{logLevel:n.Verbose,containsPii:!0,correlationId:t||o.YM.EMPTY_STRING})}trace(e,t){this.logMessage(e,{logLevel:n.Trace,containsPii:!1,correlationId:t||o.YM.EMPTY_STRING})}tracePii(e,t){this.logMessage(e,{logLevel:n.Trace,containsPii:!0,correlationId:t||o.YM.EMPTY_STRING})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}}},68537:function(e,t,r){r.a(e,(async function(e,n){try{var o=r(69475),i=e([o]);o=(i.then?(await i)():i)[0];class s{constructor(e){this.baseURL=e.baseURL,this.mode=e.mode}async get(e,t={},r={}){await this.__setAuthHeader(r);const n=new URLSearchParams(t);return await fetch(`${this.baseURL}${e}?${n.toString()}`,{method:"GET",headers:r})}async post(e,t={},r={},n={}){try{await this.__setAuthHeader(n);const o=new URLSearchParams(r);return await fetch(`${this.baseURL}${e}?${o.toString()}`,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){console.log("Errore during parsing JSON: ",e)}}async put(e,t={},r={},n={}){try{await this.__setAuthHeader(n);const o=new URLSearchParams(r);return await fetch(`${this.baseURL}${e}?${o.toString()}`,{method:"PUT",body:JSON.stringify(t),headers:n})}catch(e){console.log("Errore during parsing JSON: ",e)}}async delete(e,t={},r={}){await this.__setAuthHeader(r);const n=new URLSearchParams(t);return await fetch(`${this.baseURL}
2${e}?${n.toString()}`,{method:"DELETE",headers:r})}async __setAuthHeader(e){e.Authorization=await this.__getToken()}async __getToken(){const e=await o.Jp,t=e.getActiveAccount();if(!t)return"";let r;try{r=await e.acquireTokenSilent({...o.$8,account:t})}catch(e){(0,o.a1)()}const n=r?.accessToken;return n?`Bearer ${n}`:""}}function a(){const{USER_API_BASE_URL_SVIL:e,USER_API_BASE_URL_COLL:t,USER_API_BASE_URL_CERT:r,USER_API_BASE_URL_PROD:n,LOCALHOST_HOST:o,AUTHOR_HOST_COLL:i,PUBLISH_HOST_COLL:s,AUTHOR_HOST_CERT:a,PUBLISH_HOST_CERT:c}={CODEBUILD_VPC_AZ:"us-east-1b",PREVIOUS_PRODUCTION_VERSION:"2026.923.1192717.0009152813",BBC_MAVEN_PKG_VERSION:"3.9.4",CM_PIPELINE_ID:"30906617",MAVEN_OPTS:" -Xms2G -Xmx4G -Dmaven.wagon.http.pool=false -Daether.metadataResolver.threads=1 -Dorg.slf4j.simpleLogger.showDateTime=true -Dorg.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss,SSS -Dorg.slf4j.simpleLogger.showThreadName=true -Dmaven.wagon.httpconnectionManager.maxPerRoute=2",CODEBUILD_LAST_EXIT:"0",SQ_PLUGIN_LANGUAGES:"java,jsp",JAVA_PKG:"jdk-8u401-linux-x64.tar.gz",CODEBUILD_START_TIME:"1790694310815",TRACKING_CONTEXT_EXECUTIONID:"9189398",TRACKING_CONTEXT_PROGRAMID:"133367",TMP_LOG_DIR:"/mnt/logs",TRACKING_CONTEXT_TENANTID:"54754",CM_BUILD:"true",CODEBUILD_BMR_URL:"https://CODEBUILD_AGENT:3000",npm_config_user_agent:"npm/8.15.0 node/v16.17.0 linux x64 workspaces/false ci/aws-codebuild",FACT_TOOL_API_KEY:"cmVmdGtuOjAxOjE4MTc0MTYyMTk6Z3RyY0JzY3BGbWJ3MWtxV29YbzA4STdsbjRo",CODEBUILD_AGENT_ENDPOINT:"http://127.0.0.1:7831",TAG:"2026.923.1192717.0009152813",CODEBUILD_BUILD_ID:"cm-build-prod-va6-codebuild-54754:67b21792-5ca0-4939-90e6-2ea609505c3f",CTS_LINK_LOCAL_ADDR:"169.254.170.3",BRANCH:"main-p1p2",HOSTNAME:"ip-10-0-208-152.ec2.internal",CODEBUILD_KMS_KEY_ID:"arn:aws:kms:us-east-1:126898534526:alias/aws/s3",npm_node_execpath:"/build_root/build/primary-v2/superabile/ui.frontend/node/node",JAVA_PKG_SHA256:"19684fccd7ff32a8400e952a643f0049449a772ef63b8037d5b917cbd137d173",SHLVL:"0",CM_IMAGE_KEEPALIVE:"false",ENABLE_CMA_LOG_SCAN:"true",SQ_PLUGIN_SONAR_FINDBUGS_VERSION:"4.2.9",npm_config_noproxy:"",FACT_TOOL_COORDINATE:"com.adobe.granite:com.adobe.granite.fact:0.6.30",OLDPWD:"/build_root/build/primary-v2",SONARQUBE_PWD:"d9sVSeC91Ek20nWG",SIGNAL_BUILD_STOP:"99",HOME:"/root",RELEASE_CHANNEL:"live",FACT_TOOL_VERSION:"0.6.30",CM_TARGET_SOLUTIONS:"aemedgedeliveryservices,aemsites",CM_PIPELINE_EXECUTION_ID:"9189398",CODEBUILD_GOPATH:"/codebuild/output/src89192848",npm_package_json:"/build_root/build/primary-v2/superabile/ui.frontend/package.json",JAVA_PKG_ARM:"jdk-8u401-linux-aarch64.tar.gz",CODEBUILD_CI:"true",CODEBUILD_BUILD_SUCCEEDING:"1",TRACKING_CONTEXT_IMSORGID:"35E804F9601C21750A495E87@AdobeOrg",CM_PROGRAM_NAME:"INAIL Program 2",CODEBUILD_BUILD_NUMBER:"3605",IGNORE_DISPATCHER_PACKAGES:"true",CM_HOME:"/opt/cm",AWS_CONTAINER_CREDENTIALS_RELATIVE_URI:"/v2/credentials/ff982268-5243-4a59-b3b8-1780388510b5",CODEBUILD_BUILD_ARN:"arn:aws:codebuild:us-east-1:126898534526:build/cm-build-prod-va6-codebuild-54754:67b21792-5ca0-4939-90e6-2ea609505c3f",MAVEN_CMD_LINE_ARGS:"/root/.m2 --batch-mode org.jacoco:jacoco-maven-plugin:prepare-agent package -Dmaven.build.cache.skipCache=true -DcloudManagerOriginalVersion=1.0.0",npm_config_userconfig:"/root/.npmrc",npm_config_local_prefix:"/build_root/build/primary-v2/superabile/ui.frontend",COMMIT_SHA:"7a5665ede2047f409ecdd90e30b341cd5cba3e82",TARGET_PLATFORM:"SKYLINE",AWS_EXECUTION_ENV:"AWS_ECS_EC2",ASR_BBC_FLAVOR:"java_v8_build",CODEBUILD_ACTION_RUNNER_URL:"https://codefactory-us-east-1-prod-default-build-agent-executor.s3.us-east-1.amazonaws.com/cawsrunner.zip",JAVA_PKG_SHA256_ARM:"daa226b47bc57b03dbd6f7398eadd89d5fca5e98353e9e66017de362ecb7e7f8",COLOR:"0",CODEBUILD_INITIATOR:"cm-build-service",JAVA_VERSION:"8u401",MAVEN_PROJECTBASEDIR:"/build_root/build/primary-v2",NVM_DIR:"/usr/local/nvm",npm_config_metrics_registry:"https://registry.npmjs.org/",SONAR_RUNNER_OPTS:"-Xms2G -Xmx4G",ECS_AGENT_URI:"http://169.254.170.2/api/c7277d4f-4f16-4e93-bf22-7c021ccaba09",AWS_DEFAULT_REGION:"us-east-1",_:"/usr/lib/jvm/jdk-17.0.10/bin/java",BUILD_ROOT_DIR:"/build_root",CM_PROGRAM_ID:"133367",BBC_METADATA:"{   'BASE_FLAVOR': 'docker-base',    'BASE_VERSION': '6.0.1',    'BBC_FLAVOR': 'java_v8_build',    'BBC_VERSION': '15.5.0',    'OS_FAMILY': 'ubuntu',    'OS_FAMILY_VERSION': '22.04'}",npm_config_prefix:"/build_root/build/primary-v2/superabile/ui.frontend",JAVA_MAJOR_VERSION:"8",ARTIFACTS_VERSION:"2026.923.1192717.0009152813",ECS_CONTAINER_METADATA_URI_V4:"http://169.254.170.2/v4/c7277d4f-4f16-4e93-bf22-7c021ccaba09",CM_BUILD_DISABLE_MODULE_CACHING:"true",npm_config_cache:"/root/.npm",ECS_CONTAINER_METADATA_URI:"http://169.254.170.2/v3/c7277d4f-4f16-4e93-bf22-7c021ccaba09",SONAR_VERSION:"9.9.5.90363",MAVEN_CACHE_DIR:"/mnt/mvncache",CODEBUILD_EXECUTION_ROLE_BUILD:"",SQ_PLUGIN_AEM_RULES_VERSION:"1.6",npm_config_node_gyp:"/build_root/build/primary-v2/superabile/ui.frontend/node/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js",PATH:"/build_root/build/primary-v2/superabile/ui.frontend/node_modules/.bin:/build_root/build/primary-v2/superabile/node_modules/.bin:/build_root/build/primary-v2/node_modules/.bin:/build_root/build/node_modules/.bin:/build_root/node_modules/.bin:/node_modules/.bin:/build_root/build/primary-v2/superabile/ui.frontend/node/node_modules/npm/node_modules/@npmcli/run-script/lib/node-gyp-bin:/build_root/build/primary-v2/superabile/ui.frontend/node:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/codebuild/user/bin:",NOT_ROOT_USER:"asruser",FE_REPORT_LINK_LOCAL_ADDR:"169.254.170.8",CODEBUILD_PROJECT_ARN:"arn:aws:codebuild:us-east-1:126898534526:project/cm-build-prod-va6-codebuild-54754",NODE:"/build_root/build/primary-v2/superabile/ui.frontend/node/node",npm_package_name:"aem-maven-archetype",CODEBUILD_LOG_PATH:"67b21792-5ca0-4939-90e6-2ea609505c3f",S6_BEHAVIOUR_IF_STAGE2_FAILS:"2",BBC_MAVEN_PKG_SHA256:"ff66b70c830a38d331d44f6c25a37b582471def9a161c93902bac7bea3098319",CODEBUILD_BUILD_IMAGE:"126898534526.dkr.ecr.us-east-1.amazonaws.com/self-service-build:2026.9.0",JAVA_OPTS:"-Xms2G -Xmx6G --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED",SKIP_TAGGING:"true",TRACKING_CONTEXT_PIPELINEID:"30906617",LANG:"C.UTF-8",CM_PIPELINE_TYPE:"CI_CD",npm_lifecycle_script:"webpack --config ./webpack.prod.js && clientlib --verbose",SONARQUBE_STARTED_FILE:"/tmp/sonarqube-started",UID:"1001",CODEBUILD_CTS_ENDPOINT:"https://codebuild-builds.us-east-1.amazonaws.com",CM_EGRESS_IP:"18.214.178.13",SKIP_CHANGELOG_GENERATION:"true",CM_DISABLE_BUILD_REUSE:"true",GOPATH:"/codebuild/output/src89192848",npm_package_version:"1.0.0",npm_lifecycle_event:"prod",BUILD_CLOUD_PLATFORM:"aws",BBC_VERSION:"15.5.0",AWS_REGION:"us-east-1",CODEBUILD_BUILD_URL:"https://us-east-1.console.aws.amazon.com/codebuild/home?region=us-east-1#/builds/cm-build-prod-va6-codebuild-54754:67b21792-5ca0-4939-90e6-2ea609505c3f/view/new",S6_READ_ONLY_ROOT:"1",CODEBUILD_
2SRC_DIR:"/codebuild/output/src89192848/src",SONARQUBE_HOME:"/opt/sonarqube",S6_KILL_FINISH_MAXTIME:"5000",CODEBUILD_PROJECT_UUID:"8c6a458b-2c07-42fa-9b98-2e987e2ef481",CODEBUILD_AUTH_TOKEN:"c996e0d3-9d0f-4cd5-8b21-f06c43fac538",CODEBUILD_CONTAINER_NAME:"default",CM_BUILD_CACHE_EXTENSION_DIR:"/opt/cm/cm-build-cache-extension/",CMA_TOOL_DIRECTORY_PATH:"/opt/cm/cma-tool/",CMA_LOG_SCAN_REMOVAL_DATE_DEFS:"MjAyNS0wOC0zMT0yMDI2LTAyLTI2LDIwMjYtMDMtMzA7MjAyNi0wOS0zMD0yMDI3LTAxLTA3LDIwMjctMDItMTU=",JAVA_11_HOME:"/usr/lib/jvm/jdk-11.0.22",CODEBUILD_SCRIPT_DIR:"/codebuild/output/tmp",CM_PIPELINE_NAME:"Production Pipeline - Full stack",FACT_TOOL_DIR:"/opt/cm/fact-tool/",CM_DEBUG:"true",REPOSITORY_URL:"[email protected]:v3/adobecloudmanager-inail/primary-v2/primary-v2",npm_config_globalconfig:"/build_root/build/primary-v2/superabile/ui.frontend/etc/npmrc",npm_config_init_module:"/root/.npm-init.js",PWD:"/build_root/build/primary-v2/superabile/ui.frontend",ARTEFACT_PATH:"/artefacts",JAVA_HOME:"/usr/lib/jvm/jdk-17.0.10",SONARQUBE_METRICS:"",REPOSITORY_TYPE:"STANDARD",npm_execpath:"/build_root/build/primary-v2/superabile/ui.frontend/node/node_modules/npm/bin/npm-cli.js",CODEBUILD_FE_REPORT_ENDPOINT:"https://codebuild.us-east-1.amazonaws.com/",MAVEN_CONFIG:"/root/.m2",npm_config_global_prefix:"/build_root/build/primary-v2/superabile/ui.frontend",SYNC_CACHE_TIMEOUT:"1800s",IS_SANDBOX:"false",SONAR_JAVA_HOME:"/usr/lib/jvm/jdk-17.0.10",npm_command:"run-script",BUILD_TRANSFORM_ENABLED:"true",CM_ADDONS:"eyJhZGRvbnMiOltdfQ==",FACT_TOOL_CACHE_DIR:"/root/.m2/repository/fact-tool-cache",S6_KILL_GRACETIME:"3000",CM_AEM_PRODUCT_VERSION:"aem-skyline-dd65768dc",EXECUTE_FACT_TOOL_ONLY:"false",AWS_EMF_ENVIRONMENT:"Local",INIT_CWD:"/build_root/build/primary-v2/superabile/ui.frontend",EDITOR:"vi",APP_GQL_ENDPOINT:"content/cq:graphql/superabile/endpoint.json",GOOGLE_MAPS_API_KEY_COLL:"AIzaSyBCGAMPghvesThVG0jfAjg9JeyV1J5yqjE",GOOGLE_MAPS_API_KEY_CERT:"AIzaSyANT-ts-fmmhza_jj9T-Kw7b4cjYoY7VY0",GOOGLE_MAPS_API_KEY_PROD:"AIzaSyCqDbyltsiWe8V-ow3ddBCZ_hXjShV6GEU",LOCALHOST_HOST:"locahost:4502",AUTHOR_HOST_COLL:"author-p133367-e1313542.adobeaemcloud.com",PUBLISH_HOST_COLL:"coll2.superabile.it",AUTHOR_HOST_CERT:"author-p133367-e1445776.adobeaemcloud.com",PUBLISH_HOST_CERT:"cert2.superabile.it",USER_API_BASE_URL_SVIL:"https://app-superabile-dev-italynorth.azurewebsites.net",USER_API_BASE_URL_COLL:"https://apicoll.inailcloud.it/api/spabl/app-api",USER_API_BASE_URL_CERT:"https://apicert.inailcloud.it/api/spabl/app-api",USER_API_BASE_URL_PROD:"https://api.inailcloud.it/api/spabl/app-api",USER_CLIENT_MODE:"cors",CYPRESS_PARAM:"3e009ea927f5fcc5992d9a68d030b3df684ad56cee4bdc8c5559f1002047832a"},l=window.location.host,h=[{match:[o],url:e},{match:[i,s],url:t},{match:[a,c],url:r}];for(const{match:e,url:t}of h)if(e.some((e=>l.includes(e))))return t;return n}const c=new s({baseURL:a(),mode:"cors"});t.A=c,n()}catch(l){n(l)}}))},69475:function(e,t,r){r.a(e,(async function(e,n){try{r.d(t,{$8:function(){return h},Jp:function(){return u},RO:function(){return g},a1:function(){return p}});var o=r(55438),i=r(44081),s=r(99163),a=e([s]);s=(a.then?(await a)():a)[0];const c=document.getElementById("auth-info"),l={wellKnownURL:c?.getAttribute("data-wellKnown"),client_id:c?.getAttribute("data-clientID"),redirect_uri:c?.getAttribute("data-redirecturi"),authority:c?.getAttribute("data-authority"),knownAuthorities:c?.getAttribute("data-knownAuthorities"),cacheLocation:c?.getAttribute("data-cacheLocation"),navigateToLoginRequestUrl:c?.getAttribute("data-navigateToLoginRequestUrl"),storeAuthStateInCookie:c?.getAttribute("data-storeAuthStateInCookie"),inailGlobalConfig:c?.getAttribute("data-inailGlobalConfig"),inailEnv:c?.getAttribute("data-inailEnv")};if(!localStorage.getItem("end_session_endpoint")&&!window.location.hostname.includes("author")){const m=await fetch(l.inailGlobalConfig);if(m.ok){const f=await m.json();if(f.end_session_endpoint){const y=f.end_session_endpoint.replace("{App_URI}",l.redirect_uri);localStorage.setItem("end_session_endpoint",y)}}}const h={scopes:[l.client_id,"openid"]};let d={auth:{clientId:l.client_id,authority:l.authority,knownAuthorities:[l.knownAuthorities],redirectUri:l.redirect_uri,navigateToLoginRequestUrl:Boolean(l.navigateToLoginRequestUrl)},cache:{cacheLocation:l.cacheLocation,storeAuthStateInCookie:Boolean(l.storeAuthStateInCookie)},system:{loggerOptions:{loggerCallback:(e,t,r)=>{r||e!==o.$.Error||console.error(t)}}}};const u=(async()=>{const e=new i.vq(d);return await e.initialize(),e})();(async()=>{const e={...d,auth:{...d.auth,navigateToLoginRequestUrl:!1}},t=new i.vq(e);await t.initialize()})();async function g(e=!1){const t=await u,r=(0,s.n)();try{e&&(h.redirectStartPage="/portale/it.html"),t.loginRedirect(h)}catch(e){r.setError(e),console.error("Errore durante il login:",e)}}async function p(){const e=await u,t=(0,s.n)();t.$reset();try{const t={account:e.getAllAccounts()[0],postLogoutRedirectUri:localStorage.getItem("end_session_endpoint")};e.logoutRedirect(t)}catch(e){t.setError(e),console.error("Errore durante il logout:",e)}}n()}catch(C){n(C)}}),1)},81140:function(e,t,r){r.d(t,{$x:function(){return f},E_:function(){return _},F0:function(){return N},Fq:function(){return d},GU:function(){return w},Gd:function(){return l},I:function(){return S},IO:function(){return b},JR:function(){return A},LR:function(){return C},Lz:function(){return M},OK:function(){return c},Qd:function(){return y},RX:function(){return g},Rv:function(){return P},Xw:function(){return k},YM:function(){return n},_2:function(){return O},_A:function(){return a},_M:function(){return u},aG:function(){return I},aZ:function(){return s},gT:function(){return E},hB:function(){return v},jZ:function(){return R},p:function(){return m},t3:function(){return o},u0:function(){return T},v2:function(){return h},ym:function(){return i},zL:function(){return p}});const n={LIBRARY_NAME:"MSAL.JS",SKU:"msal.js.common",DEFAULT_AUTHORITY:"https://login.microsoftonline.com/common/",DEFAULT_AUTHORITY_HOST:"login.microsoftonline.com",DEFAULT_COMMON_TENANT:"common",ADFS:"adfs",DSTS:"dstsv2",AAD_INSTANCE_DISCOVERY_ENDPT:"https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=",CIAM_AUTH_URL:".ciamlogin.com",AAD_TENANT_DOMAIN_SUFFIX:".onmicrosoft.com",RESOURCE_DELIM:"|",NO_ACCOUNT:"NO_ACCOUNT",CLAIMS:"claims",CONSUMER_UTID:"9188040d-6c67-4c5b-b112-36a304b66dad",OPENID_SCOPE:"openid",PROFILE_SCOPE:"profile",OFFLINE_ACCESS_SCOPE:"offline_access",EMAIL_SCOPE:"email",CODE_GRANT_TYPE:"authorization_code",RT_GRANT_TYPE:"refresh_token",S256_CODE_CHALLENGE_METHOD:"S256",URL_FORM_CONTENT_TYPE:"application/x-www-form-urlencoded;charset=utf-8",AUTHORIZATION_PENDING:"authorization_pending",NOT_DEFINED:"not_defined",EMPTY_STRING:"",NOT_APPLICABLE:"N/A",NOT_AVAILABLE:"Not Available",FORWARD_SLASH:"/",IMDS_ENDPOINT:"http://169.254.169.254/metadata/instance/compute/location",IMDS_VERSION:"2020-06-01",IMDS_TIMEOUT:2e3,AZURE_REGION_AUTO_DISCOVER_FLAG:"TryAutoDetect",REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX:"login.microsoft.com",KNOWN_PUBLIC_CLOUDS:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],SHR_NONCE_VALIDITY:240,INVALID_INSTANCE:"invalid_instance"},o={SUCCESS:200,SUCCESS_RANGE_START:200,SUCCESS_RANGE_END:299,REDIRECT:302,CLIENT_ERROR:400,CLIENT_ERROR_RANGE_START:400,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,REQUEST_TIMEOUT:408,GONE:410,TOO_MANY_REQUESTS:429,CLIENT_ERROR_RANGE_END:499,SERVER_ERROR:500,SERVER_ERROR_RANGE_START:500,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,SERVER_ERROR_RANGE_END:599,MULTI_SIDED_ERROR:600},i={GET:"GET",POST:"POST"},s=[n.OPENID_SCOPE,n.PROFILE_SCOPE,n.OFFLINE_ACCESS_SCOPE],a=[...s,n.EMAIL_SCOPE],c={CONTENT_TYPE:"Content-Type",CONTENT_LENGTH:"Content-Length",RETRY_AFTER:"Retry-After",CCS_HEADER:"X-AnchorMailbox",WWWAuthenticate:"WWW-Authenticate",AuthenticationInfo:"Authentication-Info",X_MS_REQUEST_ID:"x-ms-request-id",X_MS_HTTP_VERSION:"x-ms-httpver"},l={ACTIVE_ACCOUNT_FILTERS:"active-account-filters"},h={COMMON:"common",ORGANIZATIONS:"organizations",CONSUMERS:"consumers"},d={ACCESS_TOKEN:"access_token",XMS_CC:"xms_cc"},u={LOGIN:"login",SELECT_ACCOUNT:"select_account",CONSENT:"consent",NONE:"none",CREATE:"create",NO_SESSION:"no_session"},g={CODE:"code",IDTOKEN_TOKEN:"id_token token",IDTOKEN_TOKEN_REFRESHTOKEN:"id_token token refresh_token"},p={QUERY:"query",FRAGMENT:"fragment"},m={QUERY:"query",FRAGMENT:"fragment",FORM_POST:"form_post"},f={IMPLICIT_GRANT:"implicit",AUTHORIZATION_CODE_GRANT:"authorization_code",CLIENT_CREDENTIALS_GRANT:"client_credentials",RESOURCE_OWNER_PASSWORD_GRANT:"password",REFRESH_TOKEN_GRANT:"refresh_token",DEVICE_CODE_GRANT:"device_code",JWT_BEARER:"ur
2n:ietf:params:oauth:grant-type:jwt-bearer"},y={MSSTS_ACCOUNT_TYPE:"MSSTS",ADFS_ACCOUNT_TYPE:"ADFS",MSAV1_ACCOUNT_TYPE:"MSA",GENERIC_ACCOUNT_TYPE:"Generic"},C={CACHE_KEY_SEPARATOR:"-",CLIENT_INFO_SEPARATOR:"."},I={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},w="appmetadata",A="client_info",v="1",T={CACHE_KEY:"authority-metadata",REFRESH_TIME_SECONDS:86400},_={CONFIG:"config",CACHE:"cache",NETWORK:"network",HARDCODED_VALUES:"hardcoded_values"},E={SCHEMA_VERSION:5,MAX_LAST_HEADER_BYTES:330,MAX_CACHED_ERRORS:50,CACHE_KEY:"server-telemetry",CATEGORY_SEPARATOR:"|",VALUE_SEPARATOR:",",OVERFLOW_TRUE:"1",OVERFLOW_FALSE:"0",UNKNOWN_ERROR:"unknown_error"},b={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},k={DEFAULT_THROTTLE_TIME_SECONDS:60,DEFAULT_MAX_THROTTLE_TIME_SECONDS:3600,THROTTLING_PREFIX:"throttling",X_MS_LIB_CAPABILITY_VALUE:"retry-after, h429"},S={INVALID_GRANT_ERROR:"invalid_grant",CLIENT_MISMATCH_ERROR:"client_mismatch"},R={FAILED_AUTO_DETECTION:"1",INTERNAL_CACHE:"2",ENVIRONMENT_VARIABLE:"3",IMDS:"4"},O={CONFIGURED_NO_AUTO_DETECTION:"2",AUTO_DETECTION_REQUESTED_SUCCESSFUL:"4",AUTO_DETECTION_REQUESTED_FAILED:"5"},P={NOT_APPLICABLE:"0",FORCE_REFRESH_OR_CLAIMS:"1",NO_CACHED_ACCESS_TOKEN:"2",CACHED_ACCESS_TOKEN_EXPIRED:"3",PROACTIVELY_REFRESHED:"4"},M={Jwt:"JWT",Jwk:"JWK",Pop:"pop"},N=300},84508:function(e,t,r){r.a(e,(async function(e,t){try{var n=r(69475),o=r(49133),i=e([n]);n=(i.then?(await i)():i)[0];const s=(0,o.r)()?.state?.value?.authStore?.user?.loggedIn;s||(0,n.RO)(!0),t()}catch(e){t(e)}}))},99163:function(e,t,r){r.a(e,(async function(e,n){try{r.d(t,{n:function(){return c}});var o=r(40036),i=r(16125),s=r(52442),a=e([i,s]);[i,s]=a.then?(await a)():a;const c=(0,o.defineStore)("authStore",{state:()=>({user:{nome:"",cognome:"",cf:"",sex:"",loginCount:0,interessi:[],luoghi:[],loggedIn:!1,error:""}}),actions:{setUser(e){this.user=e,this.user.loggedIn=!0},updateInteressi(e){e=e.map((e=>({dataInserimento:"",tagName:e.tagName,tagID:e.tagID}))),this.user.interessi=e,(0,i.DT)(e)},updateLuoghi(e){this.user.luoghi=e,e=e.map((e=>({dataInserimento:"",tagName:e.tagName,tagID:e.tagID}))),(0,s.GG)(e)},setError(e){this.user.error=e}},persist:{key:"auth-store",storage:localStorage}});n()}catch(e){n(e)}}))}},i={};function s(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={exports:{}};return o[e](r,r.exports,s),r.exports}e="function"==typeof Symbol?Symbol("webpack queues"):"__webpack_queues__",t="function"==typeof Symbol?Symbol("webpack exports"):"__webpack_exports__",r="function"==typeof Symbol?Symbol("webpack error"):"__webpack_error__",n=function(e){e&&e.d<1&&(e.d=1,e.forEach((function(e){e.r--})),e.forEach((function(e){e.r--?e.r++:e()})))},s.a=function(o,i,s){var a;s&&((a=[]).d=-1);var c,l,h,d=new Set,u=o.exports,g=new Promise((function(e,t){h=t,l=e}));g[t]=u,g[e]=function(e){a&&e(a),d.forEach(e),g.catch((function(){}))},o.exports=g,i((function(o){var i;c=function(o){return o.map((function(o){if(null!==o&&"object"==typeof o){if(o[e])return o;if(o.then){var i=[];i.d=0,o.then((function(e){s[t]=e,n(i)}),(function(e){s[r]=e,n(i)}));var s={};return s[e]=function(e){e(i)},s}}var a={};return a[e]=function(){},a[t]=o,a}))}(o);var s=function(){return c.map((function(e){if(e[r])throw e[r];return e[t]}))},l=new Promise((function(t){(i=function(){t(s)}).r=0;var r=function(e){e!==a&&!d.has(e)&&(d.add(e),e&&!e.d&&(i.r++,e.push(i)))};c.map((function(t){t[e](r)}))}));return i.r?l:s()}),(function(e){e?h(g[r]=e):l(u),n(a)})),a&&a.d<0&&(a.d=0)},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,{a:t}),t},s.d=function(e,t){for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};s(84508)}();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.