@azure/msal-browser
Version:
Microsoft Authentication Library for js
2 lines • 250 kB
JavaScript
/*! @azure/msal-browser v5.6.3 2026-04-01 */
"use strict";!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).msal={})}(this,(function(e){const t="https://login.microsoftonline.com/common/",r="common",n=`${t}discovery/instance?api-version=1.1&authorization_endpoint=`,o=".ciamlogin.com",i="openid",s="profile",a="offline_access",c="S256",h="Not Available",l="http://169.254.169.254/metadata/instance/compute/location",d=["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],u="GET",g="POST",p=[i,s,a],m=[...p,"email"],f="Content-Type",y="Content-Length",w="Retry-After",I="X-AnchorMailbox",C="WWW-Authenticate",v="Authentication-Info",k="x-ms-request-id",T="x-ms-httpver",b="active-account-filters",A="common",S="organizations",_="consumers",E="access_token",P="xms_cc",R={LOGIN:"login",SELECT_ACCOUNT:"select_account",CONSENT:"consent",NONE:"none",CREATE:"create",NO_SESSION:"no_session"},O="code",M="id_token token refresh_token",x={QUERY:"query",FRAGMENT:"fragment",FORM_POST:"form_post"},q="authorization_code",N="refresh_token",U="Generic",L={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},H="appmetadata",D="1",F="authority-metadata",K="config",B="cache",z="network",j="hardcoded_values",$=5,J="server-telemetry",W=",",G={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},Q="throttling",V="1",X="3",Y="4",Z="2",ee="4",te="5",re="0",ne="1",oe="2",ie="3",se="4",ae={Jwt:"JWT",Jwk:"JWK",Pop:"pop"},ce="client_id",he="redirect_uri",le="token_type",de="req_cnf",ue="return_spa_code",ge="x-client-xtra-sku",pe="brk_client_id",me="brk_redirect_uri",fe="instance_aware";function ye(e){return`See https://aka.ms/msal.js.errors#${e} for details`}class we extends Error{constructor(e,t,r){const n=t||(e?ye(e):"");super(n?`${e}: ${n}`:e),Object.setPrototypeOf(this,we.prototype),this.errorCode=e||"",this.errorMessage=n||"",this.subError=r||"",this.name="AuthError"}setCorrelationId(e){this.correlationId=e}}function Ie(e,t){return new we(e,t||ye(e))}class Ce extends we{constructor(e){super(e),this.name="ClientConfigurationError",Object.setPrototypeOf(this,Ce.prototype)}}function ve(e){return new Ce(e)}class ke{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}}}class Te extends we{constructor(e,t){super(e,t),this.name="ClientAuthError",Object.setPrototypeOf(this,Te.prototype)}}function be(e,t){return new Te(e,t)}const Ae="redirect_uri_empty",Se="authority_uri_insecure",_e="url_parse_error",Ee="empty_url_error",Pe="empty_input_scopes_error",Re="invalid_claims",Oe="token_request_empty",Me="logout_request_empty",xe="pkce_params_missing",qe="invalid_cloud_discovery_metadata",Ne="invalid_authority_metadata",Ue="untrusted_authority",Le="missing_ssh_jwk",He="missing_ssh_kid",De="missing_nonce_authentication_header",Fe="invalid_authentication_header",Ke="cannot_set_OIDCOptions",Be="cannot_allow_platform_broker",ze="authority_mismatch",je="invalid_request_method_for_EAR";var $e=Object.freeze({__proto__:null,authorityMismatch:ze,authorityUriInsecure:Se,cannotAllowPlatformBroker:Be,cannotSetOIDCOptions:Ke,claimsRequestParsingError:"claims_request_parsing_error",emptyInputScopesError:Pe,invalidAuthenticationHeader:Fe,invalidAuthorityMetadata:Ne,invalidClaims:Re,invalidCloudDiscoveryMetadata:qe,invalidCodeChallengeMethod:"invalid_code_challenge_method",invalidRequestMethodForEAR:je,logoutRequestEmpty:Me,missingNonceAuthenticationHeader:De,missingSshJwk:Le,missingSshKid:He,pkceParamsMissing:xe,redirectUriEmpty:Ae,tokenRequestEmpty:Oe,untrustedAuthority:Ue,urlEmptyError:Ee,urlParseError:_e});const Je="client_info_decoding_error",We="client_info_empty_error",Ge="token_parsing_error",Qe="null_or_empty_token",Ve="endpoints_resolution_error",Xe="network_error",Ye="openid_config_error",Ze="hash_not_deserialized",et="invalid_state",tt="state_mismatch",rt="state_not_found",nt="nonce_mismatch",ot="auth_time_not_found",it="max_age_transpired",st="multiple_matching_appMetadata",at="request_cannot_be_made",ct="cannot_remove_empty_scope",ht="cannot_append_scopeset",lt="empty_input_scopeset",dt="no_account_in_silent_request",ut="invalid_cache_record",gt="invalid_cache_environment",pt="no_account_found",mt="no_crypto_object",ft="token_refresh_required",yt="token_claims_cnf_required_for_signedjwt",wt="authorization_code_missing_from_server_response",It="binding_key_not_removed",Ct="end_session_endpoint_not_supported",vt="key_id_missing",kt="no_network_connectivity",Tt="user_canceled",bt="method_not_implemented",At="nested_app_auth_bridge_disabled",St="resource_parameter_required",_t="misplaced_resource_parameter";var Et=Object.freeze({__proto__:null,authTimeNotFound:ot,authorizationCodeMissingFromServerResponse:wt,bindingKeyNotRemoved:It,cannotAppendScopeSet:ht,cannotRemoveEmptyScope:ct,clientInfoDecodingError:Je,clientInfoEmptyError:We,emptyInputScopeSet:lt,endSessionEndpointNotSupported:Ct,endpointResolutionError:Ve,hashNotDeserialized:Ze,invalidCacheEnvironment:gt,invalidCacheRecord:ut,invalidState:et,keyIdMissing:vt,maxAgeTranspired:it,methodNotImplemented:bt,misplacedResourceParam:_t,multipleMatchingAppMetadata:st,multipleMatchingTokens:"multiple_matching_tokens",nestedAppAuthBridgeDisabled:At,networkError:Xe,noAccountFound:pt,noAccountInSilentRequest:dt,noCryptoObject:mt,noNetworkConnectivity:kt,nonceMismatch:nt,nullOrEmptyToken:Qe,openIdConfigError:Ye,platformBrokerError:"platform_broker_error",requestCannotBeMade:at,resourceParameterRequired:St,stateMismatch:tt,stateNotFound:rt,tokenClaimsCnfRequiredForSignedJwt:yt,tokenParsingError:Ge,tokenRefreshRequired:ft,unexpectedCredentialType:"unexpected_credential_type",userCanceled:Tt});class Pt{constructor(e){const t=e?ke.trimArrayEntries([...e]):[],r=t?ke.removeEmptyStringsFromArray(t):[];if(!r||!r.length)throw ve(Pe);this.scopes=new Set,r.forEach((e=>this.scopes.add(e)))}static fromString(e){const t=(e||"").split(" ");return new Pt(t)}static createSearchScopes(e){const t=e&&e.length>0?e:[...p],r=new Pt(t);return r.containsOnlyOIDCScopes()?r.removeScope(a):r.removeOIDCScopes(),r}containsScope(e){const t=this.printScopesLowerCase().split(" "),r=new Pt(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 m.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 be(ht)}}removeScope(e){if(!e)throw be(ct);this.scopes.delete(e.trim())}removeOIDCScopes(){m.forEach((e=>{this.scopes.delete(e)}))}unionScopeSets(e){if(!e)throw be(lt);const t=new Set;return e.scopes.forEach((e=>t.add(e.toLowerCase()))),this.scopes.forEach((e=>t.add(e.toLowerCase()))),t}intersectingScopeSets(e){if(!e)throw be(lt);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""}printScopesLowerCase(){return this.printScopes().toLowerCase()}}function Rt(e,t,r){if(!t)return;const n=e.get(ce);n&&e.has(pe)&&r?.addFields({embeddedClientId:n,embeddedRedirectUri:e.get(he)},t)}function Ot(e,t){e.set("response_type",t)}function Mt(e,t,r=!0,n=p){!r||n.includes("openid")||t.includes("openid")||n.push("openid");const o=r?[...t||[],...n]:t||[],i=new Pt(o);e.set("scope",i.printScopes())}function xt(e,t){e.set(ce,t)}function qt(e,t){e.set(he,t)}function Nt(e,t){e.set("login_hint",t)}function Ut(e,t){e.set(I,`UPN:${t}`)}function Lt(e,t){e.set(I,`Oid:${t.uid}@${t.utid}`)}function Ht(e,t){e.set("sid",t)}function Dt(e,t,r){const n=Yt(t,r);try{JSON.parse(n)}catch(e){throw ve(Re)}e.set("claims",n)}function Ft(e,t){e.set("client-request-id",t)}function Kt(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 Bt(e,t){t?.appName&&e.set("x-app-name",t.appName),t?.appVersion&&e.set("x-app-ver",t.appVersion)}function zt(e,t){t&&e.set("state",t)}function jt(e,t,r){if(!t||!r)throw ve(xe);e.set("code_challenge",t),e.set("code_challenge_method",r)}function $t(e,t){e.set("client_secret",t)}function Jt(e,t){t&&e.set("client_assertion",t)}function Wt(e,t){t&&e.set("client_assertion_type",t)}function Gt(e,t){e.set("grant_type",t)}function Qt(e){e.set("client_info","1")}function Vt(e){e.has(fe)||e.set(fe,"true")}function Xt(e,t){Object.entries(t).forEach((([t,r])=>{!e.has(t)&&r&&e.set(t,r)}))}function Yt(e,t){let r;if(e)try{r=JSON.parse(e)}catch(e){throw ve(Re)}else r={};return t&&t.length>0&&(r.hasOwnProperty(E)||(r[E]={}),r[E][P]={values:t}),JSON.stringify(r)}function Zt(e,t){t&&(e.set(le,G.POP),e.set(de,t))}function er(e,t){t&&(e.set(le,G.SSH),e.set(de,t))}function tr(e,t){e.set("x-client-current-telemetry",t.generateCurrentRequestHeaderValue()),e.set("x-client-last-telemetry",t.generateLastRequestHeaderValue())}function rr(e){e.set("x-ms-lib-capability","retry-after, h429")}function nr(e,t,r){e.has(pe)||e.set(pe,t),e.has(me)||e.set(me,r)}function or(e,t){t&&e.set("resource",t)}function ir(e){if(!e)return e;let t=e.toLowerCase();return ke.endsWith(t,"?")?t=t.slice(0,-1):ke.endsWith(t,"?/")&&(t=t.slice(0,-2)),ke.endsWith(t,"/")||(t+="/"),t}function sr(e){return e.startsWith("#/")?e.substring(2):e.startsWith("#")||e.startsWith("?")?e.substring(1):e}function ar(e){if(!e||e.indexOf("=")<0)return null;try{const t=sr(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 be(Ze)}return null}function cr(e){const t=new Array;return e.forEach(((e,r)=>{t.push(`${r}=${encodeURIComponent(e)}`)})),t.join("&")}function hr(e){if(!e)return e;const t=e.split("#")[0];try{const e=new URL(t);return ir(e.origin+e.pathname+e.search)}catch(e){return ir(t)}}const lr={createNewGuid:()=>{throw be(bt)},base64Decode:()=>{throw be(bt)},base64Encode:()=>{throw be(bt)},base64UrlEncode:()=>{throw be(bt)},encodeKid:()=>{throw be(bt)},async getPublicKeyThumbprint(){throw be(bt)},async removeTokenBindingKey(){throw be(bt)},async clearKeystore(){throw be(bt)},async signJwt(){throw be(bt)},async hashString(){throw be(bt)}};var dr;e.LogLevel=void 0,(dr=e.LogLevel||(e.LogLevel={}))[dr.Error=0]="Error",dr[dr.Warning=1]="Warning",dr[dr.Info=2]="Info",dr[dr.Verbose=3]="Verbose",dr[dr.Trace=4]="Trace";const ur=new Map;function gr(e,t){const r=Date.now();let n=ur.get(e);if(n)!function(e,t){ur.delete(e),ur.set(e,t)}(e,n);else if(n={logs:[],firstEventTime:r},ur.set(e,n),ur.size>50){const e=ur.keys().next().value;e&&ur.delete(e)}n.logs.push({...t,milliseconds:r-n.firstEventTime}),n.logs.length>500&&n.logs.shift()}class pr{constructor(t,r,n){this.level=e.LogLevel.Info;const o=t||pr.createDefaultLoggerOptions();this.localCallback=o.loggerCallback||(()=>{}),this.piiLoggingEnabled=o.piiLoggingEnabled||!1,this.level="number"==typeof o.logLevel?o.logLevel:e.LogLevel.Info,this.packageName=r||"",this.packageVersion=n||""}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:e.LogLevel.Info}}clone(e,t){return new pr({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level},e,t)}logMessage(t,r){const n=r.correlationId;if(function(e){if(6!==e.length)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(!(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"))return!1}return!0}(t)){gr(n,{hash:t,level:r.logLevel,containsPii:r.containsPii||!1,milliseconds:0})}if(r.logLevel>this.level||!this.piiLoggingEnabled&&r.containsPii)return;const o=`${`[${(new Date).toUTCString()}] : [${n}]`} : ${this.packageName}@${this.packageVersion} : ${e.LogLevel[r.logLevel]} - ${t}`;this.executeCallback(r.logLevel,o,r.containsPii||!1)}executeCallback(e,t,r){this.localCallback&&this.localCallback(e,t,r)}error(t,r){this.logMessage(t,{logLevel:e.LogLevel.Error,containsPii:!1,correlationId:r})}errorPii(t,r){this.logMessage(t,{logLevel:e.LogLevel.Error,containsPii:!0,correlationId:r})}warning(t,r){this.logMessage(t,{logLevel:e.LogLevel.Warning,containsPii:!1,correlationId:r})}warningPii(t,r){this.logMessage(t,{logLevel:e.LogLevel.Warning,containsPii:!0,correlationId:r})}info(t,r){this.logMessage(t,{logLevel:e.LogLevel.Info,containsPii:!1,correlationId:r})}infoPii(t,r){this.logMessage(t,{logLevel:e.LogLevel.Info,containsPii:!0,correlationId:r})}verbose(t,r){this.logMessage(t,{logLevel:e.LogLevel.Verbose,containsPii:!1,correlationId:r})}verbosePii(t,r){this.logMessage(t,{logLevel:e.LogLevel.Verbose,containsPii:!0,correlationId:r})}trace(t,r){this.logMessage(t,{logLevel:e.LogLevel.Trace,containsPii:!1,correlationId:r})}tracePii(t,r){this.logMessage(t,{logLevel:e.LogLevel.Trace,containsPii:!0,correlationId:r})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}}const mr="@azure/msal-common",fr="16.4.1",yr={None:"none",AzurePublic:"https://login.microsoftonline.com",AzurePpe:"https://login.windows-ppe.net",AzureChina:"https://login.chinacloudapi.cn",AzureGermany:"https://login.microsoftonline.de",AzureUsGovernment:"https://login.microsoftonline.us"};function wr(e,t){return!!e&&!!t&&e===t.split(".")[1]}function Ir(e,t,r,n){if(n){const{oid:t,sub:r,tid:o,name:i,tfp:s,acr:a,preferred_username:c,upn:h,login_hint:l}=n,d=o||s||a||"";return{tenantId:d,localAccountId:t||r||"",name:i,username:c||h||"",loginHint:l,isHomeTenant:wr(d,e)}}return{tenantId:r,localAccountId:t,username:"",isHomeTenant:wr(r,e)}}function Cr(e,t,r,n){let o=e;if(t){const{isHomeTenant:r,...n}=t;o={...e,...n}}if(r){const{isHomeTenant:t,...i}=Ir(e.homeAccountId,e.localAccountId,e.tenantId,r);return o={...o,...i,idTokenClaims:r,idToken:n},o}return o}function vr(e,t){const r=function(e){if(!e)throw be(Qe);const t=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(e);if(!t||t.length<4)throw be(Ge);return t[2]}(e);try{const e=t(r);return JSON.parse(e)}catch(e){throw be(Ge)}}function kr(e){if(!e.signin_state)return!1;const t=["kmsi","dvc_dmjd"];return e.signin_state.some((e=>t.includes(e.trim().toLowerCase())))}function Tr(e,t){if(0===t||Date.now()-3e5>e+t)throw be(it)}class br{get urlString(){return this._urlString}constructor(e){if(this._urlString=e,!this._urlString)throw ve(Ee);e.includes("#")||(this._urlString=br.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return ke.endsWith(t,"?")?t=t.slice(0,-1):ke.endsWith(t,"?/")&&(t=t.slice(0,-2)),ke.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch(e){throw ve(_e)}if(!e.HostNameAndPort||!e.PathSegments)throw ve(_e);if(!e.Protocol||"https:"!==e.Protocol.toLowerCase())throw ve(Se)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return br.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),r=t.PathSegments;return!e||0===r.length||r[0]!==A&&r[0]!==S||(r[0]=e),br.constructAuthorityUriFromObject(t)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw ve(_e);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 ve(_e);return r[2]}static getAbsoluteUrl(e,t){if("/"===e[0]){const r=new br(t).getUrlComponents();return r.Protocol+"//"+r.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e){return new br(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"))}}const Ar={endpointMetadata:[{host:"login.microsoftonline.com"},{host:"login.chinacloudapi.cn",issuerHost:"login.partner.microsoftonline.cn"},{host:"login.microsoftonline.us"},{host:"login.sovcloud-identity.fr"},{host:"login.sovcloud-identity.de"},{host:"login.sovcloud-identity.sg"}].reduce(((e,{host:t,issuerHost:r})=>(e[t]=function(e,t){return{token_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/token`,jwks_uri:`https://${e}/{tenantid}/discovery/v2.0/keys`,issuer:`https://${t}/{tenantid}/v2.0`,authorization_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/authorize`,end_session_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/logout`}}(t,r||t),e)),{}),instanceDiscoveryMetadata:{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"]},{preferred_network:"login.sovcloud-identity.fr",preferred_cache:"login.sovcloud-identity.fr",aliases:["login.sovcloud-identity.fr"]},{preferred_network:"login.sovcloud-identity.de",preferred_cache:"login.sovcloud-identity.de",aliases:["login.sovcloud-identity.de"]},{preferred_network:"login.sovcloud-identity.sg",preferred_cache:"login.sovcloud-identity.sg",aliases:["login.sovcloud-identity.sg"]}]}},Sr=Ar.endpointMetadata,_r=Ar.instanceDiscoveryMetadata,Er=new Set;function Pr(e,t,r,n,o){if(e.trace("1bmquz",t),r&&n){const o=Rr(n,r);if(o)return e.trace("1fotbt",t),o.aliases;e.trace("14avvj",t)}return null}function Rr(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.aliases.includes(t))return n}return null}_r.metadata.forEach((e=>{e.aliases.forEach((e=>{Er.add(e)}))}));const Or="cache_quota_exceeded";class Mr extends Error{constructor(e,t){const r=t||ye(e);super(r),Object.setPrototypeOf(this,Mr.prototype),this.name="CacheError",this.errorCode=e,this.errorMessage=r}}function xr(e){return e instanceof Error?"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||e.message.includes("exceeded the quota")?new Mr(Or):new Mr(e.name,e.message):new Mr("cache_error_unknown")}function qr(e,t){if(!e)throw be(We);try{const r=t(e);return JSON.parse(r)}catch(e){throw be(Je)}}function Nr(e){if(!e)throw be(Je);const t=e.split(".",2);return{uid:t[0],utid:t.length<2?"":t[1]}}const Ur=0,Lr=1,Hr=2,Dr=3;function Fr(e){if(e){return e.tid||e.tfp||e.acr||null}return null}const Kr={AAD:"AAD",OIDC:"OIDC",EAR:"EAR"};function Br(e){const t=e.tenantProfiles||[];return 0===t.length&&e.realm&&e.localAccountId&&t.push(Ir(e.homeAccountId,e.localAccountId,e.realm)),{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(t.map((e=>[e.tenantId,e]))),dataBoundary:e.dataBoundary}}function zr(e,t,r){const n=Array.from(e.tenantProfiles?.values()||[]);return 0===n.length&&e.tenantId&&e.localAccountId&&n.push(Ir(e.homeAccountId,e.localAccountId,e.tenantId,e.idTokenClaims)),{authorityType:e.authorityType||U,homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,nativeAccountId:e.nativeAccountId,realm:e.tenantId,environment:e.environment,username:e.username,loginHint:e.loginHint,name:e.name,cloudGraphHostName:t,msGraphHost:r,tenantProfiles:n,dataBoundary:e.dataBoundary}}function jr(e,t,r,n,o,i){if(t!==Lr&&t!==Hr){if(e)try{const t=qr(e,n.base64Decode);if(t.uid&&t.utid)return`${t.uid}.${t.utid}`}catch(e){}r.warning("1ub6wv",o)}return i?.sub||""}class $r{constructor(e,t,r,n,o){this.clientId=e,this.cryptoImpl=t,this.commonLogger=r.clone(mr,fr),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=>null==e||""===e)))return this.commonLogger.warning("1skb02",t),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?Br(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=vr(a.secret,this.cryptoImpl.base64Decode),!this.idTokenClaimsMatchTenantProfileFilter(i,o))?null:(s=Cr(e,r,i,a?.secret),s)}getTenantProfilesFromAccountEntity(e,t,r,n){const o=Br(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,o){if(!e)throw be(ut);try{e.account&&await this.setAccount(e.account,t,r,n),e.idToken&&!1!==o?.idToken&&await this.setIdTokenCredential(e.idToken,t,r),e.accessToken&&!1!==o?.accessToken&&await this.saveAccessToken(e.accessToken,t,r),e.refreshToken&&!1!==o?.refreshToken&&await this.setRefreshTokenCredential(e.refreshToken,t,r),e.appMetadata&&this.setAppMetadata(e.appMetadata,t)}catch(e){throw this.commonLogger?.error("0j476p",t),e instanceof we?e:xr(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},o=this.getTokenKeys(),i=Pt.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,t)){Pt.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,t))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,r){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,r))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(e.credentialType===L.ACCESS_TOKEN_WITH_AUTH_SCHEME){if(t.tokenType&&!this.matchTokenType(e,t.tokenType))return!1;if(t.tokenType===G.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId))return!1}return!0}getAppMetadataFilteredBy(e,t){const r=this.getKeys(),n={};return r.forEach((r=>{if(!this.isAppMetadata(r))return;const o=this.getAppMetadata(r,t);o&&(e.environment&&!this.matchEnvironment(o,e.environment,t)||e.clientId&&!this.matchClientId(o,e.clientId)||(n[r]=o))})),n}getAuthorityMetadataByAlias(e,t){const r=this.getAuthorityMetadataKeys();let n=null;return r.forEach((r=>{if(!this.isAuthorityMetadata(r)||-1===r.indexOf(this.clientId))return;const o=this.getAuthorityMetadata(r,t);o&&-1!==o.aliases.indexOf(e)&&(n=o)})),n}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(r&&(this.removeItem(e,t),this.performanceClient.incrementFields({accessTokensRemoved:1},t),r.credentialType.toLowerCase()===L.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()&&r.tokenType===G.POP)){const e=r.keyId;e&&this.cryptoImpl.removeTokenBindingKey(e,t).catch((()=>{this.commonLogger.error("0cx291",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){this.commonLogger.trace("1drz22",t);const o={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:L.ID_TOKEN,clientId:this.clientId,realm:n},i=this.getIdTokensByFilter(o,t,r),s=i.size;if(s<1)return this.commonLogger.info("1atvtd",t),null;if(s>1){let r=i;if(!n){const n=new Map;i.forEach(((t,r)=>{t.realm===e.tenantId&&n.set(r,t)}));const o=n.size;if(o<1)return this.commonLogger.info("0ooalx",t),i.values().next().value;if(1===o)return this.commonLogger.info("1eq2vc",t),n.values().next().value;r=n}return this.commonLogger.info("1ws328",t),r.forEach(((e,r)=>{this.removeIdToken(r,t)})),this.performanceClient.addFields({multiMatchedID:i.size},t),null}return this.commonLogger.info("1sm769",t),i.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,t)&&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 o=t.correlationId;this.commonLogger.trace("1t7hz1",o);const i=Pt.createSearchScopes(t.scopes),s=t.authenticationScheme||G.BEARER,a=s&&s.toLowerCase()!==G.BEARER.toLowerCase()?L.ACCESS_TOKEN_WITH_AUTH_SCHEME:L.ACCESS_TOKEN,c={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:a,clientId:this.clientId,realm:n||e.tenantId,target:i,tokenType:s,keyId:t.sshKid},h=r&&r.accessToken||this.getTokenKeys().accessToken,l=[];h.forEach((e=>{if(this.accessTokenKeyMatchesFilter(e,c,!0)){const t=this.getAccessTokenCredential(e,o);t&&this.credentialMatchesFilter(t,c,o)&&l.push(t)}}));const d=l.length;return d<1?(this.commonLogger.info("1nckna",o),null):d>1?(this.commonLogger.info("1wkfwp",o),l.forEach((e=>{this.removeAccessToken(this.generateCredentialKey(e),o)})),this.performanceClient.addFields({multiMatchedAT:l.length},o),null):(this.commonLogger.info("06yt98",o),l[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.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=[];return r.accessToken.forEach((r=>{if(!this.accessTokenKeyMatchesFilter(r,e,!0))return;const o=this.getAccessTokenCredential(r,t);o&&this.credentialMatchesFilter(o,e,t)&&n.push(o)})),n}getRefreshToken(e,t,r,n){this.commonLogger.trace("0x53vi",r);const o=t?D:void 0,i={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:L.REFRESH_TOKEN,clientId:this.clientId,familyId:o},s=n&&n.refreshToken||this.getTokenKeys().refreshToken,a=[];s.forEach((e=>{if(this.refreshTokenKeyMatchesFilter(e,i)){const t=this.getRefreshTokenCredential(e,r);t&&this.credentialMatchesFilter(t,i,r)&&a.push(t)}}));const c=a.length;return c<1?(this.commonLogger.info("0dlw11",r),null):(c>1&&this.performanceClient.addFields({multiMatchedRT:c},r),this.commonLogger.info("0wcnep",r),a[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,t){const r={environment:e,clientId:this.clientId},n=this.getAppMetadataFilteredBy(r,t),o=Object.keys(n).map((e=>n[e])),i=o.length;if(i<1)return null;if(i>1)throw be(st);return o[0]}isAppMetadataFOCI(e,t){const r=this.readAppMetadataFromCache(e,t);return!(!r||r.familyId!==D)}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,r){if(this.staticAuthorityOptions){const n=function(e,t,r){let n;const o=e.canonicalAuthority;if(o){const i=new br(o).getUrlComponents().HostNameAndPort;n=Pr(t,r,i,e.cloudDiscoveryMetadata?.metadata)||Pr(t,r,i,_r.metadata)||e.knownAuthorities}return n||[]}(this.staticAuthorityOptions,this.commonLogger,r);if(n.includes(t)&&n.includes(e.environment))return!0}const n=this.getAuthorityMetadataByAlias(t,r);return!!(n&&n.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!==L.ACCESS_TOKEN&&e.credentialType!==L.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target)return!1;return Pt.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(H)}isAuthorityMetadata(e){return-1!==e.indexOf(F)}generateAuthorityMetadataCacheKey(e){return`${F}-${this.clientId}-${e}`}static toObject(e,t){for(const r in t)e[r]=t[r];return e}}class Jr extends $r{async setAccount(){throw be(bt)}getAccount(){throw be(bt)}async setIdTokenCredential(){throw be(bt)}getIdTokenCredential(){throw be(bt)}async setAccessTokenCredential(){throw be(bt)}getAccessTokenCredential(){throw be(bt)}async setRefreshTokenCredential(){throw be(bt)}getRefreshTokenCredential(){throw be(bt)}setAppMetadata(){throw be(bt)}getAppMetadata(){throw be(bt)}setServerTelemetry(){throw be(bt)}getServerTelemetry(){throw be(bt)}setAuthorityMetadata(){throw be(bt)}getAuthorityMetadata(){throw be(bt)}getAuthorityMetadataKeys(){throw be(bt)}setThrottlingCache(){throw be(bt)}getThrottlingCache(){throw be(bt)}removeItem(){throw be(bt)}getKeys(){throw be(bt)}getAccountKeys(){throw be(bt)}getTokenKeys(){throw be(bt)}generateCredentialKey(){throw be(bt)}generateAccountKey(){throw be(bt)}}const Wr=1,Gr=2,Qr="ext.",Vr=new Set(["accessTokenSize","durationMs","idTokenSize","matsSilentStatus","matsHttpStatus","refreshTokenSize","startTimeMs","status","multiMatchedAT","multiMatchedID","multiMatchedRT","unencryptedCacheCount","encryptedCacheExpiredCount","oldAccountCount","oldAccessCount","oldIdCount","oldRefreshCount","currAccountCount","currAccessCount","currIdCount","currRefreshCount","expiredCacheRemovedCount","upgradedCacheCount","cacheMatchedAccounts","networkRtt","redirectBridgeTimeoutMs","redirectBridgeMessageVersion"]);class Xr{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:Wr,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""}}}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}incrementFields(){}cacheEventByCorrelationId(){}}const Yr={tokenRenewalOffsetSeconds:300,preventCorsPreflight:!1},Zr={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:e.LogLevel.Info,correlationId:""},en={async sendGetRequestAsync(){throw be(bt)},async sendPostRequestAsync(){throw be(bt)}},tn={sku:"msal.js.common",version:fr,cpu:"",os:""},rn={clientSecret:"",clientAssertion:void 0},nn={azureCloudInstance:yr.None,tenant:`${r}`},on={application:{appName:"",appVersion:""}};function sn({authOptions:e,systemOptions:t,loggerOptions:r,storageInterface:n,networkInterface:o,cryptoInterface:i,clientCredentials:s,libraryInfo:a,telemetry:c,serverTelemetryManager:h,persistencePlugin:l,serializableCache:d}){const u={...Zr,...r};return{authOptions:(g=e,{clientCapabilities:[],azureCloudOptions:nn,instanceAware:!1,isMcp:!1,...g}),systemOptions:{...Yr,...t},loggerOptions:u,storageInterface:n||new Jr(e.clientId,lr,new pr(u),new Xr),networkInterface:o||en,cryptoInterface:i||lr,clientCredentials:s||rn,libraryInfo:{...tn,...a},telemetry:{...on,...c},serverTelemetryManager:h||null,persistencePlugin:l||null,serializableCache:d||null};var g}function an(e){return e.authOptions.authority.options.protocolMode===Kr.OIDC}class cn{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}function hn(){return Math.round((new Date).getTime()/1e3)}function ln(e){return e.getTime()/1e3}function dn(e){return e?new Date(1e3*Number(e)):new Date}function un(e,t){const r=Number(e)||0;return hn()+t>r}function gn(e,t){const r=Number(e)+24*t*60*60*1e3;return Date.now()>r}function pn(e){return Number(e)>hn()}function mn(e,t,r,n,o){return{credentialType:L.ID_TOKEN,homeAccountId:e,environment:t,clientId:n,secret:r,realm:o,lastUpdatedAt:Date.now().toString()}}function fn(e,t,r,n,o,i,s,a,c,h,l,d,u){const g={homeAccountId:e,credentialType:L.ACCESS_TOKEN,secret:r,cachedAt:hn().toString(),expiresOn:s.toString(),extendedExpiresOn:a.toString(),environment:t,clientId:n,realm:o,target:i,tokenType:l||G.BEARER,lastUpdatedAt:Date.now().toString()};if(d&&(g.userAssertionHash=d),h&&(g.refreshOn=h.toString()),g.tokenType?.toLowerCase()!==G.BEARER.toLowerCase())switch(g.credentialType=L.ACCESS_TOKEN_WITH_AUTH_SCHEME,g.tokenType){case G.POP:const e=vr(r,c);if(!e?.cnf?.kid)throw be(yt);g.keyId=e.cnf.kid;break;case G.SSH:g.keyId=u}return g}function yn(e,t,r,n,o,i,s){const a={credentialType:L.REFRESH_TOKEN,homeAccountId:e,environment:t,clientId:n,secret:r,lastUpdatedAt:Date.now().toString()};return i&&(a.userAssertionHash=i),o&&(a.familyId=o),s&&(a.expiresOn=s.toString()),a}function wn(e){return e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("credentialType")&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("secret")}function In(e){return!!e&&(wn(e)&&e.hasOwnProperty("realm")&&e.hasOwnProperty("target")&&(e.credentialType===L.ACCESS_TOKEN||e.credentialType===L.ACCESS_TOKEN_WITH_AUTH_SCHEME))}function Cn(e){return!!e&&(wn(e)&&e.credentialType===L.REFRESH_TOKEN)}function vn(){return hn()+86400}function kn(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 Tn(e,t,r){e.aliases=t.aliases,e.preferred_cache=t.preferred_cache,e.preferred_network=t.preferred_network,e.aliasesFromNetwork=r}function bn(e){return e.expiresAt<=hn()}const An="networkClientSendPostRequestAsync",Sn="refreshTokenClientAcquireTokenWithCachedRefreshToken",_n="getAuthCodeUrl",En="handleCodeResponseFromServer",Pn="popTokenGenerateCnf",Rn="handleServerTokenResponse",On="authorityUpdateMetadataWithRegionalInformation",Mn="regionDiscoveryGetRegionFromIMDS",xn=(e,t,r,n,o)=>(...i)=>{r.trace("1plfzx",o);const s=n.startMeasurement(t,o);o&&n.incrementFields({[`ext.${t}CallCount`]:1},o);try{const t=e(...i);return s.end({success:!0}),r.trace("1g8n6a",o),t}catch(e){r.trace("0cfd8i",o);try{r.trace(JSON.stringify(e),o)}catch(e){r.trace("00dty7",o)}throw s.end({success:!1},e),e}},qn=(e,t,r,n,o)=>(...i)=>{r.trace("1plfzx",o);const s=n.startMeasurement(t,o);return o&&n.incrementFields({[`ext.${t}CallCount`]:1},o),e(...i).then((e=>(r.trace("1g8n6a",o),s.end({success:!0}),e))).catch((e=>{r.trace("0cfd8i",o);try{r.trace(JSON.stringify(e),o)}catch(e){r.trace("00dty7",o)}throw s.end({success:!1},e),e}))},Nn="sw";class Un{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){const r=await qn(this.generateKid.bind(this),Pn,t,this.performanceClient,e.correlationId)(e),n=this.cryptoUtils.base64UrlEncode(JSON.stringify(r));return{kid:r.kid,reqCnfString:n}}async generateKid(e){return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:Nn}}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,h=i?new br(i):void 0,l=h?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:hn(),m:o?.toUpperCase(),u:l?.HostNameAndPort,nonce:a||this.cryptoUtils.createNewGuid(),p:l?.AbsolutePath,q:l?.QueryString?[[],l.QueryString]:void 0,client_claims:s||void 0,...n},t,c,r.correlationId)}}const Ln="no_tokens_found",Hn="native_account_unavailable",Dn="refresh_token_expired",Fn="ux_not_allowed",Kn="interaction_required",Bn="consent_required",zn="login_required",jn="bad_token",$n="interrupted_user";var Jn=Object.freeze({__proto__:null,badToken:jn,consentRequired:Bn,interactionRequired:Kn,interruptedUser:$n,loginRequired:zn,nativeAccountUnavailable:Hn,noTokensFound:Ln,refreshTokenExpired:Dn,uxNotAllowed:Fn});const Wn=[Kn,Bn,zn,jn,Fn,$n],Gn=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token","ux_not_allowed","interrupted_user"];class Qn extends we{constructor(e,t,r,n,o,i,s,a){super(e,t,r),Object.setPrototypeOf(this,Qn.prototype),this.timestamp=n||"",this.traceId=o||"",this.correlationId=i||"",this.claims=s||"",this.name="InteractionRequiredAuthError",this.errorNo=a}}function Vn(e,t,r){const n=!!e&&Wn.indexOf(e)>-1,o=!!r&&Gn.indexOf(r)>-1,i=!!t&&Wn.some((e=>t.indexOf(e)>-1));return n||i||o}function Xn(e,t){return new Qn(e,t)}class Yn extends we{constructor(e,t,r,n,o){super(e,t,r),this.name="ServerError",this.errorNo=n,this.status=o,Object.setPrototypeOf(this,Yn.prototype)}}function Zn(e,t,r){const n=function(e,t){if(!e)throw be(mt);const r={id:e.createNewGuid()};t&&(r.meta=t);const n=JSON.stringify(r);return e.base64Encode(n)}(e,r);return t?`${n}|${t}`:n}function eo(e,t){if(!e)throw be(mt);if(!t)throw be(et);try{const r=t.split("|"),n=r[0],o=r.length>1?r.slice(1).join("|"):"",i=e(n);return{userRequestState:o||"",libraryState:JSON.parse(i)}}catch(e){throw be(et)}}class to{constructor(e,t,r,n,o,i,s){this.clientId=e,this.cacheStorage=t,this.cryptoObj=r,this.logger=n,this.performanceClient=o,this.serializableCache=i,this.persistencePlugin=s}validateTokenResponse(e,t,r){if(e.error||e.error_description||e.suberror){const n=`Error(s): ${e.error_codes||h} - Timestamp: ${e.timestamp||h} - Description: ${e.error_description||h} - Correlation ID: ${e.correlation_id||h} - Trace ID: ${e.trace_id||h}`,o=e.error_codes?.length?e.error_codes[0]:void 0,i=new Yn(e.error,n,e.suberror,o,e.status);if(r&&e.status&&e.status>=500&&e.status<=599)return void this.logger.warning("16ks7j",t);if(r&&e.status&&e.status>=400&&e.status<=499)return void this.logger.warning("0g61x3",t);if(Vn(e.error,e.error_description,e.suberror))throw new Qn(e.error,e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.correlation_id||"",e.claims||"",o);throw i}}async handleServerTokenResponse(e,t,r,n,o,i,s,a,c,h){let l,d;if(e.id_token){if(l=vr(e.id_token||"",this.cryptoObj.base64Decode),i&&i.nonce&&l.nonce!==i.nonce)throw be(nt);if(n.maxAge||0===n.maxAge){const e=l.auth_time;if(!e)throw be(ot);Tr(e,n.maxAge)}}this.homeAccountIdentifier=jr(e.client_info||"",t.authorityType,this.logger,this.cryptoObj,n.correlationId,l),i&&i.state&&(d=eo(this.cryptoObj.base64Decode,i.state)),e.key_id=e.key_id||n.sshKid||void 0;const u=this.generateCacheRecord(e,t,r,n,l,s,i);let g;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("0jbz5k",n.correlationId),g=new cn(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(g)),a&&!c&&u.account){if(this.cacheStorage.getAllAccounts({homeAccountId:u.account.homeAccountId,environment:u.account.environment},n.correlationId).length<1)return this.logger.warning("1gmt66",n.correlationId),this.performanceClient?.addFields({acntLoggedOut:!0},n.correlationId),await to.generateAuthenticationResult(this.cryptoObj,t,u,!1,n,this.performanceClient,l,d,void 0,h)}await this.cacheStorage.saveCacheRecord(u,n.correlationId,kr(l||{}),o,n.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&g&&(this.logger.verbose("1bh17u",n.correlationId),await this.persistencePlugin.afterCacheAccess(g))}return to.generateAuthenticationResult(this.cryptoObj,t,u,!1,n,this.performanceClient,l,d,e,h)}generateCacheRecord(e,t,r,n,o,i,s){const a=t.getPreferredCache();if(!a)throw be(gt);const c=Fr(o);let h,l;e.id_token&&o&&(h=mn(this.homeAccountIdentifier,a,e.id_token,this.clientId,c||""),l=ro(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,n.correlationId,o,e.client_info,a,c,s,void 0,this.logger,this.performanceClient));let d=null;if(e.access_token){const o=e.scope?Pt.fromString(e.scope):new Pt(n.scopes||[]),s=("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0,h=("string"==typeof e.ext_expires_in?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,l=("string"==typeof e.refresh_in?parseInt(e.refresh_in,10):e.refresh_in)||void 0,u=r+s,g=u+h,p=l&&l>0?r+l:void 0;d=fn(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);const m=n.resource||null;m&&(d.resource=m)}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),this.performanceClient?.addFields({ntwkRtExpiresOnSeconds:t},n.correlationId)}u=yn(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:l,idToken:h,accessToken:d,refreshToken:u,appMetadata:g}}static async generateAuthenticationResult(e,t,r,n,o,i,s,a,c,h){let l,d,u="",g=[],p=null,m="";if(r.accessToken){if(r.accessToken.tokenType!==G.POP||o.popKid)u=r.accessToken.secret;else{const t=new Un(e,i),{secret:n,keyId:s}=r.accessToken;if(!s)throw be(vt);u=await t.signPopToken(n,s,o)}g=Pt.fromString(r.accessToken.target).asArray(),p=dn(r.accessToken.expiresOn),l=dn(r.accessToken.extendedExpiresOn),r.accessToken.refreshOn&&(d=dn(r.accessToken.refreshOn))}r.appMetadata&&(m=r.appMetadata.familyId===D?D:"");const f=s?.oid||s?.sub||"",y=s?.tid||"";c?.spa_accountid&&r.account&&(r.account.nativeAccountId=c?.spa_accountid);const w=r.account?Cr(Br(r.account),void 0,s,r.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:f,tenantId:y,scopes:g,account:w,idToken:r?.idToken?.secret||"",idTokenClaims:s||{},accessToken:u,fromCache:n,expiresOn:p,extExpiresOn:l,refreshOn:d,correlationId:o.correlationId,requestId:h||"",familyId:m,tokenType:r.accessToken?.tokenType||"",state:a?a.userRequestState:"",cloudGraphHostName:r.account?.cloudGraphHostName||"",msGraphHost:r.account?.msGraphHost||"",code:c?.spa_code,fromPlatformBroker:!1}}}function ro(e,t,r,n,o,i,s,a,c,h,l,d,u){d?.verbose("09jz0t",o);const g=a||t.getPreferredCache(),p=e.getAccountsFilteredBy({homeAccountId:r,environment:g},o);u?.addFields({cacheMatchedAccounts:p.length},o),p.length>1&&d?.warning("0x7ad1",o);const m=(1===p.length?p[0]:null)||function(e,t,r){let n,o,i;n=t.authorityType===Lr?"ADFS":t.protocolMode===Kr.OIDC?U:"MSSTS",e.clientInfo&&r&&(o=qr(e.clientInfo,r),o.xms_tdbr&&(i="EU"===o.xms_tdbr?"EU":"None"));const s=e.environment||t&&t.getPreferredCache();if(!s)throw be(gt);const a=e.idTokenClaims?.preferred_username||e.idTokenClaims?.upn,c=e.idTokenClaims?.emails?e.idTokenClaims.emails[0]:null,h=a||c||"",l=e.idTokenClaims?.login_hint,d=o?.utid||Fr(e.idTokenClaims)||"",u=o?.uid||e.idTokenClaims?.oid||e.idTokenClaims?.sub||"";let g;g=e.tenantProfiles?e.tenantProfiles:[Ir(e.homeAccountId,u,d,e.idTokenClaims)];return{homeAccountId:e.homeAccountId,environment:s,realm:d,localAccountId:u,username:h,authorityType:n,loginHint:l,clientInfo:e.clientInfo,name:e.idTokenClaims?.name||"",lastModificationTime:void 0,lastModificationApp:void 0,cloudGraphHostName:e.cloudGraphHostName,msGraphHost:e.msGraphHost,nativeAccountId:e.nativeAccountId,tenantProfiles:g,dataBoundary:i}}({homeAccountId:r,idTokenClaims:i,clientInfo:s,environment:a,cloudGraphHostName:h?.cloud_graph_host_name,msGraphHost:h?.msgraph_host,nativeAccountId:l},t,n),f=m.tenantProfiles||[],y=c||m.realm;if(y&&!f.find((e=>e.tenantId===y))){const e=Ir(r,m.localAccountId,y,i);f.push(e)}return m.tenantProfiles=f,m}const no="home_account_id",oo="UPN";async function io(e,t,r){if("string"==typeof e)return e;return e({clientId:t,tokenEndpoint:r})}function so(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.extraParameters?.clientId}}class ao{static generateThrottlingStorageKey(e){return`${Q}.${JSON.stringify(e)}`}static preProcess(e,t,r){const n=ao.generateThrottlingStorageKey(t),o=e.getThrottlingCache(n,r);if(o){if(o.throttleTime<Date.now())return void e.removeItem(n,r);throw new Yn(o.errorCodes?.join(" ")||"",o.errorMessage,o.subError)}}static postProcess(e,t,r,n){if(ao.checkResponseStatus(r)||ao.checkResponseForRetryAfter(r)){const o={throttleTime:ao.calculateThrottleTime(parseInt(r.headers[w])),error:r.body.error,errorCodes:r.body.error_codes,errorMessage:r.body.error_description,subError:r.body.suberror};e.setThrottlingCache(ao.generateThrottlingStorageKey(t),o,n)}}static checkResponseStatus(e){return 429===e.status||e.status>=500&&e.status<600}static checkResponseForRetryAfter(e){return!!e.headers&&(e.headers.hasOwnProperty(w)&&(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||60),r+3600))}static removeThrottle(e,t,r,n){const o=so(t,r,n),i=this.generateThrottlingStorageKey(o);e.removeItem(i,r.correlationId)}}class co extends we{constructor(e,t,r){super(e.errorCode,e.errorMessage,e.subError),Object.setPrototypeOf(this,co.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=r}}function ho(e,t,r,n){return e.errorMessage=`${e.errorMessage}, additionalErrorInfo: error.name:${n?.name}, error.message:${n?.message}`,new co(e,t,r)}function lo(e,t,r){const n={};if(n[f]="application/x-www-form-urlencoded;charset=utf-8",!t&&r)switch(r.type){case no:try{const e=Nr(r.credential);n[I]=`Oid:${e.uid}@${e.utid}`}catch(t){e.verbose("1qhtee","")}