PageSourceSearch

https://www.ace.de/etc.clientlibs/ace/clientlibs/clientlib-site/resources/content-switch.142593ed.js

js ace.de collected 2026-09-24 19:00:07 UTC 300,440 bytes, 2 lines download raw bytes

1/*! For license information please see content-switch.142593ed.js.LICENSE.txt */
2"use strict";(self.webpackChunkaem_maven_archetype=self.webpackChunkaem_maven_archetype||[]).push([["content-switch"],{1020:function(e,t,r){var n=r(6540),o=Symbol.for("react.element"),i=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,a=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,c={key:!0,ref:!0,__self:!0,__source:!0};function l(e,t,r){var n,i={},l=null,h=null;for(n in void 0!==r&&(l=""+r),void 0!==t.key&&(l=""+t.key),void 0!==t.ref&&(h=t.ref),t)s.call(t,n)&&!c.hasOwnProperty(n)&&(i[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps)void 0===i[n]&&(i[n]=t[n]);return{$$typeof:o,type:e,key:l,ref:h,props:i,_owner:a.current}}t.Fragment=i,t.jsx=l,t.jsxs=l},4848:function(e,t,r){e.exports=r(1020)},5719:function(e,t,r){var n=r(1083),o=function(e,t,r,n){return new(r||(r=Promise))(function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},i=function(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}};t.A=function(e){var t,r,s,a=n.A.create({baseURL:(t=window.location.protocol,r=window.location.hostname,s=window.location.port,"".concat(t,"//").concat(r).concat(s?":".concat(s):"")),headers:{"Content-Type":"application/json; charset=UTF-8"},timeout:3e4,withCredentials:!0});a.interceptors.request.use(function(t){return e&&(t.headers.Authorization="Bearer ".concat(e)),t.headers["X-Requested-With"]="XMLHttpRequest",t},function(e){return Promise.reject(e)}),a.interceptors.response.use(function(e){return e},function(e){return Promise.reject(e)});var c=function(e){return e.data};return{get:function(e,t){return o(void 0,void 0,void 0,function(){var r,n;return i(this,function(o){switch(o.label){case 0:return r=function(e){if(!e)return"";var t=Array.from(e.keys()).map(function(t){return"".concat(t,"=").concat(encodeURIComponent("".concat(e.get(t))))}).join("&");return"?".concat(t)}(t),[4,a.get("".concat(e).concat(r),void 0)];case 1:return n=o.sent(),[2,c(n)]}})})},patch:function(e,t){return o(void 0,void 0,void 0,function(){var r;return i(this,function(n){switch(n.label){case 0:return[4,a.patch(e,t,void 0)];case 1:return r=n.sent(),[2,c(r)]}})})},post:function(e,t){return o(void 0,void 0,void 0,function(){var r;return i(this,function(n){switch(n.label){case 0:return[4,a.post(e,t,void 0)];case 1:return r=n.sent(),[2,c(r)]}})})},put:function(e,t){return o(void 0,void 0,void 0,function(){var r;return i(this,function(n){switch(n.label){case 0:return[4,a.put(e,t,void 0)];case 1:return r=n.sent(),[2,c(r)]}})})},delete:function(e,t){return o(void 0,void 0,void 0,function(){var r;return i(this,function(n){switch(n.label){case 0:return[4,a.delete(e,void 0!==t?{data:t}:void 0)];case 1:return r=n.sent(),[2,c(r)]}})})}}}},4333:function(e,t,r){r.d(t,{c:function(){return n}});var n=(0,r(6540).createContext)({isAuthenticated:!1,login:function(){},register:function(){},logout:function(){},userAccount:null,getAccessToken:function(){return Promise.reject()},changeEmail:function(){},changeName:function(){},changePassword:function(){},deleteAccount:function(){}})},1583:function(e,t,r){r.d(t,{O:function(){return Kl}});var n=r(4848),o=r(6540);const i={LIBRARY_NAME:"MSAL.JS",SKU:"msal.js.common",CACHE_PREFIX:"msal",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_RESPONSE_TYPE:"code",CODE_GRANT_TYPE:"authorization_code",RT_GRANT_TYPE:"refresh_token",FRAGMENT_RESPONSE_MODE:"fragment",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"],TOKEN_RESPONSE_TYPE:"token",ID_TOKEN_RESPONSE_TYPE:"id_token",SHR_NONCE_VALIDITY:240,INVALID_INSTANCE:"invalid_instance"},s=400,a=499,c=500,l=599,h=[i.OPENID_SCOPE,i.PROFILE_SCOPE,i.OFFLINE_ACCESS_SCOPE],d=[...h,i.EMAIL_SCOPE],u="Content-Type",g="Content-Length",p="Retry-After",m="X-AnchorMailbox",f="x-ms-request-id",y="x-ms-httpver",C="active-account-filters",w="common",v="organizations",I="consumers",T="access_token",A="xms_cc",b={LOGIN:"login",SELECT_ACCOUNT:"select_account",CONSENT:"consent",NONE:"none",CREATE:"create",NO_SESSION:"no_session"},S={PLAIN:"plain",S256:"S256"},k={QUERY:"query",FRAGMENT:"fragment"},E={...k,FORM_POST:"form_post"},_="authorization_code",R="refresh_token",P="MSSTS",O="ADFS",N="Generic",M="-",q=".",U={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},L="appmetadata",x="1",H="authority-metadata",D=86400,B="config",F="cache",K="network",j="hardcoded_values",z={SCHEMA_VERSION:5,MAX_CUR_HEADER_BYTES:80,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"},$={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},G=60,Q=3600,W="throttling",V="retry-after, h429",J="invalid_grant",Y="client_mismatch",X="username",Z="password",ee=200,te=400,re="1",ne="3",oe="4",ie="2",se="4",ae="5",ce="0",le="1",he="2",de="3",ue="4",ge="pop",pe="invalid_grant",me=483,fe=600,ye="msal",Ce=30,we="msal.js.browser",ve="53ee284d-920a-4b59-9d30-a60315b26836",Ie="ppnbnpeolgkicgegkbkbjmhlideopiji",Te="MATS",Ae="Handshake",be="HandshakeResponse",Se="GetToken",ke="Response",Ee="localStorage",_e="sessionStorage",Re="memoryStorage",Pe="GET",Oe="POST",Ne="authority",Me="request.state",qe="nonce.id_token",Ue="request.origin",Le="urlHash",xe="request.params",He="interaction.status",De="ccs.credential",Be="request.correlationId",Fe="request.native",Ke="msal.account.keys",je="msal.token.keys",ze="wrapper.sku",$e="wrapper.version",Ge=861,Qe=862,We=863,Ve=865,Je=866,Ye=61,Xe=961,Ze=962;var et;!function(e){e.Redirect="redirect",e.Popup="popup",e.Silent="silent",e.None="none"}(et||(et={}));const tt={Startup:"startup",Login:"login",Logout:"logout",AcquireToken:"acquireToken",SsoSilent:"ssoSilent",HandleRedirect:"handleRedirect",None:"none"},rt={scopes:h},nt={React:"@azure/msal-react",Angular:"@azure/msal-angular"},ot="msal.db",it=`${ot}.keys`,st=0,at=1,ct=2,lt=3,ht=4,dt=5,ut=[st,dt,ht];var gt;!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"}(gt||(gt={}));class pt{constructor(e,t,r){this.level=gt.Info;const n=e||pt.createDefaultLoggerOptions();this.localCallback=n.loggerCallback||(()=>{}),this.piiLoggingEnabled=n.piiLoggingEnabled||!1,this.level="number"==typeof n.logLevel?n.logLevel:gt.Info,this.correlationId=n.correlationId||i.EMPTY_STRING,this.packageName=t||i.EMPTY_STRING,this.packageVersion=r||i.EMPTY_STRING}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:gt.Info}}clone(e,t,r){return new pt({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} : ${gt[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:gt.Error,containsPii:!1,correlationId:t||i.EMPTY_STRING})}errorPii(e,t){this.logMessage(e,{logLevel:gt.Error,containsPii:!0,correlationId:t||i.EMPTY_STRING})}warning(e,t){this.logMessage(e,{logLevel:gt.Warning,containsPii:!1,correlationId:t||i.EMPTY_STRING})}warningPii(e,t){this.logMessage(e,{logLevel:gt.Warning,containsPii:!0,correlationId:t||i.EMPTY_STRING})}info(e,t){this.logMessage(e,{logLevel:gt.Info,containsPii:!1,correlationId:t||i.EMPTY_STRING})}infoPii(e,t){this.logMessage(e,{logLevel:gt.Info,containsPii:!0,correlationId:t||i.EMPTY_STRING})}verbose(e,t){this.logMessage(e,{logLevel:gt.Verbose,containsPii:!1,correlationId:t||i.EMPTY_STRING})}verbosePii(e,t){this.logMessage(e,{logLevel:gt.Verbose,containsPii:!0,correlationId:t||i.EMPTY_STRING})}trace(e,t){this.logMessage(e,{logLevel:gt.Trace,containsPii:!1,correlationId:t||i.EMPTY_STRING})}tracePii(e,t){this.logMessage(e,{logLevel:gt.Trace,containsPii:!0,correlationId:t||i.EMPTY_STRING})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}}const mt="AAD",ft="OIDC",yt="none",Ct="unexpected_error",wt="post_request_failed",vt={[Ct]:"Unexpected error in authentication.",[wt]:"Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details."};
2class It extends Error{constructor(e,t,r){super(t?`${e}: ${t}`:e),Object.setPrototypeOf(this,It.prototype),this.errorCode=e||i.EMPTY_STRING,this.errorMessage=t||i.EMPTY_STRING,this.subError=r||i.EMPTY_STRING,this.name="AuthError"}setCorrelationId(e){this.correlationId=e}}function Tt(e,t){return new It(e,t?`${vt[e]} ${t}`:vt[e])}const At="client_info_decoding_error",bt="client_info_empty_error",St="token_parsing_error",kt="null_or_empty_token",Et="endpoints_resolution_error",_t="network_error",Rt="openid_config_error",Pt="hash_not_deserialized",Ot="invalid_state",Nt="state_mismatch",Mt="state_not_found",qt="nonce_mismatch",Ut="auth_time_not_found",Lt="max_age_transpired",xt="multiple_matching_tokens",Ht="multiple_matching_accounts",Dt="multiple_matching_appMetadata",Bt="request_cannot_be_made",Ft="cannot_remove_empty_scope",Kt="cannot_append_scopeset",jt="empty_input_scopeset",zt="device_code_polling_cancelled",$t="device_code_expired",Gt="device_code_unknown_error",Qt="no_account_in_silent_request",Wt="invalid_cache_record",Vt="invalid_cache_environment",Jt="no_account_found",Yt="no_crypto_object",Xt="unexpected_credential_type",Zt="invalid_assertion",er="invalid_client_credential",tr="token_refresh_required",rr="user_timeout_reached",nr="token_claims_cnf_required_for_signedjwt",or="authorization_code_missing_from_server_response",ir="binding_key_not_removed",sr="end_session_endpoint_not_supported",ar="key_id_missing",cr="no_network_connectivity",lr="user_canceled",hr="missing_tenant_id_error",dr="method_not_implemented",ur="nested_app_auth_bridge_disabled",gr={[At]:"The client info could not be parsed/decoded correctly",[bt]:"The client info was empty",[St]:"Token cannot be parsed",[kt]:"The token is null or empty",[Et]:"Endpoints cannot be resolved",[_t]:"Network request failed",[Rt]:"Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",[Pt]:"The hash parameters could not be deserialized",[Ot]:"State was not the expected format",[Nt]:"State mismatch error",[Mt]:"State not found",[qt]:"Nonce mismatch error",[Ut]:"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.",[Lt]:"Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",[xt]:"The cache contains multiple tokens satisfying the requirements. Call AcquireToken again providing more requirements such as authority or account.",[Ht]:"The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",[Dt]:"The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",[Bt]:"Token request cannot be made without authorization code or refresh token.",[Ft]:"Cannot remove null or empty scope from ScopeSet",[Kt]:"Cannot append ScopeSet",[jt]:"Empty input ScopeSet cannot be processed",[zt]:"Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",[$t]:"Device code is expired.",[Gt]:"Device code stopped polling for unknown reasons.",[Qt]:"Please pass an account object, silent flow is not supported without account information",[Wt]:"Cache record object was null or undefined.",[Vt]:"Invalid environment when attempting to create cache entry",[Jt]:"No account found in cache for given key.",[Yt]:"No crypto object detected.",[Xt]:"Unexpected credential type.",[Zt]:"Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515",[er]:"Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",[tr]:"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.",[rr]:"User defined timeout for device code polling reached",[nr]:"Cannot generate a POP jwt if the token_claims are not populated",[or]:"Server response does not contain an authorization code to proceed",[ir]:"Could not remove the credential's binding key from storage.",[sr]:"The provided authority does not support logout",[ar]:"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.",[cr]:"No network connectivity. Check your internet connection.",[lr]:"User cancelled the flow.",[hr]:"A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",[dr]:"This method has not been implemented",[ur]:"The nested app auth bridge is disabled"};class pr extends It{constructor(e,t){super(e,t?`${gr[e]}: ${t}`:gr[e]),this.name="ClientAuthError",Object.setPrototypeOf(this,pr.prototype)}}function mr(e,t){return new pr(e,t)}const fr={createNewGuid:()=>{throw mr(dr)},base64Decode:()=>{throw mr(dr)},base64Encode:()=>{throw mr(dr)},base64UrlEncode:()=>{throw mr(dr)},encodeKid:()=>{throw mr(dr)},async getPublicKeyThumbprint(){throw mr(dr)},async removeTokenBindingKey(){throw mr(dr)},async clearKeystore(){throw mr(dr)},async signJwt(){throw mr(dr)},async hashString(){throw mr(dr)}},yr="@azure/msal-common",Cr="15.0.2";function wr(e,t){const r=function(e){if(!e)throw mr(kt);const t=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(e);if(!t||t.length<4)throw mr(St);return t[2]}(e);try{const e=t(r);return JSON.parse(e)}catch(e){throw mr(St)}}function vr(e,t){if(0===t||Date.now()-3e5>e+t)throw mr(Lt)}function Ir(){return Math.round((new Date).getTime()/1e3)}function Tr(e,t){const r=Number(e)||0;return Ir()+t>r}function Ar(e){return[_r(e),Rr(e),Pr(e),Or(e),Nr(e)].join(M).toLowerCase()}function br(e,t,r,n,o){return{credentialType:U.ID_TOKEN,homeAccountId:e,environment:t,clientId:n,secret:r,realm:o}}function Sr(e,t,r,n,o,i,s,a,c,l,h,d,u,g,p){const m={homeAccountId:e,credentialType:U.ACCESS_TOKEN,secret:r,cachedAt:Ir().toString(),expiresOn:s.toString(),extendedExpiresOn:a.toString(),environment:t,clientId:n,realm:o,target:i,tokenType:h||$.BEARER};if(d&&(m.userAssertionHash=d),l&&(m.refreshOn=l.toString()),g&&(m.requestedClaims=g,m.requestedClaimsHash=p),m.tokenType?.toLowerCase()!==$.BEARER.toLowerCase())switch(m.credentialType=U.ACCESS_TOKEN_WITH_AUTH_SCHEME,m.tokenType){case $.POP:const e=wr(r,c);if(!e?.cnf?.kid)throw mr(nr);m.keyId=e.cnf.kid;break;
2case $.SSH:m.keyId=u}return m}function kr(e,t,r,n,o,i,s){const a={credentialType:U.REFRESH_TOKEN,homeAccountId:e,environment:t,clientId:n,secret:r};return i&&(a.userAssertionHash=i),o&&(a.familyId=o),s&&(a.expiresOn=s.toString()),a}function Er(e){return e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("credentialType")&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("secret")}function _r(e){return[e.homeAccountId,e.environment].join(M).toLowerCase()}function Rr(e){const t=e.credentialType===U.REFRESH_TOKEN&&e.familyId||e.clientId;return[e.credentialType,t,e.realm||""].join(M).toLowerCase()}function Pr(e){return(e.target||"").toLowerCase()}function Or(e){return(e.requestedClaimsHash||"").toLowerCase()}function Nr(e){return e.tokenType&&e.tokenType.toLowerCase()!==$.BEARER.toLowerCase()?e.tokenType.toLowerCase():""}function Mr(){return Ir()+D}function qr(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 Ur(e,t,r){e.aliases=t.aliases,e.preferred_cache=t.preferred_cache,e.preferred_network=t.preferred_network,e.aliasesFromNetwork=r}function Lr(e){return e.expiresAt<=Ir()}const xr="redirect_uri_empty",Hr="claims_request_parsing_error",Dr="authority_uri_insecure",Br="url_parse_error",Fr="empty_url_error",Kr="empty_input_scopes_error",jr="invalid_prompt_value",zr="invalid_claims",$r="token_request_empty",Gr="logout_request_empty",Qr="invalid_code_challenge_method",Wr="pkce_params_missing",Vr="invalid_cloud_discovery_metadata",Jr="invalid_authority_metadata",Yr="untrusted_authority",Xr="missing_ssh_jwk",Zr="missing_ssh_kid",en="missing_nonce_authentication_header",tn="invalid_authentication_header",rn="cannot_set_OIDCOptions",nn="cannot_allow_platform_broker",on="authority_mismatch",sn={[xr]:"A redirect URI is required for all calls, and none has been set.",[Hr]:"Could not parse the given claims request object.",[Dr]:"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",[Br]:"URL could not be parsed into appropriate segments.",[Fr]:"URL was empty or null.",[Kr]:"Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",[jr]:"Please see here for valid configuration options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_common.html#commonauthorizationurlrequest",[zr]:"Given claims parameter must be a stringified JSON object.",[$r]:"Token request was empty and not found in cache.",[Gr]:"The logout request was null or undefined.",[Qr]:'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',[Wr]:"Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",[Vr]:"Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",[Jr]:"Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",[Yr]:"The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",[Xr]:"Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",[Zr]:"Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",[en]:"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.",[tn]:"Invalid authentication header provided",[rn]:"Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",[nn]:"Cannot set allowPlatformBroker parameter to true when not in AAD protocol mode.",[on]:"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."};class an extends It{constructor(e){super(e,sn[e]),this.name="ClientConfigurationError",Object.setPrototypeOf(this,an.prototype)}}function cn(e){return new an(e)}class ln{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," "));
2return 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 hn{constructor(e){const t=e?ln.trimArrayEntries([...e]):[],r=t?ln.removeEmptyStringsFromArray(t):[];if(!r||!r.length)throw cn(Kr);this.scopes=new Set,r.forEach(e=>this.scopes.add(e))}static fromString(e){const t=(e||i.EMPTY_STRING).split(" ");return new hn(t)}static createSearchScopes(e){const t=new hn(e);return t.containsOnlyOIDCScopes()?t.removeScope(i.OFFLINE_ACCESS_SCOPE):t.removeOIDCScopes(),t}containsScope(e){const t=this.printScopesLowerCase().split(" "),r=new hn(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 d.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 mr(Kt)}}removeScope(e){if(!e)throw mr(Ft);this.scopes.delete(e.trim())}removeOIDCScopes(){d.forEach(e=>{this.scopes.delete(e)})}unionScopeSets(e){if(!e)throw mr(jt);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 mr(jt);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 i.EMPTY_STRING}printScopesLowerCase(){return this.printScopes().toLowerCase()}}function dn(e,t){if(!e)throw mr(bt);try{const r=t(e);return JSON.parse(r)}catch(e){throw mr(At)}}function un(e){if(!e)throw mr(At);const t=e.split(q,2);return{uid:t[0],utid:t.length<2?i.EMPTY_STRING:t[1]}}function gn(e,t){return!!e&&!!t&&e===t.split(".")[1]}function pn(e,t,r,n){if(n){const{oid:t,sub:r,tid:o,name:i,tfp:s,acr:a}=n,c=o||s||a||"";return{tenantId:c,localAccountId:t||r||"",name:i,isHomeTenant:gn(c,e)}}return{tenantId:r,localAccountId:t,isHomeTenant:gn(r,e)}}function mn(e,t,r,n){let o=e;if(t){const{isHomeTenant:r,...n}=t;o={...e,...n}}if(r){const{isHomeTenant:t,...i}=pn(e.homeAccountId,e.localAccountId,e.tenantId,r);return o={...o,...i,idTokenClaims:r,idToken:n},o}return o}const fn=0,yn=1,Cn=2,wn=3;function vn(e){if(e){return e.tid||e.tfp||e.acr||null}return null}class In{generateAccountId(){return[this.homeAccountId,this.environment].join(M).toLowerCase()}generateAccountKey(){return In.generateAccountCacheKey({homeAccountId:this.homeAccountId,environment:this.environment,tenantId:this.realm,username:this.username,localAccountId:this.localAccountId})}getAccountInfo(){return{homeAccountId:this.homeAccountId,environment:this.environment,tenantId:this.realm,username:this.username,localAccountId:this.localAccountId,name:this.name,nativeAccountId:this.nativeAccountId,authorityType:this.authorityType,tenantProfiles:new Map((this.tenantProfiles||[]).map(e=>[e.tenantId,e]))}}isSingleTenant(){return!this.tenantProfiles}static generateAccountCacheKey(e){const t=e.homeAccountId.split(".")[1];return[e.homeAccountId,e.environment||"",t||e.tenantId||""].join(M).toLowerCase()}static createAccount(e,t,r){const n=new In;let o;t.authorityType===yn?n.authorityType=O:t.protocolMode===mt?n.authorityType=P:n.authorityType=N,e.clientInfo&&r&&(o=dn(e.clientInfo,r)),n.clientInfo=e.clientInfo,n.homeAccountId=e.homeAccountId,n.nativeAccountId=e.nativeAccountId;const i=e.environment||t&&t.getPreferredCache();if(!i)throw mr(Vt);n.environment=i,n.realm=o?.utid||vn(e.idTokenClaims)||"",n.localAccountId=o?.uid||e.idTokenClaims?.oid||e.idTokenClaims?.sub||"";
2const s=e.idTokenClaims?.preferred_username||e.idTokenClaims?.upn,a=e.idTokenClaims?.emails?e.idTokenClaims.emails[0]:null;if(n.username=s||a||"",n.name=e.idTokenClaims?.name||"",n.cloudGraphHostName=e.cloudGraphHostName,n.msGraphHost=e.msGraphHost,e.tenantProfiles)n.tenantProfiles=e.tenantProfiles;else{const t=pn(e.homeAccountId,n.localAccountId,n.realm,e.idTokenClaims);n.tenantProfiles=[t]}return n}static createFromAccountInfo(e,t,r){const n=new In;return n.authorityType=e.authorityType||N,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.cloudGraphHostName=t,n.msGraphHost=r,n.tenantProfiles=Array.from(e.tenantProfiles?.values()||[]),n}static generateHomeAccountId(e,t,r,n,o){if(t!==yn&&t!==Cn){if(e)try{const t=dn(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.environment===t.environment&&e.nativeAccountId===t.nativeAccountId&&n}}function Tn(e){return e.startsWith("#/")?e.substring(2):e.startsWith("#")||e.startsWith("?")?e.substring(1):e}function An(e){if(!e||e.indexOf("=")<0)return null;try{const t=Tn(e),r=Object.fromEntries(new URLSearchParams(t));if(r.code||r.error||r.error_description||r.state)return r}catch(e){throw mr(Pt)}return null}class bn{get urlString(){return this._urlString}constructor(e){if(this._urlString=e,!this._urlString)throw cn(Fr);e.includes("#")||(this._urlString=bn.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return ln.endsWith(t,"?")?t=t.slice(0,-1):ln.endsWith(t,"?/")&&(t=t.
2slice(0,-2)),ln.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch(e){throw cn(Br)}if(!e.HostNameAndPort||!e.PathSegments)throw cn(Br);if(!e.Protocol||"https:"!==e.Protocol.toLowerCase())throw cn(Dr)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return bn.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),r=t.PathSegments;return!e||0===r.length||r[0]!==w&&r[0]!==v||(r[0]=e),bn.constructAuthorityUriFromObject(t)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw cn(Br);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 cn(Br);return r[2]}static getAbsoluteUrl(e,t){if(e[0]===i.FORWARD_SLASH){const r=new bn(t).getUrlComponents();return r.Protocol+"//"+r.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e){return new bn(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"))}static hashContainsKnownProperties(e){return!!An(e)}}const Sn={"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"}},kn={tenant_discovery_endpoint:"https://{canonicalAuthority}/v2.0/.well-known/openid-configuration",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"]}]},En=new Set;function _n(e,t,r,n){if(n?.trace(`getAliasesFromMetadata called with source: ${r}`),e&&t){const o=Rn(t,e);if(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 Rn(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(n.aliases.includes(t))return n}return null}kn.metadata.forEach(e=>{e.aliases.forEach(e=>{En.add(e)})});const Pn="cache_quota_exceeded",On="cache_error_unknown",Nn={[Pn]:"Exceeded cache storage c
2apacity.",[On]:"Unexpected error occurred when using cache storage."};class Mn extends Error{constructor(e,t){const r=t||(Nn[e]?Nn[e]:Nn[On]);super(`${e}: ${r}`),Object.setPrototypeOf(this,Mn.prototype),this.name="CacheError",this.errorCode=e,this.errorMessage=r}}class qn{constructor(e,t,r,n){this.clientId=e,this.cryptoImpl=t,this.commonLogger=r.clone(yr,Cr),this.staticAuthorityOptions=n}getAllAccounts(e){return this.buildTenantProfiles(this.getAccountsFilteredBy(e||{}),e)}getAccountInfoFilteredBy(e){const t=this.getAllAccounts(e);if(t.length>1){return t.sort(e=>e.idTokenClaims?-1:1)[0]}return 1===t.length?t[0]:null}getBaseAccountInfo(e){const t=this.getAccountsFilteredBy(e);return t.length>0?t[0].getAccountInfo():null}buildTenantProfiles(e,t){return e.flatMap(e=>this.getTenantProfilesFromAccountEntity(e,t?.tenantId,t))}getTenantedAccountInfoByFilter(e,t,r,n){let o,i=null;if(n&&!this.tenantProfileMatchesFilter(r,n))return null;const s=this.getIdToken(e,t,r.tenantId);return s&&(o=wr(s.secret,this.cryptoImpl.base64Decode),!this.idTokenClaimsMatchTenantProfileFilter(o,n))?null:(i=mn(e,r,o,s?.secret),i)}getTenantProfilesFromAccountEntity(e,t,r){const n=e.getAccountInfo();let o=n.tenantProfiles||new Map;const i=this.getTokenKeys();if(t){const e=o.get(t);if(!e)return[];o=new Map([[t,e]])}const s=[];return o.forEach(e=>{const t=this.getTenantedAccountInfoByFilter(n,i,e,r);t&&s.push(t)}),s}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){if(!e)throw mr(Wt);try{e.account&&await this.setAccount(e.account,t),e.idToken&&!1!==r?.idToken&&await this.setIdTokenCredential(e.idToken,t),e.accessToken&&!1!==r?.accessToken&&await this.saveAccessToken(e.accessToken,t),e.refreshToken&&!1!==r?.refreshToken&&await this.setRefreshTokenCredential(e.refreshToken,t),e.appMetadata&&this.setAppMetadata(e.appMetadata)}catch(e){throw this.commonLogger?.error("CacheManager.saveCacheRecord: failed"),e instanceof Error?(this.commonLogger?.errorPii(`CacheManager.saveCacheRecord: ${e.message}`,t),"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||e.message.includes("exceeded the quota")?(this.commonLogger?.error("CacheManager.saveCacheRecord: exceeded storage quota",t),new Mn(Pn)):new Mn(e.name,e.message)):(this.commonLogger?.errorPii(`CacheManager.saveCacheRecord: ${e}`,t),new Mn(On))}}async saveAccessToken(e,t){const r={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType,requestedClaimsHash:e.requestedClaimsHash},n=this.getTokenKeys(),o=hn.fromString(e.target),i=[];n.accessToken.forEach(e=>{if(!this.accessTokenKeyMatchesFilter(e,r,!1))return;const t=this.getAccessTokenCredential(e);if(t&&this.credentialMatchesFilter(t,r)){hn.fromString(t.target).intersectingScopeSets(o)&&i.push(this.removeAccessToken(e))}}),await Promise.all(i),await this.setAccessTokenCredential(e,t)}getAccountsFilteredBy(e){const t=this.getAccountKeys(),r=[];return t.forEach(t=>{if(!this.isAccountKey(t,e.homeAccountId))return;const n=this.getAccount(t,this.commonLogger);if(!n)return;if(e.homeAccountId&&!this.matchHomeAccountId(n,e.homeAccountId))return;if(e.username&&!this.matchUsername(n.username,e.username))return;if(e.environment&&!this.matchEnvironment(n,e.environment))return;if(e.realm&&!this.matchRealm(n,e.realm))return;if(e.nativeAccountId&&!this.matchNativeAccountId(n,e.nativeAccountId))return;if(e.authorityType&&!this.matchAuthorityType(n,e.authorityType))return;const o={localAccountId:e?.localAccountId,name:e?.name},i=n.tenantProfiles?.filter(e=>this.tenantProfileMatchesFilter(e,o));i&&0===i.length||r.push(n)}),r}isAccountKey(e,t,r){return!(e.split(M).length<3)&&(!(t&&!e.toLowerCase().includes(t.toLowerCase()))&&!(r&&!e.toLowerCase().includes(r.toLowerCase())))}isCredentialKey(e){if(e.split(M).length<6)return!1;const t=e.toLowerCase();if(-1===t.indexOf(U.ID_TOKEN.toLowerCase())&&-1===t.indexOf(U.ACCESS_TOKEN.toLowerCase())&&-1===t.indexOf(U.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase())&&-1===t.indexOf(U.REFRESH_TOKEN.toLowerCase()))return!1;if(t.indexOf(U.REFRESH_TOKEN.toLowerCase())>-1){const e=`${U.REFRESH_TOKEN}${M}${this.clientId}${M}`,r=`${U.REFRESH_TOKEN}${M}${x}${M}`;if(-1===t.indexOf(e.toLowerCase())&&-1===t.indexOf(r.toLowerCase()))return!1}else if(-1===t.indexOf(this.clientId.toLowerCase()))return!1;return!0}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===U.ACCESS_TOKEN_WITH_AUTH_SCHEME){if(t.tokenType&&!this.matchTokenType(e,t.tokenType))return!1;if(t.tokenType===$.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}async removeAllAccounts(){const e=this.getAccountKeys(),t=[];e.forEach(e=>{t.push(this.removeAccount(e))}),await Promise.all(t)}async removeAccount(e){const t=this.getAccount(e,this.commonLogger);t&&(await this.removeAccountContext(t),this.removeItem(e))}async removeAccountContext(e){const t=this.getTokenKeys(),r=e.generateAccountId(),n=[];t.idToken.forEach(e=>{0===e.indexOf(r)&&this.removeIdToken(e)}),t.accessToken.forEach(e=>{0===e.indexOf(r)&&n.push(this.removeAccessToken(e))}),t.refreshToken.forEach(e=>{0===e.indexOf(r)&&this.removeRefreshToken(e)}),await Promise.all(n)}async removeAccessToken(e){const t=this.getAccessTokenCredential(e);if(t){if(t.credentialType.toLowerCase()===U.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()&&t.tokenType===$.POP){const e=t.keyId;if(e)try{await this.cryptoImpl.removeTokenBindingKey(e)}catch(e){throw mr(ir)}}return this.removeItem(e)}}removeAppMetadata(){return this.getKeys().forEach(e=>{this.isAppMetadata(e)&&this.removeItem(e)}),!0}readAccountFromCache(e){const t=In.generateAccountCacheKey(e);return this.getAccount(t,this.commonLogger)}getIdToken(e,t,r,n,o){this.commonLogger.trace("CacheManager - getIdToken called");const i={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:U.ID_TOKEN,clientId:this.clientId,realm:r},s=this.getIdTokensByFilter(i,t),a=s.size;if(a<1)return this.commonLogger.info("CacheManager:getIdToken - No token found"),null;if(a>1){let t=s;if(!r){const r=new Map;s.forEach((t,n)=>{t.realm===e.tenantId&&r.set(n,t)});const n=r.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"),s.values().next().value;if(1===n)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile"),r.values().next().value;t=r}return this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them"),t.forEach((e,t)=>{this.removeIdToken(t)}),n&&o&&n.addFields({multiMatchedID:s.size},o),null}return this.commonLogger.info("CacheManager:getIdToken - Returning ID token"),s.values().next().value}getIdTokensByFilter(e,t){const r=t&&t.idToken||this.getTokenKeys().idToken,n=new Map;return r.forEach(t=>{if(!this.idTokenKeyMatchesFilter(t,{clientId:this.clientId,...e}))return;const r=this.getIdTokenCredential(t);r&&this.credentialMatchesFilter(r,e)&&n.set(t,r)}),n}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){this.removeItem(e)}removeRefreshToken(e){this.removeItem(e)}getAccessToken(e,t,r,n,o,i){this.commonLogger.trace("CacheManager - getAccessToken called");const s=hn.createSearchScopes(t.scopes),a=t.authenticationScheme||$.BEARER,c=a&&a.toLowerCase()!==$.BEARER.toLowerCase()?U.ACCESS_TOKEN_WITH_AUTH_SCHEME:U.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);t&&this.credentialMatchesFilter(t,l)&&d.push(t)}});const u=d.length;return u<1?(this.commonLogger.info("CacheManager:getAccessToken - No token found"),null):u>1?(this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them"),d.forEach(e=>{this.removeAccessToken(Ar(e))}),o&&i&&o.addFields({multiMatchedAT:d.length},i),null):(this.commonLogger.info("CacheManager:getAccessToken - Returning access token"),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){const t=this.getTokenKeys(),r=[];
2return t.accessToken.forEach(t=>{if(!this.accessTokenKeyMatchesFilter(t,e,!0))return;const n=this.getAccessTokenCredential(t);n&&this.credentialMatchesFilter(n,e)&&r.push(n)}),r}getRefreshToken(e,t,r,n,o){this.commonLogger.trace("CacheManager - getRefreshToken called");const i=t?x:void 0,s={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:U.REFRESH_TOKEN,clientId:this.clientId,familyId:i},a=r&&r.refreshToken||this.getTokenKeys().refreshToken,c=[];a.forEach(e=>{if(this.refreshTokenKeyMatchesFilter(e,s)){const t=this.getRefreshTokenCredential(e);t&&this.credentialMatchesFilter(t,s)&&c.push(t)}});const l=c.length;return l<1?(this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found."),null):(l>1&&n&&o&&n.addFields({multiMatchedRT:l},o),this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token"),c[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 mr(Dt);return n[0]}isAppMetadataFOCI(e){const t=this.readAppMetadataFromCache(e);return!(!t||t.familyId!==x)}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 o=new bn(n).getUrlComponents().HostNameAndPort;r=_n(o,e.cloudDiscoveryMetadata?.metadata,B,t)||_n(o,kn.metadata,j,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!==U.ACCESS_TOKEN&&e.credentialType!==U.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target)return!1;return hn.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(L)}isAuthorityMetadata(e){return-1!==e.indexOf(H)}generateAuthorityMetadataCacheKey(e){return`${H}-${this.clientId}-${e}`}static toObject(e,t){for(const r in t)e[r]=t[r];return e}}class Un extends qn{async setAccount(){throw mr(dr)}getAccount(){throw mr(dr)}async setIdTokenCredential(){throw mr(dr)}getIdTokenCredential(){throw mr(dr)}async setAccessTokenCredential(){throw mr(dr)}getAccessTokenCredential(){throw mr(dr)}async setRefreshTokenCredential(){throw mr(dr)}getRefreshTokenCredential(){throw mr(dr)}setAppMetadata(){throw mr(dr)}getAppMetadata(){throw mr(dr)}setServerTelemetry(){throw mr(dr)}getServerTelemetry(){throw mr(dr)}setAuthorityMetadata(){throw mr(dr)}getAuthorityMetadata(){throw mr(dr)}getAuthorityMetadataKeys(){throw mr(dr)}setThrottlingCache(){throw mr(dr)}getThrottlingCache(){throw mr(dr)}removeItem(){throw mr(dr)}getKeys(){throw mr(dr)}getAccountKeys(){throw mr(dr)}getTokenKeys(){throw mr(dr)}}const Ln={tokenRenewalOffsetSeconds:300,preventCorsPreflight:!1},xn={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:gt.Info,correlationId:i.EMPTY_STRING},Hn={claimsBasedCachingEnabled:!1},Dn={async sendGetRequestAsync(){throw mr(dr)},async sendPostRequestAsync(){throw mr(dr)}},Bn={sku:i.SKU,version:Cr,cpu:i.EMPTY_STRING,os:i.EMPTY_STRING},Fn={clientSecret:i.EMPTY_STRING,clientAssertion:void 0},Kn={azureCloudInstance:yt,tenant:`${i.DEFAULT_COMMON_TENANT}`},jn={application:{appName:"",appVersion:""}};function zn(e){return e.authOptions.authority.options.protocolMode===ft}const $n={sendGetRequestAsync:()=>Promise.reject(mr(dr)),sendPostRequestAsync:()=>Promise.reject(mr(dr))},Gn="acquireTokenByCode",Qn="acquireTokenByRefreshToken",Wn="acquireTokenSilent",Vn="acquireTokenSilentAsync",Jn="acquireTokenPopup",Yn="acquireTokenPreRedirect",Xn="acquireTokenRedirect",Zn="cryptoOptsGetPublicKeyThumbprint",eo="cryptoOptsSignJwt",to="silentCacheClientAcquireToken",ro="silentIframeClientAcquireToken",no="awaitConcurrentIframe",oo="silentRefreshClientAcquireToken",io="ssoSilent",so="standardInteractionClientGetDiscoveredAuthority",ao="fetchAccountIdWithNativeBroker",co="nativeInteractionClientAcquireToken",lo="networkClientSendPostRequestAsync",ho="refreshTokenClientExecutePostToTokenEndpoint",uo="authorizationCodeClientExecutePostToTokenEndpoint",go="refreshTokenClientExecuteTokenRequest",po="refreshTokenClientAcquireToken",mo="refreshTokenClientAcquireTokenWithCachedRefreshToken",fo="refreshTokenClientAcquireTokenByRefreshToken",yo="refreshTokenClientCreateTokenRequestBody",Co="acquireTokenFromCache",wo="silentFlowClientAcquireCachedToken",vo="silentFlowClientGenerateResultFromCacheRecord",Io="acquireTokenBySilentIframe",To="initializeBaseRequest",Ao="initializeSilentRequest",bo="initializeClientApplication",So="initializeCache",ko="silentIframeClientTokenHelper",Eo="silentHandlerInitiateAuthRequest",_o="silentHandlerMonitorIframeForHash",Ro="silentHandlerLoadFrame",Po="silentHandlerLoadFrameSync",Oo="standardInteractionClientCreateAuthCodeClient",No="standardInteractionClientGetClientConfiguration",Mo="standardInteractionClientInitializeAuthorizationRequest",qo="standardInteractionClientInitializeAuthorizationCodeRequest",Uo="getAuthCodeUrl",Lo="handleCodeResponseFromServer",xo="handleCodeResponse",Ho="updateTokenEndpointAuthority",Do="authClientAcquireToken",Bo="authClientExecuteTokenRequest",Fo="authClientCreateTokenRequestBody",Ko="authClientCreateQueryString",jo="popTokenGenerateCnf",zo="popTokenGenerateKid",$o="handleServerTokenResponse",Go="deserializeResponse",Qo="authorityFactoryCreateDiscoveredInstance",Wo="authorityResolveEndpointsAsync",Vo="authorityGetCloudDiscoveryMetadataFromNetwork",Jo="authorityUpdateCloudDiscoveryMetadata",Yo="authorityGetEndpointMetadataFromNetwork",Xo="authorityUpdateEndpointMetadata",Zo="authorityUpdateMetadataWithRegionalInformation",ei="regionDiscoveryDetectRegion",ti="regionDiscoveryGetRegionFromIMDS",ri="regionDiscoveryGetCurrentVersion",ni="acquireTokenByCodeAsync",oi="handleRedirectPromise",ii="handleNativeRedirectPromise",si="nativeMessageHandlerHandshake",ai="removeHiddenIframe",ci="clearTokensAndKeysWithClaims",li="cacheManagerGetRefreshToken",hi="importExistingCache",di="setUserData",ui="generatePkceCodes",gi="generateCodeVerifier",pi="generateCodeChallengeFromVerifier",mi="sha256Digest",fi="getRandomValues",yi="generateHKDF",Ci="generateBaseKey",wi="base64Decode",vi="urlEncodeArr",Ii="encrypt",Ti="decrypt",Ai=(new Map([[Gn,"ATByCode"],[Qn,"ATByRT"],[Wn,"ATS"],[Vn,"ATSAsync"],[Jn,"ATPopup"],[Xn,"ATRedirect"],[Zn,"CryptoGetPKThumb"],[eo,"CryptoSignJwt"],[to,"SltCac
2heClientAT"],[ro,"SltIframeClientAT"],[oo,"SltRClientAT"],[io,"SsoSlt"],[so,"StdIntClientGetDiscAuth"],[ao,"FetchAccIdWithNtvBroker"],[co,"NtvIntClientAT"],["baseClientCreateTokenRequestHeaders","BaseClientCreateTReqHead"],[lo,"NetClientSendPost"],[ho,"RTClientExecPost"],[uo,"AuthCodeClientExecPost"],["brokerHandshake","BrokerHandshake"],["acquireTokenByRefreshTokenInBroker","ATByRTInBroker"],["acquireTokenByBroker","ATByBroker"],[go,"RTClientExecTReq"],[po,"RTClientAT"],[mo,"RTClientATWithCachedRT"],[fo,"RTClientATByRT"],[yo,"RTClientCreateTReqBody"],[Co,"ATFromCache"],[wo,"SltFlowClientATCached"],[vo,"SltFlowClientGenResFromCache"],[Io,"ATBySltIframe"],[To,"InitBaseReq"],[Ao,"InitSltReq"],[bo,"InitClientApplication"],[So,"InitCache"],[hi,"importCache"],[di,"setUserData"],[ko,"SIClientTHelper"],[Eo,"SHandlerInitAuthReq"],[_o,"SltHandlerMonitorIframeForHash"],[Ro,"SHandlerLoadFrame"],[Po,"SHandlerLoadFrameSync"],[Oo,"StdIntClientCreateAuthCodeClient"],[No,"StdIntClientGetClientConf"],[Mo,"StdIntClientInitAuthReq"],[qo,"StdIntClientInitAuthCodeReq"],[Uo,"GetAuthCodeUrl"],[Lo,"HandleCodeResFromServer"],[xo,"HandleCodeResp"],[Ho,"UpdTEndpointAuth"],[Do,"AuthClientAT"],[Bo,"AuthClientExecTReq"],[Fo,"AuthClientCreateTReqBody"],[Ko,"AuthClientCreateQueryStr"],[jo,"PopTGenCnf"],[zo,"PopTGenKid"],[$o,"HandleServerTRes"],[Go,"DeserializeRes"],[Qo,"AuthFactCreateDiscInst"],[Wo,"AuthResolveEndpointsAsync"],["authorityResolveEndpointsFromLocalSources","AuthResolveEndpointsFromLocal"],[Vo,"AuthGetCDMetaFromNet"],[Jo,"AuthUpdCDMeta"],[Yo,"AuthUpdCDMetaFromNet"],[Xo,"AuthUpdEndpointMeta"],[Zo,"AuthUpdMetaWithRegInfo"],[ei,"RegDiscDetectReg"],[ti,"RegDiscGetRegFromIMDS"],[ri,"RegDiscGetCurrentVer"],[ni,"ATByCodeAsync"],["getEndpointMetadataFromNetwork","GetEndpointMetaFromNet"],["getCloudDiscoveryMetadataFromNetworkMeasurement","GetCDMetaFromNet"],[oi,"HandleRedirectPromise"],[ii,"HandleNtvRedirectPromise"],["updateCloudDiscoveryMetadataMeasurement","UpdateCDMeta"],["usernamePasswordClientAcquireToken","UserPassClientAT"],[si,"NtvMsgHandlerHandshake"],["nativeGenerateAuthResult","NtvGenAuthRes"],[ai,"RemoveHiddenIframe"],[ci,"ClearTAndKeysWithClaims"],[li,"CacheManagerGetRT"],[ui,"GenPkceCodes"],[gi,"GenCodeVerifier"],[pi,"GenCodeChallengeFromVerifier"],[mi,"Sha256Digest"],[fi,"GetRandomValues"],[yi,"genHKDF"],[Ci,"genBaseKey"],[wi,"b64Decode"],[vi,"urlEncArr"],[Ii,"encrypt"],[Ti,"decrypt"]]),1);new Set(["accessTokenSize","durationMs","idTokenSize","matsSilentStatus","matsHttpStatus","refreshTokenSize","queuedTimeMs","startTimeMs","status","multiMatchedAT","multiMatchedID","multiMatchedRT","unencryptedCacheCount","encryptedCacheExpiredCount"]);class bi{startMeasurement(){}endMeasurement(){}flushMeasurement(){return null}}class Si{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:Ai,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""},measurement:new bi}}startPerformanceMeasurement(){return new bi}calculateQueuedTime(){return 0}addQueueMeasurement(){}setPreQueueTime(){}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}incrementFields(){}cacheEventByCorrelationId(){}}class ki{navigateInternal(e,t){return ki.defaultNavigateWindow(e,t)}navigateExternal(e,t){return ki.defaultNavigateWindow(e,t)}static defaultNavigateWindow(e,t){return t.noHistory?window.location.replace(e):window.location.assign(e),new Promise(e=>{setTimeout(()=>{e(!0)},t.timeout)})}}class Ei extends It{constructor(e,t,r){super(e.errorCode,e.errorMessage,e.subError),Object.setPrototypeOf(this,Ei.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=r}}function _i(e,t,r){return new Ei(e,t,r)}const Ri="pkce_not_created",Pi="crypto_nonexistent",Oi="empty_navigate_uri",Ni="hash_empty_error",Mi="no_state_in_hash",qi="hash_does_not_contain_known_properties",Ui="unable_to_parse_state",Li="state_interaction_type_mismatch",xi="interaction_in_progress",Hi="popup_window_error",Di="empty_window_error",Bi="user_cancelled",Fi="monitor_popup_timeout",Ki="monitor_window_timeout",ji="redirect_in_iframe",zi="block_iframe_reload",$i="block_nested_popups",Gi="iframe_closed_prematurely",Qi="silent_logout_unsupported",Wi="no_account_error",Vi="silent_prompt_value_error",Ji="no_token_request_cache_error",Yi="unable_to_parse_token_request_cache_error",Xi="no_cached_authority_error",Zi="auth_request_not_set_error",es="invalid_cache_type",ts="non_browser_environment",rs="database_not_open",ns="no_network_connectivity",os="post_request_failed",is="get_request_failed",ss="failed_to_parse_response",as="unable_to_load_token",cs="crypto_key_not_found",ls="auth_code_required",hs="auth_code_or_nativeAccountId_required",ds="spa_code_and_nativeAccountId_present",us="database_unavailable",gs="unable_to_acquire_token_from_native_platform",ps="native_handshake_timeout",ms="native_extension_not_installed",fs="native_connection_not_established",ys="uninitialized_public_client_application",Cs="native_prompt_not_supported",ws="invalid_base64_string",vs="invalid_pop_token_request",Is="failed_to_build_headers",Ts="failed_to_parse_headers",As="For more visit: aka.ms/msaljs/browser-errors",bs={[Ri]:"The PKCE code challenge and verifier could not be generated.",[Pi]:"The crypto object or function is not available.",[Oi]:"Navigation URI is empty. Please check stack trace for more info.",[Ni]:`Hash value cannot be processed because it is empty. Please verify that your redirectUri is not clearing the hash. ${As}`,[Mi]:"Hash does not contain state. Please verify that the request originated from msal.",[qi]:`Hash does not contain known properites. Please verify that your redirectUri is not changing the hash.  ${As}`,[Ui]:"Unable to parse state. Please verify that the request originated from msal.",[Li]:"Hash contains state but the interaction type does not match the caller.",[xi]:`Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API.   ${As}`,[Hi]:"Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser.",[Di]:"window.open returned null or undefined window object.",[Bi]:"User cancelled the flow.",[Fi]:`Token acquisition in popup failed due to timeout.  ${As}`,[Ki]:`Token acquisition in iframe failed due to timeout.  ${As}
2`,[ji]:"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.",[zi]:`Request was blocked inside an iframe because MSAL detected an authentication response.  ${As}`,[$i]:"Request was blocked inside a popup because MSAL detected it was running in a popup.",[Gi]:"The iframe being monitored was closed prematurely.",[Qi]:"Silent logout not supported. Please call logoutRedirect or logoutPopup instead.",[Wi]:"No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the request.",[Vi]:"The value given for the prompt value is not valid for silent requests - must be set to 'none' or 'no_session'.",[Ji]:"No token request found in cache.",[Yi]:"The cached token request could not be parsed.",[Xi]:"No cached authority found.",[Zi]:"Auth Request not set. Please ensure initiateAuthRequest was called from the InteractionHandler",[es]:"Invalid cache type",[ts]:"Login and token requests are not supported in non-browser environments.",[rs]:"Database is not open!",[ns]:"No network connectivity. Check your internet connection.",[os]:"Network request failed: If the browser threw a CORS error, check that the redirectUri is registered in the Azure App Portal as type 'SPA'",[is]:"Network request failed. Please check the network trace to determine root cause.",[ss]:"Failed to parse network response. Check network trace.",[as]:"Error loading token to cache.",[cs]:"Cryptographic Key or Keypair not found in browser storage.",[ls]:"An authorization code must be provided (as the `code` property on the request) to this flow.",[hs]:"An authorization code or nativeAccountId must be provided to this flow.",[ds]:"Request cannot contain both spa code and native account id.",[us]:"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.",[gs]:`Unable to acquire token from native platform.  ${As}`,[ps]:"Timed out while attempting to establish connection to browser extension",[ms]:"Native extension is not installed. If you think this is a mistake call the initialize function.",[fs]:`Connection to native platform has not been established. Please install a compatible browser extension and run initialize().  ${As}`,[ys]:`You must call and await the initialize function before attempting to call any other MSAL API.  ${As}`,[Cs]:"The provided prompt is not supported by the native platform. This request should be routed to the web based flow.",[ws]:"Invalid base64 encoded string.",[vs]:"Invalid PoP token request. The request should not have both a popKid value and signPopToken set to true.",[Is]:"Failed to build request headers object.",[Ts]:"Failed to parse response headers"};class Ss extends It{constructor(e,t){super(e,bs[e],t),Object.setPrototypeOf(this,Ss.prototype),this.name="BrowserAuthError"}}function ks(e,t){return new Ss(e,t)}class Es{async sendGetRequestAsync(e,t){let r,n={},o=0;const i=_s(t);try{r=await fetch(e,{method:Pe,headers:i})}catch(e){throw ks(window.navigator.onLine?is:ns)}n=Rs(r.headers);try{return o=r.status,{headers:n,body:await r.json(),status:o}}catch(e){throw _i(ks(ss),o,n)}}async sendPostRequestAsync(e,t){const r=t&&t.body||"",n=_s(t);let o,i=0,s={};try{o=await fetch(e,{method:Oe,headers:n,body:r})}catch(e){throw ks(window.navigator.onLine?os:ns)}s=Rs(o.headers);try{return i=o.status,{headers:s,body:await o.json(),status:i}}catch(e){throw _i(ks(ss),i,s)}}}function _s(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 ks(Is)}}function Rs(e){try{const t={};return e.forEach((e,r)=>{t[r]=e}),t}catch(e){throw ks(Ts)}}function Ps(e){return encodeURIComponent(Ns(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"))}function Os(e){return Ms(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ns(e){return Ms((new TextEncoder).encode(e))}function Ms(e){const t=Array.from(e,e=>String.fromCodePoint(e)).join("");return btoa(t)}function qs(e){return(new TextDecoder).decode(Us(e))}function Us(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 ks(ws)}const r=atob(t);return Uint8Array.from(r,e=>e.codePointAt(0)||0)}const Ls="AES-GCM",xs="HKDF",Hs="SHA-256",Ds=new Uint8Array([1,0,1]),Bs="0123456789abcdef",Fs=new Uint32Array(1),Ks="encrypt",js="decrypt",zs={name:"RSASSA-PKCS1-v1_5",hash:Hs,modulusLength:2048,publicExponent:
2Ds};async function $s(e,t,r){t?.addQueueMeasurement(mi,r);const n=(new TextEncoder).encode(e);return window.crypto.subtle.digest(Hs,n)}function Gs(e){return window.crypto.getRandomValues(e)}function Qs(){return window.crypto.getRandomValues(Fs),Fs[0]}function Ws(){const e=Date.now(),t=1024*Qs()+(1023&Qs()),r=new Uint8Array(16),n=Math.trunc(t/2**30),o=t&2**30-1,i=Qs();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+=Bs.charAt(r[e]>>>4),s+=Bs.charAt(15&r[e]),3!==e&&5!==e&&7!==e&&9!==e||(s+="-");return s}async function Vs(e){return window.crypto.subtle.exportKey("jwk",e)}async function Js(){const e=await window.crypto.subtle.generateKey({name:Ls,length:256},!0,[Ks,js]);return window.crypto.subtle.exportKey("raw",e)}async function Ys(e){return window.crypto.subtle.importKey("raw",e,xs,!1,["deriveKey"])}async function Xs(e,t,r){return window.crypto.subtle.deriveKey({name:xs,salt:t,hash:Hs,info:(new TextEncoder).encode(r)},e,{name:Ls,length:256},!1,[Ks,js])}async function Zs(e,t,r){const n=(new TextEncoder).encode(t),o=window.crypto.getRandomValues(new Uint8Array(16)),i=await Xs(e,o,r),s=await window.crypto.subtle.encrypt({name:Ls,iv:new Uint8Array(12)},i,n);return{data:Os(new Uint8Array(s)),nonce:Os(o)}}async function ea(e,t,r,n){const o=Us(n),i=await Xs(e,Us(t),r),s=await window.crypto.subtle.decrypt({name:Ls,iv:new Uint8Array(12)},i,o);return(new TextDecoder).decode(s)}async function ta(e){const t=await $s(e);return Os(new Uint8Array(t))}const ra="storage_not_supported",na="stubbed_public_client_application_called",oa="in_mem_redirect_unavailable",ia={[ra]:"Given storage configuration option was not supported.",[na]:"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",[oa]:"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 sa extends It{constructor(e,t){super(e,t),this.name="BrowserConfigurationAuthError",Object.setPrototypeOf(this,sa.prototype)}}function aa(e){return new sa(e,ia[e])}function ca(){return window.parent!==window}function la(){return"undefined"!=typeof window&&window.location?window.location.href.split("?")[0].split("#")[0]:""}function ha(){if("undefined"!=typeof window&&window.opener&&window.opener!==window&&"string"==typeof window.name&&0===window.name.indexOf(`${ye}.`))throw ks($i)}function da(){if("undefined"==typeof window)throw ks(ts)}function ua(e){if(!e)throw ks(ys)}function ga(e){da(),function(){if(bn.hashContainsKnownProperties(window.location.hash)&&ca())throw ks(zi)}(),ha(),ua(e)}function pa(e,t){if(ga(e),function(e){if(ca()&&!e)throw ks(ji)}(t.system.allowRedirectInIframe),t.cache.cacheLocation===Re&&!t.cache.storeAuthStateInCookie)throw aa(oa)}function ma(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 fa=1e4;const ya="4.0.2";class Ca{static loggerCallback(e,t){switch(e){case gt.Error:return void console.error(t);case gt.Info:case gt.Verbose:case gt.Warning:default:return}}constructor(e){let t;this.browserEnvironment="undefined"!=typeof window,this.config=function({auth:e,cache:t,system:r,telemetry:n},o){const s={clientId:i.EMPTY_STRING,authority:`${i.DEFAULT_AUTHORITY}`,knownAuthorities:[],cloudDiscoveryMetadata:i.EMPTY_STRING,authorityMetadata:i.EMPTY_STRING,redirectUri:"undefined"!=typeof window?la():"",postLogoutRedirectUri:i.EMPTY_STRING,navigateToLoginRequestUrl:!0,clientCapabilities:[],protocolMode:mt,OIDCOptions:{serverResponseType:k.FRAGMENT,defaultScopes:[i.OPENID_SCOPE,i.PROFILE_SCOPE,i.OFFLINE_ACCESS_SCOPE]},azureCloudOptions:{azureCloudInstance:yt,tenant:i.EMPTY_STRING},skipAuthorityMetadataCache:!1,supportsNestedAppAuth:!1,instanceAware:!1},a={cacheLocation:_e,temporaryCacheLocation:_e,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!(!t||t.cacheLocation!==Ee),claimsBasedCachingEnabled:!1},c={loggerCallback:()=>{},logLevel:gt.Info,piiLoggingEnabled:!1},l={...{...Ln,loggerOptions:c,networkClient:o?new Es:$n,navigationClient:new ki,loadFrameTimeout:0,windowHashTimeout:r?.loadFrameTimeout||6e4,iframeHashTimeout:r?.loadFrameTimeout||fa,navigateFrameWait:0,redirectNavigationTimeout:3e4,asyncPopups:!1,allowRedirectInIframe:!1,allowPlatformBroker:!1,nativeBrokerHandshakeTimeout:r?.nativeBrokerHandshakeTimeout||2e3,pollIntervalMilliseconds:Ce},...r,loggerOptions:r?.loggerOptions||c},h={application:{appName:i.EMPTY_STRING,appVersion:i.EMPTY_STRING},client:new Si};e?.protocolMode!==ft&&e?.OIDCOptions&&new pt(l.loggerOptions).warning(JSON.stringify(cn(rn)));if(e?.protocolMode&&e.protocolMode!==mt&&l?.allowPlatformBroker)throw cn(nn);return{auth:{...s,...e,OIDCOptions:{...s.OIDCOptions,...e?.OIDCOptions}},cache:{...a,...t},system:l,telemetry:{...h,...n}}}(e,this.browserEnvironment);try{t=window[_e]}catch(e){}const r=t?.getItem("msal.browser.log.level"),n=t?.getItem("msal.browser.log.pii")?.toLowerCase(),o="true"===n||"false"!==n&&void 0,s={...this.config.system.loggerOptions},a=r&&Object.keys(gt).includes(r)?gt[r]:void 0;
2a&&(s.loggerCallback=Ca.loggerCallback,s.logLevel=a),void 0!==o&&(s.piiLoggingEnabled=o),this.logger=new pt(s,"@azure/msal-browser",ya),this.available=!1}getConfig(){return this.config}getLogger(){return this.logger}isAvailable(){return this.available}isBrowserEnvironment(){return this.browserEnvironment}}class wa extends Ca{getModuleName(){return wa.MODULE_NAME}getId(){return wa.ID}async initialize(){return this.available="undefined"!=typeof window,this.available}}wa.MODULE_NAME="",wa.ID="StandardOperatingContext";const va="missing_kid_error",Ia="missing_alg_error",Ta={[va]:"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 It{constructor(e,t){super(e,t),this.name="JoseHeaderError",Object.setPrototypeOf(this,Aa.prototype)}}function ba(e){return new Aa(e,Ta[e])}class Sa{constructor(e){this.typ=e.typ,this.alg=e.alg,this.kid=e.kid}static getShrHeaderString(e){if(!e.kid)throw ba(va);if(!e.alg)throw ba(Ia);const t=new Sa({typ:e.typ||ge,kid:e.kid,alg:e.alg});return JSON.stringify(t)}}class ka{constructor(){this.dbName=ot,this.version=1,this.tableName=it,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;this.db=r.target.result,this.dbOpen=!0,e()}),r.addEventListener("error",()=>t(ks(us)))})}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(ks(rs));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(ks(rs));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(ks(rs));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(ks(rs));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(ks(rs));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(ot),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 Ea{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()}}class _a{constructor(e){this.inMemoryCache=new Ea,this.indexedDBCache=new ka,this.logger=e}handleDatabaseAccessError(e){if(!(e instanceof Ss&&e.errorCode===us))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 Ra{constructor(e,t,r){this.logger=e,function(e){if(!window)throw ks(ts);if(!window.crypto)throw ks(Pi);if(!e&&!window.crypto.subtle)throw ks(Pi,"crypto_subtle_undefined")}(r??!1),this.cache=new _a(this.logger),this.performanceClient=t}createNewGuid(){return Ws()}base64Encode(e){return Ns(e)}base64Decode(e){return qs(e)}base64UrlEncode(e){return Ps(e)}encodeKid(e){return this.base64UrlEncode(JSON.stringify({kid:e}))}async getPublicKeyThumbprint(e){const t=this.performanceClient?.startMeasurement(Zn,e.correlationId),r=await async function(e,t){return window.crypto.subtle.generateKey(zs,e,t)}(Ra.EXTRACTABLE,Ra.POP_KEY_USAGES),n=await Vs(r.publicKey),o=Pa({e:n.e,kty:n.kty,n:n.n}),i=await this.hashString(o),s=await Vs(r.privateKey),a=await async function(e,t,r){return window.crypto.subtle.importKey("jwk",e,zs,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);return!await this.cache.containsKey(e)}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(eo,n),i=await this.cache.getItem(t);if(!i)throw ks(cs);const s=await Vs(i.publicKey),a=Pa(s),c=Ps(JSON.stringify({kid:t})),l=Ps(Sa.getShrHeaderString({...r?.header,alg:s.alg,kid:c}));e.cnf={jwk:JSON.parse(a)};const h=`${l}.${Ps(JSON.stringify(e))}`,d=(new TextEncoder).encode(h),u=await async function(e,t){return window.crypto.subtle.sign(zs,e,t)}(i.privateKey,d),g=`${h}.${Os(new Uint8Array(u))}`;return o&&o.end({success:!0}),g}async hashString(e){return ta(e)}}function Pa(e){return JSON.stringify(e,Object.keys(e).sort())}Ra.POP_KEY_USAGES=["sign","verify"],Ra.EXTRACTABLE=!0;const Oa=(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}},Na=(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 Ma{constructor(e,t,r,n){this.networkInterface=e,this.logger=t,this.performanceClient=r,this.correlationId=n}async detectRegion(e,t){this.performanceClient?.addQueueMeasurement(ei,this.correlationId);let r=e;if(r)t.region_source=ne;else{const e=Ma.IMDS_OPTIONS;try{const n=await Na(this.getRegionFromIMDS.bind(this),ti,this.logger,this.performanceClient,this.correlationId)(i.IMDS_VERSION,e);if(n.status===ee&&(r=n.body,t.region_source=oe),n.status===te){const n=await Na(this.getCurrentVersion.bind(this),ri,this.logger,this.performanceClient,this.correlationId)(e);if(!n)return t.region_source=re,null;const o=await Na(this.getRegionFromIMDS.bind(this),ti,this.logger,this.performanceClient,this.correlationId)(n,e);o.status===ee&&(r=o.body,t.region_source=oe)}}catch(e){return t.region_source=re,null}}return r||(t.region_source=re),r||null}async getRegionFromIMDS(e,t){return this.performanceClient?.addQueueMeasurement(ti,this.correlationId),this.networkInterface.sendGetRequestAsync(`${i.IMDS_ENDPOINT}?api-version=${e}&format=text`,t,i.IMDS_TIMEOUT)}async getCurrentVersion(e){this.performanceClient?.addQueueMeasurement(ri,this.correlationId);try{const t=await this.networkInterface.sendGetRequestAsync(`${i.IMDS_ENDPOINT}?format=json`,e);return t.status===te&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch(e){return null}}}Ma.IMDS_OPTIONS={headers:{Metadata:"true"}};class qa{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 Ma(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(i.CIAM_AUTH_URL))return wn;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case i.ADFS:return yn;case i.DSTS:return Cn}return fn}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 bn(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 mr(Et)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw mr(Et)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw mr(Et)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw mr(sr);return this.replacePath(this.metadata.end_session_endpoint)}throw mr(Et)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw mr(Et)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw mr(Et)}canReplaceTenant(e){return 1===e.PathSegments.length&&!qa.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===fn&&this.protocolMode===mt}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const r=new bn(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 bn(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===yn||this.protocolMode!==mt&&!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(Wo,this.correlationId);const e=this.getCurrentMetadataEntity(),t=await Na(this.updateCloudDiscoveryMetadata.bind(this),Jo,this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const r=await Na(this.updateEndpointMetadata.bind(this),Xo,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:Mr(),jwks_uri:""}),e}updateCachedMetadata(e,t,r){t!==F&&r?.source!==F&&(e.expiresAt=Mr(),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(Xo,this.correlationId);const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===j&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){qr(e,await Na(this.updateMetadataWithRegionalInformation.bind(this),Zo,this.logger,this.performanceClient,this.correlationId)(t.metadata),!1),e.canonical_authority=this.canonicalAuthority}return t.source}let r=await Na(this.getEndpointMetadataFromNetwork.bind(this),Yo,this.logger,this.performanceClient,this.correlationId)();if(r)return this.authorityOptions.azureRegionConfiguration?.azureRegion&&(r=await Na(this.updateMetadataWithRegionalInformation.bind(this),Zo,this.logger,this.performanceClient,this.correlationId)(r)),qr(e,r,!0),K;throw mr(Rt,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"),qr(e,t,!1),{source:B};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 qr(e,t,!1),{source:j,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=Lr(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!r?(this.logger.verbose("Found endpoint metadata in the cache."),{source:F}):(r&&this.logger.verbose("The metadata entity is expired."),null)}isAuthoritySameType(e){return new bn(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 cn(Jr)}return null}async getEndpointMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(Yo,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 Sn?Sn[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){this.performanceClient?.addQueueMeasurement(Zo,this.correlationId);const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if(t!==i.AZURE_REGION_AUTO_DISCOVER_FLAG)return this.regionDiscoveryMetadata.region_outcome=ie,this.regionDiscoveryMetadata.region_used=t,qa.replaceWithRegionalInformation(e,t);const r=await Na(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),ei,this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(r)return this.regionDiscoveryMetadata.region_outcome=se,this.regionDiscoveryMetadata.region_used=r,qa.replaceWithRegionalInformation(e,r);this.regionDiscoveryMetadata.region_outcome=ae}return e}async updateCloudDiscoveryMetadata(e){this.performanceClient?.addQueueMeasurement(Jo,this.correlationId);const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const r=await Na(this.getCloudDiscoveryMetadataFromNetwork.bind(this),Vo,this.logger,this.performanceClient,this.correlationId)();if(r)return Ur(e,r,!0),K;throw cn(Yr)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("Attempting to get cloud discovery metadata  from authority configuration"),this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities||i.NOT_APPLICABLE}`),this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata||i.NOT_APPLICABLE}`),this.logger.verbosePii(`Canonical Authority: ${e.canonical_authority||i.NOT_APPLICABLE}`);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("Found cloud discovery metadata in authority configuration"),Ur(e,t,!1),B;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,Rn(kn.metadata,r));if(t)return this.logger.verbose("Found cloud discovery metadata from hardcoded values."),Ur(e,t,!1),j;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=Lr(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!n?(this.logger.verbose("Found cloud discovery metadata in the cache."),F):(n&&this.logger.verbose("The metadata entity is expired."),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===wn)return this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host."),qa.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=Rn(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."),cn(Vr)}
2}return this.isInKnownAuthorities()?(this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host."),qa.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(Vo,this.correlationId);const e=`${i.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let r=null;try{const n=await this.networkInterface.sendGetRequestAsync(e,t);let o,s;if(function(e){return e.hasOwnProperty("tenant_discovery_endpoint")&&e.hasOwnProperty("metadata")}(n.body))o=n.body,s=o.metadata,this.logger.verbosePii(`tenant_discovery_endpoint is: ${o.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}`),o=n.body,o.error===i.INVALID_INSTANCE)return this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance."),null;this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${o.error}`),this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${o.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=Rn(s,this.hostnameAndPort)}catch(e){if(e instanceof It)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=qa.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),r}isInKnownAuthorities(){return this.authorityOptions.knownAuthorities.filter(e=>e&&bn.getDomainFromUrl(e).toLowerCase()===this.hostnameAndPort).length>0}static generateAuthority(e,t){let r;if(t&&t.azureCloudInstance!==yt){const e=t.tenant?t.tenant:i.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 i.DEFAULT_AUTHORITY_HOST;if(this.discoveryComplete())return this.metadata.preferred_cache;throw mr(Et)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return En.has(e)}static isPublicCloudAuthority(e){return i.KNOWN_PUBLIC_CLOUDS.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,r){const n=new bn(e);n.validateAsUri();const o=n.getUrlComponents();let s=`${t}.${o.HostNameAndPort}`;this.isPublicCloudAuthority(o.HostNameAndPort)&&(s=`${t}.${i.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`);const a=bn.constructAuthorityUriFromObject({...n.getUrlComponents(),HostNameAndPort:s}).urlString;return r?`${a}?${r}`:a}static replaceWithRegionalInformation(e,t){const r={...e};return r.authorization_endpoint=qa.buildRegionalAuthorityString(r.authorization_endpoint,t),r.token_endpoint=qa.buildRegionalAuthorityString(r.token_endpoint,t),r.end_session_endpoint&&(r.end_session_endpoint=qa.buildRegionalAuthorityString(r.end_session_endpoint,t)),r}static transformCIAMAuthority(e){let t=e;const r=new bn(e).getUrlComponents();if(0===r.PathSegments.length&&r.HostNameAndPort.endsWith(i.CIAM_AUTH_URL)){t=`${t}${r.HostNameAndPort.split(".")[0]}${i.AAD_TENANT_DOMAIN_SUFFIX}`}return t}}function Ua(e){return e.endsWith(i.FORWARD_SLASH)?e:`${e}${i.FORWARD_SLASH}`}qa.reservedTenantDomains=new Set(["{tenant}","{tenantid}",w,I,v]);const La="no_tokens_found",xa="native_account_unavailable",Ha="refresh_token_expired",Da="bad_token",Ba=["interaction_required","consent_required","login_required",Da],Fa=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token"],Ka={[La]:"No refresh token found in the cache. Please sign-in.",[xa]:"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.",[Ha]:"Refresh token has expired.",[Da]:"Identity provider returned bad_token due to an expired or invalid refresh token. Please invoke an interactive API to resolve."};class ja extends It{constructor(e,t,r,n,o,s,a,c){super(e,t,r),Object.setPrototypeOf(this,ja.prototype),this.timestamp=n||i.EMPTY_STRING,this.traceId=o||i.EMPTY_STRING,this.correlationId=s||i.EMPTY_STRING,this.claims=a||i.EMPTY_STRING,this.name="InteractionRequiredAuthError",this.errorNo=c}}function za(e,t,r){const n=!!e&&Ba.indexOf(e)>-1,o=!!r&&Fa.indexOf(r)>-1,i=!!t&&Ba.some(e=>t.indexOf(e)>-1);return n||i||o}function $a(e){return new ja(e,Ka[e])}class Ga{static setRequestState(e,t,r){const n=Ga.generateLibraryState(e,r);return t?`${n}${i.RESOURCE_DELIM}${t}`:n}static generateLibraryState(e,t){if(!e)throw mr(Yt);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 mr(Yt);if(!t)throw mr(Ot);try{const r=t.split(i.RESOURCE_DELIM),n=r[0],o=r.length>1?r.slice(1).join(i.RESOURCE_DELIM):i.EMPTY_STRING,s=e.base64Decode(n),a=JSON.parse(s);return{userRequestState:o||i.EMPTY_STRING,libraryState:a}}catch(e){throw mr(Ot)}}}const Qa="home_account_id",Wa="UPN",Va=864e5;class Ja{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 mr(dr)}setItem(e,t,r,n=!0){let o=`${encodeURIComponent(e)}=${encodeURIComponent(t)};path=/;SameSite=Lax;`;if(r){const e=function(e){const t=new Date,r=new Date(t.getTime()+e*Va);return r.toUTCString()}(r);o+=`expires=${e};`}n&&(o+="Secure;"),document.cookie=o}async setUserData(){return Promise.reject(mr(dr))}removeItem(e){this.setItem(e,"",-1)}getKeys(){const e=document.cookie.split(";"),t=[];
2return e.forEach(e=>{const r=decodeURIComponent(e).trim().split("=");t.push(r[0])}),t}containsKey(e){return this.getKeys().includes(e)}}function Ya(e){const t=e.getItem(Ke);return t?JSON.parse(t):[]}function Xa(e,t){const r=t.getItem(`${je}.${e}`);if(r){const e=JSON.parse(r);if(e&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("accessToken")&&e.hasOwnProperty("refreshToken"))return e}return{idToken:[],accessToken:[],refreshToken:[]}}const Za="msal.cache.encryption";class ec{constructor(e,t,r){if(!window.localStorage)throw aa(ra);this.memoryStorage=new Ea,this.initialized=!1,this.clientId=e,this.logger=t,this.performanceClient=r}async initialize(e){this.initialized=!0;const t=new Ja,r=t.getItem(Za);let n={key:"",id:""};if(r)try{n=JSON.parse(r)}catch(e){}if(n.key&&n.id){const t=Oa(Us,wi,this.logger,this.performanceClient,e)(n.key);this.encryptionCookie={id:n.id,key:await Na(Ys,yi,this.logger,this.performanceClient,e)(t)},await Na(this.importExistingCache.bind(this),hi,this.logger,this.performanceClient,e)(e)}else{this.clear();const r=Ws(),n=await Na(Js,Ci,this.logger,this.performanceClient,e)(),o=Oa(Os,vi,this.logger,this.performanceClient,e)(new Uint8Array(n));this.encryptionCookie={id:r,key:await Na(Ys,yi,this.logger,this.performanceClient,e)(n)};const i={id:r,key:o};t.setItem(Za,JSON.stringify(i))}}getItem(e){return window.localStorage.getItem(e)}getUserData(e){if(!this.initialized)throw ks(ys);return this.memoryStorage.getItem(e)}setItem(e,t){window.localStorage.setItem(e,t)}async setUserData(e,t,r){if(!this.initialized||!this.encryptionCookie)throw ks(ys);const{data:n,nonce:o}=await Na(Zs,Ii,this.logger,this.performanceClient,r)(this.encryptionCookie.key,t,this.getContext(e)),i={id:this.encryptionCookie.id,nonce:o,data:n};this.memoryStorage.setItem(e,t),this.setItem(e,JSON.stringify(i))}removeItem(e){this.memoryStorage.removeItem(e),window.localStorage.removeItem(e)}getKeys(){return Object.keys(window.localStorage)}containsKey(e){return window.localStorage.hasOwnProperty(e)}clear(){this.memoryStorage.clear();Ya(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(i.CACHE_PREFIX)||-1!==e.indexOf(this.clientId))&&this.removeItem(e)})}async importExistingCache(e){if(!this.encryptionCookie)return;let t=Ya(this);t=await this.importArray(t,e),this.setItem(Ke,JSON.stringify(t));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),this.setItem(`${je}.${this.clientId}`,JSON.stringify(r))}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 n.id&&n.nonce&&n.data?n.id!==this.encryptionCookie.id?(this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},t),null):Na(ea,Ti,this.logger,this.performanceClient,t)(this.encryptionCookie.key,n.nonce,this.getContext(e),n.data):(this.performanceClient.incrementFields({unencryptedCacheCount:1},t),null)}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}}class tc{constructor(){if(!window.sessionStorage)throw aa(ra)}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)}}function rc(e,t){if(!t)return null;try{return Ga.parseRequestState(e,t).libraryState.meta}catch(e){throw mr(Ot)}}class nc extends qn{constructor(e,t,r,n,o,i){super(e,r,n,i),this.cacheConfig=t,this.logger=n,this.internalStorage=new Ea,this.browserStorage=oc(e,t.cacheLocation,n,o),this.temporaryCacheStorage=oc(e,t.temporaryCacheLocation,n,o),this.cookieStorage=new Ja,this.performanceClient=o}async initialize(e){await this.browserStorage.initialize(e)}validateAndParseJson(e){try{const t=JSON.parse(e);return t&&"object"==typeof t?t:null}catch(e){return null}}getAccount(e){this.logger.trace("BrowserCacheManager.getAccount called");const t=this.browserStorage.getUserData(e);if(!t)return this.removeAccountKeyFromMap(e),null;const r=this.validateAndParseJson(t);return r&&In.isAccountEntity(r)?qn.toObject(new In,r):(this.removeAccountKeyFromMap(e),null)}async setAccount(e,t){this.logger.trace("BrowserCacheManager.setAccount called");const r=e.generateAccountKey();await Na(this.browserStorage.setUserData.bind(this.browserStorage),di,this.logger,this.performanceClient)(r,JSON.stringify(e),t),this.addAccountKeyToMap(r)}getAccountKeys(){return Ya(this.browserStorage)}addAccountKeyToMap(e){this.logger.trace("BrowserCacheManager.addAccountKeyToMap called"),this.logger.tracePii(`BrowserCacheManager.addAccountKeyToMap called with key: ${e}`);const t=this.getAccountKeys();-1===t.indexOf(e)?(t.push(e),this.browserStorage.setItem(Ke,JSON.stringify(t)),this.logger.verbose("BrowserCacheManager.addAccountKeyToMap account key added")):this.logger.verbose("BrowserCacheManager.addAccountKeyToMap account key already exists in map")}removeAccountKeyFromMap(e){this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap called"),this.logger.tracePii(`BrowserCacheManager.removeAccountKeyFromMap called with key: ${e}`);const t=this.getAccountKeys(),r=t.indexOf(e);r>-1?(t.splice(r,1),this.browserStorage.setItem(Ke,JSON.stringify(t)),this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap account key removed")):this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap ke
2y not found in existing map")}async removeAccount(e){super.removeAccount(e),this.removeAccountKeyFromMap(e)}removeIdToken(e){super.removeIdToken(e),this.removeTokenKey(e,U.ID_TOKEN)}async removeAccessToken(e){super.removeAccessToken(e),this.removeTokenKey(e,U.ACCESS_TOKEN)}removeRefreshToken(e){super.removeRefreshToken(e),this.removeTokenKey(e,U.REFRESH_TOKEN)}getTokenKeys(){return Xa(this.clientId,this.browserStorage)}addTokenKey(e,t){this.logger.trace("BrowserCacheManager addTokenKey called");const r=this.getTokenKeys();switch(t){case U.ID_TOKEN:-1===r.idToken.indexOf(e)&&(this.logger.info("BrowserCacheManager: addTokenKey - idToken added to map"),r.idToken.push(e));break;case U.ACCESS_TOKEN:-1===r.accessToken.indexOf(e)&&(this.logger.info("BrowserCacheManager: addTokenKey - accessToken added to map"),r.accessToken.push(e));break;case U.REFRESH_TOKEN:-1===r.refreshToken.indexOf(e)&&(this.logger.info("BrowserCacheManager: addTokenKey - refreshToken added to map"),r.refreshToken.push(e));break;default:throw this.logger.error(`BrowserCacheManager:addTokenKey - CredentialType provided invalid. CredentialType: ${t}`),mr(Xt)}this.browserStorage.setItem(`${je}.${this.clientId}`,JSON.stringify(r))}removeTokenKey(e,t){this.logger.trace("BrowserCacheManager removeTokenKey called");const r=this.getTokenKeys();switch(t){case U.ID_TOKEN:this.logger.infoPii(`BrowserCacheManager: removeTokenKey - attempting to remove idToken with key: ${e} from map`);const n=r.idToken.indexOf(e);n>-1?(this.logger.info("BrowserCacheManager: removeTokenKey - idToken removed from map"),r.idToken.splice(n,1)):this.logger.info("BrowserCacheManager: removeTokenKey - idToken does not exist in map. Either it was previously removed or it was never added.");break;case U.ACCESS_TOKEN:this.logger.infoPii(`BrowserCacheManager: removeTokenKey - attempting to remove accessToken with key: ${e} from map`);const o=r.accessToken.indexOf(e);o>-1?(this.logger.info("BrowserCacheManager: removeTokenKey - accessToken removed from map"),r.accessToken.splice(o,1)):this.logger.info("BrowserCacheManager: removeTokenKey - accessToken does not exist in map. Either it was previously removed or it was never added.");break;case U.REFRESH_TOKEN:this.logger.infoPii(`BrowserCacheManager: removeTokenKey - attempting to remove refreshToken with key: ${e} from map`);const i=r.refreshToken.indexOf(e);i>-1?(this.logger.info("BrowserCacheManager: removeTokenKey - refreshToken removed from map"),r.refreshToken.splice(i,1)):this.logger.info("BrowserCacheManager: removeTokenKey - refreshToken does not exist in map. Either it was previously removed or it was never added.");break;default:throw this.logger.error(`BrowserCacheManager:removeTokenKey - CredentialType provided invalid. CredentialType: ${t}`),mr(Xt)}this.browserStorage.setItem(`${je}.${this.clientId}`,JSON.stringify(r))}getIdTokenCredential(e){const t=this.browserStorage.getUserData(e);if(!t)return this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit"),this.removeTokenKey(e,U.ID_TOKEN),null;const r=this.validateAndParseJson(t);return r&&((n=r)&&Er(n)&&n.hasOwnProperty("realm")&&n.credentialType===U.ID_TOKEN)?(this.logger.trace("BrowserCacheManager.getIdTokenCredential: cache hit"),r):(this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit"),this.removeTokenKey(e,U.ID_TOKEN),null);var n}async setIdTokenCredential(e,t){this.logger.trace("BrowserCacheManager.setIdTokenCredential called");const r=Ar(e);await Na(this.browserStorage.setUserData.bind(this.browserStorage),di,this.logger,this.performanceClient)(r,JSON.stringify(e),t),this.addTokenKey(r,U.ID_TOKEN)}getAccessTokenCredential(e){const t=this.browserStorage.getUserData(e);if(!t)return this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit"),this.removeTokenKey(e,U.ACCESS_TOKEN),null;const r=this.validateAndParseJson(t);return r&&(n=r)&&Er(n)&&n.hasOwnProperty("realm")&&n.hasOwnProperty("target")&&(n.credentialType===U.ACCESS_TOKEN||n.credentialType===U.ACCESS_TOKEN_WITH_AUTH_SCHEME)?(this.logger.trace("BrowserCacheManager.getAccessTokenCredential: cache hit"),r):(this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit"),this.removeTokenKey(e,U.ACCESS_TOKEN),null);var n}async setAccessTokenCredential(e,t){this.logger.trace("BrowserCacheManager.setAccessTokenCredential called");const r=Ar(e);await Na(this.browserStorage.setUserData.bind(this.browserStorage),di,this.logger,this.performanceClient)(r,JSON.stringify(e),t),this.addTokenKey(r,U.ACCESS_TOKEN)}getRefreshTokenCredential(e){const t=this.browserStorage.getUserData(e);if(!t)return this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit"),this.removeTokenKey(e,U.REFRESH_TOKEN),null;const r=this.validateAndParseJson(t);return r&&(n=r)&&Er(n)&&n.credentialType===U.REFRESH_TOKEN?(this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: cache hit"),r):(this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit"),this.removeTokenKey(e,U.REFRESH_TOKEN),null);var n}async setRefreshTokenCredential(e,t){this.logger.trace("BrowserCacheManager.setRefreshTokenCredential called");const r=Ar(e);await Na(this.browserStorage.setUserData.bind(this.browserStorage),di,this.logger,this.performanceClient)(r,JSON.stringify(e),t),this.addTokenKey(r,U.REFRESH_TOKEN)}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,(o=r)&&0===n.indexOf(L)&&o.hasOwnProperty("clientId")&&o.hasOwnProperty("environment"))?(this.logger.trace("BrowserCacheManager.getAppMetadata: cache hit"),r):(this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit"),null);var n,o}setAppMetadata(e){this.logger.trace("BrowserCacheManager.setAppMetadata called");const t=function({environment:e,clientId:t}){return[L,e,t].join(M).toLowerCase()}(e);this.browserStorage.setItem(t,JSON.stringify(e))}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(z.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){this.logger.trace("BrowserCacheManager.setServerTelemetry called"),this.browserStorage.setItem(e,JSON.stringify(t))}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(H)&&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(ze,e),this.internalStorage.setItem($e,t)}getWrapperMetadata(){return[this.internalStorage.getItem(ze)||i.EMPTY_STRING,this.internalStorage.getItem($e)||i.EMPTY_STRING]}setAuthorityMetadata(e,t){this.logger.trace("BrowserCacheManager.setAuthorityMetadata called"),this.internalStorage.setItem(e,JSON.stringify(t))}getActiveAccount(){const e=this.generateCacheKey(C),t=this.browserStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getActiveAccount: No active account filters found"),null;const r=this.validateAndParseJson(t);return r?(this.logger.trace("BrowserCacheManager.getActiveAccount: Active account filters schema found"),this.getAccountInfoFilteredBy({homeAccountId:r.homeAccountId,localAccountId:r.localAccountId,tenantId:r.tenantId})):(this.logger.trace("BrowserCacheManager.getActiveAccount: No active account found"),null)}setActiveAccount(e){const t=this.generateCacheKey(C);if(e){this.logger.verbose("setActiveAccount: Active account set");const r={homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,tenantId:e.tenantId};this.browserStorage.setItem(t,JSON.stringify(r))}else this.logger.verbose("setActiveAccount: No account passed, active account not set"),this.browserStorage.removeItem(t)}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;e&&(r=0===e.indexOf(W));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){this.logger.trace("BrowserCacheManager.setThrottlingCache called"),this.browserStorage.setItem(e,JSON.stringify(t))}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);
2if(!n){if(this.cacheConfig.cacheLocation===Ee){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()}async clear(){await this.removeAllAccounts(),this.removeAppMetadata(),this.temporaryCacheStorage.getKeys().forEach(e=>{-1===e.indexOf(i.CACHE_PREFIX)&&-1===e.indexOf(this.clientId)||this.removeTemporaryItem(e)}),this.browserStorage.getKeys().forEach(e=>{-1===e.indexOf(i.CACHE_PREFIX)&&-1===e.indexOf(this.clientId)||this.browserStorage.removeItem(e)}),this.internalStorage.clear()}async clearTokensAndKeysWithClaims(e,t){e.addQueueMeasurement(ci,t);const r=this.getTokenKeys(),n=[];r.accessToken.forEach(e=>{const t=this.getAccessTokenCredential(e);t?.requestedClaimsHash&&e.includes(t.requestedClaimsHash.toLowerCase())&&n.push(this.removeAccessToken(e))}),await Promise.all(n),n.length>0&&this.logger.warning(`${n.length} access tokens with claims in the cache keys have been removed from the cache.`)}generateCacheKey(e){return this.validateAndParseJson(e)?JSON.stringify(e):ln.startsWith(e,i.CACHE_PREFIX)?e:`${i.CACHE_PREFIX}.${this.clientId}.${e}`}generateAuthorityKey(e){const{libraryState:{id:t}}=Ga.parseRequestState(this.cryptoImpl,e);return this.generateCacheKey(`${Ne}.${t}`)}generateNonceKey(e){const{libraryState:{id:t}}=Ga.parseRequestState(this.cryptoImpl,e);return this.generateCacheKey(`${qe}.${t}`)}generateStateKey(e){const{libraryState:{id:t}}=Ga.parseRequestState(this.cryptoImpl,e);return this.generateCacheKey(`${Me}.${t}`)}getCachedAuthority(e){const t=this.generateStateKey(e),r=this.getTemporaryCache(t);if(!r)return null;const n=this.generateAuthorityKey(r);return this.getTemporaryCache(n)}updateCacheEntries(e,t,r,n,o){this.logger.trace("BrowserCacheManager.updateCacheEntries called");const i=this.generateStateKey(e);this.setTemporaryCache(i,e,!1);const s=this.generateNonceKey(e);this.setTemporaryCache(s,t,!1);const a=this.generateAuthorityKey(e);if(this.setTemporaryCache(a,r,!1),o){const e={credential:o.homeAccountId,type:Qa};this.setTemporaryCache(De,JSON.stringify(e),!0)}else if(n){const e={credential:n,type:Wa};this.setTemporaryCache(De,JSON.stringify(e),!0)}}resetRequestCache(e){this.logger.trace("BrowserCacheManager.resetRequestCache called"),e&&(this.temporaryCacheStorage.getKeys().forEach(t=>{-1!==t.indexOf(e)&&this.removeTemporaryItem(t)}),this.removeTemporaryItem(this.generateStateKey(e)),this.removeTemporaryItem(this.generateNonceKey(e)),this.removeTemporaryItem(this.generateAuthorityKey(e))),this.removeTemporaryItem(this.generateCacheKey(xe)),this.removeTemporaryItem(this.generateCacheKey(Ue)),this.removeTemporaryItem(this.generateCacheKey(Le)),this.removeTemporaryItem(this.generateCacheKey(Be)),this.removeTemporaryItem(this.generateCacheKey(De)),this.removeTemporaryItem(this.generateCacheKey(Fe)),this.setInteractionInProgress(!1)}cleanRequestByState(e){if(this.logger.trace("BrowserCacheManager.cleanRequestByState called"),e){const t=this.generateStateKey(e),r=this.temporaryCacheStorage.getItem(t);this.logger.infoPii(`BrowserCacheManager.cleanRequestByState: Removing temporary cache items for state: ${r}`),this.resetRequestCache(r||i.EMPTY_STRING)}}cleanRequestByInteractionType(e){this.logger.trace("BrowserCacheManager.cleanRequestByInteractionType called"),this.temporaryCacheStorage.getKeys().forEac
2h(t=>{if(-1===t.indexOf(Me))return;const r=this.temporaryCacheStorage.getItem(t);if(!r)return;const n=rc(this.cryptoImpl,r);n&&n.interactionType===e&&(this.logger.infoPii(`BrowserCacheManager.cleanRequestByInteractionType: Removing temporary cache items for state: ${r}`),this.resetRequestCache(r))}),this.setInteractionInProgress(!1)}cacheCodeRequest(e){this.logger.trace("BrowserCacheManager.cacheCodeRequest called");const t=Ns(JSON.stringify(e));this.setTemporaryCache(xe,t,!0)}getCachedRequest(e){this.logger.trace("BrowserCacheManager.getCachedRequest called");const t=this.getTemporaryCache(xe,!0);if(!t)throw ks(Ji);let r;try{r=JSON.parse(qs(t))}catch(e){throw this.logger.errorPii(`Attempted to parse: ${t}`),this.logger.error(`Parsing cached token request threw with error: ${e}`),ks(Yi)}if(this.removeTemporaryItem(this.generateCacheKey(xe)),!r.authority){const t=this.generateAuthorityKey(e),n=this.getTemporaryCache(t);if(!n)throw ks(Xi);r.authority=n}return r}getCachedNativeRequest(){this.logger.trace("BrowserCacheManager.getCachedNativeRequest called");const e=this.getTemporaryCache(Fe,!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();return e?t===this.clientId:!!t}getInteractionInProgress(){const e=`${i.CACHE_PREFIX}.${He}`;return this.getTemporaryCache(e,!1)}setInteractionInProgress(e){const t=`${i.CACHE_PREFIX}.${He}`;if(e){if(this.getInteractionInProgress())throw ks(xi);this.setTemporaryCache(t,this.clientId,!1)}else e||this.getInteractionInProgress()!==this.clientId||this.removeTemporaryItem(t)}async hydrateCache(e,t){const r=br(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:Sr(e.account?.homeAccountId,e.account.environment,e.accessToken,this.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?e.expiresOn.getTime()/1e3:0,e.extExpiresOn?e.extExpiresOn.getTime()/1e3:0,qs,void 0,e.tokenType,void 0,t.sshKid,t.claims,n)};return this.saveCacheRecord(o,e.correlationId)}async saveCacheRecord(e,t,r){try{await super.saveCacheRecord(e,t,r)}catch(e){if(e instanceof Mn&&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 oc(e,t,r,n){try{switch(t){case Ee:return new ec(e,r,n);case _e:return new tc}}catch(e){r.error(e)}return new Ea}const ic={INITIALIZE_START:"msal:initializeStart",INITIALIZE_END:"msal:initializeEnd",ACCOUNT_ADDED:"msal:accountAdded",ACCOUNT_REMOVED:"msal:accountRemoved",ACTIVE_ACCOUNT_CHANGED:"msal:activeAccountChanged",LOGIN_START:"msal:loginStart",LOGIN_SUCCESS:"msal:loginSuccess",LOGIN_FAILURE:"msal:loginFailure",ACQUIRE_TOKEN_START:"msal:acquireTokenStart",ACQUIRE_TOKEN_SUCCESS:"msal:acquireTokenSuccess",ACQUIRE_TOKEN_FAILURE:"msal:acquireTokenFailure",ACQUIRE_TOKEN_NETWORK_START:"msal:acquireTokenFromNetworkStart",SSO_SILENT_START:"msal:ssoSilentStart",SSO_SILENT_SUCCESS:"msal:ssoSilentSuccess",SSO_SILENT_FAILURE:"msal:ssoSilentFailure",ACQUIRE_TOKEN_BY_CODE_START:"msal:acquireTokenByCodeStart",ACQUIRE_TOKEN_BY_CODE_SUCCESS:"msal:acquireTokenByCodeSuccess",ACQUIRE_TOKEN_BY_CODE_FAILURE:"msal:acquireTokenByCodeFailure",HANDLE_REDIRECT_START:"msal:handleRedirectStart",HANDLE_REDIRECT_END:"msal:handleRedirectEnd",POPUP_OPENED:"msal:popupOpened",LOGOUT_START:"msal:logoutStart",LOGOUT_SUCCESS:"msal:logoutSuccess",LOGOUT_FAILURE:"msal:logoutFailure",LOGOUT_END:"msal:logoutEnd",RESTORE_FROM_BFCACHE:"msal:restoreFromBFCache"};class sc{constructor(e){this.eventCallbacks=new Map,this.logger=e||new pt({})}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){if("undefined"!=typeof window){const o={eventType:e,interactionType:t||null,payload:r||null,error:n||null,timestamp:Date.now()};this.eventCallbacks.forEach(([t,r],n)=>{(0===r.length||r.includes(e))&&(this.logger.verbose(`Emitting event to callback ${n}: ${e}`),t.apply(null,[o]))})}}}class ac extends It{constructor(e,t,r,n,o){super(e,t,r),this.name="ServerError",this.errorNo=n,this.status=o,Object.setPrototypeOf(this,ac.prototype)}}class cc{static generateThrottlingStorageKey(e){return`${W}.${JSON.stringify(e)}`}static preProcess(e,t){const r=cc.generateThrottlingStorageKey(t),n=e.getThrottlingCache(r);if(n){if(n.throttleTime<Date.now())return void e.removeItem(r);throw new ac(n.errorCodes?.join(" ")||i.EMPTY_STRING,n.errorMessage,n.subError)}}
2static postProcess(e,t,r){if(cc.checkResponseStatus(r)||cc.checkResponseForRetryAfter(r)){const n={throttleTime:cc.calculateThrottleTime(parseInt(r.headers[p])),error:r.body.error,errorCodes:r.body.error_codes,errorMessage:r.body.error_description,subError:r.body.suberror};e.setThrottlingCache(cc.generateThrottlingStorageKey(t),n)}}static checkResponseStatus(e){return 429===e.status||e.status>=500&&e.status<600}static checkResponseForRetryAfter(e){return!!e.headers&&(e.headers.hasOwnProperty(p)&&(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||G),r+Q))}static removeThrottle(e,t,r,n){const o={clientId:t,authority:r.authority,scopes:r.scopes,homeAccountIdentifier:n,claims:r.claims,authenticationScheme:r.authenticationScheme,resourceRequestMethod:r.resourceRequestMethod,resourceRequestUri:r.resourceRequestUri,shrClaims:r.shrClaims,sshKid:r.sshKid},i=this.generateThrottlingStorageKey(o);e.removeItem(i)}}const lc="client_id",hc="redirect_uri",dc="response_type",uc="token_type",gc="req_cnf",pc="return_spa_code",mc="x-client-xtra-sku",fc="brk_client_id",yc="brk_redirect_uri";class Cc{static validateRedirectUri(e){if(!e)throw cn(xr)}static validatePrompt(e){const t=[];for(const e in b)t.push(b[e]);if(t.indexOf(e)<0)throw cn(jr)}static validateClaims(e){try{JSON.parse(e)}catch(e){throw cn(zr)}}static validateCodeChallengeParams(e,t){if(!e||!t)throw cn(Wr);this.validateCodeChallengeMethod(t)}static validateCodeChallengeMethod(e){if([S.PLAIN,S.S256].indexOf(e)<0)throw cn(Qr)}}class wc{constructor(e,t){this.parameters=new Map,this.performanceClient=t,this.correlationId=e}addResponseTypeCode(){this.parameters.set(dc,encodeURIComponent(i.CODE_RESPONSE_TYPE))}addResponseTypeForTokenAndIdToken(){this.parameters.set(dc,encodeURIComponent(`${i.TOKEN_RESPONSE_TYPE} ${i.ID_TOKEN_RESPONSE_TYPE}`))}addResponseMode(e){this.parameters.set("response_mode",encodeURIComponent(e||E.QUERY))}addNativeBroker(){this.parameters.set("nativebroker",encodeURIComponent("1"))}addScopes(e,t=!0,r=h){!t||r.includes("openid")||e.includes("openid")||r.push("openid");const n=t?[...e||[],...r]:e||[],o=new hn(n);this.parameters.set("scope",encodeURIComponent(o.printScopes()))}addClientId(e){this.parameters.set(lc,encodeURIComponent(e))}addRedirectUri(e){Cc.validateRedirectUri(e),this.parameters.set(hc,encodeURIComponent(e))}addPostLogoutRedirectUri(e){Cc.validateRedirectUri(e),this.parameters.set("post_logout_redirect_uri",encodeURIComponent(e))}addIdTokenHint(e){this.parameters.set("id_token_hint",encodeURIComponent(e))}addDomainHint(e){this.parameters.set("domain_hint",encodeURIComponent(e))}addLoginHint(e){this.parameters.set("login_hint",encodeURIComponent(e))}addCcsUpn(e){this.parameters.set(m,encodeURIComponent(`UPN:${e}`))}addCcsOid(e){this.parameters.set(m,encodeURIComponent(`Oid:${e.uid}@${e.utid}`))}addSid(e){this.parameters.set("sid",encodeURIComponent(e))}addClaims(e,t){const r=this.addClientCapabilitiesToClaims(e,t);Cc.validateClaims(r),this.parameters.set("claims",encodeURIComponent(r))}addCorrelationId(e){this.parameters.set("client-request-id",encodeURIComponent(e))}addLibraryInfo(e){this.parameters.set("x-client-SKU",e.sku),this.parameters.set("x-client-VER",e.version),e.os&&this.parameters.set("x-client-OS",e.os),e.cpu&&this.parameters.set("x-client-CPU",e.cpu)}addApplicationTelemetry(e){e?.appName&&this.parameters.set("x-app-name",e.appName),e?.appVersion&&this.parameters.set("x-app-ver",e.appVersion)}addPrompt(e){Cc.validatePrompt(e),this.parameters.set("prompt",encodeURIComponent(e))}addState(e){e&&this.parameters.set("state",encodeURIComponent(e))}addNonce(e){this.parameters.set("nonce",encodeURIComponent(e))}addCodeChallengeParams(e,t){if(Cc.validateCodeChallengeParams(e,t),!e||!t)throw cn(Wr);this.parameters.set("code_challenge",encodeURIComponent(e)),this.parameters.set("code_challenge_method",encodeURIComponent(t))}addAuthorizationCode(e){this.parameters.set("code",encodeURIComponent(e))}addDeviceCode(e){this.parameters.set("device_code",encodeURIComponent(e))}addRefreshToken(e){this.parameters.set("refresh_token",encodeURIComponent(e))}
2addCodeVerifier(e){this.parameters.set("code_verifier",encodeURIComponent(e))}addClientSecret(e){this.parameters.set("client_secret",encodeURIComponent(e))}addClientAssertion(e){e&&this.parameters.set("client_assertion",encodeURIComponent(e))}addClientAssertionType(e){e&&this.parameters.set("client_assertion_type",encodeURIComponent(e))}addOboAssertion(e){this.parameters.set("assertion",encodeURIComponent(e))}addRequestTokenUse(e){this.parameters.set("requested_token_use",encodeURIComponent(e))}addGrantType(e){this.parameters.set("grant_type",encodeURIComponent(e))}addClientInfo(){this.parameters.set("client_info","1")}addExtraQueryParameters(e){Object.entries(e).forEach(([e,t])=>{!this.parameters.has(e)&&t&&this.parameters.set(e,t)})}addClientCapabilitiesToClaims(e,t){let r;if(e)try{r=JSON.parse(e)}catch(e){throw cn(zr)}else r={};return t&&t.length>0&&(r.hasOwnProperty(T)||(r[T]={}),r[T][A]={values:t}),JSON.stringify(r)}addUsername(e){this.parameters.set(X,encodeURIComponent(e))}addPassword(e){this.parameters.set(Z,encodeURIComponent(e))}addPopToken(e){e&&(this.parameters.set(uc,$.POP),this.parameters.set(gc,encodeURIComponent(e)))}addSshJwk(e){e&&(this.parameters.set(uc,$.SSH),this.parameters.set(gc,encodeURIComponent(e)))}addServerTelemetry(e){this.parameters.set("x-client-current-telemetry",e.generateCurrentRequestHeaderValue()),this.parameters.set("x-client-last-telemetry",e.generateLastRequestHeaderValue())}addThrottling(){this.parameters.set("x-ms-lib-capability",V)}addLogoutHint(e){this.parameters.set("logout_hint",encodeURIComponent(e))}addBrokerParameters(e){const t={};t[fc]=e.brokerClientId,t[yc]=e.brokerRedirectUri,this.addExtraQueryParameters(t)}createQueryString(){const e=new Array;return this.parameters.forEach((t,r)=>{e.push(`${r}=${t}`)}),function(e,t,r){if(!t)return;const n=e.get(lc);n&&e.has(fc)&&r?.addFields({embeddedClientId:n,embeddedRedirectUri:e.get(hc)},t)}(this.parameters,this.correlationId,this.performanceClient),e.join("&")}}async function vc(e,t,r,n,o,i,s){s?.addQueueMeasurement(Qo,i);const a=qa.transformCIAMAuthority(Ua(e)),c=new qa(a,t,r,n,o,i,s);try{return await Na(c.resolveEndpointsAsync.bind(c),Wo,o,s,i)(),c}catch(e){throw mr(Et)}}class Ic{constructor(e,t){this.config=function({authOptions:e,systemOptions:t,loggerOptions:r,cacheOptions:n,storageInterface:o,networkInterface:i,cryptoInterface:s,clientCredentials:a,libraryInfo:c,telemetry:l,serverTelemetryManager:h,persistencePlugin:d,serializableCache:u}){const g={...xn,...r};return{authOptions:(p=e,{clientCapabilities:[],azureCloudOptions:Kn,skipAuthorityMetadataCache:!1,instanceAware:!1,...p}),systemOptions:{...Ln,...t},loggerOptions:g,cacheOptions:{...Hn,...n},storageInterface:o||new Un(e.clientId,fr,new pt(g)),networkInterface:i||Dn,cryptoInterface:s||fr,clientCredentials:a||Fn,libraryInfo:{...Bn,...c},telemetry:{...jn,...l},serverTelemetryManager:h||null,persistencePlugin:d||null,serializableCache:u||null};var p}(e),this.logger=new pt(this.config.loggerOptions,yr,Cr),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[u]=i.URL_FORM_CONTENT_TYPE,!this.config.systemOptions.preventCorsPreflight&&e)switch(e.type){case Qa:try{const r=un(e.credential);t[m]=`Oid:${r.uid}@${r.utid}`}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case Wa:t[m]=`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 o;cc.preProcess(this.cacheManager,e);try{o=await Na(this.networkClient.sendPostRequestAsync.bind(this.networkClient),lo,this.logger,this.performanceClient,n)(t,r);const e=o.headers||{};this.performanceClient?.addFields({refreshTokenSize:o.body.refresh_token?.length||0,httpVerToken:e[y]||"",requestId:e[f]||""},n)}catch(e){if(e instanceof Ei){const t=e.responseHeaders;throw t&&this.performanceClient?.addFields({httpVerToken:t[y]||"",requestId:t[f]||"",contentTypeHeader:t[u]||void 0,contentLengthHeader:t[g]||void 0,httpStatus:e.httpStatus},n),e.error}throw e instanceof It?e:mr(_t)}return cc.postProcess(this.cacheManager,e,o),o}async updateAuthority(e,t){this.performanceClient?.addQueueMeasurement(Ho,t);const r=`https://${e}/${this.authority.tenant}/`,n=await vc(r,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=n}createTokenQueryParameters(e){const t=new wc(e.correlationId,this.performanceClient);return e.embeddedClientId&&t.addBrokerParameters({brokerClientId:this.config.authOptions.clientId,brokerRedirectUri:this.config.authOptions.redirectUri}),e.tokenQueryParameters&&t.addExtraQueryParameters(e.tokenQueryParameters),t.addCorrelationId(e.correlationId),t.createQueryString()}}const Tc="sw";class Ac{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){this.performanceClient?.addQueueMeasurement(jo,e.correlationId);const r=await Na(this.generateKid.bind(this),jo,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(zo,e.correlationId);return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:Tc}}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 bn(i):void 0,h=l?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:Ir(),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 bc{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}class Sc{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}validateServerAuthorizationCodeResponse(e,t){if(!e.state||!t)throw e.state?mr(Mt,"Cac
2hed State"):mr(Mt,"Server State");let r,n;try{r=decodeURIComponent(e.state)}catch(t){throw mr(Ot,e.state)}try{n=decodeURIComponent(t)}catch(t){throw mr(Ot,e.state)}if(r!==n)throw mr(Nt);if(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+5):void 0}(e);if(za(e.error,e.error_description,e.suberror))throw new ja(e.error||"",e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.correlation_id||"",e.claims||"",t);throw new ac(e.error||"",e.error_description,e.suberror,t)}}validateTokenResponse(e,t){if(e.error||e.error_description||e.suberror){const r=`Error(s): ${e.error_codes||i.NOT_AVAILABLE} - Timestamp: ${e.timestamp||i.NOT_AVAILABLE} - Description: ${e.error_description||i.NOT_AVAILABLE} - Correlation ID: ${e.correlation_id||i.NOT_AVAILABLE} - Trace ID: ${e.trace_id||i.NOT_AVAILABLE}`,n=e.error_codes?.length?e.error_codes[0]:void 0,o=new ac(e.error,r,e.suberror,n,e.status);if(t&&e.status&&e.status>=c&&e.status<=l)return void this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.\n${o}`);if(t&&e.status&&e.status>=s&&e.status<=a)return void this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.\n${o}`);if(za(e.error,e.error_description,e.suberror))throw new ja(e.error,e.error_description,e.suberror,e.timestamp||i.EMPTY_STRING,e.trace_id||i.EMPTY_STRING,e.correlation_id||i.EMPTY_STRING,e.claims||i.EMPTY_STRING,n);throw o}}async handleServerTokenResponse(e,t,r,n,o,s,a,c,l){let h,d;if(this.performanceClient?.addQueueMeasurement($o,e.correlation_id),e.id_token){if(h=wr(e.id_token||i.EMPTY_STRING,this.cryptoObj.base64Decode),o&&o.nonce&&h.nonce!==o.nonce)throw mr(qt);if(n.maxAge||0===n.maxAge){const e=h.auth_time;if(!e)throw mr(Ut);vr(e,n.maxAge)}}this.homeAccountIdentifier=In.generateHomeAccountId(e.client_info||i.EMPTY_STRING,t.authorityType,this.logger,this.cryptoObj,h),o&&o.state&&(d=Ga.parseRequestState(this.cryptoObj,o.state)),e.key_id=e.key_id||n.sshKid||void 0;const u=this.generateCacheRecord(e,t,r,n,h,s,o);let g;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("Persistence enabled, calling beforeCacheAccess"),g=new bc(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(g)),a&&!c&&u.account){const e=u.account.generateAccountKey();if(!this.cacheStorage.getAccount(e))return this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache"),await Sc.generateAuthenticationResult(this.cryptoObj,t,u,!1,n,h,d,void 0,l)}await this.cacheStorage.saveCacheRecord(u,n.correlationId,n.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&g&&(this.logger.verbose("Persistence enabled, calling afterCacheAccess"),await this.persistencePlugin.afterCacheAccess(g))}return Sc.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 mr(Vt);const c=vn(o);let l,h;e.id_token&&o&&(l=br(this.homeAccountIdentifier,a,e.id_token,this.clientId,c||""),h=kc(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,o,e.client_info,a,c,s,void 0,this.logger));let d=null;if(e.access_token){const o=e.scope?hn.fromString(e.scope):new hn(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=Sr(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=kr(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,o,s,a,c,l){let h,d,u=i.EMPTY_STRING,g=[],p=null,m=i.EMPTY_STRING;if(r.accessToken){if(r.accessToken.tokenType!==$.POP||o.popKid)u=r.accessToken.secret;else{const t=new Ac(e),{secret:n,keyId:i}=r.accessToken;if(!i)throw mr(ar);u=await t.signPopToken(n,i,o)}g=hn.fromString(r.accessToken.target).asArray(),p=new Date(1e3*Number(r.accessToken.expiresOn)),h=new Date(1e3*Number(r.accessToken.extendedExpiresOn)),r.accessToken.refreshOn&&(d=new Date(1e3*Number(r.accessToken.refreshOn)))}r.appMetadata&&(m=r.appMetadata.familyId===x?x:"");const f=s?.oid||s?.sub||"",y=s?.tid||"";c?.spa_accountid&&r.account&&(r.account.nativeAccountId=c?.spa_accountid);const C=r.account?mn(r.account.getAccountInfo(),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:o.correlationId,requestId:l||i.EMPTY_STRING,familyId:m,tokenType:r.accessToken?.tokenType||i.EMPTY_STRING,state:a?a.userRequestState:i.EMPTY_STRING,cloudGraphHostName:r.account?.cloudGraphHostName||i.EMPTY_STRING,msGraphHost:r.account?.msGraphHost||i.EMPTY_STRING,code:c?.spa_code,fromNativeBroker:!1}}}function kc(e,t,r,n,o,i,s,a,c,l,h){h?.verbose("setCachedAccount called");const d=e.getAccountKeys().find(e=>e.startsWith(r));let u=null;d&&(u=e.getAccount(d));const g=u||In.createAccount({homeAccountId:r,idTokenClaims:o,clientInfo:i,environment:s,cloudGraphHostName:c?.cloud_graph_host_name,msGraphHost:c?.msgraph_host,nativeAccountId:l},t,n),p=g.tenantProfiles||[],m=a||g.realm;if(m&&!p.find(e=>e.tenantId===m)){const e=pn(r,g.localAccountId,m,o);p.push(e)}return g.tenantProfiles=p,g}async function Ec(e,t,r){if("string"==typeof e)return e;return e({clientId:t,tokenEndpoint:r})}class _c extends Ic{constructor(e,t){super(e,t),this.includeRedirectUri=!0,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async getAuthCodeUrl(e){this.performanceClient?.addQueueMeasurement(Uo,e.correlationId);const t=await Na(this.createAuthCodeUrlQueryString.bind(this),Ko,this.logger,this.performanceClient,e.correlationId)(e);return bn.appendQueryString(this.authority.authorizationEndpoint,t)}async acquireToken(e,t){if(this.performanceClient?.addQueueMeasurement(Do,e.correlationId),!e.code)throw mr(Bt);const r=Ir(),n=await Na(this.executeTokenRequest.bind(this),Bo,this.logger,this.performanceClient,e.correlationId)(this.authority,e),o=n.headers?.[f],i=new Sc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin,this.performanceClient);return i.validateTokenResponse(n.body),Na(i.handleServerTokenResponse.bind(i),$o,this.logger,this.performanceClient,e.correlationId)(n.body,this.authority,r,e,t,void 0,void 0,void 0,o)}handleFragmentResponse(e,t){if(new Sc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,null,null).validateServerAuthorizationCodeResponse(e,t),!e.code)throw mr(or);return e}getLogoutUri(e){if(!e)throw cn(Gr);const t=this.createLogoutUrlQueryString(e);return bn.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(Bo,t.correlationId);const r=this.createTokenQueryParameters(t),n=bn.appendQueryString(e.tokenEndpoint,r),o=await Na(this.createTokenRequestBody.bind(this),Fo,this.logger,this.performanceClient,t.correlationId)(t);let i;if(t.clientInfo)try{const e=dn(t.clientInfo,this.cryptoUtils.base64Decode);i={credential:`${e.uid}${q}${e.utid}`,type:Qa}}catch(e){this.logger.verbose("Could not parse client info for CCS Header: "+e)}const s=this.createTokenRequestHeaders(i||t.ccsCredential),a={clientId:t.tokenBodyParameters?.clientId||this.config.authOptions.clientId,authority:e.canonicalAuthority,scopes:t.scopes,claims:t.claims,authenticationScheme:t.authenticationScheme,resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,sshKid:t.sshKid};return Na(this.executePostToTokenEndpoint.bind(this),uo,this.logger,this.performanceClient,t.correlationId)(n,o,s,a,t.correlationId,uo)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(Fo,e.correlationId);const t=new wc(e.correlationId,this.performanceClient);if(t.addClientId(e.embeddedClientId||e.tokenBodyParameters?.[lc]||this.config.authOptions.clientId),this.includeRedirectUri?t.addRedirectUri(e.redirectUri):Cc.validateRedirectUri(e.redirectUri),t.addScopes(e.scopes,!0,this.oidcDefaultScopes),t.addAuthorizationCode(e.code),t.addLibraryInfo(this.config.libraryInfo),t.addApplicationTelemetry(this.config.telemetry.application),t.addThrottling(),this.serverTelemetryManager&&!zn(this.config)&&t.addServerTelemetry(this.serverTelemetryManager),e.codeVerifier&&t.addCodeVerifier(e.codeVerifier),this.config.clientCredentials.clientSecret&&t.addClientSecret(this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;t.addClientAssertion(await Ec(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),t.addClientAssertionType(r.assertionType)}if(t.addGrantType(_),t.addClientInfo(),e.authenticationScheme===$.POP){const r=new Ac(this.cryptoUtils,this.performanceClient);let n;if(e.popKid)n=this.cryptoUtils.encodeKid(e.popKid);else{n=(await Na(r.generateCnf.bind(r),jo,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}t.addPopToken(n)}else if(e.authenticationScheme===$.SSH){if(!e.sshJwk)throw cn(Xr);t.addSshJwk(e.sshJwk)}let r;if((!ln.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&t.addClaims(e.claims,this.config.authOptions.clientCapabilities),e.clientInfo)try{const t=dn(e.clientInfo,this.cryptoUtils.base64Decode);r={credential:`${t.uid}${q}${t.utid}`,type:Qa}}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 Qa:try{const e=un(r.credential);t.addCcsOid(e)}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case Wa:t.addCcsUpn(r.credential)}return e.embeddedClientId&&t.addBrokerParameters({brokerClientId:this.config.authOptions.clientId,brokerRedirectUri:this.config.authOptions.redirectUri}),e.tokenBodyParameters&&t.addExtraQueryParameters(e.tokenBodyParameters),!e.enableSpaAuthorizationCode||e.tokenBodyParameters&&e.tokenBodyParameters[pc]||t.addExtraQueryParameters({[pc]:"1"}),t.createQueryString()}async createAuthCodeUrlQueryString(e){const t=e.correlationId||this.config.cryptoInterface.createNewGuid();this.performanceClient?.addQueueMeasurement(Ko,t);const r=new wc(t,this.performanceClient);r.addClientId(e.embeddedClientId||e.extraQueryParameters?.[lc]||this.config.authOptions.clientId);const n=[...e.scopes||[],...e.extraScopesToConsent||[]];if(r.addScopes(n,!0,this.oidcDefaultScopes),r.addRedirectUri(e.redirectUri),r.addCorrelationId(t),r.addResponseMode(e.responseMode),r.addResponseTypeCode(),r.addLibraryInfo(this.config.libraryInfo),zn(this.config)||r.addApplicationTelemetry(this.config.telemetry.application),r.addClientInfo(),e.codeChallenge&&e.codeChallengeMethod&&r.addCodeChallengeParams(e.codeChallenge,e.codeChallengeMethod),e.prompt&&r.addPrompt(e.prompt),e.domainHint&&r.addDomainHint(e.domainHint),e.prompt!==b.SELECT_ACCOUNT)if(e.sid&&e.prompt===b.NONE)this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request"),r.addSid(e.sid);else if(e.account){const t=this.extractAccountSid(e.account);let n=this.extractLoginHint(e.account);if(n&&e.domainHint&&(this.logger.warning('AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint'),n=null),n){this.logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account"),r.addLoginHint(n);try{const t=un(e.account.homeAccountId);r.addCcsOid(t)}catch(e){this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(t&&e.prompt===b.NONE){this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account"),r.addSid(t);try{const t=un(e.account.homeAccountId);r.addCcsOid(t)}catch(e){this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(e.loginHint)this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from request"),r.addLoginHint(e.loginHint),r.addCcsUpn(e.loginHint);else if(e.account.username){this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from account"),r.addLoginHint(e.account.username);try{const t=un(e.account.homeAccountId);r.addCcsOid(t)}catch(e){this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}}else e.loginHint&&(this.logger.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request"),r.addLoginHint(e.loginHint),r.addCcsUpn(e.loginHint));else this.logger.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints");if(e.nonce&&r.addNonce(e.nonce),e.state&&r.addState(e.state),(e.claims||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&r.addClaims(e.claims,this.config.authOptions.clientCapabilities),e.embeddedClientId&&r.addBrokerParameters({brokerClientId:this.config.authOptions.clientId,brokerRedirectUri:this.config.authOptions.redirectUri}),this.addExtraQueryParams(e,r),e.platformBroker&&(r.addNativeBroker(),e.authenticationScheme===$.POP)){const t=new Ac(this.cryptoUtils);let n;if(e.popKid)n=this.cryptoUtils.encodeKid(e.popKid);else{n=(await Na(t.generateCnf.bind(t),jo,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}r.addPopToken(n)}return r.createQueryString()}createLogoutUrlQueryString(e){const t=new wc(e.correlationId,this.performanceClient);return e.postLogoutRedirectUri&&t.addPostLogoutRedirectUri(e.postLogoutRedirectUri),e.correlationId&&t.addCorrelationId(e.correlationId),e.idTokenHint&&t.addIdTokenHint(e.idTokenHint),e.state&&t.addState(e.state),e.logoutHint&&t.addLogoutHint(e.logoutHint),this.addExtraQueryParams(e,t),t.createQueryString()}addExtraQueryParams(e,t){!(e.extraQueryParameters&&e.extraQueryParameters.hasOwnProperty("instance_aware"))&&this.config.authOptions.instanceAware&&(e.extraQueryParameters=e.extraQueryParameters||{},e.extraQueryParameters.instance_aware="true"),e.extraQueryParameters&&t.addExtraQueryParameters(e.extraQueryParameters)}extractAccountSid(e){return e.idTokenClaims?.sid||null}extractLoginHint(e){return e.idTokenClaims?.login_hint||null}}function Rc(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 Pc{constructor(e,t){this.cacheOutcome=ce,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||i.EMPTY_STRING,this.wrapperVer=e.wrapperVer||i.EMPTY_STRING,this.telemetryCacheKey=z.CACHE_KEY+M+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${z.VALUE_SEPARATOR}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],r=this.getNativeBrokerErrorCode();r?.length&&t.push(`broker_error=${r}`);const n=t.join(z.VALUE_SEPARATOR),o=[e,this.getRegionDiscoveryFields()].join(z.VALUE_SEPARATOR);return[z.SCHEMA_VERSION,o,n].join(z.CATEGORY_SEPARATOR)}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=Pc.maxErrorsToSend(e),r=e.failedRequests.slice(0,2*t).join(z.VALUE_SEPARATOR),n=e.errors.slice(0,t).join(z.VALUE_SEPARATOR),o=e.errors.length,i=[o,t<o?z.OVERFLOW_TRUE:z.OVERFLOW_FALSE].join(z.VALUE_SEPARATOR);return[z.SCHEMA_VERSION,e.cacheHits,r,n,i].join(z.CATEGORY_SEPARATOR)}cacheFailedRequest(e){const t=this.getLastRequests();t.errors.length>=z.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 It?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(z.UNKNOWN_ERROR),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t)}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e),e.cacheHits}getLastRequests(){return this.cacheManager.getServerTelemetry(this.telemetryCacheKey)||{failedRequests:[],errors:[],cacheHits:0}}clearTelemetryCache(){const e=this.getLastRequests(),t=Pc.maxErrorsToSend(e);if(t===e.errors.length)this.cacheManager.removeItem(this.telemetryCacheKey);else{const r={failedRequests:e.failedRequests.slice(2*t),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,r)}}static maxErrorsToSend(e){let t,r=0,n=0;const o=e.errors.length;for(t=0;t<o;t++){const o=e.failedRequests[2*t]||i.EMPTY_STRING,s=e.failedRequests[2*t+1]||i.EMPTY_STRING,a=e.errors[t]||i.EMPTY_STRING;if(n+=o.toString().length+s.toString().length+a.length+3,!(n<z.MAX_LAST_HEADER_BYTES))break;r+=1}return r}getRegionDiscoveryFields(){const e=[];return e.push(this.regionUsed||i.EMPTY_STRING),e.push(this.regionSource||i.EMPTY_STRING),e.push(this.regionOutcome||i.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)}getNativeBrokerErrorCode(){return this.getLastRequests().nativeBrokerErrorCode}clearNativeBrokerErrorCode(){const e=this.getLastRequests();delete e.nativeBrokerErrorCode,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e)}static makeExtraSkuString(e){return Rc(e)}}class Oc{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.nativeMessageHandler=a,this.correlationId=c||Ws(),this.logger=n.clone(we,ya,this.correlationId),this.performanceClient=s}async clearCacheOnLogout(e){if(e){In.accountInfoIsEqual(e,this.browserStorage.getActiveAccount(),!1)&&(this.logger.verbose("Setting active account to null"),this.browserStorage.setActiveAccount(null));try{await this.browserStorage.removeAccount(In.generateAccountCacheKey(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),await this.browserStorage.clear(),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 bn.getAbsoluteUrl(t,la())}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 Pc(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(so,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(bn.getDomainFromUrl(o),t.environment):o,a=qa.generateAuthority(s,e.requestAzureCloudOptions||this.config.auth.azureCloudOptions),c=await Na(vc,Qo,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 cn(on);return c}}async function Nc(e,t,r){e.addQueueMeasurement(ui,r);const n=Oa(Mc,gi,t,e,r)(e,t,r);return{verifier:n,challenge:await Na(qc,pi,t,e,r)(n,e,t,r)}}function Mc(e,t,r){try{const n=new Uint8Array(32);Oa(Gs,fi,t,e,r)(n);return Os(n)}catch(e){throw ks(Ri)}}async function qc(e,t,r,n){t.addQueueMeasurement(pi,n);
2try{const o=await Na($s,mi,r,t,n)(e,t,n);return Os(new Uint8Array(o))}catch(e){throw ks(Ri)}}async function Uc(e,t,r,n){r.addQueueMeasurement(To,e.correlationId);const o=e.authority||t.auth.authority,i=[...e&&e.scopes||[]],s={...e,correlationId:e.correlationId,authority:o,scopes:i};if(s.authenticationScheme){if(s.authenticationScheme===$.SSH){if(!e.sshJwk)throw cn(Xr);if(!e.sshKid)throw cn(Zr)}n.verbose(`Authentication Scheme set to "${s.authenticationScheme}" as configured in Auth request`)}else s.authenticationScheme=$.BEARER,n.verbose('Authentication Scheme wasn\'t explicitly set in request, defaulting to "Bearer" request');return t.cache.claimsBasedCachingEnabled&&e.claims&&!ln.isEmptyObj(e.claims)&&(s.requestedClaimsHash=await ta(e.claims)),s}async function Lc(e,t,r,n,o){n.addQueueMeasurement(Ao,e.correlationId);const i=await Na(Uc,To,o,n,e.correlationId)(e,r,n,o);return{...e,...i,account:t,forceRefresh:e.forceRefresh||!1}}class xc extends Oc{async initializeAuthorizationCodeRequest(e){this.performanceClient.addQueueMeasurement(qo,this.correlationId);const t=await Na(Nc,ui,this.logger,this.performanceClient,this.correlationId)(this.performanceClient,this.logger,this.correlationId),r={...e,redirectUri:e.redirectUri,code:i.EMPTY_STRING,codeVerifier:t.verifier};return e.codeChallenge=t.challenge,e.codeChallengeMethod=i.S256_CODE_CHALLENGE_METHOD,r}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=bn.getAbsoluteUrl(e.postLogoutRedirectUri,la())):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=bn.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri,la())):(this.logger.verbose("Setting postLogoutRedirectUri to current page",t.correlationId),t.postLogoutRedirectUri=bn.getAbsoluteUrl(la(),la())),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(Oo,this.correlationId);const t=await Na(this.getClientConfiguration.bind(this),No,this.logger,this.performanceClient,this.correlationId)(e);return new _c(t,this.performanceClient)}async getClientConfiguration(e){const{serverTelemetryManager:t,requestAuthority:r,requestAzureCloudOptions:n,requestExtraQueryParameters:o,account:s}=e;this.performanceClient.addQueueMeasurement(No,this.correlationId);const a=await Na(this.getDiscoveredAuthority.bind(this),so,this.logger,this.performanceClient,this.correlationId)({requestAuthority:r,requestAzureCloudOptions:n,requestExtraQueryParameters:o,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:we,version:ya,cpu:i.EMPTY_STRING,os:i.EMPTY_STRING},telemetry:this.config.telemetry}}async initializeAuthorizationRequest(e,t){this.performanceClient.addQueueMeasurement(Mo,this.correlationId);const r=this.getRedirectUri(e.redirectUri),n={interactionType:t},o=Ga.setRequestState(this.browserCrypto,e&&e.state||i.EMPTY_STRING,n),s={...await Na(Uc,To,this.logger,this.performanceClient,this.correlationId)({...e,correlationId:this.correlationId},this.config,this.performanceClient,this.logger),redirectUri:r,state:o,nonce:e.nonce||Ws(),responseMode:this.config.auth.OIDCOptions.serverResponseType};if(e.loginHint||e.sid)return s;const a=e.account||this.browserStorage.getActiveAccount();return a&&(this.logger.verbose("Setting validated request account",this.correlationId),this.logger.verbosePii(`Setting validated request account: ${a.homeAccountId}`,this.correlationId),s.account=a),s}}const Hc="user_switch",Dc={[Hc]:"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 Bc extends It{constructor(e,t,r){super(e,t),Object.setPrototypeOf(this,Bc.prototype),this.name="NativeAuthError",this.ext=r}}function Fc(e){return!(!e.ext||!e.ext.status||"PERSISTENT_ERROR"!==e.ext.status&&"DISABLED"!==e.ext.status)||(!(!e.ext||!e.ext.error||-2147186943!==e.ext.error)||"ContentError"===e.errorCode)}function Kc(e,t,r){if(r&&r.status)switch(r.status){case"ACCOUNT_UNAVAILABLE":return $a(xa);case"USER_INTERACTION_REQUIRED":return new ja(e,t);case"USER_CANCEL":return ks(Bi);case"NO_NETWORK":return ks(ns)}return new Bc(e,Dc[e]||t,r)}class jc extends Ic{constructor(e,t){super(e,t)}async acquireToken(e){this.performanceClient?.addQueueMeasurement(po,e.correlationId);const t=Ir(),r=await Na(this.executeTokenRequest.bind(this),go,this.logger,this.performanceClient,e.correlationId)(e,this.authority),n=r.headers?.[f],o=new Sc(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return o.validateTokenResponse(r.body),Na(o.handleServerTokenResponse.bind(o),$o,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 cn($r);if(this.performanceClient?.addQueueMeasurement(fo,e.correlationId),!e.account)throw mr(Qt);if(this.cacheManager.isAppMetadataFOCI(e.account.environment))try{return await Na(this.acquireTokenWithCachedRefreshToken.bind(this),mo,this.logger,this.performanceClient,e.correlationId)(e,!0)}catch(t){const r=t instanceof ja&&t.errorCode===La,n=t instanceof ac&&t.errorCode===J&&t.subError===Y;if(r||n)return Na(this.acquireTokenWithCachedRefreshToken.bind(this),mo,this.logger,this.performanceClient,e.correlationId)(e,!1);throw t}return Na(this.acquireTokenWithCachedRefreshToken.bind(this),mo,this.logger,this.performanceClient,e.correlationId)(e,!1)}async acquireTokenWithCachedRefreshToken(e,t){this.performanceClient?.addQueueMeasurement(mo,e.correlationId);const r=Oa(this.cacheManager.getRefreshToken.bind(this.cacheManager),li,this.logger,this.performanceClient,e.correlationId)(e.account,t,void 0,this.performanceClient,e.correlationId);if(!r)throw $a(La);if(r.expiresOn&&Tr(r.expiresOn,e.refreshTokenExpirationOffsetSeconds||300))throw $a(H
2a);const n={...e,refreshToken:r.secret,authenticationScheme:e.authenticationScheme||$.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:Qa}};try{return await Na(this.acquireToken.bind(this),po,this.logger,this.performanceClient,e.correlationId)(n)}catch(e){if(e instanceof ja&&e.subError===Da){this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache");const e=Ar(r);this.cacheManager.removeRefreshToken(e)}throw e}}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(go,e.correlationId);const r=this.createTokenQueryParameters(e),n=bn.appendQueryString(t.tokenEndpoint,r),o=await Na(this.createTokenRequestBody.bind(this),yo,this.logger,this.performanceClient,e.correlationId)(e),i=this.createTokenRequestHeaders(e.ccsCredential),s={clientId:e.tokenBodyParameters?.clientId||this.config.authOptions.clientId,authority:t.canonicalAuthority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid};return Na(this.executePostToTokenEndpoint.bind(this),ho,this.logger,this.performanceClient,e.correlationId)(n,o,i,s,e.correlationId,ho)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(yo,e.correlationId);const t=e.correlationId,r=new wc(t,this.performanceClient);if(r.addClientId(e.embeddedClientId||e.tokenBodyParameters?.[lc]||this.config.authOptions.clientId),e.redirectUri&&r.addRedirectUri(e.redirectUri),r.addScopes(e.scopes,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),r.addGrantType(R),r.addClientInfo(),r.addLibraryInfo(this.config.libraryInfo),r.addApplicationTelemetry(this.config.telemetry.application),r.addThrottling(),this.serverTelemetryManager&&!zn(this.config)&&r.addServerTelemetry(this.serverTelemetryManager),r.addRefreshToken(e.refreshToken),this.config.clientCredentials.clientSecret&&r.addClientSecret(this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const t=this.config.clientCredentials.clientAssertion;r.addClientAssertion(await Ec(t.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),r.addClientAssertionType(t.assertionType)}if(e.authenticationScheme===$.POP){const t=new Ac(this.cryptoUtils,this.performanceClient);let n;if(e.popKid)n=this.cryptoUtils.encodeKid(e.popKid);else{n=(await Na(t.generateCnf.bind(t),jo,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}r.addPopToken(n)}else if(e.authenticationScheme===$.SSH){if(!e.sshJwk)throw cn(Xr);r.addSshJwk(e.sshJwk)}if((!ln.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&r.addClaims(e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case Qa:try{const t=un(e.ccsCredential.credential);r.addCcsOid(t)}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case Wa:r.addCcsUpn(e.ccsCredential.credential)}return e.embeddedClientId&&r.addBrokerParameters({brokerClientId:this.config.authOptions.clientId,brokerRedirectUri:this.config.authOptions.redirectUri}),e.tokenBodyParameters&&r.addExtraQueryParameters(e.tokenBodyParameters),r.createQueryString()}}class zc extends Ic{constructor(e,t){super(e,t)}async acquireToken(e){try{const[t,r]=await this.acquireCachedToken({...e,scopes:e.scopes?.length?e.scopes:[...h]});if(r===ue){this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.");new jc(this.config,this.performanceClient).acquireTokenByRefreshToken(e).catch(()=>{})}return t}catch(t){if(t instanceof pr&&t.errorCode===tr){return new jc(this.config,this.performanceClient).acquireTokenByRefreshToken(e)}throw t}}async acquireCachedToken(e){this.performanceClient?.addQueueMeasurement(wo,e.correlationId);let t=ce;if(e.forceRefresh||!this.config.cacheOptions.claimsBasedCachingEnabled&&!ln.isEmptyObj(e.claims))throw this.setCacheOutcome(le,e.correlationId),mr(tr);if(!e.account)throw mr(Qt);const r=e.account.tenantId||function(e){const t=new bn(e).getUrlComponents(),r=t.PathSegments.slice(-1)[0]?.toLowerCase();switch(r){case w:case v:case I:return;default:return r}}(e.authority),n=this.cacheManager.getTokenKeys(),o=this.cacheManager.getAccessToken(e.account,e,n,r,this.performanceClient,e.correlationId);if(!o)throw this.setCacheOutcome(he,e.correlationId),mr(tr);if(i=o.cachedAt,Number(i)>
2Ir()||Tr(o.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(de,e.correlationId),mr(tr);var i;o.refreshOn&&Tr(o.refreshOn,0)&&(t=ue);const s=e.authority||this.authority.getPreferredCache(),a={account:this.cacheManager.readAccountFromCache(e.account),accessToken:o,idToken:this.cacheManager.getIdToken(e.account,n,r,this.performanceClient,e.correlationId),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(s)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await Na(this.generateResultFromCacheRecord.bind(this),vo,this.logger,this.performanceClient,e.correlationId)(a,e),t]}setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==ce&&this.logger.info(`Token refresh is required due to cache outcome: ${e}`)}async generateResultFromCacheRecord(e,t){let r;if(this.performanceClient?.addQueueMeasurement(vo,t.correlationId),e.idToken&&(r=wr(e.idToken.secret,this.config.cryptoInterface.base64Decode)),t.maxAge||0===t.maxAge){const e=r?.auth_time;if(!e)throw mr(Ut);vr(e,t.maxAge)}return Sc.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,r)}}class $c extends xc{async acquireToken(e){this.performanceClient.addQueueMeasurement(to,e.correlationId);const t=this.initializeServerTelemetryManager(Ye),r=await Na(this.getClientConfiguration.bind(this),No,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,account:e.account}),n=new zc(r,this.performanceClient);this.logger.verbose("Silent auth client created");try{const t=(await Na(n.acquireCachedToken.bind(n),wo,this.logger,this.performanceClient,e.correlationId)(e))[0];return this.performanceClient.addFields({fromCache:!0},e.correlationId),t}catch(e){throw e instanceof Ss&&e.errorCode===cs&&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?.account)}}class Gc extends Oc{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.nativeMessageHandler=c,this.nativeStorageManager=h,this.silentCacheClient=new $c(e,this.nativeStorageManager,r,n,o,i,a,c,d);const u=this.nativeMessageHandler.getExtensionId()===Ie?"chrome":this.nativeMessageHandler.getExtensionId()?.length?"unknown":void 0;this.skus=Pc.makeExtraSkuString({libraryName:we,libraryVersion:ya,extensionName:u,extensionVersion:this.nativeMessageHandler.getExtensionVersion()})}addRequestSKUs(e){e.extraParameters={...e.extraParameters,[mc]:this.skus}}async acquireToken(e){this.performanceClient.addQueueMeasurement(co,e.correlationId),this.logger.trace("NativeInteractionClient - acquireToken called.");const t=this.performanceClient.startMeasurement(co,e.correlationId),r=Ir(),n=this.initializeServerTelemetryManager(this.apiId);try{const o=await this.initializeNativeRequest(e);try{const e=await this.acquireTokensFromCache(this.accountId,o);return t.end({success:!0,isNativeBroker:!1,fromCache:!0}),e}catch(e){this.logger.info("MSAL internal Cache does not contain tokens, proceed to make a native call")}const{...i}=o,s={method:Se,request:i},a=await this.nativeMessageHandler.sendMessage(s),c=this.validateNativeResponse(a);return await this.handleNativeResponse(c,o,r).then(e=>(t.end({success:!0,isNativeBroker:!0,requestId:e.requestId}),n.clearNativeBrokerErrorCode(),e)).catch(e=>{throw t.end({success:!1,errorCode:e.errorCode,subErrorCode:e.subError,isNativeBroker:!0}),e})}catch(e){throw e instanceof Bc&&n.setNativeBrokerErrorCode(e.errorCode),e}}createSilentCacheRequest(e,t){return{authority:e.authority,correlationId:this.correlationId,scopes:hn.fromString(e.scope).asArray(),account:t,forceRefresh:!1}}async acquireTokensFromCache(e,t){if(!e)throw this.logger.warning("NativeInteractionClient:acquireTokensFromCac
2he - No nativeAccountId provided"),mr(Jt);const r=this.browserStorage.getBaseAccountInfo({nativeAccountId:e});if(!r)throw mr(Jt);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),o={method:Se,request:n};try{const e=await this.nativeMessageHandler.sendMessage(o);this.validateNativeResponse(e)}catch(e){if(e instanceof Bc){if(this.initializeServerTelemetryManager(this.apiId).setNativeBrokerErrorCode(e.errorCode),Fc(e))throw e}}this.browserStorage.setTemporaryCache(Fe,JSON.stringify(n),!0);const i={apiId:Ge,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},s=this.config.auth.navigateToLoginRequestUrl?window.location.href:this.getRedirectUri(e.redirectUri);t.end({success:!0}),await this.navigationClient.navigateExternal(s,i)}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, removing prompt from cached request to prevent second interaction with native broker window."),this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Fe));const i={method:Se,request:o},s=Ir();try{this.logger.verbose("NativeInteractionClient - handleRedirectPromise sending message to native broker.");const e=await this.nativeMessageHandler.sendMessage(i);this.validateNativeResponse(e);const t=this.handleNativeResponse(e,o,s);this.browserStorage.setInteractionInProgress(!1);const r=await t;return this.initializeServerTelemetryManager(this.apiId).clearNativeBrokerErrorCode(),r}catch(e){throw this.browserStorage.setInteractionInProgress(!1),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=wr(e.id_token,qs),o=this.createHomeAccountIdentifier(e,n),i=this.browserStorage.getAccountInfoFilteredBy({nativeAccountId:t.accountId})?.homeAccountId;if(o!==i&&e.account.id!==t.accountId)throw Kc(Hc);const s=await this.getDiscoveredAuthority({requestAuthority:t.authority}),a=kc(this.browserStorage,s,o,qs,n,e.client_info,void 0,n.tid,void 0,e.account.id,this.logger),c=await this.generateAuthenticationResult(e,t,n,a,s.canonicalAuthority,r);return await this.cacheAccount(a),await this.cacheNativeTokens(e,t,o,n,e.access_token,c.tenantId,r),c}createHomeAccountIdentifier(e,t){return In.generateHomeAccountId(e.client_info||i.EMPTY_STRING,fn,this.logger,this.browserCrypto,t)}generateScopes(e,t){return e.scope?hn.fromString(e.scope):hn.fromString(t.scope)}async generatePopAccessToken(e,t){if(t.tokenType===$.POP&&t.signPopToken){if(e.shr)return this.logger.trace("handleNativeServerResponse: SHR is enabled in native layer"),e.shr;const r=new Ac(this.browserCrypto),n={resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,shrNonce:t.shrNonce};if(!t.keyId)throw mr(ar);return r.signPopToken(e.access_token,t.keyId,n)}return e.access_token}async generateAuthenticationResult(e,t,r,n,o,s){const a=this.addTelemetryFromNativeResponse(e),c=e.scope?hn.fromString(e.scope):hn.fromString(t.scope),l=e.account.properties||{},h=l.UID||r.oid||r.sub||i.EMPTY_STRING,d=l.TenantId||r.tid||i.EMPTY_STRING,u=mn(n.getAccountInfo(),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===$.POP?$.POP:$.BEARER;return{authority:o,uniqueId:h,tenantId:d,scopes:c.asArray(),account:u,idToken:e.id_token,idTokenClaims:r,accessToken:g,fromCache:!!a&&this.isResponseFromCache(a),expiresOn:new Date(1e3*Number(s+e.expires_in)),tokenType:p,correlationId:this.correlationId,state:e.state,fromNativeBroker:!0}}async cacheAccount(e){await this.browserStorage.setAccount(e,this.correlationId),this.browserStorage.removeAccountContext(e).catch(e=>{this.logger.error(`Error occurred while removing account context from browser storage. ${e}`)})}cacheNativeTokens(e,t,r,n,o,s,a){const c=br(r,t.authority,e.id_token||"",t.clientId,n.tid||""),l=a+(t.tokenType===$.POP?i.SHR_NONCE_VALIDITY:("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0),h=this.generateScopes(e,t),d={idToken:c,accessToken:Sr(r,t.authority,o,t.clientId,n.tid||s,h.printScopes(),l,0,qs,void 0,t.tokenType,void 0,t.keyId)};return this.nativeStorageManager.saveCacheRecord(d,this.correlationId,t.storeInCache)}addTelemetryFromNativeResponse(e){const t=this.getMATSFromResponse(e);return t?(this.performanceClient.addFields({extensionId:this.nativeMessageHandler.getExtensionId(),extensionVersion:this.nativeMessageHandler.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}validateNativeResponse(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 Tt(Ct,"Response missing expected properties.")}getMATSFromResponse(e){if(e.properties.MATS)try{return JSON.parse(e.properties.MATS)}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=e.authority||this.config.auth.authority;e.account&&await this.getDiscoveredAuthority({requestAuthority:t,requestAzureCloudOptions:e.azureCloudOptions,account:e.account});const r=new bn(t);r.validateAsUri();const{scopes:n,...o}=e,i=new hn(n||[]);i.appendScopes(h);const s={...o,accountId:this.accountId,clientId:this.config.auth.clientId,authority:r.urlString,scope:i.printScopes(),redirectUri:this.getRedirectUri(e.redirectUri),prompt:(()=>{switch(this.apiId){case We:case Ye:return this.logger.trace("initializeNativeRequest: silent request sets prompt to none"),b.NONE}if(e.prompt)switch(e.prompt){case b.NONE:case b.CONSENT:case b.LOGIN:return this.logger.trace("initializeNativeRequest: prompt is compatible with native flow"),e.prompt;default:throw this.logger.trace(`initializeNativeRequest: prompt = ${e.prompt} is not compatible with native flow`),ks(Cs)}else this.logger.trace("initializeNativeRequest: prompt was not provided")})(),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 ks(vs);if(this.handleExtraBrokerParams(s),s.extraParameters=s.extraParameters||{},s.extraParameters.telemetry=Te,e.authenticationScheme===$.POP){const t={resourceRequestUri:e.resourceRequestUri,resourceRequestMethod:e.resourceRequestMethod,shrClaims:e.shrClaims,shrNonce:e.shrNonce},r=new Ac(this.browserCrypto);let n;if(s.keyId)n=this.browserCrypto.base64UrlEncode(JSON.stringify({kid:s.keyId})),s.signPopToken=!1;else{const o=await Na(r.generateCnf.bind(r),jo,this.logger,this.performanceClient,e.correlationId)(t,this.logger);
2n=o.reqCnfString,s.keyId=o.kid,s.signPopToken=!0}s.reqCnf=n}return this.addRequestSKUs(s),s}handleExtraBrokerParams(e){const t=e.extraParameters&&e.extraParameters.hasOwnProperty(fc)&&e.extraParameters.hasOwnProperty(yc)&&e.extraParameters.hasOwnProperty(lc);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[yc],r=e.extraParameters[lc]),e.extraParameters={child_client_id:r,child_redirect_uri:n},this.performanceClient?.addFields({embeddedClientId:r,embeddedRedirectUri:n},e.correlationId)}}class Qc{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(si)}async sendMessage(e){this.logger.trace("NativeMessageHandler - sendMessage called.");const t={channel:ve,extensionId:this.extensionId,responseId:Ws(),body:e};return this.logger.trace("NativeMessageHandler - Sending request to browser extension"),this.logger.tracePii(`NativeMessageHandler - Sending request to browser extension: ${JSON.stringify(t)}`),this.messageChannel.port1.postMessage(t),new Promise((e,r)=>{this.resolvers.set(t.responseId,{resolve:e,reject:r})})}static async createProvider(e,t,r){e.trace("NativeMessageHandler - createProvider called.");try{const n=new Qc(e,t,r,Ie);return await n.sendHandshakeRequest(),n}catch(n){const o=new Qc(e,t,r);return await o.sendHandshakeRequest(),o}}async sendHandshakeRequest(){this.logger.trace("NativeMessageHandler - sendHandshakeRequest called."),window.addEventListener("message",this.windowListener,!1);const e={channel:ve,extensionId:this.extensionId,responseId:Ws(),body:{method:Ae}};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(ks(ps)),this.handshakeResolvers.delete(e.responseId)},this.handshakeTimeoutMs)})}onWindowMessage(e){if(this.logger.trace("NativeMessageHandler - onWindowMessage called"),e.source!==window)return;const t=e.data;if(t.channel&&t.channel===ve&&(!t.extensionId||t.extensionId===this.extensionId)&&t.body.method===Ae){const e=this.handshakeResolvers.get(t.responseId);if(!e)return void this.logger.trace(`NativeMessageHandler.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(ks(ms))}}onChannelMessage(e){this.logger.trace("NativeMessageHandler - 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===ke){if(!r)return;const e=t.body.response;if(this.logger.trace("NativeMessageHandler - Received response from browser extension"),this.logger.tracePii(`NativeMessageHandler - Received response from browser extension: ${JSON.stringify(e)}`),"Success"!==e.status)r.reject(Kc(e.code,e.description,e.ext));else{if(!e.result)throw Tt(Ct,"Event does not contain result.");e.result.code&&e.result.description?r.reject(Kc(e.result.code,e.result.description,e.result.ext)):r.resolve(e.result)}this.resolvers.delete(t.responseId)}else if(e===be){if(!n)return void this.logger.trace(`NativeMessageHandler.onCh
2annelMessage - 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(`NativeMessageHandler - 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)}}getExtensionId(){return this.extensionId}getExtensionVersion(){return this.extensionVersion}static isPlatformBrokerAvailable(e,t,r,n){if(t.trace("isPlatformBrokerAvailable called"),!e.system.allowPlatformBroker)return t.trace("isPlatformBrokerAvailable: allowPlatformBroker is not enabled, returning false"),!1;if(!r)return t.trace("isPlatformBrokerAvailable: Platform extension provider is not initialized, returning false"),!1;if(n)switch(n){case $.BEARER:case $.POP:return t.trace("isPlatformBrokerAvailable: authenticationScheme is supported, returning true"),!0;default:return t.trace("isPlatformBrokerAvailable: authenticationScheme is not supported, returning false"),!1}return!0}}class Wc{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(xo,t.correlationId);try{r=this.authModule.handleFragmentResponse(e,t.state)}catch(e){throw e instanceof ac&&e.subError===Bi?ks(Bi):e}return Na(this.handleCodeResponseFromServer.bind(this),Lo,this.logger,this.performanceClient,t.correlationId)(r,t)}async handleCodeResponseFromServer(e,t,r=!0){if(this.performanceClient.addQueueMeasurement(Lo,t.correlationId),this.logger.trace("InteractionHandler.handleCodeResponseFromServer called"),this.authCodeRequest.code=e.code,e.cloud_instance_host_name&&await Na(this.authModule.updateAuthority.bind(this.authModule),Ho,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 Na(this.authModule.acquireToken.bind(this.authModule),Do,this.logger,this.performanceClient,t.correlationId)(this.authCodeRequest,e)}createCcsCredentials(e){return e.account?{credential:e.account.homeAccountId,type:Qa}:e.loginHint?{credential:e.loginHint,type:Wa}:null}}function Vc(e,t,r){const n=An(e);if(!n)throw Tn(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}`),ks(qi)):(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.`),ks(Ni));return n}class Jc extends xc{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}acquireToken(e){try{const t={popupName:this.generatePopupName(e.scopes||h,e.authority||this.config.auth.authority),popupWindowAttributes:e.popupWindowAttributes||{},popupWindowParent:e.popupWindowParent??window};return this.config.system.asyncPopups?(this.logger.verbose("asyncPopups set to true, acquiring token"),this.acquireTokenPopupAsync(e,t)):(this.logger.verbose("asyncPopup set to false, opening popup before acquiring token"),t.popup=this.openSizedPopup("about:blank",t),this.acquireTokenPopupAsync(e,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){this.logger.verbose("acquireTokenPopupAsync called");const r=this.initializeServerTelemetryManager(Qe),n=await Na(this.initializeAuthorizationRequest.bind(this),Mo,this.logger,this.performanceClient,this.correlationId)(e,et.Popup);ma(n.authority);try{const o=await Na(this.initializeAuthorizationCodeRequest.bind(this),qo,this.logger,this.performanceClient,this.correlationId)(n),i=await Na(this.createAuthCodeClient.bind(this),Oo,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:n.authority,requestAzureCloudOptions:n.azureCloudOptions,requestExtraQueryParameters:n.extraQueryParameters,account:n.account}),s=Qc.isPlatformBrokerAvailable(this.config,this.logger,this.nativeMessageHandler,e.authenticationScheme);let a;s&&(a=this.performanceClient.startMeasurement(ao,e.correlationId));const c=await i.getAuthCodeUrl({...n,platformBroker:s}),l=new Wc(i,this.browserStorage,o,this.logger,this.performanceClient),h=this.initiateAuthRequest(c,t);this.eventHandler.emitEvent(ic.POPUP_OPENED,et.Popup,{popupWindow:h},null);const d=await this.monitorPopupForHash(h,t.popupWindowParent),u=Oa(Vc,Go,this.logger,this.performanceClient,this.correlationId)(d,this.config.auth.OIDCOptions.serverResponseType,this.logger);if(cc.removeThrottle(this.browserStorage,this.config.auth.clientId,o),u.accountId){if
2(this.logger.verbose("Account id found in hash, calling WAM for token"),a&&a.end({success:!0,isNativeBroker:!0}),!this.nativeMessageHandler)throw ks(fs);const e=new Gc(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Qe,this.performanceClient,this.nativeMessageHandler,u.accountId,this.nativeStorage,n.correlationId),{userRequestState:t}=Ga.parseRequestState(this.browserCrypto,n.state);return await e.acquireToken({...n,state:t,prompt:void 0})}return await l.handleCodeResponse(u,n)}catch(e){throw t.popup?.close(),e instanceof It&&(e.setCorrelationId(this.correlationId),r.cacheFailedRequest(e)),e}}async logoutPopupAsync(e,t,r,n){this.logger.verbose("logoutPopupAsync called"),this.eventHandler.emitEvent(ic.LOGOUT_START,et.Popup,e);const o=this.initializeServerTelemetryManager(Ze);try{await this.clearCacheOnLogout(e.account);const i=await Na(this.createAuthCodeClient.bind(this),Oo,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===ft){if(this.browserStorage.removeAccount(e.account?.homeAccountId),this.eventHandler.emitEvent(ic.LOGOUT_SUCCESS,et.Popup,e),n){const e={apiId:Ze,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=bn.getAbsoluteUrl(n,la());await this.navigationClient.navigateInternal(t,e)}return void t.popup?.close()}}const s=i.getLogoutUri(e);this.eventHandler.emitEvent(ic.LOGOUT_SUCCESS,et.Popup,e);const a=this.openPopup(s,t);if(this.eventHandler.emitEvent(ic.POPUP_OPENED,et.Popup,{popupWindow:a},null),await this.monitorPopupForHash(a,t.popupWindowParent).catch(()=>{}),n){const e={apiId:Ze,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=bn.getAbsoluteUrl(n,la());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 It&&(e.setCorrelationId(this.correlationId),o.cacheFailedRequest(e)),this.browserStorage.setInteractionInProgress(!1),this.eventHandler.emitEvent(ic.LOGOUT_FAILURE,et.Popup,null,e),this.eventHandler.emitEvent(ic.LOGOUT_END,et.Popup),e}this.eventHandler.emitEvent(ic.LOGOUT_END,et.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"),ks(Oi)}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(ks(Bi));let o="";try{o=e.location.href}catch(e){}if(!o||"about:blank"===o)return;clearInterval(n);let i="";const s=this.config.auth.OIDCOptions.serverResponseType;e&&(i=s===k.QUERY?e.location.search:e.location.hash),this.logger.verbose("PopupHandler.monitorPopupForHash - popup window is on same origin as caller"),t(i)},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 ks(Di);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),this.browserStorage.setInteractionInProgress(!1),ks(Hi)}}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;
2let 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=me),(!l||l<0||l>a)&&(this.logger.verbose("Default popup window height used. Window height not configured or invalid."),l=fe),(!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-fe/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-me/2+o)),n.open(e,t,`width=${c}, height=${l}, top=${h}, left=${d}, scrollbars=yes`)}unloadWindow(e){this.browserStorage.cleanRequestByInteractionType(et.Popup),this.currentWindow&&this.currentWindow.close(),e.preventDefault()}cleanPopup(e,t){e.close(),t.removeEventListener("beforeunload",this.unloadWindow),this.browserStorage.setInteractionInProgress(!1)}generatePopupName(e,t){return`${ye}.${this.config.auth.clientId}.${e.join("-")}.${t}.${this.correlationId}`}generateLogoutPopupName(e){const t=e.account&&e.account.homeAccountId;return`${ye}.${this.config.auth.clientId}.${t}.${this.correlationId}`}}class Yc{constructor(e,t,r,n,o){this.authModule=e,this.browserStorage=t,this.authCodeRequest=r,this.logger=n,this.performanceClient=o}async initiateAuthRequest(e,t){if(this.logger.verbose("RedirectHandler.initiateAuthRequest called"),e){t.redirectStartPage&&(this.logger.verbose("RedirectHandler.initiateAuthRequest: redirectStartPage set, caching start page"),this.browserStorage.setTemporaryCache(Ue,t.redirectStartPage,!0)),this.browserStorage.setTemporaryCache(Be,this.authCodeRequest.correlationId,!0),this.browserStorage.cacheCodeRequest(this.authCodeRequest),this.logger.infoPii(`RedirectHandler.initiateAuthRequest: Navigate to: ${e}`);const r={apiId:Ge,timeout:t.redirectTimeout,noHistory:!1};if("function"==typeof t.onRedirectNavigate){this.logger.verbose("RedirectHandler.initiateAuthRequest: Invoking onRedirectNavigate callback");return!1!==t.onRedirectNavigate(e)?(this.logger.verbose("RedirectHandler.initiateAuthRequest: onRedirectNavigate did not return false, navigating"),void await t.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 t.navigationClient.navigateExternal(e,r)}throw this.logger.info("RedirectHandler.initiateAuthRequest: Navigate url is empty"),ks(Oi)}async handleCodeResponse(e,t){this.logger.verbose("RedirectHandler.handleCodeResponse called"),this.browserStorage.setInteractionInProgress(!1);const r=this.browserStorage.generateStateKey(t),n=this.browserStorage.getTemporaryCache(r);if(!n)throw mr(Mt,"Cached State");let o;try{o=this.authModule.handleFragmentResponse(e,n)}catch(e){throw e instanceof ac&&e.subError===Bi?ks(Bi):e}const i=this.browserStorage.generateNonceKey(n),s=this.browserStorage.getTemporaryCache(i);if(this.authCodeRequest.code=o.code,o.cloud_instance_host_name&&await Na(this.authModule.updateAuthority.bind(this.authModule),Ho,this.logger,this.performanceClient,this.authCodeRequest.correlationId)(o.cloud_instance_host_name,this.authCodeRequest.correlationId),o.nonce=s||void 0,o.state=n,o.client_info)this.authCodeRequest.clientInfo=o.client_info;else{const e=this.checkCcsCredentials();e&&(this.authCodeRequest.ccsCredential=e)}const a=await this.authModule.acquireToken(this.authCodeRequest,o);return this.browserStorage.cleanRequestByState(t),a}checkCcsCredentials(){const e=this.browserStorage.getTemporaryCache(De,!0);if(e)try{return JSON.parse(e)}catch(t){this.authModule.logger.error("Cache credential could not be parsed"),this.authModule.logger.errorPii(`Cache 
2credential could not be parsed: ${e}`)}return null}}class Xc extends xc{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 Na(this.initializeAuthorizationRequest.bind(this),Mo,this.logger,this.performanceClient,this.correlationId)(e,et.Redirect);this.browserStorage.updateCacheEntries(t.state,t.nonce,t.authority,t.loginHint||"",t.account||null);const r=this.initializeServerTelemetryManager(Ge),n=e=>{e.persisted&&(this.logger.verbose("Page was restored from back/forward cache. Clearing temporary cache."),this.browserStorage.cleanRequestByState(t.state),this.eventHandler.emitEvent(ic.RESTORE_FROM_BFCACHE,et.Redirect))};try{const o=await Na(this.initializeAuthorizationCodeRequest.bind(this),qo,this.logger,this.performanceClient,this.correlationId)(t),i=await Na(this.createAuthCodeClient.bind(this),Oo,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account}),s=new Yc(i,this.browserStorage,o,this.logger,this.performanceClient),a=await i.getAuthCodeUrl({...t,platformBroker:Qc.isPlatformBrokerAvailable(this.config,this.logger,this.nativeMessageHandler,e.authenticationScheme)}),c=this.getRedirectStartPage(e.redirectStartPage);return this.logger.verbosePii(`Redirect start page: ${c}`),window.addEventListener("pageshow",n),await s.initiateAuthRequest(a,{navigationClient:this.navigationClient,redirectTimeout:this.config.system.redirectNavigationTimeout,redirectStartPage:c,onRedirectNavigate:e.onRedirectNavigate||this.config.auth.onRedirectNavigate})}catch(e){throw e instanceof It&&(e.setCorrelationId(this.correlationId),r.cacheFailedRequest(e)),window.removeEventListener("pageshow",n),this.browserStorage.cleanRequestByState(t.state),e}}async handleRedirectPromise(e="",t){const r=this.initializeServerTelemetryManager(Ve);try{if(!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null."),null;const[n,o]=this.getRedirectResponse(e||"");if(!n)return this.logger.info("handleRedirectPromise did not detect a response as a result of a redirect. Cleaning temporary cache."),this.browserStorage.cleanRequestByInteractionType(et.Redirect),"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}()?t.event.errorCode="no_server_response":this.logger.verbose("Back navigation event detected. Muting no_server_response error"),null;const s=this.browserStorage.getTemporaryCache(Ue,!0)||i.EMPTY_STRING,a=bn.removeHashFromUrl(s);if(a===bn.removeHashFromUrl(window.location.href)&&this.config.auth.navigateToLoginRequestUrl){this.logger.verbose("Current page is loginRequestUrl, handling response"),s.indexOf("#")>-1&&function(e){const t=e.split("#");t.shift(),window.location.hash=t.length>0?t.join("#"):""}(s);return await this.handleResponse(n,r)}if(!this.config.auth.navigateToLoginRequestUrl)return this.logger.verbose("NavigateToLoginRequestUrl set to false, handling response"),await this.handleResponse(n,r);if(!ca()||this.config.system.allowRedirectInIframe){this.browserStorage.setTemporaryCache(Le,o,!0);const e={apiId:Ve,timeout:this.config.system.redirectNavigationTimeout,noHistory:!0};let t=!0;if(s&&"null"!==s)this.logger.verbose(`Navigating to loginRequestUrl: ${s}`),t=await this.navigationClient.navigateInternal(s,e);else{const r=function(){const e=new bn(window.location.href).getUrlComponents();return`${e.Protocol}//${e.HostNameAndPort}/`}();this.browserStorage.setTemporaryCache(Ue,r,!0),this.logger.warning("Unable to get valid login request url from cache, redirecting to home page"),t=await this.navigationClient.navigateInternal(r,e)}if(!t)return await this.handleResponse(n,r)}return null}catch(e){throw e instanceof It&&(e.setCorrelationId(this.correlationId),r.cacheFailedRequest(e)),this.browserStorage.cleanRequestByInteractionType(et.Redirect),e}}getRedirectResponse(e){this.logger.verbose("getRedirectResponseHash called");let t=e;t||(t=this.config.auth.OIDCOptions.serverResponseType===k.QUERY?window.location.search:window.location.hash);let r=An(t);if(r){try{!function(e,t,r){if(!e.state)throw ks(Mi);const n=rc(t,e.state);if(!n)throw ks(Ui);if(n.interactionType!==r)throw ks(Li)}(r,this.browserCrypto,et.Redirect)}catch(e){return e instanceof It&&this.logger.error(`Interaction type validation failed due to ${e.errorCode}: ${e.errorMessage}`),[null,""]}return(n=window).location.hash="","function"==typeof n.history.replaceState&&n.history.replaceState(null,"",`${n.location.origin}${n.location.pathname}${n.location.search}`),this.logger.verbose("Hash contains known properties, returning response hash"),[r,t]}var n;const o=this.browserStorage.getTemporaryCache(Le,!0);return this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Le)),o&&(r=An(o),r)?(this.logger.verbose("Hash does not contain known properties, returning c
2ached hash"),[r,o]):[null,""]}async handleResponse(e,t){const r=e.state;if(!r)throw ks(Mi);const n=this.browserStorage.getCachedRequest(r);if(this.logger.verbose("handleResponse called, retrieved cached request"),e.accountId){if(this.logger.verbose("Account id found in hash, calling WAM for token"),!this.nativeMessageHandler)throw ks(fs);const t=new Gc(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Qe,this.performanceClient,this.nativeMessageHandler,e.accountId,this.nativeStorage,n.correlationId),{userRequestState:o}=Ga.parseRequestState(this.browserCrypto,r);return t.acquireToken({...n,state:o,prompt:void 0}).finally(()=>{this.browserStorage.cleanRequestByState(r)})}const o=this.browserStorage.getCachedAuthority(r);if(!o)throw ks(Xi);const i=await Na(this.createAuthCodeClient.bind(this),Oo,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:o});cc.removeThrottle(this.browserStorage,this.config.auth.clientId,n);return new Yc(i,this.browserStorage,n,this.logger,this.performanceClient).handleCodeResponse(e,r)}async logout(e){this.logger.verbose("logoutRedirect called");const t=this.initializeLogoutRequest(e),r=this.initializeServerTelemetryManager(Xe);try{this.eventHandler.emitEvent(ic.LOGOUT_START,et.Redirect,e),await this.clearCacheOnLogout(t.account);const n={apiId:Xe,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},o=await Na(this.createAuthCodeClient.bind(this),Oo,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===ft)try{o.authority.endSessionEndpoint}catch{if(t.account?.homeAccountId)return this.browserStorage.removeAccount(t.account?.homeAccountId),void this.eventHandler.emitEvent(ic.LOGOUT_SUCCESS,et.Redirect,t)}const i=o.getLogoutUri(t);if(this.eventHandler.emitEvent(ic.LOGOUT_SUCCESS,et.Redirect,t),!e||"function"!=typeof e.onRedirectNavigate)return this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0),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),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 It&&(e.setCorrelationId(this.correlationId),r.cacheFailedRequest(e)),this.eventHandler.emitEvent(ic.LOGOUT_FAILURE,et.Redirect,null,e),this.eventHandler.emitEvent(ic.LOGOUT_END,et.Redirect),e}this.eventHandler.emitEvent(ic.LOGOUT_END,et.Redirect)}getRedirectStartPage(e){const t=e||window.location.href;return bn.getAbsoluteUrl(t,la())}}async function Zc(e,t,r,n,o){if(t.addQueueMeasurement(Eo,n),!e)throw r.info("Navigate url is empty"),ks(Oi);return o?Na(tl,Ro,r,t,n)(e,o,t,n):Oa(rl,Po,r,t,n)(e)}async function el(e,t,r,n,o,i,s){return n.addQueueMeasurement(_o,i),new Promise((n,i)=>{t<fa&&o.warning(`system.loadFrameTimeout or system.iframeHashTimeout set to lower (${t}ms) than the default (10000ms). This may result in timeouts.`);const a=window.setTimeout(()=>{window.clearInterval(c),i(ks(Ki))},t),c=window.setInterval(()=>{let t="";const r=e.contentWindow;try{t=r?r.location.href:""}catch(e){}if(!t||"about:blank"===t)return;let o="";r&&(o=s===k.QUERY?r.location.search:r.location.hash),window.clearTimeout(a),window.clearInterval(c),n(o)},r)}).finally(()=>{Oa(ol,ai,o,n,i)(e)})}function tl(e,t,r,n){return r.addQueueMeasurement(Ro,n),new Promise((r,n)=>{const o=nl();window.setTimeout(()=>{o?(o.src=e,r(o)):n("Unable to load iframe")},t)})}function rl(e){const t=nl();return t.src=e,t}function nl(){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"),document.body.appendChild(e),e}function ol(e){document.body===e.parentNode&&document.body.removeChild(e)}class il extends xc{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(ro,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!==b.NONE&&t.prompt!==b.NO_SESSION&&(this.logger.warning(`SilentIframeClient. Replacing invalid prompt ${t.prompt} with ${b.NONE}`),t.prompt=b.NONE):t.prompt=b.NONE;const r=await Na(this.initializeAuthorizationRequest.bind(this),Mo,this.logger,this.performanceClient,e.correlationId)(t,et.Silent);ma(r.authority);const n=this.initializeServerTelemetryManager(this.apiId);let o;try{return o=await Na(this.createAuthCodeClient.bind(this),Oo,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:n,requestAuthority:r.authority,requestAzureCloudOptions:r.azureCloudOptions,requestExtraQueryParameters:r.extraQueryParameters,account:r.account}),await Na(this.silentTokenHelper.bind(this),ko,this.logger,this.performanceClient,e.correlationId)(o,r)}catch(r){if(r instanceof It&&(r.setCorrelationId(this.correlationId),n.cacheFailedRequest(r)),!(o&&r instanceof It&&r.errorCode===pe))throw r;this.performanceClient.addFields({retryError:r.errorCode},this.correlationId);const i=await Na(this.initializeAuthorizationRequest.bind(this),Mo,this.logger,this.performanceClient,e.correlationId)(t,et.Silent);return await Na(this.silentTokenHelper.bind(this),ko,this.logger,this.performanceClient,this.correlationId)(o,i)}}logout(){return Promise.reject(ks(Qi))}async silentTokenHelper(e,t){const r=t.correlationId;this.performanceClient.addQueueMeasurement(ko,r);const n=await Na(this.initializeAuthorizationCodeRequest.bind(this),qo,this.logger,this.performanceClient,r)(t),o=await Na(e.getAuthCodeUrl.bind(e),Uo,this.logger,this.performanceClient,r)({...t,platformBroker:Qc.isPlatformBrokerAvailable(this.config,this.logger,this.nativeMessageHandler,t.authenticationScheme)}),i=new Wc(e,this.browserStorage,n,this.logger,this.performanceClient),s=await Na(Zc,Eo,this.logger,this.performanceClient,r)(o,this.performanceClient,this.logger,r,this.config.system.navigateFrameWait),a=this.config.auth.OIDCOptions.serverResponseType,c=await Na(el,_o,this.logger,this.performanceClient,r)(s,this.config.system.iframeHashTimeout,this.config.system.pollIntervalMilliseconds,this.performanceClient,this.logger,r,a),l=Oa(Vc,Go,this.logger,this.performanceClient,this.correlationId)(c,a,this.logger);
2if(l.accountId){if(this.logger.verbose("Account id found in hash, calling WAM for token"),!this.nativeMessageHandler)throw ks(fs);const e=new Gc(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.apiId,this.performanceClient,this.nativeMessageHandler,l.accountId,this.browserStorage,r),{userRequestState:n}=Ga.parseRequestState(this.browserCrypto,t.state);return Na(e.acquireToken.bind(e),co,this.logger,this.performanceClient,r)({...t,state:n,prompt:t.prompt||b.NONE})}return Na(i.handleCodeResponse.bind(i),xo,this.logger,this.performanceClient,r)(l,t)}}class sl extends xc{async acquireToken(e){this.performanceClient.addQueueMeasurement(oo,e.correlationId);const t=await Na(Uc,To,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(Ye),o=await this.createRefreshTokenClient({serverTelemetryManager:n,authorityUrl:r.authority,azureCloudOptions:r.azureCloudOptions,account:r.account});return Na(o.acquireTokenByRefreshToken.bind(o),fo,this.logger,this.performanceClient,e.correlationId)(r).catch(e=>{throw e.setCorrelationId(this.correlationId),n.cacheFailedRequest(e),e})}logout(){return Promise.reject(ks(Qi))}async createRefreshTokenClient(e){const t=await Na(this.getClientConfiguration.bind(this),No,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:e.serverTelemetryManager,requestAuthority:e.authorityUrl,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return new jc(t,this.performanceClient)}}class al{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 ks(ts);const n=e.correlationId||Ws(),o=t.id_token?wr(t.id_token,qs):void 0,i={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},s=e.authority?new qa(qa.generateAuthority(e.authority,e.azureCloudOptions),this.config.system.networkClient,this.storage,i,this.logger,e.correlationId||Ws()):void 0,a=await this.loadAccount(e,r.clientInfo||t.client_info||"",n,o,s),c=await this.loadIdToken(t,a.homeAccountId,a.environment,a.realm,n),l=await this.loadAccessToken(e,t,a.homeAccountId,a.environment,a.realm,r,n),h=await this.loadRefreshToken(t,a.homeAccountId,a.environment,n);return this.generateAuthenticationResult(e,{account:a,idToken:c,accessToken:l,refreshToken:h},o,s)}async loadAccount(e,t,r,n,o){if(this.logger.verbose("TokenCache - loading account"),e.account){const t=In.createFromAccountInfo(e.account);return await this.storage.setAccount(t,r),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."),ks(as);const i=In.generateHomeAccountId(t,o.authorityType,this.logger,this.cryptoObj,n),s=n?.tid,a=kc(this.storage,o,i,qs,n,t,o.hostnameAndPort,s,void 0,void 0,this.logger);return await this.storage.setAccount(a,r),a}async loadIdToken(e,t,r,n,o){if(!e.id_token)return this.logger.verbose("TokenCache - no id token found in response"),null;this.logger.verbose("TokenCache - loading id token");const i=br(t,r,e.id_token,this.config.auth.clientId,n);return await this.storage.setIdTokenCredential(i,o),i}async loadAccessToken(e,t,r,n,o,i,s){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 a=t.scope?hn.fromString(t.scope):new hn(e.scopes),c=i.expiresOn||t.expires_in+(new Date).getTime()/1e3,l=i.extendedExpiresOn||(t.ext_expires_in||t.expires_in)+(new Date).getTime()/1e3,h=Sr(r,n,t.access_token,this.config.auth.clientId,o,a.printScopes(),c,l,qs);return await this.storage.setAccessTokenCredential(h,s),h}async loadRefreshToken(e,t,r,n){if(!e.refresh_token)return this.logger.verbose("TokenCache - no refresh token found in response"),null;this.logger.verbose("TokenCache - loading refresh token");const o=kr(t,r,e.refresh_token,this.config.auth.clientId,e.foci,void 0,e.refresh_token_expires_in);return await this.storage.setRefreshTokenCredential(o,n),o}generateAuthenticationResult(e,t,r,n){let o,i="",s=[],a=null;t?.accessToken&&(i=t.accessToken.secret,s=hn.fromString(t.accessToken.target).asArray(),a=new Date(1e3*Number(t.accessToken.expiresOn)),o=new Date(1e3*Number(t.accessToken.extendedExpiresOn)));const c=t.account;return{authority:n?n.canonicalAuthority:"",uniqueId:t.account.localAccountId,tenantId:t.account.realm,scopes:s,account:c.getAccountInfo(),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 cl extends _c{constructor(e){super(e),this.includeRedirectUri=!1}}class ll extends xc{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 ks(ls);const t=await Na(this.initializeAuthorizationRequest.bind(this),Mo,this.logger,this.performanceClient,e.correlationId)(e,et.Silent),r=this.initializeServerTelemetryManager(this.apiId);try{const n={...t,code:e.code},o=await Na(this.getClientConfiguration.bind(this),No,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:r,requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account}),i=new cl(o);this.logger.verbose("Auth code client created");const s=new Wc(i,this.browserStorage,n,this.logger,this.performanceClient);return await Na(s.handleCodeResponseFromServer.bind(s),Lo,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 It&&(e.setCorrelationId(this.correlationId),r.cacheFailedRequest(e)),e}}logout(){return Promise.reject(ks(Qi))}}function hl(e){const t=e?.idTokenClaims;return t?.tfp||t?.acr?"B2C":t?.tid?"9188040d-6c67-4c5b-b112-36a304b66dad"===t?.tid?"MSA":"AAD":void 0}function dl(e,t){try{ga(e)}catch(e){throw t.end({success:!1},e),e}}class ul{constructor(e){var t,r,n;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 Ra(this.logger,this.performanceClient):fr,this.eventHandler=new sc(this.logger),this.browserStorage=this.isBrowserEnvironment?new nc(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,this.performanceClient,function(e){const t=e.cloudDiscoveryMetadata;let r;if(t)try{r=JSON.parse(t)}catch(e){throw cn(Vr)}return{canonicalAuthority:e.authority?Ua(e.authority):void 0,knownAuthorities:e.knownAuthorities,cloudDiscoveryMetadata:r}}(this.config.auth)):(t=this.config.auth.clientId,r=this.logger,n=this.performanceClient,new nc(t,{cacheLocation:Re,temporaryCacheLocation:Re,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!1,claimsBasedCachingEnabled:!1},fr,r,n));const o={cacheLocation:Re,temporaryCacheLocation:Re,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!1,claimsBasedCachingEnabled:!1};this.nativeInternalStorage=new nc(this.config.auth.clientId,o,this.browserCrypto,this.logger,this.performanceClient),this.tokenCache=new al(this.config,this.browserStorage,this.logger,this.browserCrypto),this.activeSilentTokenRequests=new Map,this.trackPageVisibility=this.trackPageVisibility.bind(this),this.trackPageVisibilityWithMeasurement=this.trackPageVisibilityWithMeasurement.bind(this),this.listeningToStorageEvents=!1,this.handleAccountCacheChange=this.handleAccountCacheChange.bind(this)}static async createController(e,t){const r=new ul(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){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(ic.INITIALIZE_END);const t=e?.correlationId||this.getRequestCorrelationId(),r=this.config.system.allowPlatformBroker,n=this.performanceClient.startMeasurement(bo,t);if(this.eventHandler.emitEvent(ic.INITIALIZE_START),await Na(this.browserStorage.initialize.bind(this.browserStorage),So,this.logger,this.performanceClient,t)(t),r)try{this.nativeExtensionProvider=await Qc.createProvider(this.logger,this.config.system.nativeBrokerHandshakeTimeout,this.performanceClient)}catch(e){this.logger.verbose(e)}this.config.cache.claimsBasedCachingEnabled||(this.logger.verbose("Claims-based caching is disabled. Clearing the previous cache with claims"),await Na(this.browserStorage.clearTokensAndKeysWithClaims.bind(this.browserStorage),ci,this.logger,this.performanceClient,t)(this.performanceClient,t)),this.initialized=!0,this.eventHandler.emitEvent(ic.INITIALIZE_END),n.end({allowPlatformBroker:r,success:!0})}async handleRedirectPromise(e){if(this.logger.verbose("handleRedirectPromise called"),ua(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){const t=this.getAllAccounts(),r=this.browserStorage.getCachedNativeRequest(),n=r&&Qc.isPlatformBrokerAvailable(this.config,this.logger,this.nativeExtensionProvider)&&this.nativeExtensionProvider&&!e,o=n?r?.correlationId:this.browserStorage.getTemporaryCache(Be,!0)||"",i=this.performanceClient.startMeasurement(Xn,o);let s;if(this.eventHandler.emitEvent(ic.HANDLE_REDIRECT_START,et.Redirect),n&&this.nativeExtensionProvider){this.logger.trace("handleRedirectPromise - acquiring token from native platform");const e=new Gc(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Ve,this.performanceClient,this.nativeExtensionProvider,r.accountId,this.nativeInternalStorage,r.correlationId);s=Na(e.handleRedirectPromise.bind(e),ii,this.logger,this.performanceClient,i.event.correlationId)(this.performanceClient,i.event.correlationId)}else{this.logger.trace("handleRedirectPromise - acquiring token from web flow");const t=this.createRedirectClient(o);s=Na(t.handleRedirectPromise.bind(t),oi,this.logger,this.performanceClient,i.event.correlationId)(e,i)}return s.then(e=>{if(e){t.length<this.getAllAccounts().length?(this.eventHandler.emitEvent(ic.LOGIN_SUCCESS,et.Redirect,e),this.logger.verbose("handleRedirectResponse returned result, login success")):(this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_SUCCESS,et.Redirect,e),this.logger.verbose("handleRedirectResponse returned result, acquire token success")),i.end({success:!0,accountType:hl(e.account)})}else i.event.errorCode?i.end({success:!1}):i.discard();return this.eventHandler.emitEvent(ic.HANDLE_REDIRECT_END,et.Redirect),e}).catch(e=>{const r=e;throw t.length>0?this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_FAILURE,et.Redirect,null,r):this.eventHandler.emitEvent(ic.LOGIN_FAILURE,et.Redirect,null,r),this.eventHandler.emitEvent(ic.HANDLE_REDIRECT_END,et.Redirect),i.end({success:!1},r),e})}async acquireTokenRedirect(e){const t=this.getRequestCorrelationId(e);this.logger.verbose("acquireTokenRedirect called",t);const r=this.performanceClient.startMeasurement(Yn,t);r.add({accountType:hl(e.account),scenarioId:e.scenarioId});const n=e.onRedirectNavigate;if(n)e.onRedirectNavigate=e=>{const t="function"==typeof n?n(e):void 0;return!1!==t?r.end({success:!0}):r.discard(),t};else{const e=this.config.auth.onRedirectNavigate;this.config.auth.onRedirectNavigate=t=>{const n="function"==typeof e?e(t):void 0;return!1!==n?r.end({success:!0}):r.discard(),n}}const o=this.getAllAccounts().length>0;try{let n;if(pa(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0),o?this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_START,et.Redirect,e):this.eventHandler.emitEvent(ic.LOGIN_START,et.Redirect,e),this.nativeExtensionProvider&&this.canUsePlatformBroker(e)){n=new Gc(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Ge,this.performanceClient,this.nativeExtensionProvider,this.getNativeAccountId(e),this.nativeInternalStorage,t).acquireTokenRedirect(e,r).catch(r=>{if(r instanceof Bc&&Fc(r)){this.nativeExtensionProvider=void 0;return this.createRedirectClient(t).acquireToken(e)}if(r instanceof ja){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 this.browserStorage.setInteractionInProgress(!1),r})}else{n=this.createRedirectClient(t).acquireToken(e)}return await n}catch(e){throw r.end({success:!1},e),o?this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_FAILURE,et.Redirect,null,e):this.eventHandler.emitEvent(ic.LOGIN_FAILURE,et.Redirect,null,e),e}}acquireTokenPopup(e){const t=this.getRequestCorrelationId(e),r=this.performanceClient.startMeasurement(Jn,t);r.add({scenarioId:e.scenarioId,accountType:hl(e.account)});try{this.logger.verbose("acquireTokenPopup called",t),dl(this.initialized,r),this.browserStorage.setInteractionInProgress(!0)}catch(e){return Promise.reject(e)}const n=this.getAllAccounts();let o;if(n.length>0?this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_START,et.Popup,e):this.eventHandler.emitEvent(ic.LOGIN_START,et.Popup,e),this.canUsePlatformBroker(e))o=this.acquireTokenNative({...e,correlationId:t},Qe).then(e=>(this.browserStorage.setInteractionInProgress(!1),r.end({success:!0,isNativeBroker:!0,accountType:hl(e.account)}),e)).catch(r=>{if(r instanceof Bc&&Fc(r)){this.nativeExtensionProvider=void 0;return this.createPopupClient(t).acquireToken(e)}if(r instanceof ja){this.logger.verbose("acquireTokenPopup - Resolving interaction required error thrown by native broker by falling back to web flow");return this.createPopupClient(t).acquireToken(e)}throw this.browserStorage.setInteractionInProgress(!1),r});else{o=this.createPopupClient(t).acquireToken(e)}return o.then(e=>(n.length<this.getAllAccounts().length?this.eventHandler.emitEvent(ic.LOGIN_SUCCESS,et.Popup,e):this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_SUCCESS,et.Popup,e),r.end({success:!0,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length,accountType:hl(e.account)}),e)).catch(e=>(n.length>0?this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_FAILURE,et.Popup,null,e):this.eventHandler.emitEvent(ic.LOGIN_FAILURE,et.Popup,null,e),r.end({success:!1},e),Promise.reject(e)))}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(io,t),this.ssoSilentMeasurement?.add({scenarioId:e.scenarioId,accountType:hl(e.account)}),dl(this.initialized,this.ssoSilentMeasurement),this.ssoSilentMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement),this.logger.verbose("ssoSilent called",t),this.eventHandler.emitEvent(ic.SSO_SILENT_START,et.Silent,r),this.canUsePlatformBroker(r))n=this.acquireTokenNative(r,We).catch(e=>{if(e instanceof Bc&&Fc(e)){this.nativeExtensionProvider=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(ic.SSO_SILENT_SUCCESS,et.Silent,e),this.ssoSilentMeasurement?.end({success:!0,isNativeBroker:e.fromNativeBroker,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length,accountType:hl(e.account)}),e)).catch(e=>{throw this.eventHandler.emitEvent(ic.SSO_SILENT_FAILURE,et.Silent,null,e),this.ssoSilentMeasurement?.end({success:!1},e),e}).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(Gn,t);dl(this.initialized,r),this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_BY_CODE_START,et.Silent,e),r.add({scenarioId:e.scenarioId});try{if(e.code&&e.nativeAccountId)throw ks(ds);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.ACQUIRE_TOKEN_BY_CODE_SUCCESS,et.Silent,e),this.hybridAuthCodeResponses.delete(n),r.end({success:!0,isNativeBroker:e.fromNativeBroker,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length,accountType:hl(e.account)}),e)).catch(e=>{throw this.hybridAuthCodeResponses.delete(n),this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_BY_CODE_FAILURE,et.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)){const n=await this.acquireTokenNative({...e,correlationId:t},Je,e.nativeAccountId).catch(e=>{throw e instanceof Bc&&Fc(e)&&(this.nativeExtensionProvider=void 0),e});return r.end({accountType:hl(n.account),success:!0}),n}throw ks(gs)}throw ks(hs)}catch(e){throw this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_BY_CODE_FAILURE,et.Silent,null,e),r.end({success:!1},e),e}}async acquireTokenByCodeAsync(e){this.logger.trace("acquireTokenByCodeAsync called",e.correlationId),this.acquireTokenByCodeAsyncMeasurement=this.performanceClient.startMeasurement(ni,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,isNativeBroker:e.fromNativeBroker}),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(Co,e.correlationId),t){case st:case at:case ct:const t=this.createSilentCacheClient(e.correlationId);return Na(t.acquireToken.bind(t),to,this.logger,this.performanceClient,e.correlationId)(e);default:throw mr(tr)}}async acquireTokenByRefreshToken(e,t){switch(this.performanceClient.addQueueMeasurement(Qn,e.correlationId),t){case st:case ct:case lt:case ht:const t=this.createSilentRefreshClient(e.correlationId);return Na(t.acquireToken.bind(t),oo,this.logger,this.performanceClient,e.correlationId)(e);default:throw mr(tr)}}async acquireTokenBySilentIframe(e){this.performanceClient.addQueueMeasurement(Io,e.correlationId);const t=this.createSilentIframeClient(e.correlationId);return Na(t.acquireToken.bind(t),ro,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);pa(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0);return this.createRedirectClient(t).logout(e)}logoutPopup(e){try{const t=this.getRequestCorrelationId(e);ga(this.initialized),this.browserStorage.setInteractionInProgress(!0);return this.createPopupClient(t).logout(e)}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){return function(e,t,r,n){return e.verbose("getAllAccounts called"),r?t.getAllAccounts(n):[]}(this.logger,this.browserStorage,this.isBrowserEnvironment,e)}getAccount(e){return function(e,t,r){if(t.trace("getAccount called"),0===Object.keys(e).length)return t.warning("getAccount: No accountFilter provided"),null;const n=r.getAccountInfoFilteredBy(e);return n?(t.verbose("getAccount: Account matching provided filter found, returning"),n):(t.verbose("getAccount: No matching account found, returning null"),null)}(e,this.logger,this.browserStorage)}getAccountByUsername(e){return function(e,t,r){if(t.trace("getAccountByUsername called"),!e)return t.warning("getAccountByUsername: No username provided"),null;const n=r.getAccountInfoFilteredBy({username:e});return n?(t.verbose("getAccountByUsername: Account matching username found, returning"),t.verbosePii(`getAccountByUsername: Returning signed-in accounts matching username: ${e}`),n):(t.verbose("getAccountByUsername: No matching account found, returning null"),null)}(e,this.logger,this.browserStorage)}getAccountByHomeId(e){return function(e,t,r){if(t.trace("getAccountByHomeId called"),!e)return t.warning("getAccountByHomeId: No homeAccountId provided"),null;const n=r.getAccountInfoFilteredBy({homeAccountId:e});return n?(t.verbose("getAccountByHomeId: Account matching homeAccountId found, returning"),t.verbosePii(`getAccountByHomeId: Returning signed-in accounts matching homeAccountId: ${e}`),n):(t.verbose("getAccountByHomeId: No matching account found, returning null"),null)}(e,this.logger,this.browserStorage)}getAccountByLocalId(e){return function(e,t,r){if(t.trace("getAccountByLocalId called"),!e)return t.warning("getAccountByLocalId: No localAccountId provided"),null;const n=r.getAccountInfoFilteredBy({localAccountId:e});return n?(t.verbose("getAccountByLocalId: Account matching localAccountId found, returning"),t.verbosePii(`getAccountByLocalId: Returning signed-in accounts matching localAccountId: ${e}`),n):(t.verbose("getAccountByLocalId: No matching account found, returning null"),null)}(e,this.logger,this.browserStorage)}setActiveAccount(e){!function(e,t){t.setActiveAccount(e)}(e,this.browserStorage)}getActiveAccount(){return this.browserStorage.getActiveAccount()}async hydrateCache(e,t){this.logger.verbose("hydrateCache called");const r=In.createFromAccountInfo(e.account,e.cloudGraphHostName,e.msGraphHost);return await this.browserStorage.setAccount(r,e.correlationId),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){if(this.logger.trace("acquireTokenNative called"),!this.nativeExtensionProvider)throw ks(fs);return new Gc(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,t,this.performanceClient,this.nativeExtensionProvider,r||this.getNativeAccountId(e),this.nativeInternalStorage,e.correlationId).acquireToken(e)}canUsePlatformBroker(e,t){if(this.logger.trace("canUsePlatformBroker called"),!Qc.isPlatformBrokerAvailable(this.config,this.logger,this.nativeExtensionProvider,e.authenticationScheme))return this.logger.trace("canUsePlatformBroker: isPlatformBrokerAvailable returned false, returning false"),!1;if(e.prompt)switch(e.prompt){case b.NONE:case b.CONSENT:case b.LOGIN: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 Jc(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,this.nativeExtensionProvider,e)}createRedirectClient(e){return new Xc(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,this.nativeExtensionProvider,e)}createSilentIframeClient(e){return new il(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,We,this.performanceClient,this.nativeInternalStorage,this.nativeExtensionProvider,e)}createSilentCacheClient(e){return new $c(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeExtensionProvider,e)}createSilentRefreshClient(e){return new sl(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeExtensionProvider,e)}createSilentAuthCodeClient(e){return new ll(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Je,this.performanceClient,this.nativeExtensionProvider,e)}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){return da(),this.performanceClient.addPerformanceCallback(e)}removePerformanceCallback(e){return this.performanceClient.removePerformanceCallback(e)}enableAccountStorageEvents(){"undefined"!=typeof window&&(this.listeningToStorageEvents?this.logger.verbose("Account storage listener already registered."):(this.logger.verbose("Adding account storage listener."),this.listeningToStorageEvents=!0,window.addEventListener("storage",this.handleAccountCacheChange)))}disableAccountStorageEvents(){"undefined"!=typeof window&&(this.listeningToStorageEvents?(this.logger.verbose("Removing account storage listener."),window.removeEventListener("storage",this.handleAccountCacheChange),this.listeningToStorageEvents=!1):this.logger.verbose("No account storage listener registered."))}handleAccountCacheChange(e){try{e.key?.includes(C)&&this.eventHandler.emitEvent(ic.ACTIVE_ACCOUNT_CHANGED);const t=e.newValue||e.oldValue;if(!t)return;const r=JSON.parse(t);if("object"!=typeof r||!In.isAccountEntity(r))return;const n=qn.toObject(new In,r).getAccountInfo();!e.oldValue&&e.newValue?(this.logger.info("Account was added to cache in a different window"),this.eventHandler.emitEvent(ic.ACCOUNT_ADDED,void 0,n)):!e.newValue&&e.oldValue&&(this.logger.info("Account was removed from cache in a different window"),this.eventHandler.emitEvent(ic.ACCOUNT_REMOVED,void 0,n))}catch(e){return}}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():i.EMPTY_STRING}async loginRedirect(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("loginRedirect called",t),this.acquireTokenRedirect({correlationId:t,...e||rt})}loginPopup(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("loginPopup called",t),this.acquireTokenPopup({correlationId:t,...e||rt})}async acquireTokenSilent(e){const t=this.getRequestCorrelationId(e),r=this.performanceClient.startMeasurement(Wn,t);r.add({cacheLookupPolicy:e.cacheLookupPolicy,scenarioId:e.scenarioId}),dl(this.initialized,r),this.logger.verbose("acquireTokenSilent called",t);const n=e.account||this.getActiveAccount();if(!n)throw ks(Wi);r.add({accountType:hl(n)});const o={clientId:this.config.auth.clientId,authority:e.authority||i.EMPTY_STRING,scopes:e.scopes,homeAccountIdentifier:n.homeAccountId,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid,shrOptions:e.shrOptions},s=JSON.stringify(o),a=this.activeSilentTokenRequests.get(s);if(void 0===a){this.logger.verbose("acquireTokenSilent called for the first time, storing active request",t);const o=Na(this.acquireTokenSilentAsync.bind(this),Vn,this.logger,this.performanceClient,t)({...e,correlationId:t},n).then(t=>(this.activeSilentTokenRequests.delete(s),r.end({success:!0,fromCache:t.fromCache,isNativeBroker:t.fromNativeBroker,cacheLookupPolicy:e.cacheLookupPolicy,accessTokenSize:t.accessToken.length,idTokenSize:t.idToken.length}),t)).catch(e=>{throw this.activeSilentTokenRequests.delete(s),r.end({success:!1},e),e});return this.activeSilentTokenRequests.set(s,o),{...await o,state:e.state}}return this.logger.verbose("acquireTokenSilent has been called previously, returning the result from the first call",t),r.discard(),{...await a,state:e.state}}async acquireTokenSilentAsync(e,t){const r=()=>this.trackPageVisibility(e.correlationId);this.performanceClient.addQueueMeasurement(Vn,e.correlationId),this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_START,et.Silent,e),e.correlationId&&this.performanceClient.incrementFields({visibilityChangeCount:0},e.correlationId),document.addEventListener("visibilitychange",r);const n=await Na(Lc,Ao,this.logger,this.performanceClient,e.correlationId)(e,t,this.config,this.performanceClient,this.logger),o=e.cacheLookupPolicy||st;return this.acquireTokenSilentNoIframe(n,o).catch(async e=>
2{const t=function(e,t){const r=!(e instanceof ja&&e.subError!==Da),n=e.errorCode===pe||e.errorCode===tr,o=r&&n||e.errorCode===La||e.errorCode===Ha,i=ut.includes(t);return o&&i}(e,o);if(t){if(this.activeIframeRequest){if(o!==dt){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(no,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),Na(this.acquireTokenBySilentIframe.bind(this),Io,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),Na(this.acquireTokenBySilentIframe.bind(this),Io,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(ic.ACQUIRE_TOKEN_SUCCESS,et.Silent,t),e.correlationId&&this.performanceClient.addFields({fromCache:t.fromCache,isNativeBroker:t.fromNativeBroker},e.correlationId),t)).catch(e=>{throw this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_FAILURE,et.Silent,null,e),e}).finally(()=>{document.removeEventListener("visibilitychange",r)})}async acquireTokenSilentNoIframe(e,t){return Qc.isPlatformBrokerAvailable(this.config,this.logger,this.nativeExtensionProvider,e.authenticationScheme)&&e.account.nativeAccountId?(this.logger.verbose("acquireTokenSilent - attempting to acquire token from native platform"),this.acquireTokenNative(e,Ye).catch(async e=>{if(e instanceof Bc&&Fc(e))throw this.logger.verbose("acquireTokenSilent - native platform unavailable, falling back to web flow"),this.nativeExtensionProvider=void 0,mr(tr);throw e})):(this.logger.verbose("acquireTokenSilent - attempting to acquire token from web flow"),Na(this.acquireTokenFromCache.bind(this),Co,this.logger,this.performanceClient,e.correlationId)(e,t).catch(r=>{if(t===at)throw r;return this.eventHandler.emitEvent(ic.ACQUIRE_TOKEN_NETWORK_START,et.Silent,e),Na(this.acquireTokenByRefreshToken.bind(this),Qn,this.logger,this.performanceClient,e.correlationId)(e,t)}))}}class gl{static async createPublicClientApplication(e){const t=await async function(e,t){const r=new wa(e);return await r.initialize(),ul.createController(r,t)}(e);return new gl(e,t)}constructor(e,t){this.controller=t||new ul(new wa(e))}async initialize(e){return this.controller.initialize(e)}async acquireTokenPopup(e){return this.controller.acquireTokenPopup(e)}acquireTokenRedirect(e){return this.controller.acquireTokenRedirect(e)}acquireTokenSilent(e){return this.controller.acquireTokenSilent(e)}acquireTokenByCode(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)}}var pl=window.navigator.userAgent,ml=pl.indexOf("MSIE "),fl=pl.indexOf("Trident/"),yl=pl.indexOf("Edge/"),Cl=pl.indexOf("Firefox"),wl=ml>0||fl>0,vl=yl>0,Il=Cl>0;function Tl(e){var t="https://".concat(e.domain,"/").concat(e.domain);return{authorities:{signUpSignIn:{authority:"".concat(t,"/B2C_1A_SIGNUP_SIGNIN")},signUp:{authority:"".concat(t,"/B2C_1A_SIGNUP")},changeSignInName:{authority:"".concat(t,"/B2C_1A_SIGNINNAMECHANGE")},changeName:{authority:"".concat(t,"/B2C_1A_NAMECHANGE")},passwordChange:{authority:"".concat(t,"/B2C_1A_PASSWORDCHANGE")},deleteAccount:{authority:"".concat(t,"/B2C_1A_DELETEACCOUNT")}},authorityDomain:e.domain}}var Al=Sl();function bl(e){var t,r,n="undefined"!=typeof window&&window.location&&window.location.href?window.location.href:void 0,o=null!==(r=null!==(t=null!=e?e:n)&&void 0!==t?t:Al.myAceUrl)&&void 0!==r?r:"";return{authority:Tl(Al).authorities.signUpSignIn.authority,scopes:[Al.scopes],state:o}}function Sl(){var e=document.getElementById("authConfig");if(e){var t=e.textContent;if(t)return JSON.parse(t);throw new Error("Auth config is empty")}throw new Error("Auth config not found")}var kl,El,_l=new gl((kl=Sl(),El=Tl(kl),{auth:{clientId:kl.clientId,authority:El.authorities.signUpSignIn.authority,knownAuthorities:[El.authorityDomain],redirectUri:kl.redirectUrl,postLogoutRedirectUri:kl.postLogoutRedirectUrl},cache:{cacheLocation:_e,storeAuthStateInCookie:wl||vl||Il},system:{allowNativeBroker:!1,loggerOptions:{loggerCallback:function(e,t,r){if(!r)switch(e){case gt.Error:return void console.error(t);case gt.Info:case gt.Verbose:case gt.Warning:default:return}}}}}));_l.initialize().then(function(){!_l.getActiveAccount()&&_l.getAllAccounts().length>0&&_l.setActiveAccount(_l.getAllAccounts()[0]),_l.handleRedirectPromise().then(function(e){var t;e&&e.state&&e.state!==window.location.href&&(window.location.href=(null===(t=window.AppSelector)||void 0===t?void 0:t.addAppSelector(e.state))||e.state)}).catch(function(e){console.error("Redirect error",e)})});var Rl=r(4333);const Pl={instance:{initialize:()=>Promise.reject(aa(na)),acquireTokenPopup:()=>Promise.reject(aa(na)),acquireTokenRedirect:()=>Promise.reject(aa(na)),acquireTokenSilent:()=>Promise.reject(aa(na)),acquireTokenByCode:()=>Promise.reject(aa(na)),getAllAccounts:()=>[],getAccount:()=>null,getAccountByHomeId:()=>null,getAccountByUsername:()=>null,getAccountByLocalId:()=>null,handleRedirectPromise:()=>Promise.reject(aa(na)),loginPopup:()=>Promise.reject(aa(na)),loginRedirect:()=>Promise.reject(aa(na)),logout:()=>Promise.reject(aa(na)),logoutRedirect:()=>Promise.reject(aa(na)),logoutPopup:()=>Promise.reject(aa(na)),ssoSilent:()=>Promise.reject(aa(na)),addEventCallback:()=>null,removeEventCallback:()=>{},addPerformanceCallback:()=>"",removePerformanceCallback:()=>!1,enableAccountStorageEvents:()=>{},disableAccountStorageEvents:()=>{},getTokenCache:()=>{throw aa(na)},getLogger:()=>{throw aa(na)}
2,setLogger:()=>{},setActiveAccount:()=>{},getActiveAccount:()=>null,initializeWrapperLibrary:()=>{},setNavigationClient:()=>{},getConfiguration:()=>{throw aa(na)},hydrateCache:()=>Promise.reject(aa(na)),clearCache:()=>Promise.reject(aa(na))},inProgress:tt.None,accounts:[],logger:new pt({})},Ol=o.createContext(Pl);Ol.Consumer;class Nl{static getInteractionStatusFromEvent(e,t){switch(e.eventType){case ic.LOGIN_START:return tt.Login;case ic.SSO_SILENT_START:return tt.SsoSilent;case ic.ACQUIRE_TOKEN_START:if(e.interactionType===et.Redirect||e.interactionType===et.Popup)return tt.AcquireToken;break;case ic.HANDLE_REDIRECT_START:return tt.HandleRedirect;case ic.LOGOUT_START:return tt.Logout;case ic.SSO_SILENT_SUCCESS:case ic.SSO_SILENT_FAILURE:if(t&&t!==tt.SsoSilent)break;return tt.None;case ic.LOGOUT_END:if(t&&t!==tt.Logout)break;return tt.None;case ic.HANDLE_REDIRECT_END:if(t&&t!==tt.HandleRedirect)break;return tt.None;case ic.LOGIN_SUCCESS:case ic.LOGIN_FAILURE:case ic.ACQUIRE_TOKEN_SUCCESS:case ic.ACQUIRE_TOKEN_FAILURE:case ic.RESTORE_FROM_BFCACHE:if(e.interactionType===et.Redirect||e.interactionType===et.Popup){if(t&&t!==tt.Login&&t!==tt.AcquireToken)break;return tt.None}}return null}}function Ml(e,t){if(e.length!==t.length)return!1;const r=[...t];return e.every(e=>{const t=r.shift();return!(!e||!t)&&(e.homeAccountId===t.homeAccountId&&e.localAccountId===t.localAccountId&&e.username===t.username)})}const ql="@azure/msal-react",Ul="3.0.2",Ll={UNBLOCK_INPROGRESS:"UNBLOCK_INPROGRESS",EVENT:"EVENT"},xl=(e,t)=>{const{type:r,payload:n}=t;let o=e.inProgress;switch(r){case Ll.UNBLOCK_INPROGRESS:e.inProgress===tt.Startup&&(o=tt.None,n.logger.info("MsalProvider - handleRedirectPromise resolved, setting inProgress to 'none'"));break;case Ll.EVENT:const t=n.message,i=Nl.getInteractionStatusFromEvent(t,e.inProgress);i&&(n.logger.info(`MsalProvider - ${t.eventType} results in setting inProgress from ${e.inProgress} to ${i}`),o=i);break;default:throw new Error(`Unknown action type: ${r}`)}const i=n.instance.getAllAccounts();return o===e.inProgress||Ml(i,e.accounts)?o!==e.inProgress?{...e,inProgress:o}:Ml(i,e.accounts)?e:{...e,accounts:i}:{...e,inProgress:o,accounts:i}};function Hl({instance:e,children:t}){(0,o.useEffect)(()=>{e.initializeWrapperLibrary(nt.React,Ul)},[e]);const r=(0,o.useMemo)(()=>e.getLogger().clone(ql,Ul),[e]),[n,i]=(0,o.useReducer)(xl,void 0,()=>({inProgress:tt.Startup,accounts:e.getAllAccounts()}));(0,o.useEffect)(()=>{const t=e.addEventCallback(t=>{i({payload:{instance:e,logger:r,message:t},type:Ll.EVENT})});return r.verbose(`MsalProvider - Registered event callback with id: ${t}`),e.initialize().then(()=>{e.handleRedirectPromise().catch(()=>{}).finally(()=>{i({payload:{instance:e,logger:r},type:Ll.UNBLOCK_INPROGRESS})})}).catch(()=>{}),()=>{t&&(r.verbose(`MsalProvider - Removing event callback ${t}`),e.removeEventCallback(t))}},[e,r]);const s={instance:e,inProgress:n.inProgress,accounts:n.accounts,logger:r};return o.createElement(Ol.Provider,{value:s},t)}var Dl=function(){return Dl=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},Dl.apply(this,arguments)},Bl=function(e,t,r,n){return new(r||(r=Promise))(function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},Fl=function(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}};function Kl(e){var t=this,r=e.children,i=(0,o.useState)(null),s=i[0],a=i[1],c=(0,o.useState)(!1),l=c[0],h=c[1],d=function(){var e,t,r,n,o=_l.getAllAccounts();if(o.length>0){var i=o[0];_l.setActiveAccount(i);var s=(null===(e=null==i?void 0:i.idTokenClaims)||void 0===e?void 0:e.given_name)||"",c=(null===(t=null==i?void 0:i.idTokenClaims)||void 0===t?void 0:t.family_name)||"",l=(null===(r=null==i?void 0:i.idTokenClaims)||void 0===r?void 0:r.memberNumber)||"",d=(null===(n=null==i?void 0:i.idTokenClaims)||void 0===n?void 0:n.email)||"",u=i?{name:"".concat(s," ").concat(c).trim(),memberNumber:"".concat(l).trim(),email:"".concat(d).trim(),isMember:!!l}:null;a(u),h(!!u)}else a(null),h(!1)};(0,o.useEffect)(function(){_l.enableAccountStorageEvents(),_l.initialize().then(function(){_l.getAllAccounts()[0]?d():_l.ssoSilent(bl()).then(function(){d()}).catch(function(e){d()})});var e=_l.addEventCallback(function(e){new Set([ic.LOGIN_SUCCESS,ic.ACQUIRE_TOKEN_SUCCESS,ic.LOGOUT_SUCCESS,ic.ACCOUNT_ADDED,ic.ACCOUNT_REMOVED,ic.ACTIVE_ACCOUNT_CHANGED]).has(e.eventType)&&d()});return function(){e&&_l.removeEventCallback(e),_l.disableAccountStorageEvents()}},[_l]);return(0,n.jsx)(Hl,Dl({instance:_l},{children:(0,n.jsx)(Rl.c.Provider,Dl({value:{isAuthenticated:l,login:function(e){return Bl(t,void 0,void 0,function(){var t;return Fl(this,function(r){switch(r.label){case 0:return r.trys.push([0,2,,3]),[4,_l.loginRedirect(bl(e))];case 1:return r.sent(),[3,3];case 2:return t=r.sent(),console.error(t),[3,3];case 3:return[2]}})})},logout:function(){return Bl(t,void 0,void 0,function(){var e;return Fl(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,_l.logoutRedirect()];case 1:return t.sent(),[3,3];case 2:return e=t.sent(),console.error("Logout failed",e),[3,3];case 3:return[2]}})})},register:function(){return Bl(t,void 0,void 0,function(){var e;return Fl(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,_l.loginRedirect({authority:Tl(Al).authorities.signUp.authority,scopes:[Al.scopes],state:window.location.href})];case 1:return t.sent(),[3,3];case 2:return e=t.sent(),console.error("Register failed",e),[3,3];case 3:return[2]}})})},userAccount:s,getAccessToken:function(){return Bl(t,void 0,void 0,function(){var e;return Fl(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,_l.acquireTokenSilent(Dl({account:_l.getActiveAccount()},bl()))];case 1:return[2,t.sent().accessToken];case 2:throw e=t.sent(),console.error("Failed to acquire access token",e),e;case 3:return[2]}})})},changeEmail:function(){return Bl(t,void 0,void 0,function(){var e;return Fl(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,_l.loginRedirect({authority:Tl(Al).authorities.changeSignInName.authority,scopes:[Al.scopes],state:window.location.href})];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.error("Change mail failed",e),[3,4];case 4:return[2]}})})},changeName:function(){return Bl(t,void 0,void 0,function(){var e;return Fl(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,_l.loginRedirect({authority:Tl(Al).authorities.changeName.authority,scopes:[Al.scopes],state:window.location.href})];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.error("Change name failed",e),[3,4];case 4:return[2]}})})},changePassword:function(){return Bl(t,void 0,void 0,function(){var e;return Fl(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,_l.loginRedirect({authority:Tl(Al).authorities.passwordChange.authority,scopes:[Al.scopes],state:window.location.href})];case 2:return t.sent(),[3,4];case 3:return e=t.sent(),console.error("Change password failed",e),[3,4];case 4:return[2]}})})},deleteAccount:function(){return Bl(t,void 0,void 0,function(){var e;return Fl(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,4,,5]),[4,_l.logoutRedirect({onRedirectNavigate:function(){return!1}})];case 2:return t.sent(),[4,_l.loginRedirect({authority:Tl(Al).authorities.deleteAccount.authority,scopes:[Al.scopes],state:window.location.href})];case 3:return t.sent(),[3,5];case 4:return e=t.sent(),console.error("Delete account failed",e),[3,5];case 5:return[2]}})})}}},{children:r}))}))}},9153:function(e,t,r){r.d(t,{A:function(){return i}});var n=r(6540),o=r(4333);function i(){return(0,n.useContext)(o.c)}},44:function(e,t,r){r.r(t),r.d(t,{default:function(){return f}});var n=r(4848),o=r(6540),i=r(5719),s=function(e,t,r,n){return new(r||(r=Promise))(function(o,i){function s(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},a=function(e,t){var r,n,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;
2function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){s.label=a[1];break}if(6===a[0]&&s.label<o[1]){s.label=o[1],o=a;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(a);break}o[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}},c={getProtectedHTML:function(e){return s(this,void 0,void 0,function(){var t;return a(this,function(r){switch(r.label){case 0:if(!e)throw new Error("protectedUrl is required");r.label=1;case 1:return r.trys.push([1,3,,4]),[4,(0,i.A)().get(e)];case 2:return[2,r.sent()];case 3:throw t=r.sent(),console.error("Error fetching data:",t),t;case 4:return[2]}})})}},l=r(9153),h=r(1921),d=r(2857),u=r(1583),g=r(8227),p=function(){return p=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},p.apply(this,arguments)},m=function(e){var t=(0,o.useState)(""),r=t[0],i=t[1],s=(0,o.useState)(null),a=s[0],u=s[1],m=(0,o.useState)(!1),f=m[0],y=m[1];if(!e.isAuthorInstance){var C=(0,l.A)(),w=C.isAuthenticated,v=C.userAccount&&C.userAccount.isMember;if((0,o.useEffect)(function(){if(w){y(!0);var t=atob(e.protectedUrl);c.getProtectedHTML(t).then(function(e){i(e),y(!1)}).catch(function(e){y(!1),u("Failed to load data from AEM."),console.error("Error fetching data from API:",e)})}},[w]),(0,o.useEffect)(function(){var e=r.match(/data-react-component="([^"]+)"/);if(e){var t=e[1];(0,g.CH)(t)}},[r]),f)return(0,n.jsx)("div",{children:"loading..."});if(a)return(0,n.jsxs)("div",p({style:{color:"red"}},{children:["Error: ",a]}));var I=function(){var t;window.location.href=(null===(t=window.AppSelector)||void 0===t?void 0:t.addAppSelector(e.memberPage))||e.memberPage};return w?v?(0,n.jsx)("div",{dangerouslySetInnerHTML:{__html:r}}):(0,n.jsx)("section",p({className:"content-switch"},{children:(0,n.jsxs)("article",p({className:"content-switch__card"},{children:[(0,n.jsxs)("div",p({className:"content-switch__content"},{children:[(0,n.jsx)("h4",{children:e.pendingMember.headline}),(0,n.jsx)("p",{dangerouslySetInnerHTML:{__html:e.pendingMember.infoText}}),(0,n.jsx)(d.$,{onClick:I,text:"Jetzt Mitglied werden",className:"button--primary button__anchor button__anchor--full-width--small",icon:h.I.NavArrowRight}),(0,n.jsxs)("div",p({className:"content-switch__content__pending-member"},{children:[(0,n.jsx)("p",p({className:"text__body-copy--small"},{children:"Bereits Mitglied?"})),(0,n.jsxs)("a",p({role:"button",className:"button button__anchor button__anchor--card button--xs text__body-copy--small",href:e.myACEPage,target:"_self"},{children:[(0,n.jsx)("span",{children:"Mitgliedschaft verknüpfen"}),(0,n.jsx)("i",{className:"iconoir-nav-arrow-right"})]}))]}))]})),e.pendingMember.image&&(0,n.jsx)("img",{className:"content-switch__image",alt:e.guest.image.alt,loading:"lazy",src:e.guest.image.url})]}))})):(0,n.jsx)("section",p({className:"content-switch"},{children:(0,n.jsxs)("article",p({className:"content-switch__card"},{children:[(0,n.jsxs)("div",p({className:"content-switch__content"},{children:[(0,n.jsx)("h4",{children:e.guest.headline}),(0,n.jsx)("p",{dangerouslySetInnerHTML:{__html:e.guest.infoText}}),(0,n.jsx)(d.$,{onClick:function(){return C.login()},text:"Jetzt einloggen",className:"button--primary button__anchor button__anchor--full-width--small",icon:h.I.NavArrowRight})]})),e.guest.image&&(0,n.jsx)("img",{className:"content-switch__image",alt:e.guest.image.alt,loading:"lazy",src:e.guest.image.url})]}))}))}};var f=function(e){return(0,n.jsx)(u.O,{children:(0,n.jsx)(m,p({},e))})}},1921:function(e,t,r){var n,o;r.d(t,{I:function(){return n},f:function(){return o}}
2),function(e){e.NavArrowLeft="nav-arrow-left",e.NavArrowRight="nav-arrow-right",e.FastArrowLeft="fast-arrow-left",e.FastArrowRight="fast-arrow-right",e.Plus="plus",e.Upload="upload",e.Prohibition="prohibition",e.XMark="xmark",e.MapPin="map-pin",e.Check="check",e.EditPencil="edit-pencil",e.Trash="trash",e.RefreshDouble="refresh-double"}(n||(n={})),function(e){e[e.Start=0]="Start",e[e.End=1]="End"}(o||(o={}))},2857:function(e,t,r){r.d(t,{$:function(){return s}});var n=r(4848),o=r(1921),i=function(){return i=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},i.apply(this,arguments)};function s(e){var t=e.text,r=e.onClick,s=e.type,a=void 0===s?"button":s,c=e.className,l=e.small,h=void 0!==l&&l,d=e.icon,u=e.iconPosition,g=void 0===u?o.f.End:u,p=e.disabled,m=e.ariaLabel;return(0,n.jsxs)("button",i({type:a,onClick:r,disabled:p,"aria-label":m,className:"button ".concat(h?"button--small":""," ").concat(c||"").trim()},{children:[d&&g===o.f.Start&&(0,n.jsx)("i",{className:"iconoir-".concat(d," button__icon--left")}),(0,n.jsx)("span",i({className:"button__label-wrapper ".concat(h?"button__label-wrapper--small":"")},{children:t})),d&&g===o.f.End&&(0,n.jsx)("i",{className:"iconoir-".concat(d," button__icon--right")})]}))}},1083:function(e,t,r){r.d(t,{A:function(){return wt}});var n={};function o(e,t){return function(){return e.apply(t,arguments)}}r.r(n),r.d(n,{hasBrowserEnv:function(){return de},hasStandardBrowserEnv:function(){return ge},hasStandardBrowserWebWorkerEnv:function(){return pe},navigator:function(){return ue},origin:function(){return me}});const{toString:i}=Object.prototype,{getPrototypeOf:s}=Object,{iterator:a,toStringTag:c}=Symbol,l=(h=Object.create(null),e=>{const t=i.call(e);return h[t]||(h[t]=t.slice(8,-1).toLowerCase())});var h;const d=e=>(e=e.toLowerCase(),t=>l(t)===e),u=e=>t=>typeof t===e,{isArray:g}=Array,p=u("undefined");function m(e){return null!==e&&!p(e)&&null!==e.constructor&&!p(e.constructor)&&C(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const f=d("ArrayBuffer");const y=u("string"),C=u("function"),w=u("number"),v=e=>null!==e&&"object"==typeof e,I=e=>{if("object"!==l(e))return!1;const t=s(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||c in e||a in e)},T=d("Date"),A=d("File"),b=d("Blob"),S=d("FileList"),k=d("URLSearchParams"),[E,_,R,P]=["ReadableStream","Request","Response","Headers"].map(d);function O(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,o;if("object"!=typeof e&&(e=[e]),g(e))for(n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else{if(m(e))return;const o=r?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let s;for(n=0;n<i;n++)s=o[n],t.call(null,e[s],s,e)}}function N(e,t){if(m(e))return null;t=t.toLowerCase();const r=Object.keys(e);let n,o=r.length;for(;o-- >0;)if(n=r[o],t===n.toLowerCase())return n;return null}const M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:r.g,q=e=>!p(e)&&e!==M;const U=(L="undefined"!=typeof Uint8Array&&s(Uint8Array),e=>L&&e instanceof L);var L;const x=d("HTMLFormElement"),H=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),D=d("RegExp"),B=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};O(r,(r,o)=>{let i;!1!==(i=t(r,o,e))&&(n[o]=i||r)}),Object.defineProperties(e,n)};const F=d("AsyncFunction"),K=(j="function"==typeof setImmediate,z=C(M.postMessage),j?setImmediate:z?($=`axios@${Math.random()}`,G=[],M.addEventListener("message",({source:e,data:t})=>{e===M&&t===$&&G.length&&G.shift()()},!1),e=>{G.push(e),M.postMessage($,"*")}):e=>setTimeout(e));var j,z,$,G;const Q="undefined"!=typeof queueMicrotask?queueMicrotask.bind(M):"undefined"!=typeof process&&process.nextTick||K;var W={isArray:g,isArrayBuffer:f,isBuffer:m,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||C(e.append)&&("formdata"===(t=l(e))||"object"===t&&C(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&f(e.buffer),t},isString:y,isNumber:w,isBoolean:e=>!0===e||!1===e,isObject:v,isPlainObject:I,isEmptyObject:e=>{if(!v(e)||m(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:E,isRequest:_,isResponse:R,isHeaders:P,isUndefined:p,isDate:T,isFile:A,isBlob:b,isRegExp:D,isFunction:C,isStream:e=>v(e)&&C(e.pipe),isURLSearchParams:k,isTypedArray:U,isFileList:S,forEach:O,merge:function e(){const{caseless:t,skipUndefined:r}=q(this)&&this||{},n={},o=(o,i)=>{const s=t&&N(n,i)||i;I(n[s])&&I(o)?n[s]=e(n[s],o):I(o)?n[s]=e({},o):g(o)?n[s]=o.slice():r&&p(o)||(n[s]=o)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&O(arguments[e],o);return n},extend:(e,t,r,{allOwnKeys:n}={})=>(O(t,(t,n)=>{r&&C(t)?Object.defineProperty(e,n,{value:o(t,r),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,
vendor: 4,096 bytes, line 2
2configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let o,i,a;const c={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)a=o[i],n&&!n(a,e,t)||c[a]||(t[a]=e[a],c[a]=!0);e=!1!==r&&s(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:l,kindOfTest:d,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(g(e))return e;let t=e.length;if(!w(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[a]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:x,hasOwnProperty:H,hasOwnProp:H,reduceDescriptors:B,freezeMethods:e=>{B(e,(t,r)=>{if(C(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];C(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach(e=>{r[e]=!0})};return g(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:N,global:M,isContextDefined:q,isSpecCompliantForm:function(e){return!!(e&&C(e.append)&&"FormData"===e[c]&&e[a])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(v(e)){if(t.indexOf(e)>=0)return;if(m(e))return e;if(!("toJSON"in e)){t[n]=e;const o=g(e)?[]:{};return O(e,(e,t)=>{const i=r(e,n+1);!p(i)&&(o[t]=i)}),t[n]=void 0,o}}return e};return r(e,0)},isAsyncFn:F,isThenable:e=>e&&(v(e)||C(e))&&C(e.then)&&C(e.catch),setImmediate:K,asap:Q,isIterable:e=>null!=e&&C(e[a])};class V extends Error{static from(e,t,r,n,o,i){const s=new V(e.message,t||e.code,r,n,o);return s.cause=e,s.name=e.name,i&&Object.assign(s,i),s}constructor(e,t,r,n,o){super(e),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o,this.status=o.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:W.toJSONObject(this.config),code:this.code,status:this.status}}}V.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",V.ERR_BAD_OPTION="ERR_BAD_OPTION",V.ECONNABORTED="ECONNABORTED",V.ETIMEDOUT="ETIMEDOUT",V.ERR_NETWORK="ERR_NETWORK",V.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",V.ERR_DEPRECATED="ERR_DEPRECATED",V.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",V.ERR_BAD_REQUEST="ERR_BAD_REQUEST",V.ERR_CANCELED="ERR_CANCELED",V.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",V.ERR_INVALID_URL="ERR_INVALID_URL";var J=V;function Y(e){return W.isPlainObject(e)||W.isArray(e)}function X(e){return W.endsWith(e,"[]")?e.slice(0,-2):e}function Z(e,t,r){return e?e.concat(t).map(function(e,t){return e=X(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const ee=W.toFlatObject(W,{},null,function(e){return/^is[A-Z]/.test(e)});var te=function(e,t,r){if(!W.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=W.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!W.isUndefined(t[e])})).metaTokens,o=r.visitor||l,i=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&W.isSpecCompliantForm(t);if(!W.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(W.isDate(e))return e.toISOString();if(W.isBoolean(e))return e.toString();if(!a&&W.isBlob(e))throw new J("Blob is not supported. Use a Buffer instead.");return W.isArrayBuffer(e)||W.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,o){let a=e;if(e&&!o&&"object"==typeof e)if(W.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(W.isArray(e)&&function(e){return W.isArray(e)&&!e.some(Y)}
2(e)||(W.isFileList(e)||W.endsWith(r,"[]"))&&(a=W.toArray(e)))return r=X(r),a.forEach(function(e,n){!W.isUndefined(e)&&null!==e&&t.append(!0===s?Z([r],n,i):null===s?r:r+"[]",c(e))}),!1;return!!Y(e)||(t.append(Z(o,r,i),c(e)),!1)}const h=[],d=Object.assign(ee,{defaultVisitor:l,convertValue:c,isVisitable:Y});if(!W.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!W.isUndefined(r)){if(-1!==h.indexOf(r))throw Error("Circular reference detected in "+n.join("."));h.push(r),W.forEach(r,function(r,i){!0===(!(W.isUndefined(r)||null===r)&&o.call(t,r,W.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])}),h.pop()}}(e),t};function re(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function ne(e,t){this._pairs=[],e&&te(e,this,t)}const oe=ne.prototype;oe.append=function(e,t){this._pairs.push([e,t])},oe.toString=function(e){const t=e?function(t){return e.call(this,t,re)}:re;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};var ie=ne;function se(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function ae(e,t,r){if(!t)return e;const n=r&&r.encode||se,o=W.isFunction(r)?{serialize:r}:r,i=o&&o.serialize;let s;if(s=i?i(t,o):W.isURLSearchParams(t)?t.toString():new ie(t,o).toString(n),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}var ce=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){W.forEach(this.handlers,function(t){null!==t&&e(t)})}},le={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},he={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:ie,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const de="undefined"!=typeof window&&"undefined"!=typeof document,ue="object"==typeof navigator&&navigator||void 0,ge=de&&(!ue||["ReactNative","NativeScript","NS"].indexOf(ue.product)<0),pe="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,me=de&&window.location.href||"http://localhost";var fe={...n,...he};var ye=function(e){function t(e,r,n,o){let i=e[o++];if("__proto__"===i)return!0;const s=Number.isFinite(+i),a=o>=e.length;if(i=!i&&W.isArray(n)?n.length:i,a)return W.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!s;n[i]&&W.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],o)&&W.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const o=r.length;let i;for(n=0;n<o;n++)i=r[n],t[i]=e[i];return t}(n[i])),!s}if(W.isFormData(e)&&W.isFunction(e.entries)){const r={};return W.forEachEntry(e,(e,n)=>{t(function(e){return W.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),n,r,0)}),r}return null};const Ce={transitional:le,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,o=W.isObject(e);o&&W.isHTMLForm(e)&&(e=new FormData(e));if(W.isFormData(e))return n?JSON.stringify(ye(e)):e;if(W.isArrayBuffer(e)||W.isBuffer(e)||W.isStream(e)||W.isFile(e)||W.isBlob(e)||W.isReadableStream(e))return e;if(W.isArrayBufferView(e))return e.buffer;if(W.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return te(e,new fe.classes.URLSearchParams,{visitor:function(e,t,r,n){return fe.isNode&&W.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((i=W.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return te(i?{"files[]":e}
vendor: 4,176 bytes, line 2
2:e,t&&new t,this.formSerializer)}}return o||n?(t.setContentType("application/json",!1),function(e,t,r){if(W.isString(e))try{return(t||JSON.parse)(e),W.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Ce.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(W.isResponse(e)||W.isReadableStream(e))return e;if(e&&W.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e,this.parseReviver)}catch(e){if(r){if("SyntaxError"===e.name)throw J.from(e,J.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:fe.classes.FormData,Blob:fe.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};W.forEach(["delete","get","head","post","put","patch"],e=>{Ce.headers[e]={}});var we=Ce;const ve=W.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Ie=Symbol("internals");function Te(e){return e&&String(e).trim().toLowerCase()}function Ae(e){return!1===e||null==e?e:W.isArray(e)?e.map(Ae):String(e)}function be(e,t,r,n,o){return W.isFunction(n)?n.call(this,t,r):(o&&(t=r),W.isString(t)?W.isString(n)?-1!==t.indexOf(n):W.isRegExp(n)?n.test(t):void 0:void 0)}class Se{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function o(e,t,r){const o=Te(t);if(!o)throw new Error("header name must be a non-empty string");const i=W.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=Ae(e))}const i=(e,t)=>W.forEach(e,(e,r)=>o(e,r,t));if(W.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(W.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,o;return e&&e.split("\n").forEach(function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),n=e.substring(o+1).trim(),!r||t[r]&&ve[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)}),t})(e),t);else if(W.isObject(e)&&W.isIterable(e)){let r,n,o={};for(const t of e){if(!W.isArray(t))throw TypeError("Object iterator must return a key-value pair");o[n=t[0]]=(r=o[n])?W.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}i(o,t)}else null!=e&&o(t,e,r);return this}get(e,t){if(e=Te(e)){const r=W.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(W.isFunction(t))return t.call(this,e,r);if(W.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Te(e)){const r=W.findKey(this,e);return!(!r||void 0===this[r]||t&&!be(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function o(e){if(e=Te(e)){const o=W.findKey(r,e);!o||t&&!be(0,r[o],o,t)||(delete r[o],n=!0)}}return W.isArray(e)?e.forEach(o):o(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const o=t[r];e&&!be(0,this[o],o,e,!0)||(delete this[o],n=!0)}return n}normalize(e){const t=this,r={};return W.forEach(this,(n,o)=>{const i=W.findKey(r,o);if(i)return t[i]=Ae(n),void delete t[o];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(o):String(o).trim();s!==o&&delete t[o],t[s]=Ae(n),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return W.forEach(this,(r,n)=>{null!=r&&!1!==r&&(t[n]=e&&W.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);
2return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[Ie]=this[Ie]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=Te(e);t[n]||(!function(e,t){const r=W.toCamelCase(" "+t);["get","set","has"].forEach(n=>{Object.defineProperty(e,n+r,{value:function(e,r,o){return this[n].call(this,t,e,r,o)},configurable:!0})})}(r,e),t[n]=!0)}return W.isArray(e)?e.forEach(n):n(e),this}}Se.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),W.reduceDescriptors(Se.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),W.freezeMethods(Se);var ke=Se;function Ee(e,t){const r=this||we,n=t||r,o=ke.from(n.headers);let i=n.data;return W.forEach(e,function(e){i=e.call(r,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function _e(e){return!(!e||!e.__CANCEL__)}var Re=class extends J{constructor(e,t,r){super(null==e?"canceled":e,J.ERR_CANCELED,t,r),this.name="CanceledError",this.__CANCEL__=!0}};function Pe(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new J("Request failed with status code "+r.status,[J.ERR_BAD_REQUEST,J.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}var Oe=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o,i=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[s];o||(o=c),r[i]=a,n[i]=c;let h=s,d=0;for(;h!==i;)d+=r[h++],h%=e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),c-o<t)return;const u=l&&c-l;return u?Math.round(1e3*d/u):void 0}};var Ne=function(e,t){let r,n,o=0,i=1e3/t;const s=(t,i=Date.now())=>{o=i,r=null,n&&(clearTimeout(n),n=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-o;a>=i?s(e,t):(r=e,n||(n=setTimeout(()=>{n=null,s(r)},i-a)))},()=>r&&s(r)]};const Me=(e,t,r=3)=>{let n=0;const o=Oe(50,250);return Ne(r=>{const i=r.loaded,s=r.lengthComputable?r.total:void 0,a=i-n,c=o(a);n=i;e({loaded:i,total:s,progress:s?i/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&i<=s?(s-i)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},qe=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},Ue=e=>(...t)=>W.asap(()=>e(...t));var Le=fe.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,fe.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(fe.origin),fe.navigator&&/(msie|trident)/i.test(fe.navigator.userAgent)):()=>!0,xe=fe.hasStandardBrowserEnv?{write(e,t,r,n,o,i,s){if("undefined"==typeof document)return;const a=[`${e}=${encodeURIComponent(t)}`];W.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),W.isString(n)&&a.push(`path=${n}`),W.isString(o)&&a.push(`domain=${o}`),!0===i&&a.push("secure"),W.isString(s)&&a.push(`SameSite=${s}`),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function He(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const De=e=>e instanceof ke?{...e}:e;function Be(e,t){t=t||{};const r={};function n(e,t,r,n){return W.isPlainObject(e)&&W.isPlainObject(t)?W.merge.call({caseless:n},e,t):W.isPlainObject(t)?W.merge({},t):W.isArray(t)?t.slice():t}function o(e,t,r,o){return W.isUndefined(t)?W.isUndefined(e)?void 0:n(void 0,e,0,o):n(e,t,0,o)}function i(e,t){if(!W.isUndefined(t))return n(void 0,t)}function s(e,t){return W.isUndefined(t)?W.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,o,i){return i in t?n(r,o):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>o(De(e),De(t),0,!0)};return W.forEach(Object.keys({...e,...t}),function(n){const i=c[n]||o,s=i(e[n],t[n],n);W.isUndefined(s)&&i!==a||(r[n]=s)}),r}var Fe=e=>{const t=Be({},e);let{data:r,withXSRFToken:n,xsrfHeaderName:o,xsrfCookieName:i,headers:s,auth:a}=t;if(t.headers=s=ke.from(s),t.url=ae(He(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),W.isFormData(r))if(fe.hasStandardBrowserEnv||fe.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);
vendor: 4,340 bytes, line 2
2else if(W.isFunction(r.getHeaders)){const e=r.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,r])=>{t.includes(e.toLowerCase())&&s.set(e,r)})}if(fe.hasStandardBrowserEnv&&(n&&W.isFunction(n)&&(n=n(t)),n||!1!==n&&Le(t.url))){const e=o&&i&&xe.read(i);e&&s.set(o,e)}return t};var Ke="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const n=Fe(e);let o=n.data;const i=ke.from(n.headers).normalize();let s,a,c,l,h,{responseType:d,onUploadProgress:u,onDownloadProgress:g}=n;function p(){l&&l(),h&&h(),n.cancelToken&&n.cancelToken.unsubscribe(s),n.signal&&n.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const n=ke.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Pe(function(e){t(e),p()},function(e){r(e),p()},{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new J("Request aborted",J.ECONNABORTED,e,m)),m=null)},m.onerror=function(t){const n=t&&t.message?t.message:"Network Error",o=new J(n,J.ERR_NETWORK,e,m);o.event=t||null,r(o),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const o=n.transitional||le;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new J(t,o.clarifyTimeoutError?J.ETIMEDOUT:J.ECONNABORTED,e,m)),m=null},void 0===o&&i.setContentType(null),"setRequestHeader"in m&&W.forEach(i.toJSON(),function(e,t){m.setRequestHeader(t,e)}),W.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),d&&"json"!==d&&(m.responseType=n.responseType),g&&([c,h]=Me(g,!0),m.addEventListener("progress",c)),u&&m.upload&&([a,l]=Me(u),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(s=t=>{m&&(r(!t||t.type?new Re(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(s),n.signal&&(n.signal.aborted?s():n.signal.addEventListener("abort",s)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);y&&-1===fe.protocols.indexOf(y)?r(new J("Unsupported protocol "+y+":",J.ERR_BAD_REQUEST,e)):m.send(o||null)})};var je=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const o=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof J?t:new Re(t instanceof Error?t.message:t))}};let i=t&&setTimeout(()=>{i=null,o(new J(`timeout of ${t}ms exceeded`,J.ETIMEDOUT))},t);const s=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)}),e=null)};e.forEach(e=>e.addEventListener("abort",o));const{signal:a}=n;return a.unsubscribe=()=>W.asap(s),a}};const ze=function*(e,t){let r=e.byteLength;if(!t||r<t)return void(yield e);let n,o=0;for(;o<r;)n=o+t,yield e.slice(o,n),o=n},$e=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Ge=(e,t,r,n)=>{const o=async function*(e,t){for await(const r of $e(e))yield*ze(r,t)}(e,t);let i,s=0,a=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await o.next();if(t)return a(),void e.close();let i=n.byteLength;if(r){let e=s+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(e){throw a(e),e}},cancel(e){return a(e),o.return()}},{highWaterMark:2})},{isFunction:Qe}=W,We=(({Request:e,Response:t})=>({Request:e,Response:t}))(W.global),{ReadableStream:Ve,TextEncoder:Je}=W.global,Ye=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Xe=e=>{e=W.merge.call({skipUndefined:!0},We,e);const{fetch:t,Request:r,Response:n}=e,o=t?Qe(t):"function"==typeof fetch,i=Qe(r),s=Qe(n);if(!o)return!1;const a=o&&Qe(Ve),c=o&&("function"==typeof Je?(l=new Je,e=>l.encode(e)):async e=>new Uint8Array(await new r(e).arrayBuffer()));var l;const h=i&&a&&Ye(()=>{let e=!1;const t=new r(fe.origin,{body:new Ve,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),d=s&&a&&Ye(()=>
2W.isReadableStream(new n("").body)),u={stream:d&&(e=>e.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!u[e]&&(u[e]=(t,r)=>{let n=t&&t[e];if(n)return n.call(t);throw new J(`Response type '${e}' is not supported`,J.ERR_NOT_SUPPORT,r)})});const g=async(e,t)=>{const n=W.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(W.isBlob(e))return e.size;if(W.isSpecCompliantForm(e)){const t=new r(fe.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return W.isArrayBufferView(e)||W.isArrayBuffer(e)?e.byteLength:(W.isURLSearchParams(e)&&(e+=""),W.isString(e)?(await c(e)).byteLength:void 0)})(t):n};return async e=>{let{url:o,method:s,data:a,signal:c,cancelToken:l,timeout:p,onDownloadProgress:m,onUploadProgress:f,responseType:y,headers:C,withCredentials:w="same-origin",fetchOptions:v}=Fe(e),I=t||fetch;y=y?(y+"").toLowerCase():"text";let T=je([c,l&&l.toAbortSignal()],p),A=null;const b=T&&T.unsubscribe&&(()=>{T.unsubscribe()});let S;try{if(f&&h&&"get"!==s&&"head"!==s&&0!==(S=await g(C,a))){let e,t=new r(o,{method:"POST",body:a,duplex:"half"});if(W.isFormData(a)&&(e=t.headers.get("content-type"))&&C.setContentType(e),t.body){const[e,r]=qe(S,Me(Ue(f)));a=Ge(t.body,65536,e,r)}}W.isString(w)||(w=w?"include":"omit");const t=i&&"credentials"in r.prototype,c={...v,signal:T,method:s.toUpperCase(),headers:C.normalize().toJSON(),body:a,duplex:"half",credentials:t?w:void 0};A=i&&new r(o,c);let l=await(i?I(A,v):I(o,c));const p=d&&("stream"===y||"response"===y);if(d&&(m||p&&b)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=l[t]});const t=W.toFiniteNumber(l.headers.get("content-length")),[r,o]=m&&qe(t,Me(Ue(m),!0))||[];l=new n(Ge(l.body,65536,r,()=>{o&&o(),b&&b()}),e)}y=y||"text";let k=await u[W.findKey(u,y)||"text"](l,e);return!p&&b&&b(),await new Promise((t,r)=>{Pe(t,r,{data:k,headers:ke.from(l.headers),status:l.status,statusText:l.statusText,config:e,request:A})})}catch(t){if(b&&b(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new J("Network Error",J.ERR_NETWORK,e,A),{cause:t.cause||t});throw J.from(t,t&&t.code,e,A)}}},Ze=new Map,et=e=>{let t=e&&e.env||{};const{fetch:r,Request:n,Response:o}=t,i=[n,o,r];let s,a,c=i.length,l=Ze;for(;c--;)s=i[c],a=l.get(s),void 0===a&&l.set(s,a=c?new Map:Xe(t)),l=a;return a};et();const tt={http:null,xhr:Ke,fetch:{get:et}};W.forEach(tt,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const rt=e=>`- ${e}`,nt=e=>W.isFunction(e)||null===e||!1===e;var ot={getAdapter:function(e,t){e=W.isArray(e)?e:[e];const{length:r}=e;let n,o;const i={};for(let s=0;s<r;s++){let r;if(n=e[s],o=n,!nt(n)&&(o=tt[(r=String(n)).toLowerCase()],void 0===o))throw new J(`Unknown adapter '${r}'`);if(o&&(W.isFunction(o)||(o=o.get(t))))break;i[r||"#"+s]=o}if(!o){const e=Object.entries(i).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));let t=r?e.length>1?"since :\n"+e.map(rt).join("\n"):" "+rt(e[0]):"as no adapter specified";throw new J("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return o},adapters:tt};function it(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Re(null,e)}function st(e){it(e),e.headers=ke.from(e.headers),e.data=Ee.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return ot.getAdapter(e.adapter||we.adapter,e)(e).then(function(t){return it(e),t.data=Ee.call(e,e.transformResponse,t),t.headers=ke.from(t.headers),t},function(t){return _e(t)||(it(e),t&&t.response&&(t.response.data=Ee.call(e,e.transformResponse,t.response),t.response.headers=ke.from(t.response.headers))),Promise.reject(t)})}const at="1.13.4",ct={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ct[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const lt={};ct.transitional=function(e,t,r){return(n,o,i)=>{if(!1===e)throw new J(function(e,t){return"[Axios v"+at+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}(o," has been removed"+(t?" in "+t:"")),J.ERR_DEPRECATED);return t&&!lt[o]&&(lt[o]=!0),!e||e(n,o,i)}},ct.spelling=function(e){return(e,t)=>!0};var ht={assertOptions:function(e,t,r){if("object"!=typeof e)throw new J("options must be an object",J.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const i=n[o],s=t[i];if(s){const t=e[i],r=void 0===t||s(t,i,e);if(!0!==r)throw new J("option "+i+" must be "+r,J.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new J("Unknown option "+i,J.ERR_BAD_OPTION)}},validators:ct};const dt=ht.validators;class ut{constructor(e){this.defaults=e||{},this.interceptors={request:new ce,response:new ce}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const r=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?r&&!String(e.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+r):e.stack=r}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Be(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:o}=t;void 0!==r&&ht.assertOptions(r,{silentJSONParsing:dt.transitional(dt.boolean),forcedJSONParsing:dt.transitional(dt.boolean),clarifyTimeoutError:dt.transitional(dt.boolean)}
vendor: 2,882 bytes, line 2
2,!1),null!=n&&(W.isFunction(n)?t.paramsSerializer={serialize:n}:ht.assertOptions(n,{encode:dt.function,serialize:dt.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),ht.assertOptions(t,{baseUrl:dt.spelling("baseURL"),withXsrfToken:dt.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&W.merge(o.common,o[t.method]);o&&W.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=ke.concat(i,o);const s=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let h,d=0;if(!a){const e=[st.bind(this),void 0];for(e.unshift(...s),e.push(...c),h=e.length,l=Promise.resolve(t);d<h;)l=l.then(e[d++],e[d++]);return l}h=s.length;let u=t;for(;d<h;){const e=s[d++],t=s[d++];try{u=e(u)}catch(e){t.call(this,e);break}}try{l=st.call(this,u)}catch(e){return Promise.reject(e)}for(d=0,h=c.length;d<h;)l=l.then(c[d++],c[d++]);return l}getUri(e){return ae(He((e=Be(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}W.forEach(["delete","get","head","options"],function(e){ut.prototype[e]=function(t,r){return this.request(Be(r||{},{method:e,url:t,data:(r||{}).data}))}}),W.forEach(["post","put","patch"],function(e){function t(t){return function(r,n,o){return this.request(Be(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}ut.prototype[e]=t(),ut.prototype[e+"Form"]=t(!0)});var gt=ut;class pt{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const n=new Promise(e=>{r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e(function(e,n,o){r.reason||(r.reason=new Re(e,n,o),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new pt(function(t){e=t}),cancel:e}}}var mt=pt;const ft={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,Parti
2alContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(ft).forEach(([e,t])=>{ft[t]=e});var yt=ft;const Ct=function e(t){const r=new gt(t),n=o(gt.prototype.request,r);return W.extend(n,gt.prototype,r,{allOwnKeys:!0}),W.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(Be(t,r))},n}(we);Ct.Axios=gt,Ct.CanceledError=Re,Ct.CancelToken=mt,Ct.isCancel=_e,Ct.VERSION=at,Ct.toFormData=te,Ct.AxiosError=J,Ct.Cancel=Ct.CanceledError,Ct.all=function(e){return Promise.all(e)},Ct.spread=function(e){return function(t){return e.apply(null,t)}},Ct.isAxiosError=function(e){return W.isObject(e)&&!0===e.isAxiosError},Ct.mergeConfig=Be,Ct.AxiosHeaders=ke,Ct.formToJSON=e=>ye(W.isHTMLForm(e)?new FormData(e):e),Ct.getAdapter=ot.getAdapter,Ct.HttpStatusCode=yt,Ct.default=Ct;var wt=Ct}}]);

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.