),kt=bt.test.bind(bt);async function St(e){const t=kt(e),r=e.startsWith("v1.")||e.startsWith("ghs_"),o=e.startsWith("ghu_");return{type:"token",token:e,tokenType:t?"app":r?"installation":o?"user-to-server":"oauth"}}async function Tt(e,t,r,o){const n=t.endpoint.merge(r,o);return n.headers.authorization=function(e){return 3===e.split(/\./).length?`bearer ${e}`:`token ${e}`}(e),t(n)}var At=function(e){if(!e)throw new Error("[@octokit/auth-token] No token passed to createTokenAuth");if("string"!=typeof e)throw new Error("[@octokit/auth-token] Token passed to createTokenAuth is not a string");return e=e.replace(/^(token|bearer) +/i,""),Object.assign(St.bind(null,e),{hook:Tt.bind(null,e)})};const _t="6.1.4",Et=()=>{},Pt=console.warn.bind(console),xt=console.error.bind(console),Ot=`octokit-core.js/${_t} ${Fe()}`;class Rt{static VERSION=_t;static defaults(e){return class extends(this){constructor(...t){const r=t[0]||{};super("function"!=typeof e?Object.assign({},e,r,r.userAgent&&e.userAgent?{userAgent:`${r.userAgent} ${e.userAgent}`}:null):e(r))}}}static plugins=[];static plugin(...e){const t=this.plugins;return class extends(this){static plugins=t.concat(e.filter(e=>!t.includes(e)))}}constructor(e={}){const t=new Ve.Collection,r={baseUrl:mt.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};var o;if(r.headers["user-agent"]=e.userAgent?`${e.userAgent} ${Ot}`:Ot,e.baseUrl&&(r.baseUrl=e.baseUrl),e.previews&&(r.mediaType.previews=e.previews),e.timeZone&&(r.headers["time-zone"]=e.timeZone),this.request=mt.defaults(r),this.graphql=(o=this.request,Ct(o,{method:"POST",url:"/graphql"})).defaults(r),this.log=Object.assign({debug:Et,info:Et,warn:Pt,error:xt},e.log),this.hook=t,e.authStrategy){const{authStrategy:r,...o}=e,n=r(Object.assign({request:this.request,log:this.log,octokit:this,octokitOptions:o},e.auth));t.wrap("request",n.hook),this.auth=n}else if(e.auth){const r=At(e.auth);t.wrap("request",r.hook),this.auth=r}else this.auth=async()=>({type:"unauthenticated"});const n=this.constructor;for(let t=0;t{})}if(s={v:1,ref:v},w&&u){let t,r;if(e.hash){const o=/(L(?\d+)(?:-L(?\d+))?)|(C(?\d+)(\:L(?\d+)(?:-L(?\d+))?)?)/.exec(e.hash);if(o?.groups){const{cell:e,start:n,end:i,cell_line_start:s,cell_line_end:a}=o.groups;void 0!==n&&(t={startLineNumber:Number(n),startColumn:0,endLineNumber:Number(i??n)+1,endColumn:0}),void 0!==e&&(r={indexedCellOptions:{index:Math.max(0,Number(e)-1),selection:void 0===s?void 0:{startLineNumber:Number(s),startColumn:1,endLineNumber:Number(a??s)+1,endColumn:1}}})}}i={force:!0,editors:[{uri:{scheme:"vscode-vfs",authority:qe("github",s),path:`/${h}/${d}${w?.startsWith("/")?w:w?`/${w}`:""}`},options:{...r,selection:t},openOnlyIfExists:!0}]}}}else g?s={v:1,ref:{type:xe.Commit,id:g}}:m?s={v:1,ref:{type:xe.PullRequest,id:m}}:v?s={v:1,ref:v}:f={"workbench.startupEditor":"readme"};c&&(s||(s={v:1}),s.idx=l||"latest");const C=e.searchParams.get("editSessionId")??void 0;e.searchParams.delete("editSessionId"),window.history.replaceState(void 0,document.title,e.toString());let I={configurationDefaults:{"workbench.startupEditor":"none","remoteHub.richNavigation.enabled":!0,"extensions.experimental.affinity":{"ms-vscode.remote-repositories":1,"GitHub.remotehub":1,"GitHub.vscode-pull-request-github":1,"vscode.github-authentication":1,"vscode.typescript-language-features":1,"vscode.git-base":1,"ms-vscode.anycode":1,"ms-vscode.vscode-python-web-wasm":1,"ms-azuretools.vscode-azurestaticwebapps":1,"eamodio.gitlens-insiders":1,"eamodio.gitlens":1},...f},_tarballProxyEndpoints:{"github.com":`https://${"stable"===r?"vscode.dev":"insiders.vscode.dev"}/indexes/github2/{owner}/{repo}/{sha}`},editSessionId:C,defaultLayout:i,commands:[{id:"_remotehub.getTarballProxyEndpoints",handler:()=>({"github.com":`https://${"stable"===r?"vscode.dev":"insiders.vscode.dev"}/indexes/github2/{owner}/{repo}/{sha}`})}]},b={};return"codetour"===a&&(I={...I,configurationDefaults:{...I.configurationDefaults,"workbench.startupEditor":"none"},enabledExtensions:["vsls-contrib.codetour"]},b={...b,openUri:{authority:"vsls-contrib.codetour",path:"/startDefaultTour"}}),{workspace:{folderUri:o.from({scheme:"vscode-vfs",authority:qe("github",s),path:`/${h}/${d}`})},workbenchOptions:I,onDidCreateWorkbench:b}}}qt.RX=/^\/(?github|codetour)(?\+idx=?(?latest|[0-9a-fA-F]{40})?)?\/(?[^/]+)\/(?[^/?#]+)(?:|\.git|\/tree\/(?.+)|\/blob\/(?.+)|\/commit\/(?[0-9a-f]{40})|\/pull\/(?[0-9]+))?/i;async function $t(e,t,r,o){const n=await e.request(`GET /repos/{owner}/{repo}/git/extract-ref/${o??"HEAD"}`,{owner:t,repo:r});return[t,r]=n.data.name_with_owner.split("/"),o?{owner:t,repo:r,ref:{type:xe.Tree,id:n.data.ref},path:n.data.path}:{owner:t,repo:r}}re(new qt),re(new class extends qt{constructor(){super(...arguments),this.path="codetour",this.additionalBuiltinExtensions=["GitHub.vscode-pull-request-github","vsls-contrib.codetour"]}}),De("github",new class{resolveRemoteHubWorkspace(e,t){const r=new URL(document.location.href);let o=new URLSearchParams(e.query).get("vscode-experience")??"github";switch(void 0!==t&&("latest"===t.idx?o+="+idx":Re(t.idx)&&(o+=`+idx=${t.idx}`)),r.pathname=`/${o}${e.path}`,t?.ref?.type){case xe.PullRequest:r.pathname+=`/pull/${t.ref.id}`;break;case xe.Tree:r.pathname+=`/tree/${t.ref.id}`;break;case xe.Commit:r.pathname+=`/commit/${t.ref.id}`}return r.toString()}}),X(new Pe("github.com","github")),X(new class{redirect(e){const t=e.searchParams.get("from");if(null===t)return;const r=new URL(e.toString());return r.searchParams.delete("from"),"open"===t&&(r.pathname="/github"+r.pathname),r}});X(new class{redirect(e){const t=e.searchParams.get("idx");if(null===t)return;const r=/\/(?[^/]+)\/(?.*)/.exec(e.pathname);if(!r?.groups)return;const o=new URL(e.toString());return o.searchParams.delete("idx"),""===t||"latest"===t?o.pathname=`/${r.groups.service}+idx/${r.groups.rest}`:/^[0-9a-f]{40}$/i.exec(t)&&(o.pathname=`/${r.groups.service}+idx=${t}/${r.groups.rest}`),o}});class Ut{constructor(){this.path="editor/liveshare",this.additionalBuiltinExtensions=["MS-vsliveshare.vsliveshare"]}async route({url:e}){const t=Ut.RX.exec(e.pathname);if(!t?.groups?.sessionId)return;const r=new URLSearchParams(e.searchParams);return r.set("sessionId",t.groups.sessionId),{workspace:{workspaceUri:o.from({scheme:"vsls",authority:"",path:"/Live Share.code-workspace",query:r.toString()})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},enabledExtensions:this.additionalBuiltinExtensions},onWillDisposeWorkbench:{runCommands:[{command:"liveshare.workbench.dispose",args:[]}]}}}}Ut.RX=/^\/editor\/liveshare\/(?[^/]+)/i;re(new Ut),X({redirect(e){if(!/^\/liveshare\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}}),ne(new class{resolveWorkspace(e){if(!ie(e))return;const t=e.folderUri;if("vsls"===t.scheme&&""===t.authority&&"/"===t.path){const e=new URL(document.location.href);return e.pathname="/liveshare",e.toString()}if("vsls"!==t.scheme||""!==t.authority||"/Live Share.code-workspace"!==t.path)return;const r=new URLSearchParams(t.query).get("sessionId");if(!r)return;const o=new URL(document.location.href);return o.pathname=`/liveshare/${r}`,o.toString()}});const Lt="https://arcade.makecode.com";class Nt{constructor(){this.path="edu/makecode",this.additionalBuiltinExtensions=[{id:"ms-edu.pxt-vscode-web",preRelease:!0}]}async route({url:e}){const t=Nt.routeRegex.exec(e.pathname);if(!t)return;const r=[],n=t.groups?.projectId;return n&&(r.push({command:"makecodeActions.focus",args:[]}),r.push({command:"makecode.importUrl",args:[n]})),{workspace:{workspaceUri:o.from({scheme:"tmp",path:"/default.code-workspace"})},workbenchOptions:{enabledExtensions:this.additionalBuiltinExtensions[0]?[this.additionalBuiltinExtensions[0].id]:[],configurationDefaults:{"workbench.startupEditor":"none"},homeIndicator:{icon:"smiley",title:"Microsoft MakeCode Arcade",href:Lt},windowIndicator:{onDidChange:()=>({dispose:()=>{}}),label:"MakeCode Arcade",tooltip:de.MakeCodePrompt.toString()},additionalTrustedDomains:[Lt]},onDidCreateWorkbench:{runCommands:r}}}}Nt.routeRegex=/^\/edu\/makecode(\/(?(S?\d{4}[\d\-]+|_[a-zA-Z0-9]{10,}))\/?)?$/i,re(new Nt),X({redirect(e){if(!/^\/makecode\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/edu${e.pathname}`,t}});class Dt{constructor(){this.path="editor/marketplace",this.additionalBuiltinExtensions=["ms-vscode.vscode-marketplace-extension-browser"]}async route({url:e}){const t=Dt.RX.exec(e.pathname);if(t?.groups)return{workspace:{folderUri:o.from({scheme:"vscode-marketplace",authority:"",path:`/${t.groups.owner}/${t.groups.repo}/${t.groups.version}`})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{openUri:{authority:this.additionalBuiltinExtensions[0],path:"/open"}}}}}Dt.RX=/^\/editor\/marketplace\/(?[^/]+)\/(?[^/]+)\/(?\d+\.\d+\.\d+(-.*)?)$/i,re(new Dt),X({redirect(e){if(!/^\/marketplace\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}});class Ht{constructor(){this.path="editor/theme",this.additionalBuiltinExtensions=["ms-vscode.theme-tester"]}async route({url:e}){if(Ht.RX.exec(e.pathname))return{workspace:{folderUri:o.from({scheme:"vscode-theme-tester",authority:"",path:"/"})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{openUri:{authority:this.additionalBuiltinExtensions[0],path:"/open"}}}}}Ht.RX=/^\/editor\/theme\//i,re(new Ht),X({redirect(e){if(!/^\/theme\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}});const Ft=new Uint8Array(16);const zt=[];for(let e=0;e<256;++e)zt.push((e+256).toString(16).slice(1));function jt(e,t=0){return(zt[e[t+0]]+zt[e[t+1]]+zt[e[t+2]]+zt[e[t+3]]+"-"+zt[e[t+4]]+zt[e[t+5]]+"-"+zt[e[t+6]]+zt[e[t+7]]+"-"+zt[e[t+8]]+zt[e[t+9]]+"-"+zt[e[t+10]]+zt[e[t+11]]+zt[e[t+12]]+zt[e[t+13]]+zt[e[t+14]]+zt[e[t+15]]).toLowerCase()}const Bt=function(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){e=e||{};const o=e.random??e.rng?.()??crypto.getRandomValues(Ft);if(o.length<16)throw new Error("Random bytes length must be >= 16");if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=o[e];return t}return jt(o)}(e,t,r):crypto.randomUUID()};class Kt{constructor(){this.path="editor/profile",this.additionalBuiltinExtensions=[]}async route({url:e,quality:t}){const r=Kt.RX.exec(e.pathname),n=r?.groups?.path;if(!n)return;let i="code-oss";switch(t){case"stable":i="vscode";break;case"insider":i="vscode-insiders"}return{workspace:{workspaceUri:o.from({scheme:"tmp",path:`/${Bt()}`})},workbenchOptions:{profileToPreview:o.from({scheme:i,authority:"profile",path:`/${n}`})}}}}Kt.RX=/^\/editor\/profile\/(?.+)$/i,re(new Kt),X({redirect(e){if(!/^\/profile\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}});re(new class{constructor(){this.path="tsplay",this.additionalBuiltinExtensions=["Orta.tspl"],this.excludeDefaultExtensions=!0,this.scheme="playfs"}async route({url:e,quality:t}){if(e.href.includes("localhost")||"stable"!==t)return{workspace:{folderUri:o.from({scheme:this.scheme,authority:"",path:"/"})},workbenchOptions:{configurationDefaults:{"scm.alwaysShowProviders":!1,"workbench.experimental.sidePanel.enabled":!0},enabledExtensions:this.additionalBuiltinExtensions,defaultLayout:{views:[{id:"ts-playground"}]}},onDidCreateWorkbench:{openUri:{authority:this.additionalBuiltinExtensions[0],path:e.pathname,query:e.search,fragment:e.hash},runCommands:[{command:"workbench.action.focusAuxiliaryBar",args:[]}]},welcomeBanner:{message:"TypeScript Playground in Code (Preview)",actions:[{href:`https://www.typescriptlang.org/play/${e.search}${e.hash}`,label:"Go back to TypeScript Playground"},{href:"https://privacy.microsoft.com/en-us/privacystatement",label:de.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:de.TermsofUse.toString()}]}}}});class Wt{constructor(){this.path="power",this.additionalBuiltinExtensions=["microsoft-IsvExpTools.powerplatform-vscode"]}async route({url:e}){const t=Wt.RX1.exec(e.pathname),r=Wt.RX2.exec(e.pathname);if(void 0===t?.groups&&void 0===r?.groups)return;const n=t?.groups?.appName??r?.groups?.appName,i=t?.groups?.entity,s=t?.groups?.entityId;let a=e.search,c="";c=!n||"portal"!==n&&"pages"!==n?"PowerPlatform":"PowerPages";const l=new URLSearchParams(a),h=l.get("enableMultifile"),d=l.get("websiteId")?.replace(/\//g,""),u="true"===h?.toLowerCase()&&d;return{workspace:{workspaceUri:o.from({scheme:"powerplatform-vfs",authority:"",path:!u&&i&&s?`/${i}/${s}/${c}`:`/${d}/${c}`})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none","files.autoSave":"off"},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{runCommands:[{command:"microsoft-powerapps-portals.webExtension.init",args:i&&s?[{appName:n,entity:i,entityId:s,searchParams:a}]:[{appName:n,searchParams:a}]}]}}}}Wt.RX1=/^\/(?power)\/(?[^/]+)\/?(?[^/]+)?\/?(?[^/?]+)?([?])?(?[^#]+)?/i,Wt.RX2=/^\/(?power)\/(?[^/]+)(?:\/(?[^#]+))?/i,re(new Wt),X({redirect(e){if(!/^\/powerplatform\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=t.pathname.replace(/^\/powerplatform/,"/power"),t}});class Jt{constructor(){this.path="contentmentor",this.additionalBuiltinExtensions=[]}async route({url:e}){if(!Jt.RX.test(e.pathname))return;const t=Jt.ACTION_RX.exec(e.pathname),r=t?.[1],o=e.searchParams.get("url"),n=e.searchParams.get("action");let i;if(o){const e=[`url=${encodeURIComponent(o)}`];!r&&n&&e.push(`action=${encodeURIComponent(n)}`),i={authority:Jt.EXTENSION_ID,path:r?`/${r}`:"/",query:e.join("&")}}return{workspace:ee,workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},windowIndicator:{onDidChange:()=>({dispose:()=>{}}),label:"Content Mentor",tooltip:"Content Mentor"},additionalTrustedDomains:["https://*.sharepoint.com"],commands:[{id:Jt.BOOTSTRAP_COMMAND,handler:()=>Jt.bootstrap(i)}]},disableWelcomeBanner:!0,onDidCreateWorkbench:{runCommands:[{command:Jt.BOOTSTRAP_COMMAND,args:[]}]}}}static async bootstrap(e){try{await n.executeCommand("workbench.extensions.installExtension",Jt.EXTENSION_ID)}catch(e){return void console.error(`[contentmentor] failed to install ${Jt.EXTENSION_ID}`,e)}e?await s.openUri(o.from({...e,scheme:await s.getUriScheme(),query:e.query||window.location.href})):await n.executeCommand("workbench.view.extension.content-mentor")}}Jt.RX=/^\/contentmentor(\/|$)/i,Jt.ACTION_RX=/^\/contentmentor\/([^/?]+)/i,Jt.EXTENSION_ID="msft-content.content-mentor",Jt.BOOTSTRAP_COMMAND="_contentmentor.bootstrap",re(new Jt);const Vt={dispose(){}},Gt=()=>Vt;const Qt="ms-edu.vscode-learning",Yt={homepageBase:"https://vscodeedu.com",signInUrl:"https://vscodeedu.com/signin",apiBase:"https://vscodeedu.com"},Xt={homepageBase:"https://vscodeedu.com/beta",signInUrl:"https://vscodeedu.com/beta/signin",apiBase:"https://vscodeedu.com"},Zt={homepageBase:"https://ppe.vscodeedu.com",signInUrl:"https://ppe.vscodeedu.com/signin",apiBase:"https://ppe.vscodeedu.com"};function er(e){return"ppe"===e?Zt:"beta"===e?Xt:Yt}const tr="requestId",rr="otac",or="redirectUri",nr="codeChallenge",ir="codeVerifier";const sr=e=>e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");function ar(e){return`treehouse.auth.state.${e}`}function cr(){return JSON.stringify({extensionId:"ms-edu.vscode-learning",key:"VSCE_SESSIONTOKEN"})}re(new class{constructor(){this.path="edu",this.additionalBuiltinExtensions=[{id:"ms-vscode.wasm-wasi-core"},{id:"ms-python.python",preRelease:!1},{id:"ms-vscode.remote-repositories",preRelease:!0}],this.excludeDefaultExtensions=!0}async route({url:e,secretStorageProvider:t,githubAuthentication:r}){if(!/^\/edu\/?$/i.test(e.pathname))return;const n=e.searchParams.get("env")?.match(/^(ppe|prod|beta)$/i)?.[0]?.toLowerCase()??"prod",i="ppe"===n,s=i?Zt.apiBase:Yt.apiBase;!!e.searchParams.get("sign-out")?.match(/^(true|1)$/i)?.[0]&&await t.delete(cr()),await this.redirectToHomePageIfNecessary(e,er(n).homepageBase);if(!e.searchParams.get("auth")?.match(/^(false|0)$/i)?.[0]){const r=e.searchParams.get(tr),o=e.searchParams.get(rr),i=e.searchParams.get("region"),a=er(n).signInUrl;r&&o?await async function(e,t,r,o,n){try{if(await e.get(cr()))return;const i=ar(t),s=sessionStorage.getItem(i);if(!s)return void console.error("Invalid request ID for VSCode Edu sign-in flow");sessionStorage.removeItem(i);const a=new URL("api/auth/otac:exchange",n);a.searchParams.set(rr,r),a.searchParams.set(ir,encodeURIComponent(s));const c=await fetch(a.toString(),{method:"POST",mode:"cors",headers:null!==o?{"x-ms-affinity-region":o}:void 0});if(!c.ok)throw new Error(`Unexpected ${c.status} from ${a.toString()}`);const l=await c.text();await e.set(cr(),l)}catch(e){console.error("Error completing VSCode Edu sign-in flow"),console.error(e)}}(t,r,o,i,s):await async function(e,t,r){try{const o=cr();let n=await e.get(o);if(n){const t=function(e){e.startsWith("#")&&(e=e.substring(1));const t=e.split("&"),r={};for(const e of t)if(-1===e.indexOf("="))r[e]="true";else{const t=e.split("=");2==t.length&&(r[t[0]]=t[1])}return r}(r)["account-id"];if(!t)return;const i=function(e){try{var t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(window.atob(t).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(r)}catch(e){return void console.error(e)}}(n);if(i&&i.oid===t)return;await e.delete(o),n=void 0}if(!n){const e=await async function(){const e=crypto.randomUUID(),t=await self.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)),r=sr(btoa(String.fromCharCode(...new Uint8Array(t))));return{codeVerifier:e,codeChallenge:r}}(),r=crypto.randomUUID(),o=new URL(t);o.searchParams.set(or,window.location.href),o.searchParams.set(tr,r),o.searchParams.set(nr,e.codeChallenge),sessionStorage.setItem(ar(r),e.codeVerifier),window.location.href=o.toString()}}catch(e){console.error("Error starting VSCode Edu sign-in flow"),console.error(e)}}(t,a,e.hash)}const a=await this.getConfig(s),c=e.searchParams.get("extension")?.match(/^([0-9a-z]{7})$/i)?.[0]?.toLowerCase()??a[`${n}.extension`],l=o.parse(`${s}/extension/${c}/extension`),h=e.searchParams.get("profile")??"default-dark",d=h.includes("/")?h:`${a[`${n}.profile`]??""}/${h}`,u=o.parse(`${s}/profile/${d}.code-profile`),g=await this.getProfileName(u,h);let p,m=e.searchParams.get("workspace-scheme")??"vscode-edu-workspace",f=e.searchParams.get("workspace-path")??"/";const y=e.searchParams.get("courseId"),w=e.searchParams.get("curriculumId"),v={};e.searchParams.forEach((e,t)=>{v[t]=e});const C=e.hash.slice(1),I=[{command:"vscode-learning.handleRouteOptions",args:[v,C]}];if((y||w)&&I.push({command:"workbench.view.extension.learningView",args:[]}),w&&!y){const t=e.searchParams.get("githubRepo");if("string"!=typeof t)throw new Error("Missing githubRepo parameter for curriculum authoring scenario.");await async function(e,t){const[r,o]=t.split("/");if(!r||!o)return console.error("Invalid format for githubRepo: "+t),!1;try{const t=(await e.login(["repo","read:user","user:email","workflow"])).accessToken;if(void 0!==t){const e=new Rt({auth:`token ${t}`}),n=await async function(e,t,r,o){const n=await e.request(`GET /repos/{owner}/{repo}/git/extract-ref/${o??"HEAD"}`,{owner:t,repo:r});return[t,r]=n.data.name_with_owner.split("/"),o?{owner:t,repo:r,ref:{type:xe.Tree,id:n.data.ref},path:n.data.path}:{owner:t,repo:r}}(e,r,o);return void 0!==n}}catch(e){console.error(e)}return!1}(r,t),m="vscode-vfs",p="github",f=`/${t}`}return{workspace:m?{folderUri:o.from({scheme:m,authority:p,path:f})}:{workspaceUri:o.from({scheme:"tmp",path:`/${Bt()}`})},workbenchOptions:{enableWorkspaceTrust:!1,additionalBuiltinExtensions:[l],additionalTrustedDomains:[s],enabledExtensions:[Qt,...this.additionalBuiltinExtensions.map(e=>e.id)],configurationDefaults:{"workbench.startupEditor":"none","vscode-learning.usePPEHost":i,"vscode-learning.env":n},windowIndicator:{onDidChange:Gt,label:"Education",tooltip:"Learn to code"},profile:{name:g,contents:u},commands:this.createCommands(),productConfiguration:{extensionEnabledApiProposals:{[Qt]:["codiconDecoration"]}}},onDidCreateWorkbench:{runCommands:I},onWillDisposeWorkbench:{runCommands:[{command:"vscode-learning.beforeUnload",args:[]}]},disableWelcomeBanner:!0}}createCommands(){return[{id:"vscode-edu.openUrlInSameTab",label:void 0,menu:void 0,handler:async e=>{const t=new URL(e);if(t.origin!==Zt.homepageBase&&t.origin!==Yt.homepageBase)throw new Error(`URL must be of origin ${Zt.homepageBase} or ${Yt.homepageBase}`);window.open(t.toString(),"_self")}}]}async redirectToHomePageIfNecessary(e,t){const r=e.searchParams.get("courseId"),o=e.searchParams.get("curriculumId"),n=e.searchParams.get("projectId"),i=e.searchParams.get("sharedLinkId"),s=n||i;let a=!1;s&&(e.searchParams.get("workspace-scheme")||e.searchParams.get("workspace-path")||(a=!0)),r||s||o||(a=!0),a&&(window.location.href=t,await new Promise(()=>{}))}async getProfileName(e,t){const r=await fetch(e.toString());if(!r.ok)throw new Error(`Unexpected ${r.status} from ${e.toString()}`);const o=(await r.json()).name;return o&&"string"==typeof o?o:t}async getConfig(e){const t=`${e}/api/config`,r=await fetch(t);return r.ok?r.json():{}}});re(new class{constructor(){this.path="editor/treesitter",this.additionalBuiltinExtensions=["jrieken.vscode-tree-sitter-query"],this.excludeDefaultExtensions=!0}async route({url:e,quality:t}){if(e.href.includes("localhost")||"stable"!==t)return{workspace:ee,workbenchOptions:{configurationDefaults:{"scm.alwaysShowProviders":!1},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{runCommands:[{command:"vscode-treesitter-notebook.new",args:[]}]},welcomeBanner:{message:"Tree-sitter Playground (Preview)",actions:[{href:"https://tree-sitter.github.io/tree-sitter/",label:"Learn more about Tree-sitter"},{href:"https://tree-sitter.github.io/tree-sitter/playground",label:"Go back to Tree-sitter Playground"},{href:"https://privacy.microsoft.com/en-us/privacystatement",label:de.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:de.TermsofUse.toString()}]}}}});const lr={homepageBase:"https://studio.discovery.microsoft.com",extensionVsixUri:"https://studio.discovery.microsoft.com/ext"},hr={homepageBase:"https://studio-dev.discovery.microsoft.com",extensionVsixUri:"https://studio-dev.discovery.microsoft.com/ext"},dr={homepageBase:"https://studio-dev2.discovery.microsoft.com",extensionVsixUri:"https://studio-dev2.discovery.microsoft.com/ext"},ur={homepageBase:"https://studio-dev3.discovery.microsoft.com",extensionVsixUri:"https://studio-dev3.discovery.microsoft.com/ext"},gr={homepageBase:"https://studio-staging.discovery.microsoft.com",extensionVsixUri:"https://studio-staging.discovery.microsoft.com/ext"},pr={homepageBase:"https://localhost:8080",extensionVsixUri:"https://localhost:8080/ext"};re(new class{constructor(){this.ExtensionId="ms-discovery.studio",this.path="discovery",this.additionalBuiltinExtensions=[],this.excludeDefaultExtensions=!0}async route({url:e,secretStorageProvider:t}){if(!/^\/discovery\/?$/i.test(e.pathname))return;const r=e.searchParams.get("env")?.match(/^(dev|dev2|dev3|staging|local)$/i)?.[0]?.toLowerCase()??"prod";let n=lr;switch(r){case"staging":n=gr;break;case"local":n=pr;break;case"dev":n=hr;break;case"dev2":n=dr;break;case"dev3":n=ur}const i=e.searchParams.get("workspaceName"),s=e.searchParams.get("projectName"),a=e.searchParams.get("tenantId"),c=e.searchParams.get("subscriptionId"),l=e.searchParams.get("resourceGroupName"),h=e.searchParams.get("apiVersion"),d=e.searchParams.get("featureFlags");if(t&&(i||s||a||c||l||h||d)){const e={workspaceName:i||void 0,projectName:s||void 0,tenantId:a||void 0,subscriptionId:c||void 0,resourceGroupName:l||void 0,apiVersion:h||void 0,featureFlags:d||void 0,environment:r},o=JSON.stringify({extensionId:"ms-discovery.studio",key:"DISCOVERY_STUDIO_CONTEXT"});await t.set(o,JSON.stringify(e))}const u=o.parse(`${n.extensionVsixUri}/resources/Discovery.code-profile`),g=o.parse(n.extensionVsixUri);return{workbenchOptions:{configurationDefaults:{"scm.alwaysShowProviders":!1,"workbench.colorTheme":"Light Modern","workbench.startupEditor":"none"},profile:{name:"Discovery",contents:u},enabledExtensions:[this.ExtensionId],additionalBuiltinExtensions:[g]},onDidCreateWorkbench:{runCommands:[{command:"workbench.action.focusAuxiliaryBar",args:[]}]},disableWelcomeBanner:!0}}});class mr{constructor(e,t){this.secretStorageProvider=e,this.url=t,this.GITHUB_AUTHORIZE_URL="https://github.com/login/oauth/authorize",this.GITHUB_AUTH_EXTENSION_ID="vscode.github-authentication",this.GITHUB_AUTH_SECRET_STORAGE_KEY="github.auth",this.SECRET_STORAGE_PROVIDER_KEY=JSON.stringify({extensionId:this.GITHUB_AUTH_EXTENSION_ID,key:this.GITHUB_AUTH_SECRET_STORAGE_KEY}),this.SESSION_STORAGE_KEY="github.auth"}async tryCompleteAuthExchange(){const e=this.url.searchParams.get("code"),t=sessionStorage.getItem(this.SESSION_STORAGE_KEY);if(!e||!t)return this.url;const r=JSON.parse(t),o=await this.exchangeCodeForAccessToken(e);return void 0!==o&&(await this.persistInSecretStorageProvider(o,r),this.url.searchParams.delete("code"),this.url.searchParams.delete("state"),sessionStorage.removeItem(this.SESSION_STORAGE_KEY),window.history.replaceState(void 0,document.title,this.url.toString())),this.url}async login(e){await this.tryCompleteAuthExchange();const t=await this.getAuthSessions(),r=this.findSessionWithRequestedScopes(t,e);if(void 0!==r)return r;const o=this.url,n=`${this.url.protocol}//${this.url.host}/redirect`,i=new URLSearchParams([["client_id","localhost"===this.url.hostname?"c8d3980f24ffff70fbd6":"01ab8ac9400c4e429b23"],["redirect_uri",n],["scope",e.join(" ")],["state",o.toString()]]);sessionStorage.setItem(this.SESSION_STORAGE_KEY,JSON.stringify(e));const s=new URL(this.GITHUB_AUTHORIZE_URL);return s.search=i.toString(),window.location.href=s.toString(),await new Promise(()=>{})}async persistInSecretStorageProvider(e,t){const r=await this.getAuthSessions(),o={id:Bt(),accessToken:e,scopes:t};r.push(o),await this.secretStorageProvider.set(this.SECRET_STORAGE_PROVIDER_KEY,JSON.stringify(r))}findSessionWithRequestedScopes(e,t){function r(e,t){return e.reduce((e,r)=>e&&t.includes(r),!0)}for(const o of e)if(r(t,o.scopes))return o}async getAuthSessions(){let e=await this.secretStorageProvider.get(this.SECRET_STORAGE_PROVIDER_KEY);if(e)try{return JSON.parse(e)}catch(e){console.log(e)}return[]}async exchangeCodeForAccessToken(e){let t;try{const r=`code=${e}`,o=await fetch("/codeExchangeProxyEndpoints/github/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","Content-Length":`${r.toString().length}`},body:r});if(o.ok){t=(await o.json()).access_token}}catch(e){console.error(e)}return t}}const fr="https://login.microsoftonline.com/common/",yr="common",wr=`${fr}discovery/instance?api-version=1.1&authorization_endpoint=`,vr=".ciamlogin.com",Cr=".onmicrosoft.com",Ir="openid",br="profile",kr="offline_access",Sr="S256",Tr="N/A",Ar="Not Available",_r="http://169.254.169.254/metadata/instance/compute",Er=["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],Pr="GET",xr="POST",Or=[Ir,br,kr],Rr=[...Or,"email"],Mr="Content-Type",qr="Content-Length",$r="Retry-After",Ur="X-AnchorMailbox",Lr="x-ms-request-id",Nr="x-ms-httpver",Dr="active-account-filters",Hr="common",Fr="organizations",zr="consumers",jr="access_token",Br="xms_cc",Kr="id_token",Wr="signin_state",Jr="login_hint",Vr="login",Gr="select_account",Qr="consent",Yr="none",Xr="no_session",Zr="code",eo="id_token token refresh_token",to="query",ro="fragment",oo="authorization_code",no="refresh_token",io="Generic",so={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},ao="appmetadata",co="1",lo="authority-metadata",ho="config",uo="cache",go="network",po="hardcoded_values",mo=5,fo="server-telemetry",yo=",",wo={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},vo="throttling",Co="1",Io="3",bo="4",ko="2",So="4",To="5",Ao="0",_o="1",Eo="2",Po="3",xo="4",Oo="pop",Ro="invalid_grant",Mo=483,qo=600,$o="msal",Uo="msal.js.browser",Lo="53ee284d-920a-4b59-9d30-a60315b26836",No="ppnbnpeolgkicgegkbkbjmhlideopiji",Do="MATS",Ho="MicrosoftEntra",Fo="DOM API",zo="get-token-and-sign-out",jo="PlatformAuthDOMHandler",Bo="PlatformAuthExtensionHandler",Ko="Handshake",Wo="HandshakeResponse",Jo="GetToken",Vo="Response",Go="localStorage",Qo="sessionStorage",Yo="memoryStorage",Xo="GET",Zo="POST",en="signin",tn="signout",rn="request.origin",on="urlHash",nn="request.params",sn="code.verifier",an="interaction.status",cn="request.native",ln="wrapper.sku",hn="wrapper.version",dn=861,un=862,gn=863,pn=865,mn=866,fn=61,yn=961,wn=962,vn=963,Cn={861:"acquireTokenRedirect",862:"acquireTokenPopup",863:"ssoSilent",864:"acquireTokenSilent_authCode",865:"handleRedirectPromise",866:"acquireTokenByCode",61:"acquireTokenSilent_silentFlow",961:"logout",962:"logoutPopup",963:"hydrateCache",964:"loadExternalTokens"};var In;!function(e){e.Redirect="redirect",e.Popup="popup",e.Silent="silent",e.None="none"}(In||(In={}));const bn={scopes:Or},kn="msal.db",Sn=`${kn}.keys`,Tn=0,An=1,_n=2,En=3,Pn=4,xn=5,On=[Tn,xn,Pn];function Rn(e){return`See https://aka.ms/msal.js.errors#${e} for details`}class Mn extends Error{constructor(e,t,r,o){const n=r||(e?Rn(e):"");super(n?`${e}: ${n}`:e),Object.setPrototypeOf(this,Mn.prototype),this.errorCode=e||"",this.errorMessage=n||"",this.subError=o||"",this.correlationId=t,this.name="AuthError"}}function qn(e,t,r){return new Mn(e,t,r||Rn(e))}const $n="no_tokens_found",Un="refresh_token_expired",Ln="ui_not_allowed",Nn="bad_token",Dn=["interaction_required","consent_required","login_required",Nn,Ln,"interrupted_user"],Hn=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token","ui_not_allowed","interrupted_user"];class Fn extends Mn{constructor(e,t,r,o,n,i,s,a){super(e,t,r,o),Object.setPrototypeOf(this,Fn.prototype),this.timestamp=n||"",this.traceId=i||"",this.claims=s||"",this.name="InteractionRequiredAuthError",this.errorNo=a}}function zn(e,t,r){const o=!!e&&Dn.indexOf(e)>-1,n=!!r&&Hn.indexOf(r)>-1,i=!!t&&Dn.some(e=>t.indexOf(e)>-1);return o||i||n}function jn(e,t,r){return new Fn(e,t,r)}const Bn=["openid","email","profile","offline_access"];class Kn{constructor(e=[],t){this.originalScopes=e;const r=[...e];r.sort(),this.allScopes=r,this.scopeStr=r.join(" "),this.claims=t,this.scopesToSend=this.getScopesToSend(r),this.clientId=this.getClientId(this.allScopes),this.tenant=this.getTenantId(this.allScopes),this.tenantId=["common","organizations","consumers"].includes(this.tenant)?void 0:this.tenant}getClientId(e){return e.reduce((e,t)=>t.startsWith("VSCODE_CLIENT_ID:")?t.split("VSCODE_CLIENT_ID:")[1]:e,void 0)??"aebc6443-996d-45c2-90f0-388ff96faa56"}getTenantId(e){return e.reduce((e,t)=>t.startsWith("VSCODE_TENANT:")?t.split("VSCODE_TENANT:")[1]:e,void 0)??"organizations"}getScopesToSend(e){const t=e.filter(e=>!e.startsWith("VSCODE_")),r=new Set(t);for(const e of Bn)r.delete(e);return r.size||t.push("User.Read"),t}}class Wn extends Mn{constructor(e,t,r){super(e,t,r),this.name="ClientAuthError",Object.setPrototypeOf(this,Wn.prototype)}}function Jn(e,t,r){return new Wn(e,t,r)}const Vn="client_info_decoding_error",Gn="token_parsing_error",Qn="null_or_empty_token",Yn="endpoints_resolution_error",Xn="network_error",Zn="invalid_state",ei="state_not_found",ti="empty_input_scopeset",ri="no_account_in_silent_request",oi="invalid_cache_environment",ni="no_account_found",ii="no_crypto_object",si="token_refresh_required",ai="key_id_missing",ci="method_not_implemented";class li extends Mn{constructor(e,t,r){super(e,t,r),this.name="JoseHeaderError",Object.setPrototypeOf(this,li.prototype)}}function hi(e,t){return new li(e,t)}class di{constructor(e){this.typ=e.typ,this.alg=e.alg,this.kid=e.kid}static getShrHeaderString(e){if(!e.kid)throw hi("missing_kid_error","");if(!e.alg)throw hi("missing_alg_error","");const t=new di({typ:e.typ||Oo,kid:e.kid,alg:e.alg});return JSON.stringify(t)}}const ui="standardInteractionClientGetDiscoveredAuthority",gi="nativeInteractionClientAcquireToken",pi="acquireTokenBySilentIframe",mi="initializeBaseRequest",fi="silentIframeClientTokenHelper",yi="silentHandlerInitiateAuthRequest",wi="silentHandlerMonitorIframeForHash",vi="standardInteractionClientCreateAuthCodeClient",Ci="standardInteractionClientGetClientConfiguration",Ii="standardInteractionClientInitializeAuthorizationRequest",bi="handleResponseEar",ki="handleResponsePlatformBroker",Si="handleResponseCode",Ti="deserializeResponse",Ai="removeHiddenIframe",_i="generatePkceCodes",Ei="generateHKDF",Pi="decrypt",xi="generateEarKey";function Oi(e){return encodeURIComponent(Mi(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"))}function Ri(e){return qi(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Mi(e){return qi((new TextEncoder).encode(e))}function qi(e){const t=Array.from(e,e=>String.fromCodePoint(e)).join("");return btoa(t)}function $i(e){return`See https://aka.ms/msal.js.errors#${e} for details`}class Ui extends Mn{constructor(e,t,r){super(e,t,$i(e),r),Object.setPrototypeOf(this,Ui.prototype),this.name="BrowserAuthError"}}function Li(e,t,r){return new Ui(e,t,r)}const Ni="pkce_not_created",Di="ear_jwk_empty",Hi="crypto_nonexistent",Fi="empty_navigate_uri",zi="no_state_in_hash",ji="unable_to_parse_state",Bi="user_cancelled",Ki="silent_logout_unsupported",Wi="non_browser_environment",Ji="database_not_open",Vi="no_network_connectivity",Gi="failed_to_parse_response",Qi="crypto_key_not_found",Yi="database_unavailable",Xi="native_connection_not_established",Zi="uninitialized_public_client_application",es="failed_to_decrypt_ear_response",ts="timed_out";function rs(e){return(new TextDecoder).decode(os(e))}function os(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 Li("invalid_base64_string","")}const r=atob(t);return Uint8Array.from(r,e=>e.codePointAt(0)||0)}const ns="AES-GCM",is="HKDF",ss="SHA-256",as=new Uint8Array([1,0,1]),cs="0123456789abcdef",ls=new Uint32Array(1),hs="raw",ds="encrypt",us="decrypt",gs={name:"RSASSA-PKCS1-v1_5",hash:ss,modulusLength:2048,publicExponent:as};async function ps(e){const t=(new TextEncoder).encode(e);return window.crypto.subtle.digest(ss,t)}function ms(e){return window.crypto.getRandomValues(e)}function fs(){return window.crypto.getRandomValues(ls),ls[0]}function ys(){const e=Date.now(),t=1024*fs()+(1023&fs()),r=new Uint8Array(16),o=Math.trunc(t/2**30),n=t&2**30-1,i=fs();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|o>>>8,r[7]=o,r[8]=128|n>>>24,r[9]=n>>>16,r[10]=n>>>8,r[11]=n,r[12]=i>>>24,r[13]=i>>>16,r[14]=i>>>8,r[15]=i;let s="";for(let e=0;e>>4),s+=cs.charAt(15&r[e]),3!==e&&5!==e&&7!==e&&9!==e||(s+="-");return s}async function ws(e){return window.crypto.subtle.exportKey("jwk",e)}async function vs(){const e=await Is(),t={alg:"dir",kty:"oct",k:Ri(new Uint8Array(e))};return Mi(JSON.stringify(t))}async function Cs(e,t){const r=t.split(".");if(5!==r.length)throw Li(es,"","jwe_length");const o=await async function(e){const t=rs(e),r=os(JSON.parse(t).k);return window.crypto.subtle.importKey(hs,r,ns,!1,[us])}(e).catch(()=>{throw Li(es,"","import_key")});try{const e=(new TextEncoder).encode(r[0]),t=os(r[2]),n=os(r[3]),i=os(r[4]),s=8*i.byteLength,a=new Uint8Array(n.length+i.length);a.set(n),a.set(i,n.length);const c=await window.crypto.subtle.decrypt({name:ns,iv:t,tagLength:s,additionalData:e},o,a);return(new TextDecoder).decode(c)}catch(e){throw Li(es,"","decrypt")}}async function Is(){const e=await window.crypto.subtle.generateKey({name:ns,length:256},!0,[ds,us]);return window.crypto.subtle.exportKey(hs,e)}async function bs(e){return window.crypto.subtle.importKey(hs,e,is,!1,["deriveKey"])}async function ks(e,t,r){return window.crypto.subtle.deriveKey({name:is,salt:t,hash:ss,info:(new TextEncoder).encode(r)},e,{name:ns,length:256},!1,[ds,us])}async function Ss(e,t,r){const o=(new TextEncoder).encode(t),n=window.crypto.getRandomValues(new Uint8Array(16)),i=await ks(e,n,r),s=await window.crypto.subtle.encrypt({name:ns,iv:new Uint8Array(12)},i,o);return{data:Ri(new Uint8Array(s)),nonce:Ri(n)}}async function Ts(e,t,r,o){const n=os(o),i=await ks(e,os(t),r),s=await window.crypto.subtle.decrypt({name:ns,iv:new Uint8Array(12)},i,n);return(new TextDecoder).decode(s)}class As{constructor(){this.dbName=kn,this.version=1,this.tableName=Sn,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(Li(Yi,"")))})}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(Li(Ji,""));const o=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).get(e);o.addEventListener("success",e=>{const r=e;this.closeConnection(),t(r.target.result)}),o.addEventListener("error",e=>{this.closeConnection(),r(e)})})}async setItem(e,t){return await this.validateDbIsOpen(),new Promise((r,o)=>{if(!this.db)return o(Li(Ji,""));const n=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).put(t,e);n.addEventListener("success",()=>{this.closeConnection(),r()}),n.addEventListener("error",e=>{this.closeConnection(),o(e)})})}async removeItem(e){return await this.validateDbIsOpen(),new Promise((t,r)=>{if(!this.db)return r(Li(Ji,""));const o=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).delete(e);o.addEventListener("success",()=>{this.closeConnection(),t()}),o.addEventListener("error",e=>{this.closeConnection(),r(e)})})}async getKeys(){return await this.validateDbIsOpen(),new Promise((e,t)=>{if(!this.db)return t(Li(Ji,""));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(Li(Ji,""));const o=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).count(e);o.addEventListener("success",e=>{const r=e;this.closeConnection(),t(1===r.target.result)}),o.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(kn),o=setTimeout(()=>t(!1),200);r.addEventListener("success",()=>(clearTimeout(o),e(!0))),r.addEventListener("blocked",()=>(clearTimeout(o),e(!0))),r.addEventListener("error",()=>(clearTimeout(o),t(!1)))})}}class _s{constructor(){this.cache=new Map}async initialize(){}getItem(e){return this.cache.get(e)||null}getUserData(e){return this.getItem(e)}setItem(e,t){this.cache.set(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){this.cache.delete(e)}getKeys(){const e=[];return this.cache.forEach((t,r)=>{e.push(r)}),e}containsKey(e){return this.cache.has(e)}clear(){this.cache.clear()}decryptData(){return Promise.resolve(null)}}class Es{constructor(e){this.inMemoryCache=new _s,this.indexedDBCache=new As,this.logger=e}handleDatabaseAccessError(e,t){if(!(e instanceof Ui&&e.errorCode===Yi))throw e;this.logger.error("1wx7zz",t)}async getItem(e,t){const r=this.inMemoryCache.getItem(e);if(!r)try{return this.logger.verbose("0naxpl",t),await this.indexedDBCache.getItem(e)}catch(e){this.handleDatabaseAccessError(e,t)}return r}async setItem(e,t,r){this.inMemoryCache.setItem(e,t);try{await this.indexedDBCache.setItem(e,t)}catch(e){this.handleDatabaseAccessError(e,r)}}async removeItem(e,t){this.inMemoryCache.removeItem(e);try{await this.indexedDBCache.removeItem(e)}catch(e){this.handleDatabaseAccessError(e,t)}}async getKeys(e){const t=this.inMemoryCache.getKeys();if(0===t.length)try{return this.logger.verbose("1iqrbq",e),await this.indexedDBCache.getKeys()}catch(t){this.handleDatabaseAccessError(t,e)}return t}async containsKey(e,t){const r=this.inMemoryCache.containsKey(e);if(!r)try{return this.logger.verbose("03zl2j",t),await this.indexedDBCache.containsKey(e)}catch(e){this.handleDatabaseAccessError(e,t)}return r}clearInMemory(e){this.logger.verbose("03r21p",e),this.inMemoryCache.clear(),this.logger.verbose("0uksk1",e)}async clearPersistent(e){try{this.logger.verbose("0rdqut",e);const t=await this.indexedDBCache.deleteDatabase();return t&&this.logger.verbose("149ouc",e),t}catch(t){return this.handleDatabaseAccessError(t,e),!1}}}class Ps{constructor(e,t,r){this.logger=e,function(e){if(!window)throw Li(Wi,"");if(!window.crypto)throw Li(Hi,"");if(!e&&!window.crypto.subtle)throw Li(Hi,"","crypto_subtle_undefined")}(r??!1),this.cache=new Es(this.logger),this.performanceClient=t}createNewGuid(){return ys()}base64Encode(e){return Mi(e)}base64Decode(e){return rs(e)}base64UrlEncode(e){return Oi(e)}encodeKid(e){return this.base64UrlEncode(JSON.stringify({kid:e}))}async getPublicKeyThumbprint(e){const t=this.performanceClient?.startMeasurement("cryptoOptsGetPublicKeyThumbprint",e.correlationId),r=await async function(e,t){return window.crypto.subtle.generateKey(gs,e,t)}(Ps.EXTRACTABLE,Ps.POP_KEY_USAGES),o=await ws(r.publicKey),n=xs({e:o.e,kty:o.kty,n:o.n}),i=await this.hashString(n),s=await ws(r.privateKey),a=await async function(e,t,r){return window.crypto.subtle.importKey("jwk",e,gs,t,r)}(s,!1,["sign"]);return await this.cache.setItem(i,{privateKey:a,publicKey:r.publicKey,requestMethod:e.resourceRequestMethod,requestUri:e.resourceRequestUri},e.correlationId),t&&t.end({success:!0}),i}async removeTokenBindingKey(e,t){await this.cache.removeItem(e,t);if(await this.cache.containsKey(e,t))throw Jn("binding_key_not_removed",t)}async clearKeystore(e){this.cache.clearInMemory(e);try{return await this.cache.clearPersistent(e),!0}catch(t){return t instanceof Error?this.logger.error(`1owpn8 ${t.message}`,e):this.logger.error("0yrmwo",e),!1}}async signJwt(e,t,r,o){const n=this.performanceClient?.startMeasurement("cryptoOptsSignJwt",o),i=await this.cache.getItem(t,o||"");if(!i)throw Li(Qi,o||"");const s=await ws(i.publicKey),a=xs(s),c=Oi(JSON.stringify({kid:t})),l=Oi(di.getShrHeaderString({...r?.header,alg:s.alg,kid:c}));e.cnf={jwk:JSON.parse(a)};const h=`${l}.${Oi(JSON.stringify(e))}`,d=(new TextEncoder).encode(h),u=await async function(e,t){return window.crypto.subtle.sign(gs,e,t)}(i.privateKey,d),g=`${h}.${Ri(new Uint8Array(u))}`;return n&&n.end({success:!0}),g}async hashString(e){return async function(e){const t=await ps(e);return Ri(new Uint8Array(t))}(e)}}function xs(e){return JSON.stringify(e,Object.keys(e).sort())}function Os(e,t){if(e){if(t.resource&&(Rs(t.extraParameters)||Rs(t.extraQueryParameters)))throw Jn("misplaced_resource_parameter",t.correlationId||"");if(!t.resource)throw Jn("resource_parameter_required",t.correlationId||"")}}function Rs(e){return!!e&&Object.prototype.hasOwnProperty.call(e,"resource")}Ps.POP_KEY_USAGES=["sign","verify"],Ps.EXTRACTABLE=!0;const Ms={createNewGuid:()=>{throw Jn(ci,"")},base64Decode:()=>{throw Jn(ci,"")},base64Encode:()=>{throw Jn(ci,"")},base64UrlEncode:()=>{throw Jn(ci,"")},encodeKid:()=>{throw Jn(ci,"")},async getPublicKeyThumbprint(){throw Jn(ci,"")},async removeTokenBindingKey(){throw Jn(ci,"")},async clearKeystore(){throw Jn(ci,"")},async signJwt(){throw Jn(ci,"")},async hashString(){throw Jn(ci,"")}},qs=0,$s=1,Us=2,Ls=3;class Ns extends Mn{constructor(e,t){super(e,t),this.name="ClientConfigurationError",Object.setPrototypeOf(this,Ns.prototype)}}function Ds(e,t){return new Ns(e,t)}class Hs{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("&"),o=e=>decodeURIComponent(e.replace(/\+/g," "));return r.forEach(e=>{if(e.trim()){const[r,n]=e.split(/=(.+)/g,2);r&&n&&(t[o(r)]=o(n))}}),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}}}const Fs="url_parse_error",zs="pkce_params_missing",js="invalid_cloud_discovery_metadata",Bs="missing_ssh_jwk",Ks="issuer_validation_failed";class Ws{get urlString(){return this._urlString}constructor(e,t){if(this._urlString=e,this.correlationId=t,!this._urlString)throw Ds("empty_url_error",t);e.includes("#")||(this._urlString=Ws.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return Hs.endsWith(t,"?")?t=t.slice(0,-1):Hs.endsWith(t,"?/")&&(t=t.slice(0,-2)),Hs.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch(e){throw Ds(Fs,this.correlationId)}if(!e.HostNameAndPort||!e.PathSegments)throw Ds(Fs,this.correlationId);if(!e.Protocol||"https:"!==e.Protocol.toLowerCase())throw Ds("authority_uri_insecure",this.correlationId)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return Ws.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),r=t.PathSegments;return!e||0===r.length||r[0]!==Hr&&r[0]!==Fr||(r[0]=e),Ws.constructAuthorityUriFromObject(t,this.correlationId)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw Ds(Fs,this.correlationId);const r={Protocol:t[1],HostNameAndPort:t[4],AbsolutePath:t[5],QueryString:t[7]};let o=r.AbsolutePath.split("/");return o=o.filter(e=>e&&e.length>0),r.PathSegments=o,r.QueryString&&r.QueryString.endsWith("/")&&(r.QueryString=r.QueryString.substring(0,r.QueryString.length-1)),r}static getDomainFromUrl(e,t){const r=RegExp("^([^:/?#]+://)?([^/?#]*)"),o=e.match(r);if(!o)throw Ds(Fs,t);return o[2]}static getAbsoluteUrl(e,t,r){if("/"===e[0]){const o=new Ws(t,r).getUrlComponents();return o.Protocol+"//"+o.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e,t){return new Ws(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"),t)}}const Js={endpointMetadata:[{host:"login.microsoftonline.com"},{host:"login.chinacloudapi.cn",issuerHost:"login.partner.microsoftonline.cn"},{host:"login.microsoftonline.us"},{host:"login.sovcloud-identity.fr"},{host:"login.sovcloud-identity.de"},{host:"login.sovcloud-identity.sg"}].reduce((e,{host:t,issuerHost:r})=>(e[t]=function(e,t){return{token_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/token`,jwks_uri:`https://${e}/{tenantid}/discovery/v2.0/keys`,issuer:`https://${t}/{tenantid}/v2.0`,authorization_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/authorize`,end_session_endpoint:`https://${e}/{tenantid}/oauth2/v2.0/logout`}}(t,r||t),e),{}),instanceDiscoveryMetadata:{metadata:[{preferred_network:"login.microsoftonline.com",preferred_cache:"login.windows.net",aliases:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"]},{preferred_network:"login.partner.microsoftonline.cn",preferred_cache:"login.partner.microsoftonline.cn",aliases:["login.partner.microsoftonline.cn","login.chinacloudapi.cn"]},{preferred_network:"login.microsoftonline.de",preferred_cache:"login.microsoftonline.de",aliases:["login.microsoftonline.de"]},{preferred_network:"login.microsoftonline.us",preferred_cache:"login.microsoftonline.us",aliases:["login.microsoftonline.us","login.usgovcloudapi.net"]},{preferred_network:"login-us.microsoftonline.com",preferred_cache:"login-us.microsoftonline.com",aliases:["login-us.microsoftonline.com"]},{preferred_network:"login.sovcloud-identity.fr",preferred_cache:"login.sovcloud-identity.fr",aliases:["login.sovcloud-identity.fr"]},{preferred_network:"login.sovcloud-identity.de",preferred_cache:"login.sovcloud-identity.de",aliases:["login.sovcloud-identity.de"]},{preferred_network:"login.sovcloud-identity.sg",preferred_cache:"login.sovcloud-identity.sg",aliases:["login.sovcloud-identity.sg"]},{preferred_network:"login.windows-ppe.net",preferred_cache:"login.windows-ppe.net",aliases:["login.windows-ppe.net","sts.windows-ppe.net","login.microsoft-ppe.com"]}]}},Vs=Js.endpointMetadata,Gs=Js.instanceDiscoveryMetadata,Qs=new Set;function Ys(e,t,r,o,n){if(e.trace(`1bmquz ${n}`,t),r&&o){const i=Xs(o,r);if(i)return e.trace(`1fotbt ${n}`,t),i.aliases;e.trace(`14avvj ${n}`,t)}return null}function Xs(e,t){for(let r=0;r{e.aliases.forEach(e=>{Qs.add(e)})});const Zs="AAD",ea="OIDC",ta="EAR",ra="none";const oa="networkClientSendPostRequestAsync",na="refreshTokenClientAcquireTokenWithCachedRefreshToken",ia="getAuthCodeUrl",sa="handleCodeResponseFromServer",aa="popTokenGenerateCnf",ca="handleServerTokenResponse",la="authorityUpdateMetadataWithRegionalInformation",ha="regionDiscoveryGetRegionFromIMDS",da=(e,t,r,o,n)=>(...i)=>{r.trace(`1plfzx ${t}`,n);const s=o.startMeasurement(t,n);n&&o.incrementFields({[`ext.${t}CallCount`]:1},n);try{const o=e(...i);return s.end({success:!0}),r.trace(`1g8n6a ${t}`,n),o}catch(e){r.trace(`0cfd8i ${t}`,n);try{r.trace(JSON.stringify(e),n)}catch(e){r.trace("00dty7",n)}throw s.end({success:!1},e),e}},ua=(e,t,r,o,n)=>(...i)=>{r.trace(`1plfzx ${t}`,n);const s=o.startMeasurement(t,n);return n&&o.incrementFields({[`ext.${t}CallCount`]:1},n),e(...i).then(e=>(r.trace(`1g8n6a ${t}`,n),s.end({success:!0}),e)).catch(e=>{r.trace(`0cfd8i ${t}`,n);try{r.trace(JSON.stringify(e),n)}catch(e){r.trace("00dty7",n)}throw s.end({success:!1},e),e})};class ga{constructor(e,t,r,o){this.networkInterface=e,this.logger=t,this.performanceClient=r,this.correlationId=o}async detectRegion(e,t){let r=e;if(r)t.region_source=Io;else{const e=ga.IMDS_OPTIONS;try{const o=await ua(this.getRegionFromIMDS.bind(this),ha,this.logger,this.performanceClient,this.correlationId)("2021-02-01",e);if(200===o.status&&(r=o.body?.location,r&&(t.region_source=bo)),400===o.status){const o=await ua(this.getCurrentVersion.bind(this),"regionDiscoveryGetCurrentVersion",this.logger,this.performanceClient,this.correlationId)(e);if(!o)return t.region_source=Co,null;const n=await ua(this.getRegionFromIMDS.bind(this),ha,this.logger,this.performanceClient,this.correlationId)(o,e);200===n.status&&(r=n.body?.location,r&&(t.region_source=bo))}}catch(e){return t.region_source=Co,null}}return r||(t.region_source=Co),r||null}async getRegionFromIMDS(e,t){return this.networkInterface.sendGetRequestAsync(`${_r}?api-version=${e}`,t,2e3)}async getCurrentVersion(e){try{const t=await this.networkInterface.sendGetRequestAsync(`${_r}?format=json`,e);return 400===t.status&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch(e){return null}}}function pa(e,t,r){const o=function(e,t){if(!e)throw Jn(Qn,t);const r=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(e);if(!r||r.length<4)throw Jn(Gn,t);return r[2]}(e,r);try{const e=t(o);return JSON.parse(e)}catch(e){throw Jn(Gn,r)}}function ma(e){if(!e.signin_state)return!1;const t=["kmsi","dvc_dmjd"];return e.signin_state.some(e=>t.includes(e.trim().toLowerCase()))}function fa(){return Math.round((new Date).getTime()/1e3)}function ya(e){return e.getTime()/1e3}function wa(e){return e?new Date(1e3*Number(e)):new Date}function va(e,t){const r=Number(e)||0;return fa()+t>r}function Ca(e,t){const r=Number(e)+24*t*60*60*1e3;return Date.now()>r}function Ia(e,t,r,o,n){return{credentialType:so.ID_TOKEN,homeAccountId:e,environment:t,clientId:o,secret:r,realm:n,lastUpdatedAt:Date.now().toString()}}function ba(e,t,r,o,n,i,s,a,c,l,h,d,u,g,p){const m={homeAccountId:e,credentialType:so.ACCESS_TOKEN,secret:r,cachedAt:fa().toString(),expiresOn:s.toString(),extendedExpiresOn:a.toString(),environment:t,clientId:o,realm:n,target:i,tokenType:d||wo.BEARER,lastUpdatedAt:Date.now().toString()};if(u&&(m.userAssertionHash=u),h&&(m.refreshOn=h.toString()),m.tokenType?.toLowerCase()!==wo.BEARER.toLowerCase())switch(m.credentialType=so.ACCESS_TOKEN_WITH_AUTH_SCHEME,m.tokenType){case wo.POP:const e=pa(r,c,l);if(!e?.cnf?.kid)throw Jn("token_claims_cnf_required_for_signedjwt",l);m.keyId=e.cnf.kid;break;case wo.SSH:m.keyId=g}return p&&Object.keys(p).length>0&&(m.additionalCacheKeyComponents=p),m}function ka(e){return e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("credentialType")&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("secret")}function Sa(e){return!!e&&(ka(e)&&e.hasOwnProperty("realm")&&e.hasOwnProperty("target")&&(e.credentialType===so.ACCESS_TOKEN||e.credentialType===so.ACCESS_TOKEN_WITH_AUTH_SCHEME))}function Ta(e){return!!e&&(ka(e)&&e.credentialType===so.REFRESH_TOKEN)}function Aa(){return fa()+86400}function _a(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 Ea(e,t,r){e.aliases=t.aliases,e.preferred_cache=t.preferred_cache,e.preferred_network=t.preferred_network,e.aliasesFromNetwork=r}function Pa(e){return e.expiresAt<=fa()}ga.IMDS_OPTIONS={headers:{Metadata:"true"}};class xa{constructor(e,t,r,o,n,i,s,a){this.canonicalAuthority=e,this._canonicalAuthority.validateAsUri(),this.networkInterface=t,this.cacheManager=r,this.authorityOptions=o,this.regionDiscoveryMetadata={region_used:void 0,region_source:void 0,region_outcome:void 0},this.logger=n,this.performanceClient=s,this.correlationId=i,this.managedIdentity=a||!1,this.regionDiscovery=new ga(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(vr))return Ls;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case"adfs":return $s;case"dstsv2":return Us}return qs}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 Ws(e,this.correlationId),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 Jn(Yn,this.correlationId)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw Jn(Yn,this.correlationId)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw Jn(Yn,this.correlationId)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw Jn("end_session_endpoint_not_supported",this.correlationId);return this.replacePath(this.metadata.end_session_endpoint)}throw Jn(Yn,this.correlationId)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw Jn(Yn,this.correlationId)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw Jn(Yn,this.correlationId)}canReplaceTenant(e){return 1===e.PathSegments.length&&!xa.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===qs&&this.protocolMode!==ea}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const r=new Ws(this.metadata.canonical_authority,this.correlationId).getUrlComponents(),o=r.PathSegments;return this.canonicalAuthorityUrlComponents.PathSegments.forEach((e,n)=>{let i=o[n];if(0===n&&this.canReplaceTenant(r)){const e=new Ws(this.metadata.authorization_endpoint,this.correlationId).getUrlComponents().PathSegments[0];i!==e&&(this.logger.verbose(`1q3g2x ${i} ${e}`,this.correlationId),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===$s||this.protocolMode===ea&&!this.isAliasOfKnownMicrosoftAuthority(e)?`${this.canonicalAuthority}.well-known/openid-configuration`:`${this.canonicalAuthority}v2.0/.well-known/openid-configuration`}discoveryComplete(){return!!this.metadata}async resolveEndpointsAsync(){const e=this.getCurrentMetadataEntity(),t=await ua(this.updateCloudDiscoveryMetadata.bind(this),"authorityUpdateCloudDiscoveryMetadata",this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const r=await ua(this.updateEndpointMetadata.bind(this),"authorityUpdateEndpointMetadata",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,this.correlationId);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:Aa(),jwks_uri:""}),e}updateCachedMetadata(e,t,r){t!==uo&&r?.source!==uo&&(e.expiresAt=Aa(),e.canonical_authority=this.canonicalAuthority);const o=this.cacheManager.generateAuthorityMetadataCacheKey(e.preferred_cache,this.correlationId);this.cacheManager.setAuthorityMetadata(o,e,this.correlationId),this.metadata=e}async updateEndpointMetadata(e){const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===po&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){_a(e,await ua(this.updateMetadataWithRegionalInformation.bind(this),la,this.logger,this.performanceClient,this.correlationId)(t.metadata),!1),e.canonical_authority=this.canonicalAuthority}return t.source}let r=await ua(this.getEndpointMetadataFromNetwork.bind(this),"authorityGetEndpointMetadataFromNetwork",this.logger,this.performanceClient,this.correlationId)();if(r)return this.validateIssuer(r.issuer),this.authorityOptions.azureRegionConfiguration?.azureRegion&&(r=await ua(this.updateMetadataWithRegionalInformation.bind(this),la,this.logger,this.performanceClient,this.correlationId)(r)),_a(e,r,!0),go;throw Jn("openid_config_error",this.defaultOpenIdConfigurationEndpoint,this.correlationId)}updateEndpointMetadataFromLocalSources(e){this.logger.verbose("1fi0kc",this.correlationId);const t=this.getEndpointMetadataFromConfig();if(t)return this.logger.verbose("06t0uj",this.correlationId),_a(e,t,!1),{source:ho};this.logger.verbose("151k0p",this.correlationId);const r=this.getEndpointMetadataFromHardcodedValues();if(r)return _a(e,r,!1),{source:po,metadata:r};this.logger.verbose("1imop5",this.correlationId);const o=Pa(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!o?(this.logger.verbose("16uq31",""),{source:uo}):(o&&this.logger.verbose("0uoibc",""),null)}isAuthoritySameType(e){return new Ws(e.canonical_authority,this.correlationId).getUrlComponents().PathSegments.length===this.canonicalAuthorityUrlComponents.PathSegments.length}getEndpointMetadataFromConfig(){if(this.authorityOptions.authorityMetadata)try{return JSON.parse(this.authorityOptions.authorityMetadata)}catch(e){throw Ds("invalid_authority_metadata",this.correlationId)}return null}async getEndpointMetadataFromNetwork(){const e={},t=this.defaultOpenIdConfigurationEndpoint;this.logger.verbose(`1y65x6 ${t}`,this.correlationId);try{const r=await this.networkInterface.sendGetRequestAsync(t,e),o=function(e){return e.hasOwnProperty("authorization_endpoint")&&e.hasOwnProperty("token_endpoint")&&e.hasOwnProperty("issuer")&&e.hasOwnProperty("jwks_uri")}(r.body);return o?r.body:(this.logger.verbose("1koyv8",this.correlationId),null)}catch(e){return this.logger.verbose(`0a9wik ${e}`,this.correlationId),null}}getEndpointMetadataFromHardcodedValues(){return this.hostnameAndPort in Vs?Vs[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if("TryAutoDetect"!==t)return this.regionDiscoveryMetadata.region_outcome=ko,this.regionDiscoveryMetadata.region_used=t,xa.replaceWithRegionalInformation(e,t,this.correlationId);const r=await ua(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),"regionDiscoveryDetectRegion",this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(r)return this.regionDiscoveryMetadata.region_outcome=So,this.regionDiscoveryMetadata.region_used=r,xa.replaceWithRegionalInformation(e,r,this.correlationId);this.regionDiscoveryMetadata.region_outcome=To}return e}async updateCloudDiscoveryMetadata(e){const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const r=await ua(this.getCloudDiscoveryMetadataFromNetwork.bind(this),"authorityGetCloudDiscoveryMetadataFromNetwork",this.logger,this.performanceClient,this.correlationId)();if(r)return Ea(e,r,!0),go;throw Ds("untrusted_authority",this.correlationId)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("1tpqlr",this.correlationId),this.logger.verbosePii(`1fy7uz ${this.authorityOptions.knownAuthorities||Tr}`,this.correlationId),this.logger.verbosePii(`08zabj ${this.authorityOptions.authorityMetadata||Tr}`,this.correlationId),this.logger.verbosePii(`1o1kv3 ${e.canonical_authority||Tr}`,this.correlationId);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("1nakio",this.correlationId),Ea(e,t,!1),ho;this.logger.verbose("1x74aj",this.correlationId);const r=(o=this.hostnameAndPort,Xs(Gs.metadata,o));var o;if(r)return this.logger.verbose("0by47c",this.correlationId),Ea(e,r,!1),po;this.logger.verbose("0r2fzy",this.correlationId);const n=Pa(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!n?(this.logger.verbose("1uffgh",""),uo):(n&&this.logger.verbose("0uoibc",""),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===Ls)return this.logger.verbose("04y84h",this.correlationId),xa.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);if(this.authorityOptions.cloudDiscoveryMetadata){this.logger.verbose("0gszr3",this.correlationId);try{this.logger.verbose("1iifkx",this.correlationId);const e=Xs(JSON.parse(this.authorityOptions.cloudDiscoveryMetadata).metadata,this.hostnameAndPort);if(this.logger.verbose("0q67e3",""),e)return this.logger.verbose("0hzfao",this.correlationId),e;this.logger.verbose("1ajz3u",this.correlationId)}catch(e){throw this.logger.verbose("1wq5tu",this.correlationId),Ds(js,this.correlationId)}}return this.isInKnownAuthorities(this.hostnameAndPort)?(this.logger.verbose("0mt9al",this.correlationId),xa.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){const e=`${wr}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let r=null;try{const o=await this.networkInterface.sendGetRequestAsync(e,t);let n,i;if(function(e){return e.hasOwnProperty("tenant_discovery_endpoint")&&e.hasOwnProperty("metadata")}(o.body))n=o.body,i=n.metadata,this.logger.verbosePii(`1vglyt ${n.tenant_discovery_endpoint}`,this.correlationId);else{if(!function(e){return e.hasOwnProperty("error")&&e.hasOwnProperty("error_description")}(o.body))return this.logger.error("0768g0",this.correlationId),null;if(this.logger.warning(`062uto ${o.status}`,this.correlationId),n=o.body,"invalid_instance"===n.error)return this.logger.error("1x90tm",this.correlationId),null;this.logger.warning(`0wchdm ${n.error}`,this.correlationId),this.logger.warning(`1s5mpv ${n.error_description}`,this.correlationId),this.logger.warning("1yhqpw",this.correlationId),i=[]}this.logger.verbose("1lrobr",this.correlationId),r=Xs(i,this.hostnameAndPort)}catch(e){if(e instanceof Mn)this.logger.error(`0vwhc7 ${e.errorCode} ${e.errorMessage}`,this.correlationId);else{const t=e;this.logger.error(`0s2z41 ${t.name} ${t.message}`,this.correlationId)}return null}return r||(this.logger.warning("0jp28q",this.correlationId),this.logger.verbose("130sd8",this.correlationId),r=xa.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),r}isInKnownAuthorities(e){const t=e.toLowerCase();return this.authorityOptions.knownAuthorities.filter(e=>e&&Ws.getDomainFromUrl(e,this.correlationId).toLowerCase()===t).length>0}static generateAuthority(e,t){let r;if(t&&t.azureCloudInstance!==ra){const e=t.tenant?t.tenant:yr;r=`${t.azureCloudInstance}/${e}/`}return r||e}static createCloudDiscoveryMetadataFromHost(e){return{preferred_network:e,preferred_cache:e,aliases:[e]}}getPreferredCache(){if(this.managedIdentity)return"login.microsoftonline.com";if(this.discoveryComplete())return this.metadata.preferred_cache;throw Jn(Yn,this.correlationId)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return Qs.has(e)}validateIssuer(e){if(!e)throw Ds(Ks,this.correlationId);let t;try{t=new URL(e)}catch{throw Ds(Ks,this.correlationId)}const r=t.protocol,o=t.host,n=(this.canonicalAuthorityUrlComponents.Protocol||"").toLowerCase(),i=(this.canonicalAuthorityUrlComponents.HostNameAndPort||"").toLowerCase(),s=this.matchesAuthorityOrigin(r,o,n,i),a="https:"===r&&this.isAliasOfKnownMicrosoftAuthority(o),c="https:"===r&&this.matchesRegionalMicrosoftHost(o),l=this.matchesCiamTenantPattern(t,i,this.canonicalAuthorityUrlComponents.PathSegments),h="https:"===r&&this.isInKnownAuthorities(o);if(!(s||a||c||l||h))throw Ds(Ks,this.correlationId)}matchesAuthorityOrigin(e,t,r,o){return e===r&&t===o}matchesRegionalMicrosoftHost(e){const t=e.indexOf(".");if(t>0&&te===c)}static isPublicCloudAuthority(e){return Er.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,r,o){const n=new Ws(e,r);n.validateAsUri();const i=n.getUrlComponents();let s=`${t}.${i.HostNameAndPort}`;this.isPublicCloudAuthority(i.HostNameAndPort)&&(s=`${t}.login.microsoft.com`);const a=Ws.constructAuthorityUriFromObject({...n.getUrlComponents(),HostNameAndPort:s},r).urlString;return o?`${a}?${o}`:a}static replaceWithRegionalInformation(e,t,r){const o={...e};return o.authorization_endpoint=xa.buildRegionalAuthorityString(o.authorization_endpoint,t,r),o.token_endpoint=xa.buildRegionalAuthorityString(o.token_endpoint,t,r),o.end_session_endpoint&&(o.end_session_endpoint=xa.buildRegionalAuthorityString(o.end_session_endpoint,t,r)),o}static transformCIAMAuthority(e,t){let r=e;const o=new Ws(e,t).getUrlComponents();if(0===o.PathSegments.length&&o.HostNameAndPort.endsWith(vr)){r=`${r}${o.HostNameAndPort.split(".")[0]}${Cr}`}return r}}function Oa(e){return e.endsWith("/")?e:`${e}/`}function Ra(e,t){if(!e)throw Jn("client_info_empty_error","");try{const r=t(e);return JSON.parse(r)}catch(e){throw Jn(Vn,"")}}function Ma(e){if(!e)throw Jn(Vn,"");const t=e.split(".",2);return{uid:t[0],utid:t.length<2?"":t[1]}}function qa(e,t){return!!e&&!!t&&e===t.split(".")[1]}function $a(e,t,r,o,n){if(n){const{oid:t,sub:r,tid:i,name:s,tfp:a,acr:c,preferred_username:l,upn:h,login_hint:d}=n,u=i||a||c||"";return{tenantId:u,localAccountId:t||r||"",name:s,username:l||h||"",loginHint:d,isHomeTenant:qa(u,e),upn:h,...o&&{nativeAccountId:o}}}return{tenantId:r,localAccountId:t,username:"",isHomeTenant:qa(r,e),...o&&{nativeAccountId:o}}}function Ua(e,t,r,o){let n=e;if(t){const{isHomeTenant:r,...o}=t;n={...e,...o}}if(r){const{isHomeTenant:t,...i}=$a(e.homeAccountId,e.localAccountId,e.tenantId,n.nativeAccountId,r);return n={...n,...i,idTokenClaims:r,idToken:o,kmsi:ma(r)},n}return n}function La(e){if(e){return e.tid||e.tfp||e.acr||null}return null}function Na(e){const t=e.tenantProfiles||[];0===t.length&&e.realm&&e.localAccountId&&t.push($a(e.homeAccountId,e.localAccountId,e.realm,e.nativeAccountId));const r=t.find(t=>t.tenantId===e.realm),o=r?.nativeAccountId||e.nativeAccountId;return{homeAccountId:e.homeAccountId,environment:e.environment,tenantId:e.realm,username:e.username,localAccountId:e.localAccountId,loginHint:e.loginHint,name:e.name,nativeAccountId:o,authorityType:e.authorityType,tenantProfiles:new Map(t.map(e=>[e.tenantId,e])),dataBoundary:e.dataBoundary}}function Da(e,t,r,o,n,i){if(t!==$s&&t!==Us){if(e)try{const t=Ra(e,o.base64Decode);if(t.uid&&t.utid)return`${t.uid}.${t.utid}`}catch(e){}r.warning("1ub6wv",n)}return i?.sub||""}function Ha(e,t,r){return{clientId:e,authority:t.authority,scopes:t.scopes,homeAccountIdentifier:r,claims:t.claims,authenticationScheme:t.authenticationScheme,resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,sshKid:t.sshKid,embeddedClientId:t.embeddedClientId||t.extraParameters?.clientId,resource:t.resource}}xa.reservedTenantDomains=new Set(["{tenant}","{tenantid}",Hr,zr,Fr]);const Fa="acquireTokenRedirect",za="cache_quota_exceeded";class ja extends Error{constructor(e,t){const r=t||Rn(e);super(r),Object.setPrototypeOf(this,ja.prototype),this.name="CacheError",this.errorCode=e,this.errorMessage=r}}function Ba(e){return e instanceof Error?"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||e.message.includes("exceeded the quota")?new ja(za):new ja(e.name,e.message):new ja("cache_error_unknown")}const Ka="@azure/msal-common",Wa="16.11.0";class Ja{constructor(e,t){this.correlationId=t;const r=e?Hs.trimArrayEntries([...e]):[],o=r?Hs.removeEmptyStringsFromArray(r):[];if(!o||!o.length)throw Ds("empty_input_scopes_error",t);this.scopes=new Set,o.forEach(e=>this.scopes.add(e))}static fromString(e,t){const r=(e||"").split(" ");return new Ja(r,t)}static createSearchScopes(e,t){const r=e&&e.length>0?e:[...Or],o=new Ja(r,t);return o.containsOnlyOIDCScopes()?o.removeScope(kr):o.removeOIDCScopes(),o}containsScope(e){const t=this.printScopesLowerCase().split(" "),r=new Ja(t,this.correlationId);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 Rr.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 Jn("cannot_append_scopeset",this.correlationId)}}removeScope(e){if(!e)throw Jn("cannot_remove_empty_scope",this.correlationId);this.scopes.delete(e.trim())}removeOIDCScopes(){Rr.forEach(e=>{this.scopes.delete(e)})}unionScopeSets(e){if(!e)throw Jn(ti,this.correlationId);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 Jn(ti,this.correlationId);e.containsOnlyOIDCScopes()||e.removeOIDCScopes();const t=this.unionScopeSets(e),r=e.getScopeCount(),o=this.getScopeCount();return t.sizee.push(t)),e}printScopes(){if(this.scopes){return this.asArray().join(" ")}return""}printScopesLowerCase(){return this.printScopes().toLowerCase()}}class Va{constructor(e,t,r,o,n){this.clientId=e,this.cryptoImpl=t,this.commonLogger=r.clone(Ka,Wa),this.staticAuthorityOptions=n,this.performanceClient=o}getAllAccounts(e={},t){return this.buildTenantProfiles(this.getAccountsFilteredBy(e,t),t,e)}getAccountInfoFilteredBy(e,t){if(0===Object.keys(e).length||Object.values(e).every(e=>null==e||""===e))return this.commonLogger.warning("1skb02",t),null;const r=this.getAllAccounts(e,t);if(r.length>1){return r.sort((e,t)=>{const r=e.idTokenClaims?1:0;return(t.idTokenClaims?1:0)-r})[0]}return 1===r.length?r[0]:null}getBaseAccountInfo(e,t){const r=this.getAccountsFilteredBy(e,t);return r.length>0?Na(r[0]):null}buildTenantProfiles(e,t,r){return e.flatMap(e=>this.getTenantProfilesFromAccountEntity(e,t,r?.tenantId,r))}getTenantedAccountInfoByFilter(e,t,r,o,n){let i,s=null;if(n&&!this.tenantProfileMatchesFilter(r,n))return null;const a=this.getIdToken(e,o,t,r.tenantId);return a&&(i=pa(a.secret,this.cryptoImpl.base64Decode,o),!this.idTokenClaimsMatchTenantProfileFilter(i,n))?null:(s=Ua(e,r,i,a?.secret),s)}getTenantProfilesFromAccountEntity(e,t,r,o){const n=Na(e);let i=n.tenantProfiles||new Map;const s=this.getTokenKeys();if(r){const e=i.get(r);if(!e)return[];i=new Map([[r,e]])}const a=[];return i.forEach(e=>{const r=this.getTenantedAccountInfoByFilter(n,s,e,t,o);r&&a.push(r)}),a}tenantProfileMatchesFilter(e,t){return!(t.localAccountId&&!this.matchLocalAccountIdFromTenantProfile(e,t.localAccountId))&&((!t.name||e.name===t.name)&&((void 0===t.isHomeTenant||e.isHomeTenant===t.isHomeTenant)&&(!(t.username&&!this.matchUsername(e.username,t.username)&&!this.matchUsername(e.upn,t.username))&&(!(t.loginHint&&!this.matchLoginHintWithTenantProfile(e,t.loginHint))&&((!t.upn||e.upn===t.upn)&&(!t.nativeAccountId||e.nativeAccountId===t.nativeAccountId))))))}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)&&!this.matchUsername(e.upn,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,o,n){if(!e)throw Jn("invalid_cache_record",t);try{e.account&&await this.setAccount(e.account,t,r,o),e.idToken&&!1!==n?.idToken&&await this.setIdTokenCredential(e.idToken,t,r),e.accessToken&&!1!==n?.accessToken&&await this.saveAccessToken(e.accessToken,t,r),e.refreshToken&&!1!==n?.refreshToken&&await this.setRefreshTokenCredential(e.refreshToken,t,r),e.appMetadata&&this.setAppMetadata(e.appMetadata,t)}catch(e){throw this.commonLogger?.error("0j476p",t),e instanceof Mn?e:Ba(e)}}async saveAccessToken(e,t,r){const o={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType},n=this.getTokenKeys(),i=Ja.fromString(e.target,t);n.accessToken.forEach(e=>{if(!this.accessTokenKeyMatchesFilter(e,o,!1))return;const r=this.getAccessTokenCredential(e,t);if(r&&this.credentialMatchesFilter(r,o,t)){Ja.fromString(r.target,t).intersectingScopeSets(i)&&this.removeAccessToken(e,t)}}),await this.setAccessTokenCredential(e,t,r)}getAccountsFilteredBy(e,t){const r=this.getAccountKeys(),o=[];return r.forEach(r=>{const n=this.getAccount(r,t);if(!n)return;if(e.homeAccountId&&!this.matchHomeAccountId(n,e.homeAccountId))return;if(e.environment&&!this.matchEnvironment(n,e.environment,t))return;if(e.realm&&!this.matchRealm(n,e.realm))return;if(e.authorityType&&!this.matchAuthorityType(n,e.authorityType))return;const i={localAccountId:e?.localAccountId,name:e?.name,username:e?.username,loginHint:e?.loginHint,upn:e?.upn,nativeAccountId:e?.nativeAccountId},s=n.tenantProfiles?.filter(e=>this.tenantProfileMatchesFilter(e,i));s&&0===s.length||o.push(n)}),o}credentialMatchesFilter(e,t,r){if(t.clientId&&!this.matchClientId(e,t.clientId))return!1;if(t.userAssertionHash&&!this.matchUserAssertionHash(e,t.userAssertionHash))return!1;if("string"==typeof t.homeAccountId&&!this.matchHomeAccountId(e,t.homeAccountId))return!1;if(t.environment&&!this.matchEnvironment(e,t.environment,r))return!1;if(t.realm&&!this.matchRealm(e,t.realm))return!1;if(t.credentialType&&!this.matchCredentialType(e,t.credentialType))return!1;if(t.familyId&&!this.matchFamilyId(e,t.familyId))return!1;if(t.target&&!this.matchTarget(e,t.target,r))return!1;if(e.credentialType===so.ACCESS_TOKEN_WITH_AUTH_SCHEME){if(t.tokenType&&!this.matchTokenType(e,t.tokenType))return!1;if(t.tokenType===wo.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId))return!1}const o=e.additionalCacheKeyComponents,n=t.additionalCacheKeyComponents,i=!!o&&Object.keys(o).length>0,s=!!n&&Object.keys(n).length>0;if(i!==s)return!1;if(i&&s){const e=Object.keys(o).sort(),t=Object.keys(n).sort();if(e.length!==t.length)return!1;for(let r=0;r{if(!this.isAppMetadata(r))return;const n=this.getAppMetadata(r,t);n&&(e.environment&&!this.matchEnvironment(n,e.environment,t)||e.clientId&&!this.matchClientId(n,e.clientId)||(o[r]=n))}),o}getAuthorityMetadataByAlias(e,t){const r=this.getAuthorityMetadataKeys();let o=null;return r.forEach(r=>{if(!this.isAuthorityMetadata(r)||-1===r.indexOf(this.clientId))return;const n=this.getAuthorityMetadata(r,t);n&&-1!==n.aliases.indexOf(e)&&(o=n)}),o}removeAllAccounts(e){this.getAllAccounts({},e).forEach(t=>{this.removeAccount(t,e)})}removeAccount(e,t){this.removeAccountContext(e,t);this.getAccountKeys().filter(t=>t.includes(e.homeAccountId)&&t.includes(e.environment)).forEach(e=>{this.removeItem(e,t),this.performanceClient.incrementFields({accountsRemoved:1},t)})}removeAccountContext(e,t){const r=this.getTokenKeys(),o=t=>t.includes(e.homeAccountId)&&t.includes(e.environment);r.idToken.filter(o).forEach(e=>{this.removeIdToken(e,t)}),r.accessToken.filter(o).forEach(e=>{this.removeAccessToken(e,t)}),r.refreshToken.filter(o).forEach(e=>{this.removeRefreshToken(e,t)})}removeAccessToken(e,t){const r=this.getAccessTokenCredential(e,t);if(r&&(this.removeItem(e,t),this.performanceClient.incrementFields({accessTokensRemoved:1},t),r.credentialType.toLowerCase()===so.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()&&r.tokenType===wo.POP)){const e=r.keyId;e&&this.cryptoImpl.removeTokenBindingKey(e,t).catch(()=>{this.commonLogger.error(`0cx291 ${e}`,t),this.performanceClient?.incrementFields({removeTokenBindingKeyFailure:1},t)})}}removeAppMetadata(e){return this.getKeys().forEach(t=>{this.isAppMetadata(t)&&this.removeItem(t,e)}),!0}getIdToken(e,t,r,o){this.commonLogger.trace("1drz22",t);const n={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:so.ID_TOKEN,clientId:this.clientId,realm:o},i=this.getIdTokensByFilter(n,t,r),s=i.size;if(s<1)return this.commonLogger.info("1atvtd",t),null;if(s>1){let r=i;if(!o){const o=new Map;i.forEach((t,r)=>{t.realm===e.tenantId&&o.set(r,t)});const n=o.size;if(n<1)return this.commonLogger.info("0ooalx",t),i.values().next().value??null;if(1===n)return this.commonLogger.info("1eq2vc",t),o.values().next().value??null;r=o}return this.commonLogger.info("1ws328",t),r.forEach((e,r)=>{this.removeIdToken(r,t)}),this.performanceClient.addFields({multiMatchedID:i.size},t),null}return this.commonLogger.info("1sm769",t),i.values().next().value??null}getIdTokensByFilter(e,t,r){const o=r&&r.idToken||this.getTokenKeys().idToken,n=new Map;return o.forEach(r=>{if(!this.idTokenKeyMatchesFilter(r,{clientId:this.clientId,...e}))return;const o=this.getIdTokenCredential(r,t);o&&this.credentialMatchesFilter(o,e,t)&&n.set(r,o)}),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,t){this.removeItem(e,t)}removeRefreshToken(e,t){this.removeItem(e,t)}getAccessToken(e,t,r,o){const n=t.correlationId;this.commonLogger.trace("1t7hz1",n);const i=Ja.createSearchScopes(t.scopes,n),s=t.authenticationScheme||wo.BEARER,a=s&&s.toLowerCase()!==wo.BEARER.toLowerCase()?so.ACCESS_TOKEN_WITH_AUTH_SCHEME:so.ACCESS_TOKEN,c={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:a,clientId:this.clientId,realm:o||e.tenantId,target:i,tokenType:s,keyId:t.sshKid},l=r&&r.accessToken||this.getTokenKeys().accessToken,h=[];l.forEach(e=>{if(this.accessTokenKeyMatchesFilter(e,c,!0)){const t=this.getAccessTokenCredential(e,n);t&&this.credentialMatchesFilter(t,c,n)&&h.push(t)}});const d=h.length;return d<1?(this.commonLogger.info("1nckna",n),null):d>1?(this.commonLogger.info("1wkfwp",n),h.forEach(e=>{this.removeAccessToken(this.generateCredentialKey(e),n)}),this.performanceClient.addFields({multiMatchedAT:h.length},n),null):(this.commonLogger.info("06yt98",n),h[0])}accessTokenKeyMatchesFilter(e,t,r){const o=e.toLowerCase();if(t.clientId&&-1===o.indexOf(t.clientId.toLowerCase()))return!1;if(t.homeAccountId&&-1===o.indexOf(t.homeAccountId.toLowerCase()))return!1;if(t.realm&&-1===o.indexOf(t.realm.toLowerCase()))return!1;if(t.target){const e=t.target.asArray();for(let t=0;t{if(!this.accessTokenKeyMatchesFilter(r,e,!0))return;const n=this.getAccessTokenCredential(r,t);n&&this.credentialMatchesFilter(n,e,t)&&o.push(n)}),o}getRefreshToken(e,t,r,o){this.commonLogger.trace("0x53vi",r);const n=t?co:void 0,i={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:so.REFRESH_TOKEN,clientId:this.clientId,familyId:n},s=o&&o.refreshToken||this.getTokenKeys().refreshToken,a=[];s.forEach(e=>{if(this.refreshTokenKeyMatchesFilter(e,i)){const t=this.getRefreshTokenCredential(e,r);t&&this.credentialMatchesFilter(t,i,r)&&a.push(t)}});const c=a.length;return c<1?(this.commonLogger.info("0dlw11",r),null):(c>1&&this.performanceClient.addFields({multiMatchedRT:c},r),this.commonLogger.info("0wcnep",r),a[0])}refreshTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.familyId||-1!==r.indexOf(t.familyId.toLowerCase()))&&(!(!t.familyId&&t.clientId&&-1===r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase())))}readAppMetadataFromCache(e,t){const r={environment:e,clientId:this.clientId},o=this.getAppMetadataFilteredBy(r,t),n=Object.keys(o).map(e=>o[e]),i=n.length;if(i<1)return null;if(i>1)throw Jn("multiple_matching_appMetadata",t);return n[0]}isAppMetadataFOCI(e,t){const r=this.readAppMetadataFromCache(e,t);return!(!r||r.familyId!==co)}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())}matchLoginHintWithTenantProfile(e,t){return e.loginHint===t||e.username===t||e.upn===t}matchUserAssertionHash(e,t){return!(!e.userAssertionHash||t!==e.userAssertionHash)}matchEnvironment(e,t,r){if(this.staticAuthorityOptions){const o=function(e,t,r){let o;const n=e.canonicalAuthority;if(n){const i=new Ws(n,r).getUrlComponents().HostNameAndPort;o=Ys(t,r,i,e.cloudDiscoveryMetadata?.metadata,ho)||Ys(t,r,i,Gs.metadata,po)||e.knownAuthorities}return o||[]}(this.staticAuthorityOptions,this.commonLogger,r);if(o.includes(t)&&o.includes(e.environment))return!0}const o=this.getAuthorityMetadataByAlias(t,r);return!!(o&&o.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())}matchLoginHintFromTokenClaims(e,t){return e.login_hint===t||(e.preferred_username===t||(e.upn===t||!(!e.emails||!e.emails.includes(t))))}matchSid(e,t){return e.sid===t}matchAuthorityType(e,t){return!(!e.authorityType||t.toLowerCase()!==e.authorityType.toLowerCase())}matchTarget(e,t,r){if(e.credentialType!==so.ACCESS_TOKEN&&e.credentialType!==so.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target)return!1;return Ja.fromString(e.target,r).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(ao)}isAuthorityMetadata(e){return-1!==e.indexOf(lo)}generateAuthorityMetadataCacheKey(e){return`${lo}-${this.clientId}-${e}`}static toObject(e,t){for(const r in t)e[r]=t[r];return e}}class Ga extends Va{async setAccount(){throw Jn(ci,"")}getAccount(){throw Jn(ci,"")}async setIdTokenCredential(){throw Jn(ci,"")}getIdTokenCredential(){throw Jn(ci,"")}async setAccessTokenCredential(){throw Jn(ci,"")}getAccessTokenCredential(){throw Jn(ci,"")}async setRefreshTokenCredential(){throw Jn(ci,"")}getRefreshTokenCredential(){throw Jn(ci,"")}setAppMetadata(){throw Jn(ci,"")}getAppMetadata(){throw Jn(ci,"")}setServerTelemetry(){throw Jn(ci,"")}getServerTelemetry(){throw Jn(ci,"")}setAuthorityMetadata(){throw Jn(ci,"")}getAuthorityMetadata(){throw Jn(ci,"")}getAuthorityMetadataKeys(){throw Jn(ci,"")}setThrottlingCache(){throw Jn(ci,"")}getThrottlingCache(){throw Jn(ci,"")}removeItem(){throw Jn(ci,"")}getKeys(){throw Jn(ci,"")}getAccountKeys(){throw Jn(ci,"")}getTokenKeys(){throw Jn(ci,"")}generateCredentialKey(){throw Jn(ci,"")}generateAccountKey(){throw Jn(ci,"")}}const Qa="msal",Ya="browser",Xa=`${Qa}.${Ya}.log.level`,Za=`${Qa}.${Ya}.log.pii`,ec=`${Qa}.version`,tc="account.keys",rc="token.keys",oc=`${Qa}.${Ya}.sso.capable`;function nc(e=3){return e<1?`${Qa}.${tc}`:`${Qa}.${e}.${tc}`}function ic(e,t=3){return t<1?`${Qa}.${rc}.${e}`:`${Qa}.${t}.${rc}.${e}`}class sc extends Mn{constructor(e,t,r){super(e,t,r),this.name="BrowserConfigurationAuthError",Object.setPrototypeOf(this,sc.prototype)}}function ac(e,t){return new sc(e,t,$i(e))}const cc=864e5,lc="Lax",hc="None";class dc{initialize(){return Promise.resolve()}getItem(e){const t=encodeURIComponent(e),r=document.cookie.split(";");for(let e=0;e{const r=e.trim(),o=r.indexOf("="),n=-1===o?r:r.substring(0,o);try{t.push(decodeURIComponent(n))}catch{}}),t}containsKey(e){return this.getKeys().includes(e)}decryptData(){return Promise.resolve(null)}}function uc(e,t){const r=e.getItem(nc(t));return r?JSON.parse(r):[]}function gc(e,t,r){const o=t.getItem(ic(e,r));if(o){const e=JSON.parse(o);if(e&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("accessToken")&&e.hasOwnProperty("refreshToken"))return e}return{idToken:[],accessToken:[],refreshToken:[]}}function pc(e){return e.hasOwnProperty("id")&&e.hasOwnProperty("nonce")&&e.hasOwnProperty("data")}const mc="storage_not_supported",fc="msal.cache.encryption";class yc{constructor(e,t,r){if(!window.localStorage)throw ac(mc,"");this.memoryStorage=new _s,this.initialized=!1,this.clientId=e,this.logger=t,this.performanceClient=r,this.broadcast=new BroadcastChannel("msal.broadcast.cache")}async initialize(e){const t=new dc,r=t.getItem(fc);let o={key:"",id:""};if(r)try{o=JSON.parse(r)}catch(e){}if(o.key&&o.id){const t=da(os,"base64Decode",this.logger,this.performanceClient,e)(o.key);this.encryptionCookie={id:o.id,key:await ua(bs,Ei,this.logger,this.performanceClient,e)(t)}}else{const r=ys(),o=await ua(Is,"generateBaseKey",this.logger,this.performanceClient,e)(),n=da(Ri,"urlEncodeArr",this.logger,this.performanceClient,e)(new Uint8Array(o));this.encryptionCookie={id:r,key:await ua(bs,Ei,this.logger,this.performanceClient,e)(o)};const i={id:r,key:n};t.setItem(fc,JSON.stringify(i),0,!0,hc)}await ua(this.importExistingCache.bind(this),"importExistingCache",this.logger,this.performanceClient,e)(e),this.broadcast.addEventListener("message",t=>{this.updateCache(t,e)}),this.initialized=!0}getItem(e){return window.localStorage.getItem(e)}getUserData(e){if(!this.initialized)throw Li(Zi,"");return this.memoryStorage.getItem(e)}async decryptData(e,t,r){if(!this.initialized||!this.encryptionCookie)throw Li(Zi,"");if(t.id!==this.encryptionCookie.id)return this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},r),null;const o=await ua(Ts,Pi,this.logger,this.performanceClient,r)(this.encryptionCookie.key,t.nonce,this.getContext(e),t.data);if(!o)return null;try{return{...JSON.parse(o),lastUpdatedAt:t.lastUpdatedAt}}catch(e){return this.performanceClient.incrementFields({encryptedCacheCorruptionCount:1},r),null}}setItem(e,t){window.localStorage.setItem(e,t)}async setUserData(e,t,r,o,n){if(!this.initialized||!this.encryptionCookie)throw Li(Zi,"");if(n)this.setItem(e,t);else{const{data:n,nonce:i}=await ua(Ss,"encrypt",this.logger,this.performanceClient,r)(this.encryptionCookie.key,t,this.getContext(e)),s={id:this.encryptionCookie.id,nonce:i,data:n,lastUpdatedAt:o};this.setItem(e,JSON.stringify(s))}this.memoryStorage.setItem(e,t),this.broadcast.postMessage({key:e,value:t,context:this.getContext(e)})}removeItem(e){this.memoryStorage.containsKey(e)&&(this.memoryStorage.removeItem(e),this.broadcast.postMessage({key:e,value:null,context:this.getContext(e)})),window.localStorage.removeItem(e)}getKeys(){return Object.keys(window.localStorage)}containsKey(e){return window.localStorage.hasOwnProperty(e)}clear(){this.memoryStorage.clear();uc(this).forEach(e=>this.removeItem(e));const e=gc(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(Qa)||-1!==e.indexOf(this.clientId))&&this.removeItem(e)})}async importExistingCache(e){if(!this.encryptionCookie)return;let t=uc(this);t=await this.importArray(t,e),t.length?this.setItem(nc(),JSON.stringify(t)):this.removeItem(nc());const r=gc(this.clientId,this);r.idToken=await this.importArray(r.idToken,e),r.accessToken=await this.importArray(r.accessToken,e),r.refreshToken=await this.importArray(r.refreshToken,e),r.idToken.length||r.accessToken.length||r.refreshToken.length?this.setItem(ic(this.clientId),JSON.stringify(r)):this.removeItem(ic(this.clientId))}async getItemFromEncryptedCache(e,t){if(!this.encryptionCookie)return null;const r=this.getItem(e);if(!r)return null;let o;try{o=JSON.parse(r)}catch(e){return null}return pc(o)?o.id!==this.encryptionCookie.id?(this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},t),null):(this.performanceClient.incrementFields({encryptedCacheCount:1},t),ua(Ts,Pi,this.logger,this.performanceClient,t)(this.encryptionCookie.key,o.nonce,this.getContext(e),o.data)):(this.performanceClient.incrementFields({unencryptedCacheCount:1},t),r)}async importArray(e,t){const r=[],o=[];return e.forEach(e=>{const n=this.getItemFromEncryptedCache(e,t).then(t=>{t?(this.memoryStorage.setItem(e,t),r.push(e)):this.removeItem(e)});o.push(n)}),await Promise.all(o),r}getContext(e){let t="";return e.includes(this.clientId)&&(t=this.clientId),t}updateCache(e,t){this.logger.trace("17cxcm",t);const r=this.performanceClient.startMeasurement("localStorageUpdated");r.add({isBackground:!0});const{key:o,value:n,context:i}=e.data;return o?i&&i!==this.clientId?(this.logger.trace(`04rtdy ${i}`,t),void r.end({success:!1,errorCode:"contextMismatch"})):(n?(this.memoryStorage.setItem(o,n),this.logger.verbose("1vzsgt",t)):(this.memoryStorage.removeItem(o),this.logger.verbose("04ypih",t)),void r.end({success:!0})):(this.logger.error("0e10qr",t),void r.end({success:!1,errorCode:"noKey"}))}}class wc{constructor(){if(!window.sessionStorage)throw ac(mc,"")}async initialize(){}getItem(e){return window.sessionStorage.getItem(e)}getUserData(e){return this.getItem(e)}setItem(e,t){window.sessionStorage.setItem(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){window.sessionStorage.removeItem(e)}getKeys(){return Object.keys(window.sessionStorage)}containsKey(e){return window.sessionStorage.hasOwnProperty(e)}decryptData(){return Promise.resolve(null)}}const vc="msal:initializeStart",Cc="msal:initializeEnd",Ic="msal:activeAccountChanged",bc="msal:loginSuccess",kc="msal:acquireTokenStart",Sc="msal:acquireTokenSuccess",Tc="msal:acquireTokenFailure",Ac="msal:acquireTokenFromNetworkStart",_c="msal:handleRedirectStart",Ec="msal:handleRedirectEnd",Pc="msal:popupOpened",xc="msal:logoutStart",Oc="msal:logoutSuccess",Rc="msal:logoutFailure",Mc="msal:logoutEnd",qc="msal:restoreFromBFCache";function $c(e,t,r,o){const n=function(e,t,r){if(!e)throw Jn(ii,t);const o={id:e.createNewGuid()};r&&(o.meta=r);const n=JSON.stringify(o);return e.base64Encode(n)}(e,o,r);return t?`${n}|${t}`:n}function Uc(e,t,r){if(!e)throw Jn(ii,r);if(!t)throw Jn(Zn,r);try{const r=t.split("|"),o=r[0],n=r.length>1?r.slice(1).join("|"):"",i=e(o);return{userRequestState:n||"",libraryState:JSON.parse(i)}}catch(e){throw Jn(Zn,r)}}function Lc(e){return e.startsWith("#/")?e.substring(2):e.startsWith("#")||e.startsWith("?")?e.substring(1):e}function Nc(e){if(!e||e.indexOf("=")<0)return null;try{const t=Lc(e),r=Object.fromEntries(new URLSearchParams(t));if(r.code||r.ear_jwe||r.error||r.error_description||r.state)return r}catch(e){throw Jn("hash_not_deserialized","")}return null}function Dc(e){const t=new Array;return e.forEach((e,r)=>{t.push(`${r}=${encodeURIComponent(e)}`)}),t.join("&")}function Hc(e,t,r){if(!e)return e;const o=e.split("#")[0];if(!o)return o;try{const e=new URL(o);let t;e.search||(e.search="");try{t=decodeURIComponent(e.pathname)}catch(r){t=e.pathname}return t.endsWith("/")||(t+="/"),e.pathname=t,e.href}catch(e){throw t?.error(`15apdm ${e}`,r||""),Ds(Fs,r||"")}}const Fc="client_id",zc="redirect_uri",jc="token_type",Bc="req_cnf",Kc="return_spa_code",Wc="x-client-xtra-sku",Jc="brk_client_id",Vc="brk_redirect_uri",Gc="instance_aware";function Qc(e,t,r){if(!t)return;const o=e.get(Fc);o&&e.has(Jc)&&r?.addFields({embeddedClientId:o,embeddedRedirectUri:e.get(zc)},t)}function Yc(e,t){e.set("response_type",t)}function Xc(e,t,r,o=!0,n=Or){!o||n.includes("openid")||t.includes("openid")||n.push("openid");const i=o?[...t||[],...n]:t||[],s=new Ja(i,r);e.set("scope",s.printScopes())}function Zc(e,t){e.set(Fc,t)}function el(e,t){e.set(zc,t)}function tl(e,t){e.set("login_hint",t)}function rl(e,t){e.set(Ur,`UPN:${t}`)}function ol(e,t){e.set(Ur,`Oid:${t.uid}@${t.utid}`)}function nl(e,t){e.set("sid",t)}function il(e,t,r,o,n){const i=vl(r,n&&e.has(Jc)?void 0:o,t);e.set("claims",i)}function sl(e,t){e.set("client-request-id",t)}function al(e,t){e.set("x-client-SKU",t.sku),e.set("x-client-VER",t.version),t.os&&e.set("x-client-OS",t.os),t.cpu&&e.set("x-client-CPU",t.cpu)}function cl(e,t){t?.appName&&e.set("x-app-name",t.appName),t?.appVersion&&e.set("x-app-ver",t.appVersion)}function ll(e,t){t&&e.set("state",t)}function hl(e,t,r){if(!t||!r)throw Ds(zs,"");e.set("code_challenge",t),e.set("code_challenge_method",r)}function dl(e,t){e.set("client_secret",t)}function ul(e,t){t&&e.set("client_assertion",t)}function gl(e,t){t&&e.set("client_assertion_type",t)}function pl(e,t){e.set("grant_type",t)}function ml(e){e.set("client_info","1")}function fl(e){e.has(Gc)||e.set(Gc,"true")}function yl(e,t){Object.entries(t).forEach(([t,r])=>{!e.has(t)&&r&&e.set(t,r)})}const wl={[Wr]:{essential:!1},[Jr]:{essential:!1}};function vl(e,t,r=""){let o;if(e)try{const t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))throw new Error("Claims must be a JSON object");o=t}catch(e){throw Ds("invalid_claims",r)}else o={};Object.prototype.hasOwnProperty.call(o,Kr)||(o[Kr]={});const n=o[Kr];for(const[e,t]of Object.entries(wl))e in n||(n[e]=t);return t&&t.length>0&&(Object.prototype.hasOwnProperty.call(o,jr)||(o[jr]={}),o[jr][Br]={values:t}),JSON.stringify(o)}function Cl(e,t){t&&(e.set(jc,wo.POP),e.set(Bc,t))}function Il(e,t){t&&(e.set(jc,wo.SSH),e.set(Bc,t))}function bl(e,t){e.set("x-client-current-telemetry",t.generateCurrentRequestHeaderValue()),e.set("x-client-last-telemetry",t.generateLastRequestHeaderValue())}function kl(e){e.set("x-ms-lib-capability","retry-after, h429")}function Sl(e,t,r){e.has(Jc)||e.set(Jc,t),e.has(Vc)||e.set(Vc,r)}function Tl(e,t){t&&e.set("resource",t)}function Al(e){e.location.hash="","function"==typeof e.history.replaceState&&e.history.replaceState(null,"",`${e.location.origin}${e.location.pathname}${e.location.search}`)}function _l(){return window.parent!==window}function El(){if(_l())return!1;try{const{libraryState:e}=function(){const e=window.location.hash,t=window.location.search;let r,o=!1,n=!1,i="";if(e&&e.length>1){const t="#"===e.charAt(0)?e.substring(1):e,n=new URLSearchParams(t);n.has("state")&&(o=!0,i=t,r=n)}if(t&&t.length>1){const e="?"===t.charAt(0)?t.substring(1):t,o=new URLSearchParams(e);o.has("state")&&(n=!0,i=e,r=o)}o&&n&&(i=`${"?"===t.charAt(0)?t.substring(1):t}${"#"===e.charAt(0)?e.substring(1):e}`,r=new URLSearchParams(i));if(!i||!r)throw Li("empty_response","");const s=r.get("state");if(!s)throw Li(zi,"");const{libraryState:a}=Uc(rs,s,""),{id:c,meta:l}=a;if(!c||!l)throw Li(ji,"","missing_library_state");return{params:r,payload:i,urlHash:e,urlQuery:t,hasResponseInHash:o,hasResponseInQuery:n,libraryState:{id:c,meta:l}}}(),{meta:t}=e;return t.interactionType===In.Popup}catch(e){return!1}}let Pl=null;async function xl(e,t,r,o,n){return new Promise((i,s)=>{t.verbose("1rf6em",r.correlationId);const a=r.correlationId;o.addFields({redirectBridgeTimeoutMs:e,lateResponseExperimentEnabled:n?.iframeTimeoutTelemetry||!1},a);const{libraryState:c}=Uc(rs,r.state||"",r.correlationId),l=new BroadcastChannel(c.id);let h,d,u,g=!1;const p=window.setTimeout(()=>{Pl=null,n?.iframeTimeoutTelemetry?(u=o.startMeasurement("waitForBridgeLateResponse",a),g=!0,d=window.setTimeout(()=>{u?.end({success:!1}),clearTimeout(d),l.close()},6e4)):l.close(),s(Li(ts,"","redirect_bridge_timeout"))},e);Pl={timeoutId:p,channel:l,reject:s},l.onmessage=e=>{h=e.data.payload;const t=e?.data&&"number"==typeof e.data.v?e.data.v:void 0;if(g)return u?.end({success:!!h}),clearTimeout(d),void l.close();o.addFields({redirectBridgeMessageVersion:t},a),Pl=null,clearTimeout(p),l.close(),h?i(h):s(Li("redirect_bridge_empty_response",a))}})}function Ol(){return"undefined"!=typeof window&&window.location?window.location.href.split("?")[0].split("#")[0]:""}function Rl(){if("undefined"==typeof window)throw Li(Wi,"")}function Ml(e){if(!e)throw Li(Zi,"")}function ql(e){Rl(),function(){if(Nc(window.location.hash)&&_l())throw Li("block_iframe_reload","")}(),function(){if(El())throw Li("block_nested_popups","")}(),Ml(e)}function $l(e,t){if(ql(e),function(e){if(_l()&&!e)throw Li("redirect_in_iframe","")}(t.system.allowRedirectInIframe),t.cache.cacheLocation===Yo)throw ac("in_mem_redirect_unavailable","")}function Ul(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)}function Ll(){return ys()}const Nl="@azure/msal-browser",Dl="5.16.0";function Hl(e,t){const r=e.indexOf(t);r>-1&&e.splice(r,1)}const Fl="invalid",zl="ttlExpired",jl="decryptFailed",Bl="expired";class Kl extends Va{constructor(e,t,r,o,n,i,s){super(e,r,o,n,s),this.cacheConfig=t,this.logger=o,this.internalStorage=new _s,this.browserStorage=Wl(e,t.cacheLocation,o,n),this.temporaryCacheStorage=Wl(e,Qo,o,n),this.cookieStorage=new dc,this.eventHandler=i}async initialize(e){this.performanceClient.addFields({cacheLocation:this.cacheConfig.cacheLocation,cacheRetentionDays:this.cacheConfig.cacheRetentionDays},e),await this.browserStorage.initialize(e),await this.migrateExistingCache(e),this.trackVersionChanges(e)}async migrateExistingCache(e){let t=uc(this.browserStorage),r=gc(this.clientId,this.browserStorage);this.performanceClient.addFields({preMigrateAcntCount:t.length,preMigrateATCount:r.accessToken.length,preMigrateITCount:r.idToken.length,preMigrateRTCount:r.refreshToken.length},e);for(let t=0;t<3;t++){const r=t;await this.removeStaleAccounts(t,r,e)}for(let t=0;t<3;t++){const r=t;await this.migrateIdTokens(t,r,e)}const o=this.getKMSIValues();for(let t=0;t<3;t++)await this.migrateAccessTokens(t,o,e),await this.migrateRefreshTokens(t,o,e);t=uc(this.browserStorage),r=gc(this.clientId,this.browserStorage),this.performanceClient.addFields({postMigrateAcntCount:t.length,postMigrateATCount:r.accessToken.length,postMigrateITCount:r.idToken.length,postMigrateRTCount:r.refreshToken.length},e)}async updateOldEntry(e,t){const r=this.browserStorage.getItem(e),o=this.validateAndParseJson(r||"");if(!o)return this.browserStorage.removeItem(e),{entry:null,removalReason:Fl};if(o.lastUpdatedAt){if(Ca(o.lastUpdatedAt,this.cacheConfig.cacheRetentionDays))return this.browserStorage.removeItem(e),{entry:null,removalReason:zl}}else o.lastUpdatedAt=Date.now().toString(),this.setItem(e,JSON.stringify(o),t);const n=pc(o),i=n?await this.browserStorage.decryptData(e,o,t):o;return i?ka(i)?(Sa(i)||Ta(i))&&i.expiresOn&&va(i.expiresOn,300)?(this.browserStorage.removeItem(e),{entry:null,removalReason:Bl}):{entry:i}:(this.browserStorage.removeItem(e),{entry:null,removalReason:Fl}):(this.browserStorage.removeItem(e),{entry:null,removalReason:n?jl:Fl})}async removeStaleAccounts(e,t,r){const o=uc(this.browserStorage,e);if(0!==o.length){for(const e of[...o]){this.performanceClient.incrementFields({oldAcntCount:1},r);const n=this.browserStorage.getItem(e),i=this.validateAndParseJson(n||"");if(i)if(i.lastUpdatedAt){if(Ca(i.lastUpdatedAt,this.cacheConfig.cacheRetentionDays))await this.removeAccountOldSchema(e,i,t,r),this.performanceClient.incrementFields({ttlExpiredAcntCount:1},r),Hl(o,e);else if(pc(i)){await this.browserStorage.decryptData(e,i,r)||(this.browserStorage.removeItem(e),this.performanceClient.incrementFields({decryptFailedAcntCount:1},r),Hl(o,e))}}else i.lastUpdatedAt=Date.now().toString(),this.setItem(e,JSON.stringify(i),r);else this.browserStorage.removeItem(e),this.performanceClient.incrementFields({invalidAcntCount:1},r),Hl(o,e)}this.setAccountKeys(o,r,e)}}async removeAccountOldSchema(e,t,r,o){const n=pc(t)?await this.browserStorage.decryptData(e,t,o):t,i=n?.homeAccountId;if(i){const e=this.getTokenKeys(r);[...e.idToken].filter(e=>e.includes(i)).forEach(t=>{this.browserStorage.removeItem(t),Hl(e.idToken,t)}),[...e.accessToken].filter(e=>e.includes(i)).forEach(t=>{this.browserStorage.removeItem(t),Hl(e.accessToken,t)}),[...e.refreshToken].filter(e=>e.includes(i)).forEach(t=>{this.browserStorage.removeItem(t),Hl(e.refreshToken,t)}),this.setTokenKeys(e,o,r)}this.browserStorage.removeItem(e)}getKMSIValues(){const e={},t=this.getTokenKeys().idToken;for(const r of t){const t=this.browserStorage.getUserData(r);if(t){const r=JSON.parse(t),o=pa(r.secret,rs,"");o&&(e[r.homeAccountId]=ma(o))}}return e}async migrateIdTokens(e,t,r){const o=gc(this.clientId,this.browserStorage,e);if(0===o.idToken.length)return;const n=gc(this.clientId,this.browserStorage,3),i=uc(this.browserStorage),s=uc(this.browserStorage,t);for(const e of[...o.idToken]){this.performanceClient.incrementFields({oldITCount:1},r);const t=await this.updateOldEntry(e,r),a=t.entry;if(!a){switch(t.removalReason){case zl:this.performanceClient.incrementFields({ttlExpiredITCount:1},r);break;case jl:this.performanceClient.incrementFields({decryptFailedITCount:1},r);break;case Fl:this.performanceClient.incrementFields({invalidITCount:1},r)}Hl(o.idToken,e);continue}const c=i.find(e=>e.includes(a.homeAccountId)),l=s.find(e=>e.includes(a.homeAccountId));let h=null;if(c)h=this.getAccount(c,r);else if(l){const e=this.browserStorage.getItem(l),t=this.validateAndParseJson(e||"");h=t&&pc(t)?await this.browserStorage.decryptData(l,t,r):t}if(!h){this.performanceClient.incrementFields({skipITMigrateCount:1},r);continue}const d=pa(a.secret,rs,r),u=this.generateCredentialKey(a),g=this.getIdTokenCredential(u,r),p=Object.keys(d).includes("signin_state"),m=g&&Object.keys(pa(g.secret,rs,r)||{}).includes("signin_state");if(!g||a.lastUpdatedAt>g.lastUpdatedAt&&(p||!m)){const e=h.tenantProfiles||[],t=La(d)||h.realm;if(t&&!e.find(e=>e.tenantId===t)){const r=$a(h.homeAccountId,h.localAccountId,t,h.nativeAccountId,d);e.push(r)}h.tenantProfiles=e;const o=this.generateAccountKey(Na(h)),s=ma(d);await this.setUserData(o,JSON.stringify(h),r,h.lastUpdatedAt,s),i.includes(o)||i.push(o),await this.setUserData(u,JSON.stringify(a),r,a.lastUpdatedAt,s),this.performanceClient.incrementFields({migratedITCount:1},r),n.idToken.includes(u)||n.idToken.push(u)}}this.setTokenKeys(o,r,e),this.setTokenKeys(n,r),this.setAccountKeys(i,r)}async migrateAccessTokens(e,t,r){const o=gc(this.clientId,this.browserStorage,e);if(0===o.accessToken.length)return;const n=gc(this.clientId,this.browserStorage,3);for(const e of[...o.accessToken]){this.performanceClient.incrementFields({oldATCount:1},r);const i=await this.updateOldEntry(e,r),s=i.entry;if(!s){switch(i.removalReason){case zl:this.performanceClient.incrementFields({ttlExpiredATCount:1},r);break;case jl:this.performanceClient.incrementFields({decryptFailedATCount:1},r);break;case Bl:this.performanceClient.incrementFields({expiredATCount:1},r);break;case Fl:this.performanceClient.incrementFields({invalidATCount:1},r)}Hl(o.accessToken,e);continue}if(!(s.homeAccountId in t)){this.performanceClient.incrementFields({skipATMigrateCount:1},r);continue}const a=this.generateCredentialKey(s),c=t[s.homeAccountId];if(n.accessToken.includes(a)){const e=this.getAccessTokenCredential(a,r);(!e||s.lastUpdatedAt>e.lastUpdatedAt)&&(await this.setUserData(a,JSON.stringify(s),r,s.lastUpdatedAt,c),this.performanceClient.incrementFields({migratedATCount:1},r))}else await this.setUserData(a,JSON.stringify(s),r,s.lastUpdatedAt,c),this.performanceClient.incrementFields({migratedATCount:1},r),n.accessToken.push(a)}this.setTokenKeys(o,r,e),this.setTokenKeys(n,r)}async migrateRefreshTokens(e,t,r){const o=gc(this.clientId,this.browserStorage,e);if(0===o.refreshToken.length)return;const n=gc(this.clientId,this.browserStorage,3);for(const e of[...o.refreshToken]){this.performanceClient.incrementFields({oldRTCount:1},r);const i=await this.updateOldEntry(e,r),s=i.entry;if(!s){switch(i.removalReason){case zl:this.performanceClient.incrementFields({ttlExpiredRTCount:1},r);break;case jl:this.performanceClient.incrementFields({decryptFailedRTCount:1},r);break;case Bl:this.performanceClient.incrementFields({expiredRTCount:1},r);break;case Fl:this.performanceClient.incrementFields({invalidRTCount:1},r)}Hl(o.refreshToken,e);continue}if(!(s.homeAccountId in t)){this.performanceClient.incrementFields({skipRTMigrateCount:1},r);continue}const a=this.generateCredentialKey(s),c=t[s.homeAccountId];if(n.refreshToken.includes(a)){const e=this.getRefreshTokenCredential(a,r);(!e||s.lastUpdatedAt>e.lastUpdatedAt)&&(await this.setUserData(a,JSON.stringify(s),r,s.lastUpdatedAt,c),this.performanceClient.incrementFields({migratedRTCount:1},r))}else await this.setUserData(a,JSON.stringify(s),r,s.lastUpdatedAt,c),this.performanceClient.incrementFields({migratedRTCount:1},r),n.refreshToken.push(a)}this.setTokenKeys(o,r,e),this.setTokenKeys(n,r)}trackVersionChanges(e){const t=this.browserStorage.getItem(ec);t&&(this.logger.info(`1wuc87 ${t}`,e),this.performanceClient.addGlobalFields({previousLibraryVersion:t})),t!==Dl&&this.setItem(ec,Dl,e)}validateAndParseJson(e){if(!e)return null;try{const t=JSON.parse(e);return t&&"object"==typeof t?t:null}catch(e){return null}}setItem(e,t,r){const o=new Array(4).fill(0),n=[];for(let i=0;i<=20;i++)try{if(this.browserStorage.setItem(e,t),i>0)for(let e=0;e<=3;e++){const t=o.slice(0,e).reduce((e,t)=>e+t,0);if(t>=i)break;const s=i>t+o[e]?t+o[e]:i;i>t&&o[e]>0&&this.removeAccessTokenKeys(n.slice(t,s),r,e)}break}catch(s){const a=Ba(s);if(!(a.errorCode===za&&i<20))throw a;if(!n.length)for(let r=0;r<=3;r++)if(e===ic(this.clientId,r)){const e=JSON.parse(t).accessToken;n.push(...e),o[r]=e.length}else{const e=this.getTokenKeys(r).accessToken;n.push(...e),o[r]=e.length}if(n.length<=i)throw a;this.removeAccessToken(n[i],r,!1)}}async setUserData(e,t,r,o,n){const i=new Array(4).fill(0),s=[];for(let a=0;a<=20;a++)try{if(await ua(this.browserStorage.setUserData.bind(this.browserStorage),"setUserData",this.logger,this.performanceClient,r)(e,t,r,o,n),a>0)for(let e=0;e<=3;e++){const t=i.slice(0,e).reduce((e,t)=>e+t,0);if(t>=a)break;const o=a>t+i[e]?t+i[e]:a;a>t&&i[e]>0&&this.removeAccessTokenKeys(s.slice(t,o),r,e)}break}catch(e){const t=Ba(e);if(!(t.errorCode===za&&a<20))throw t;if(!s.length)for(let e=0;e<=3;e++){const t=this.getTokenKeys(e).accessToken;s.push(...t),i[e]=t.length}if(s.length<=a)throw t;this.removeAccessToken(s[a],r,!1)}}getAccount(e,t){this.logger.trace("1lfvm6",t);const r=this.browserStorage.getUserData(e);if(!r)return this.removeAccountKeyFromMap(e,t),null;const o=this.validateAndParseJson(r);if(!(o&&(n=o,n&&n.hasOwnProperty("homeAccountId")&&n.hasOwnProperty("environment")&&n.hasOwnProperty("realm")&&n.hasOwnProperty("localAccountId")&&n.hasOwnProperty("username")&&n.hasOwnProperty("authorityType"))))return null;var n;const i=Va.toObject({},o);var s;return this.performanceClient.addFields({accountCachedBy:(s=i.cachedByApiId,"number"==typeof s&&s in Cn?Cn[s]:"unknown")},t),i}async setAccount(e,t,r,o){this.logger.trace("1bz3wr",t);const n=this.generateAccountKey(Na(e)),i=Date.now().toString();e.lastUpdatedAt=i,e.cachedByApiId=o,await this.setUserData(n,JSON.stringify(e),t,i,r),this.addAccountKeyToMap(n,t),this.performanceClient.addFields({kmsi:r},t)}setAccountKeys(e,t,r=3){0===e.length?this.removeItem(nc(r)):this.setItem(nc(r),JSON.stringify(e),t)}getAccountKeys(){return uc(this.browserStorage)}addAccountKeyToMap(e,t){this.logger.trace("0rb85k",t),this.logger.tracePii(`1l9bdo ${e}`,t);const r=this.getAccountKeys();return-1===r.indexOf(e)?(r.push(e),this.setItem(nc(),JSON.stringify(r),t),this.logger.verbose("0xia39",t),!0):(this.logger.verbose("0161kk",t),!1)}removeAccountKeyFromMap(e,t){this.logger.trace("1jpigu",t),this.logger.tracePii(`1xzspl ${e}`,t);const r=this.getAccountKeys(),o=r.indexOf(e);o>-1?(r.splice(o,1),this.setAccountKeys(r,t)):this.logger.trace("1dytu2",t)}removeAccount(e,t){const r=this.getActiveAccount(t);r?.homeAccountId===e.homeAccountId&&r?.environment===e.environment&&this.setActiveAccount(null,t),super.removeAccount(e,t),this.removeAccountKeyFromMap(this.generateAccountKey(e),t),this.browserStorage.getKeys().forEach(t=>{t.includes(e.homeAccountId)&&t.includes(e.environment)&&this.browserStorage.removeItem(t)})}removeIdToken(e,t){super.removeIdToken(e,t);const r=this.getTokenKeys(),o=r.idToken.indexOf(e);o>-1&&(this.logger.info("05udv9",t),r.idToken.splice(o,1),this.setTokenKeys(r,t))}removeAccessToken(e,t,r=!0){super.removeAccessToken(e,t),r&&this.removeAccessTokenKeys([e],t)}removeAccessTokenKeys(e,t,r=3){this.logger.trace("17o18n",t);const o=this.getTokenKeys(r);let n=0;if(e.forEach(e=>{const t=o.accessToken.indexOf(e);t>-1&&(o.accessToken.splice(t,1),n++)}),n>0)return this.logger.info(`15i5d5 ${n}`,t),void this.setTokenKeys(o,t,r)}removeRefreshToken(e,t){super.removeRefreshToken(e,t);const r=this.getTokenKeys(),o=r.refreshToken.indexOf(e);o>-1&&(this.logger.info("1f4fq3",t),r.refreshToken.splice(o,1),this.setTokenKeys(r,t))}getTokenKeys(e=3){return gc(this.clientId,this.browserStorage,e)}setTokenKeys(e,t,r=3){0!==e.idToken.length||0!==e.accessToken.length||0!==e.refreshToken.length?this.setItem(ic(this.clientId,r),JSON.stringify(e),t):this.removeItem(ic(this.clientId,r))}getIdTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("1jukz6",t),this.removeIdToken(e,t),null;const o=this.validateAndParseJson(r);return o&&((n=o)&&ka(n)&&n.hasOwnProperty("realm")&&n.credentialType===so.ID_TOKEN)?(this.logger.trace("01ju66",t),o):(this.logger.trace("1jukz6",t),null);var n}async setIdTokenCredential(e,t,r){this.logger.trace("13hjll",t);const o=this.generateCredentialKey(e),n=Date.now().toString();e.lastUpdatedAt=n,await this.setUserData(o,JSON.stringify(e),t,n,r);const i=this.getTokenKeys();-1===i.idToken.indexOf(o)&&(this.logger.info("07jy92",t),i.idToken.push(o),this.setTokenKeys(i,t))}getAccessTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("0bqvx8",t),this.removeAccessTokenKeys([e],t),null;const o=this.validateAndParseJson(r);return o&&Sa(o)?(this.logger.trace("1o81rl",t),o):(this.logger.trace("0bqvx8",t),null)}async setAccessTokenCredential(e,t,r){this.logger.trace("1pondb",t);const o=this.generateCredentialKey(e),n=Date.now().toString();e.lastUpdatedAt=n,await this.setUserData(o,JSON.stringify(e),t,n,r);const i=this.getTokenKeys(),s=i.accessToken.indexOf(o);-1!==s&&i.accessToken.splice(s,1),this.logger.trace("1onhey "+(-1===s?"added to":"updated in"),t),i.accessToken.push(o),this.setTokenKeys(i,t)}getRefreshTokenCredential(e,t){const r=this.browserStorage.getUserData(e);if(!r)return this.logger.trace("0jlizt",t),this.removeRefreshToken(e,t),null;const o=this.validateAndParseJson(r);return o&&Ta(o)?(this.logger.trace("0nokxi",t),o):(this.logger.trace("0jlizt",t),null)}async setRefreshTokenCredential(e,t,r){this.logger.trace("0tcg8d",t);const o=this.generateCredentialKey(e),n=Date.now().toString();e.lastUpdatedAt=n,await this.setUserData(o,JSON.stringify(e),t,n,r);const i=this.getTokenKeys();-1===i.refreshToken.indexOf(o)&&(this.logger.info("0eckjs",t),i.refreshToken.push(o),this.setTokenKeys(i,t))}getAppMetadata(e,t){const r=this.browserStorage.getItem(e);if(!r)return this.logger.trace("1q101h",t),null;const o=this.validateAndParseJson(r);return o&&(n=e,(i=o)&&0===n.indexOf(ao)&&i.hasOwnProperty("clientId")&&i.hasOwnProperty("environment"))?(this.logger.trace("19pvg2",t),o):(this.logger.trace("1q101h",t),null);var n,i}setAppMetadata(e,t){this.logger.trace("0cyma6",t);const r=function({environment:e,clientId:t}){return[ao,e,t].join("-").toLowerCase()}(e);this.setItem(r,JSON.stringify(e),t)}getServerTelemetry(e,t){const r=this.browserStorage.getItem(e);if(!r)return this.logger.trace("0jk19c",t),null;const o=this.validateAndParseJson(r);return o&&function(e,t){const r=0===e.indexOf(fo);let o=!0;return t&&(o=t.hasOwnProperty("failedRequests")&&t.hasOwnProperty("errors")&&t.hasOwnProperty("cacheHits")),r&&o}(e,o)?(this.logger.trace("12jguk",t),o):(this.logger.trace("0jk19c",t),null)}setServerTelemetry(e,t,r){this.logger.trace("1poh61",r),this.setItem(e,JSON.stringify(t),r)}getAuthorityMetadata(e,t){const r=this.internalStorage.getItem(e);if(!r)return this.logger.trace("1r39oe",t),null;const o=this.validateAndParseJson(r);return o&&function(e,t){return!!t&&0===e.indexOf(lo)&&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,o)?(this.logger.trace("1ohvk3",t),o):null}getAuthorityMetadataKeys(){return this.internalStorage.getKeys().filter(e=>this.isAuthorityMetadata(e))}setWrapperMetadata(e,t){this.internalStorage.setItem(ln,e),this.internalStorage.setItem(hn,t)}getWrapperMetadata(){return[this.internalStorage.getItem(ln)||"",this.internalStorage.getItem(hn)||""]}setAuthorityMetadata(e,t,r){this.logger.trace("07w8n2",r),this.internalStorage.setItem(e,JSON.stringify(t))}getActiveAccount(e){const t=this.generateCacheKey(Dr),r=this.browserStorage.getItem(t);if(!r)return this.logger.trace("08gw0e",e),null;const o=this.validateAndParseJson(r);return o?(this.logger.trace("1t3ch7",e),this.getAccountInfoFilteredBy({homeAccountId:o.homeAccountId,localAccountId:o.localAccountId,tenantId:o.tenantId},e)):(this.logger.trace("0me1up",e),null)}setActiveAccount(e,t){const r=this.generateCacheKey(Dr);if(e){this.logger.verbose("0rsj80",t);const o={homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,tenantId:e.tenantId};this.setItem(r,JSON.stringify(o),t)}else this.logger.verbose("1bp5z5",t),this.browserStorage.removeItem(r);this.eventHandler.emitEvent(Ic,t)}getThrottlingCache(e,t){const r=this.browserStorage.getItem(e);if(!r)return this.logger.trace("1h4wa6",t),null;const o=this.validateAndParseJson(r);return o&&function(e,t){let r=!1;e&&(r=0===e.indexOf(vo));let o=!0;return t&&(o=t.hasOwnProperty("throttleTime")),r&&o}(e,o)?(this.logger.trace("0of6n8",t),o):(this.logger.trace("1h4wa6",t),null)}setThrottlingCache(e,t,r){this.logger.trace("0wfgh6",r),this.setItem(e,JSON.stringify(t),r)}getTemporaryCache(e,t,r){this.logger.trace("1ordf8",t);const o=r?this.generateCacheKey(e):e;return this.temporaryCacheStorage.getItem(o)}setTemporaryCache(e,t,r){const o=r?this.generateCacheKey(e):e;this.temporaryCacheStorage.setItem(o,t)}removeItem(e){this.browserStorage.removeItem(e)}removeTemporaryItem(e){this.temporaryCacheStorage.removeItem(e)}getKeys(){return this.browserStorage.getKeys()}clear(e){this.removeAllAccounts(e),this.removeAppMetadata(e),this.temporaryCacheStorage.getKeys().forEach(e=>{-1===e.indexOf(Qa)&&-1===e.indexOf(this.clientId)||this.removeTemporaryItem(e)}),this.browserStorage.getKeys().forEach(e=>{-1===e.indexOf(Qa)&&-1===e.indexOf(this.clientId)||this.browserStorage.removeItem(e)}),this.internalStorage.clear()}generateCacheKey(e){return Hs.startsWith(e,Qa)?e:`${Qa}.${this.clientId}.${e}`}generateCredentialKey(e){const t=e.credentialType===so.REFRESH_TOKEN&&e.familyId||e.clientId,r=e.tokenType&&e.tokenType.toLowerCase()!==wo.BEARER.toLowerCase()?e.tokenType.toLowerCase():"";return[`${Qa}.3`,e.homeAccountId,e.environment,e.credentialType,t,e.realm||"",e.target||"",r].join("|").toLowerCase()}generateAccountKey(e){const t=e.homeAccountId.split(".")[1];return[`${Qa}.3`,e.homeAccountId,e.environment,t||e.tenantId||""].join("|").toLowerCase()}resetRequestCache(e){this.logger.trace("0h0ynu",e),this.removeTemporaryItem(this.generateCacheKey(nn)),this.removeTemporaryItem(this.generateCacheKey(sn)),this.removeTemporaryItem(this.generateCacheKey(rn)),this.removeTemporaryItem(this.generateCacheKey(on)),this.removeTemporaryItem(this.generateCacheKey(cn)),this.setInteractionInProgress(!1,void 0)}cacheAuthorizeRequest(e,t,r){this.logger.trace("1tzef5",t);const o=Mi(JSON.stringify(e));if(this.setTemporaryCache(nn,o,!0),r){const e=Mi(r);this.setTemporaryCache(sn,e,!0)}}getCachedRequest(e){this.logger.trace("0uen20",e);const t=this.getTemporaryCache(nn,e,!0);if(!t)throw Li("no_token_request_cache_error","");const r=this.getTemporaryCache(sn,e,!0);let o,n="";try{o=JSON.parse(rs(t)),r&&(n=rs(r))}catch(r){throw this.logger.errorPii(`0ewsey ${t}`,e),this.logger.error(`0tvdic ${r}`,e),Li("unable_to_parse_token_request_cache_error","")}return[o,n]}getCachedNativeRequest(){this.logger.trace("1yxcdm","");const e=this.getTemporaryCache(cn,"",!0);if(!e)return this.logger.trace("0mnxd4",""),null;const t=this.validateAndParseJson(e);return t||(this.logger.error("0rrkip",""),null)}isInteractionInProgress(e){const t=this.getInteractionInProgress()?.clientId;return e?t===this.clientId:!!t}getInteractionInProgress(){const e=`${Qa}.${an}`,t=this.getTemporaryCache(e,"",!1);try{return t?JSON.parse(t):null}catch(t){return this.logger.error("0jjyys",""),this.removeTemporaryItem(e),this.resetRequestCache(""),Al(window),null}}setInteractionInProgress(e,t=en,r=!1,o=""){const n=`${Qa}.${an}`;if(e){const e=this.getInteractionInProgress();if(e){if(!r)throw Li("interaction_in_progress","");this.logger.warning(`1pmscr ${e.clientId} ${e.type}`,o),function(e,t){Pl&&(e.verbose("18y01k",t),clearTimeout(Pl.timeoutId),Pl.channel.close(),Pl.reject(Li("interaction_in_progress_cancelled","")),Pl=null)}(this.logger,o),this.removeTemporaryItem(n)}this.setTemporaryCache(n,JSON.stringify({clientId:this.clientId,type:t}),!1)}else e||this.getInteractionInProgress()?.clientId!==this.clientId||this.removeTemporaryItem(n)}async hydrateCache(e,t){const r=Ia(e.account.homeAccountId,e.account.environment,e.idToken,this.clientId,e.tenantId),o=ba(e.account.homeAccountId,e.account.environment,e.accessToken,this.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?ya(e.expiresOn):0,e.extExpiresOn?ya(e.extExpiresOn):0,rs,t.correlationId||"",void 0,e.tokenType,void 0,t.sshKid);t.resource&&(o.resource=t.resource);const n={idToken:r,accessToken:o};return this.saveCacheRecord(n,e.correlationId,ma(pa(e.idToken,rs,e.correlationId)),vn)}async saveCacheRecord(e,t,r,o,n){try{await super.saveCacheRecord(e,t,r,o,n)}catch(e){if(e instanceof ja&&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 Wl(e,t,r,o){try{switch(t){case Go:return new yc(e,r,o);case Qo:return new wc}}catch(e){r.error(e,"")}return new _s}var Jl;!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"}(Jl||(Jl={}));const Vl=new Map;function Gl(e,t){const r=Date.now();let o=Vl.get(e);if(o)!function(e,t){Vl.delete(e),Vl.set(e,t)}(e,o);else if(o={logs:[],firstEventTime:r},Vl.set(e,o),Vl.size>50){const e=Vl.keys().next().value;void 0!==e&&Vl.delete(e)}o.logs.push({...t,milliseconds:r-o.firstEventTime}),o.logs.length>500&&o.logs.shift()}class Ql{constructor(e,t,r){this.level=Jl.Info;const o=e||Ql.createDefaultLoggerOptions();this.localCallback=o.loggerCallback||(()=>{}),this.piiLoggingEnabled=o.piiLoggingEnabled||!1,this.level="number"==typeof o.logLevel?o.logLevel:Jl.Info,this.packageName=t||"",this.packageVersion=r||""}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:Jl.Info}}clone(e,t){return new Ql({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level},e,t)}logMessage(e,t){const r=t.correlationId,o=function(e){if(e.length<6)return null;if(e.length>6&&" "!==e[6])return null;for(let t=0;t<6;t++){const r=e[t];if(!(r>="a"&&r<="z"||r>="A"&&r<="Z"||r>="0"&&r<="9"))return null}return e.substring(0,6)}(e);if(o){Gl(r,{hash:o,level:t.logLevel,containsPii:t.containsPii||!1,milliseconds:0})}if(t.logLevel>this.level||!this.piiLoggingEnabled&&t.containsPii)return;const n=`${`[${(new Date).toUTCString()}] : [${r}]`} : ${this.packageName}@${this.packageVersion} : ${Jl[t.logLevel]} - ${e}`;this.executeCallback(t.logLevel,n,t.containsPii||!1)}executeCallback(e,t,r){this.localCallback&&this.localCallback(e,t,r)}error(e,t){this.logMessage(e,{logLevel:Jl.Error,containsPii:!1,correlationId:t})}errorPii(e,t){this.logMessage(e,{logLevel:Jl.Error,containsPii:!0,correlationId:t})}warning(e,t){this.logMessage(e,{logLevel:Jl.Warning,containsPii:!1,correlationId:t})}warningPii(e,t){this.logMessage(e,{logLevel:Jl.Warning,containsPii:!0,correlationId:t})}info(e,t){this.logMessage(e,{logLevel:Jl.Info,containsPii:!1,correlationId:t})}infoPii(e,t){this.logMessage(e,{logLevel:Jl.Info,containsPii:!0,correlationId:t})}verbose(e,t){this.logMessage(e,{logLevel:Jl.Verbose,containsPii:!1,correlationId:t})}verbosePii(e,t){this.logMessage(e,{logLevel:Jl.Verbose,containsPii:!0,correlationId:t})}trace(e,t){this.logMessage(e,{logLevel:Jl.Trace,containsPii:!1,correlationId:t})}tracePii(e,t){this.logMessage(e,{logLevel:Jl.Trace,containsPii:!0,correlationId:t})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}}class Yl{constructor(e){this.eventCallbacks=new Map,this.logger=e||new Ql({},Nl,Dl),"undefined"!=typeof BroadcastChannel&&(this.broadcastChannel=new BroadcastChannel("msal.broadcast.event")),this.invokeCrossTabCallbacks=this.invokeCrossTabCallbacks.bind(this)}addEventCallback(e,t,r){if("undefined"!=typeof window){const o=r||Ll();return this.eventCallbacks.has(o)?(this.logger.error(`1578i0 ${o}`,""),null):(this.eventCallbacks.set(o,[e,t||[]]),this.logger.verbose(`1cnec4 ${o}`,""),o)}return null}removeEventCallback(e){this.eventCallbacks.delete(e),this.logger.verbose(`12zotd ${e}`,"")}emitEvent(e,t,r,o,n){const i={eventType:e,interactionType:r||null,payload:o||null,error:n||null,correlationId:t,timestamp:Date.now()};switch(e){case bc:case Oc:case Ic:this.broadcastChannel?.postMessage(i)}this.invokeCallbacks(i)}invokeCallbacks(e){this.eventCallbacks.forEach(([t,r],o)=>{(0===r.length||r.includes(e.eventType))&&(this.logger.verbose(`15jpwk ${o} ${e.eventType}`,""),t.apply(null,[e]))})}invokeCrossTabCallbacks(e){const t=e.data;this.invokeCallbacks(t)}subscribeCrossTab(){this.broadcastChannel?.addEventListener("message",this.invokeCrossTabCallbacks)}unsubscribeCrossTab(){this.broadcastChannel?.removeEventListener("message",this.invokeCrossTabCallbacks)}}const Xl=1;new Set(["accessTokenSize","durationMs","idTokenSize","matsSilentStatus","matsHttpStatus","refreshTokenSize","startTimeMs","status","multiMatchedAT","multiMatchedID","multiMatchedRT","unencryptedCacheCount","encryptedCacheExpiredCount","oldAccountCount","oldAccessCount","oldIdCount","oldRefreshCount","currAccountCount","currAccessCount","currIdCount","currRefreshCount","ttlExpiredAcntCount","ttlExpiredITCount","ttlExpiredATCount","ttlExpiredRTCount","decryptFailedAcntCount","decryptFailedITCount","decryptFailedATCount","decryptFailedRTCount","invalidAcntCount","invalidITCount","invalidATCount","invalidRTCount","expiredATCount","expiredRTCount","upgradedCacheCount","cacheMatchedAccounts","networkRtt","redirectBridgeTimeoutMs","redirectBridgeMessageVersion"]);class Zl{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:Xl,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""}}}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}addGlobalFields(){}incrementFields(){}cacheEventByCorrelationId(){}}const eh={tokenRenewalOffsetSeconds:300,preventCorsPreflight:!1},th={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:Jl.Info,correlationId:""},rh={async sendGetRequestAsync(){throw Jn(ci,"")},async sendPostRequestAsync(){throw Jn(ci,"")}},oh={sku:"msal.js.common",version:Wa,cpu:"",os:""},nh={clientSecret:"",clientAssertion:void 0},ih={azureCloudInstance:ra,tenant:`${yr}`},sh={application:{appName:"",appVersion:""}};function ah({authOptions:e,systemOptions:t,loggerOptions:r,storageInterface:o,networkInterface:n,cryptoInterface:i,clientCredentials:s,libraryInfo:a,telemetry:c,serverTelemetryManager:l,persistencePlugin:h,serializableCache:d}){const u={...th,...r};return{authOptions:(g=e,{clientCapabilities:[],azureCloudOptions:ih,instanceAware:!1,isMcp:!1,...g}),systemOptions:{...eh,...t},loggerOptions:u,storageInterface:o||new Ga(e.clientId,Ms,new Ql(u,Ka,Wa),new Zl),networkInterface:n||rh,cryptoInterface:i||Ms,clientCredentials:s||nh,libraryInfo:{...oh,...a},telemetry:{...sh,...c},serverTelemetryManager:l||null,persistencePlugin:h||null,serializableCache:d||null};var g}function ch(e){return e.authOptions.authority.options.protocolMode===ea}class lh{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}const hh="sw";class dh{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){const r=await ua(this.generateKid.bind(this),aa,t,this.performanceClient,e.correlationId)(e),o=this.cryptoUtils.base64UrlEncode(JSON.stringify(r));return{kid:r.kid,reqCnfString:o}}async generateKid(e){return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:hh}}async signPopToken(e,t,r){return this.signPayload(e,t,r)}async signPayload(e,t,r,o){const{resourceRequestMethod:n,resourceRequestUri:i,shrClaims:s,shrNonce:a,shrOptions:c}=r,l=i?new Ws(i,r.correlationId):void 0,h=l?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:fa(),m:n?.toUpperCase(),u:h?.HostNameAndPort,nonce:a||this.cryptoUtils.createNewGuid(),p:h?.AbsolutePath,q:h?.QueryString?[[],h.QueryString]:void 0,client_claims:s||void 0,...o},t,c,r.correlationId)}}class uh extends Mn{constructor(e,t,r,o,n,i){super(e,t,r,o),this.name="ServerError",this.errorNo=n,this.status=i,Object.setPrototypeOf(this,uh.prototype)}}class gh{constructor(e,t,r,o,n,i,s){this.clientId=e,this.cacheStorage=t,this.cryptoObj=r,this.logger=o,this.performanceClient=n,this.serializableCache=i,this.persistencePlugin=s}validateTokenResponse(e,t,r){if(e.error||e.error_description||e.suberror){const o=`Error(s): ${e.error_codes||Ar} - Timestamp: ${e.timestamp||Ar} - Description: ${e.error_description||Ar} - Correlation ID: ${e.correlation_id||Ar} - Trace ID: ${e.trace_id||Ar}`,n=e.error_codes?.length?e.error_codes[0]:void 0,i=new uh(e.error||"",e.correlation_id||"",o,e.suberror,n,e.status);if(r&&e.status&&e.status>=500&&e.status<=599)return void this.logger.warning(`16ks7j ${i}`,t);if(r&&e.status&&e.status>=400&&e.status<=499)return void this.logger.warning(`0g61x3 ${i}`,t);if(zn(e.error,e.error_description,e.suberror))throw new Fn(e.error||"",e.correlation_id||"",e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.claims||"",n);throw i}}async handleServerTokenResponse(e,t,r,o,n,i,s,a,c,l,h){let d,u;if(e.id_token&&(d=pa(e.id_token||"",this.cryptoObj.base64Decode,o.correlationId),i&&i.nonce&&d.nonce!==i.nonce))throw Jn("nonce_mismatch",o.correlationId);this.homeAccountIdentifier=Da(e.client_info||"",t.authorityType,this.logger,this.cryptoObj,o.correlationId,d),i&&i.state&&(u=Uc(this.cryptoObj.base64Decode,i.state,o.correlationId)),e.key_id=e.key_id||o.sshKid||void 0;const g=this.generateCacheRecord(e,t,r,o,d,s,i,h);let p;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("0jbz5k",o.correlationId),p=new lh(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(p)),a&&!c&&g.account){if(this.cacheStorage.getAllAccounts({homeAccountId:g.account.homeAccountId,environment:g.account.environment},o.correlationId).length<1)return this.logger.warning("1gmt66",o.correlationId),this.performanceClient?.addFields({acntLoggedOut:!0},o.correlationId),await gh.generateAuthenticationResult(this.cryptoObj,t,g,!1,o,this.performanceClient,d,u,void 0,l)}await this.cacheStorage.saveCacheRecord(g,o.correlationId,ma(d||{}),n,o.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&p&&(this.logger.verbose("1bh17u",o.correlationId),await this.persistencePlugin.afterCacheAccess(p))}return gh.generateAuthenticationResult(this.cryptoObj,t,g,!1,o,this.performanceClient,d,u,e,l)}generateCacheRecord(e,t,r,o,n,i,s,a){const c=t.getPreferredCache();if(!c)throw Jn(oi,o.correlationId);const l=La(n);let h,d;e.id_token&&n&&(h=Ia(this.homeAccountIdentifier,c,e.id_token,this.clientId,l||""),d=ph(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,o.correlationId,n,e.client_info,c,l,s,void 0,this.logger,this.performanceClient));let u=null;if(e.access_token){const n=e.scope?Ja.fromString(e.scope,o.correlationId):new Ja(o.scopes||[],o.correlationId),s=("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0,h=("string"==typeof e.ext_expires_in?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,d=("string"==typeof e.refresh_in?parseInt(e.refresh_in,10):e.refresh_in)||void 0,g=r+s,p=g+h,m=d&&d>0?r+d:void 0;u=ba(this.homeAccountIdentifier,c,e.access_token,this.clientId,l||t.tenant||"",n.printScopes(),g,p,this.cryptoObj.base64Decode,o.correlationId,m,e.token_type,i,e.key_id,a);const f=o.resource||null;f&&(u.resource=f)}let g=null;if(e.refresh_token){let t;if(e.refresh_token_expires_in){t=r+("string"==typeof e.refresh_token_expires_in?parseInt(e.refresh_token_expires_in,10):e.refresh_token_expires_in),this.performanceClient?.addFields({ntwkRtExpiresOnSeconds:t},o.correlationId)}g=function(e,t,r,o,n,i,s){const a={credentialType:so.REFRESH_TOKEN,homeAccountId:e,environment:t,clientId:o,secret:r,lastUpdatedAt:Date.now().toString()};return i&&(a.userAssertionHash=i),n&&(a.familyId=n),s&&(a.expiresOn=s.toString()),a}(this.homeAccountIdentifier,c,e.refresh_token,this.clientId,e.foci,i,t)}let p=null;return e.foci&&(p={clientId:this.clientId,environment:c,familyId:e.foci}),{account:d,idToken:h,accessToken:u,refreshToken:g,appMetadata:p}}static async generateAuthenticationResult(e,t,r,o,n,i,s,a,c,l){let h,d,u="",g=[],p=null,m="";if(r.accessToken){if(r.accessToken.tokenType!==wo.POP||n.popKid)u=r.accessToken.secret;else{const t=new dh(e,i),{secret:o,keyId:s}=r.accessToken;if(!s)throw Jn(ai,n.correlationId);u=await t.signPopToken(o,s,n)}g=Ja.fromString(r.accessToken.target,n.correlationId).asArray(),p=wa(r.accessToken.expiresOn),h=wa(r.accessToken.extendedExpiresOn),r.accessToken.refreshOn&&(d=wa(r.accessToken.refreshOn))}r.appMetadata&&(m=r.appMetadata.familyId===co?co:"");const f=s?.oid||s?.sub||"",y=s?.tid||"";if(c?.spa_accountid&&r.account){r.account.nativeAccountId=c?.spa_accountid;const e=y||r.account.realm;if(r.account.tenantProfiles){const t=r.account.tenantProfiles.find(t=>t.tenantId===e);t&&(t.nativeAccountId=c.spa_accountid)}}const w=r.account?Ua(Na(r.account),void 0,s,r.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:f,tenantId:y,scopes:g,account:w,idToken:r?.idToken?.secret||"",idTokenClaims:s||{},accessToken:u,fromCache:o,expiresOn:p,extExpiresOn:h,refreshOn:d,correlationId:n.correlationId,requestId:l||"",familyId:m,tokenType:r.accessToken?.tokenType||"",state:a?a.userRequestState:"",cloudGraphHostName:r.account?.cloudGraphHostName||"",msGraphHost:r.account?.msGraphHost||"",code:c?.spa_code,fromPlatformBroker:!1}}}function ph(e,t,r,o,n,i,s,a,c,l,h,d,u){d?.verbose("09jz0t",n);const g=a||t.getPreferredCache(),p=e.getAccountsFilteredBy({homeAccountId:r,environment:g},n);u?.addFields({cacheMatchedAccounts:p.length},n),p.length>1&&d?.warning("0x7ad1",n);const m=(1===p.length?p[0]:null)||function(e,t,r,o){let n,i,s;n=t.authorityType===$s?"ADFS":t.protocolMode===ea?io:"MSSTS",e.clientInfo&&o&&(i=Ra(e.clientInfo,o),i.xms_tdbr&&(s="EU"===i.xms_tdbr?"EU":"None"));const a=e.environment||t&&t.getPreferredCache();if(!a)throw Jn(oi,r);const c=e.idTokenClaims?.preferred_username||e.idTokenClaims?.upn,l=e.idTokenClaims?.emails?e.idTokenClaims.emails[0]:null,h=c||l||"",d=e.idTokenClaims?.login_hint,u=i?.utid||La(e.idTokenClaims)||"",g=i?.uid||e.idTokenClaims?.oid||e.idTokenClaims?.sub||"";let p;p=e.tenantProfiles?e.tenantProfiles:[$a(e.homeAccountId,g,u,e.nativeAccountId,e.idTokenClaims)];return{homeAccountId:e.homeAccountId,environment:a,realm:u,localAccountId:g,username:h,authorityType:n,loginHint:d,clientInfo:e.clientInfo,name:e.idTokenClaims?.name||"",lastModificationTime:void 0,lastModificationApp:void 0,cloudGraphHostName:e.cloudGraphHostName,msGraphHost:e.msGraphHost,nativeAccountId:e.nativeAccountId,tenantProfiles:p,dataBoundary:s}}({homeAccountId:r,idTokenClaims:i,clientInfo:s,environment:a,cloudGraphHostName:l?.cloud_graph_host_name,msGraphHost:l?.msgraph_host,nativeAccountId:h},t,n,o),f=m.tenantProfiles||[],y=c||m.realm;if(y&&!f.find(e=>e.tenantId===y)){const e=$a(r,m.localAccountId,y,h,i);f.push(e)}return m.tenantProfiles=f,m}const mh="home_account_id",fh="UPN";async function yh(e,t,r,o){if("string"==typeof e)return e;return e({clientId:t,tokenEndpoint:r,fmiPath:o})}class wh{static generateThrottlingStorageKey(e){return`${vo}.${JSON.stringify(e)}`}static preProcess(e,t,r){const o=wh.generateThrottlingStorageKey(t),n=e.getThrottlingCache(o,r);if(n){if(n.throttleTime=500&&e.status<600}static checkResponseForRetryAfter(e){return!!e.headers&&(e.headers.hasOwnProperty($r)&&(e.status<200||e.status>=300))}static calculateThrottleTime(e){const t=e<=0?0:e,r=Date.now()/1e3;return Math.floor(1e3*Math.min(r+(t||60),r+3600))}static removeThrottle(e,t,r,o){const n=Ha(t,r,o),i=this.generateThrottlingStorageKey(n);e.removeItem(i,r.correlationId)}}class vh extends Mn{constructor(e,t,r){super(e.errorCode,e.correlationId,e.errorMessage,e.subError),Object.setPrototypeOf(this,vh.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=r}}function Ch(e,t,r,o){return e.errorMessage=`${e.errorMessage}, additionalErrorInfo: error.name:${o?.name}, error.message:${o?.message}`,new vh(e,t,r)}function Ih(e,t,r){const o={};if(o[Mr]="application/x-www-form-urlencoded;charset=utf-8",!t&&r)switch(r.type){case mh:try{const e=Ma(r.credential);o[Ur]=`Oid:${e.uid}@${e.utid}`}catch(t){e.verbose(`1qhtee ${t}`,"")}break;case fh:o[Ur]=`UPN: ${r.credential}`}return o}function bh(e,t,r,o){const n=new Map;return e.embeddedClientId&&Sl(n,t,r),e.extraQueryParameters&&yl(n,e.extraQueryParameters),sl(n,e.correlationId),Qc(n,e.correlationId,o),Dc(n)}async function kh(e,t,r,o,n,i,s,a,c,l){const h=await async function(e,t,r,o,n,i,s,a){let c;wh.preProcess(n,e,o);try{c=await ua(i.sendPostRequestAsync.bind(i),oa,s,a,o)(t,r);const e=c.headers||{};a?.addFields({refreshTokenSize:c.body.refresh_token?.length||0,httpVerToken:e[Nr]||"",requestId:e[Lr]||""},o)}catch(e){if(e instanceof vh){const t=e.responseHeaders;throw t&&a?.addFields({httpVerToken:t[Nr]||"",requestId:t[Lr]||"",contentTypeHeader:t[Mr]||void 0,contentLengthHeader:t[qr]||void 0,httpStatus:e.httpStatus},o),e.error}throw e instanceof Mn?e:Jn(Xn,o)}return wh.postProcess(n,e,c,o),c}(o,e,{body:t,headers:r},n,i,s,a,c);return l&&h.status<500&&429!==h.status&&l.clearTelemetryCache(),h}async function Sh(e,t,r,o,n,i,s){const a=xa.transformCIAMAuthority(Oa(e),i),c=new xa(a,t,r,o,n,i,s);try{return await ua(c.resolveEndpointsAsync.bind(c),"authorityResolveEndpointsAsync",n,s,i)(),c}catch(e){throw Jn(Yn,i)}}class Th{constructor(e,t){this.includeRedirectUri=!0,this.config=ah(e),this.logger=new Ql(this.config.loggerOptions,Ka,Wa),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,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async acquireToken(e,t,r){if(!e.code)throw Jn("request_cannot_be_made",e.correlationId);r&&r.cloud_instance_host_name&&await ua(this.updateTokenEndpointAuthority.bind(this),"updateTokenEndpointAuthority",this.logger,this.performanceClient,e.correlationId)(r.cloud_instance_host_name,e.correlationId);const o=fa(),n=await ua(this.executeTokenRequest.bind(this),"authClientExecuteTokenRequest",this.logger,this.performanceClient,e.correlationId)(this.authority,e,this.serverTelemetryManager),i=n.headers?.[Lr],s=new gh(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.performanceClient,this.config.serializableCache,this.config.persistencePlugin);return s.validateTokenResponse(n.body,e.correlationId),ua(s.handleServerTokenResponse.bind(s),ca,this.logger,this.performanceClient,e.correlationId)(n.body,this.authority,o,e,t,r,void 0,void 0,void 0,i)}getLogoutUri(e){if(!e)throw Ds("logout_request_empty","");const t=this.createLogoutUrlQueryString(e);return Ws.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t,r){const o=bh(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri,this.performanceClient),n=Ws.appendQueryString(e.tokenEndpoint,o),i=await ua(this.createTokenRequestBody.bind(this),"authClientCreateTokenRequestBody",this.logger,this.performanceClient,t.correlationId)(t);let s;if(t.clientInfo)try{const e=Ra(t.clientInfo,this.cryptoUtils.base64Decode);s={credential:`${e.uid}.${e.utid}`,type:mh}}catch(e){this.logger.verbose(`0wznt3 ${e}`,t.correlationId)}const a=Ih(this.logger,this.config.systemOptions.preventCorsPreflight,s||t.ccsCredential),c=Ha(this.config.authOptions.clientId,t);return ua(kh,"authorizationCodeClientExecutePostToTokenEndpoint",this.logger,this.performanceClient,t.correlationId)(n,i,a,c,t.correlationId,this.cacheManager,this.networkClient,this.logger,this.performanceClient,r)}async createTokenRequestBody(e){const t=new Map;if(Zc(t,e.embeddedClientId||e.extraParameters?.[Fc]||this.config.authOptions.clientId),this.includeRedirectUri)el(t,e.redirectUri);else if(!e.redirectUri)throw Ds("redirect_uri_empty",e.correlationId);if(Xc(t,e.scopes,e.correlationId,!0,this.oidcDefaultScopes),Tl(t,e.resource),function(e,t){e.set("code",t)}(t,e.code),al(t,this.config.libraryInfo),cl(t,this.config.telemetry.application),kl(t),this.serverTelemetryManager&&!ch(this.config)&&bl(t,this.serverTelemetryManager),e.codeVerifier&&function(e,t){e.set("code_verifier",t)}(t,e.codeVerifier),this.config.clientCredentials.clientSecret&&dl(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;ul(t,await yh(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),gl(t,r.assertionType)}if(pl(t,oo),ml(t),e.authenticationScheme===wo.POP){const r=new dh(this.cryptoUtils,this.performanceClient);let o;if(e.popKid)o=this.cryptoUtils.encodeKid(e.popKid);else{o=(await ua(r.generateCnf.bind(r),aa,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}Cl(t,o)}else if(e.authenticationScheme===wo.SSH){if(!e.sshJwk)throw Ds(Bs,e.correlationId);Il(t,e.sshJwk)}let r;if(e.clientInfo)try{const t=Ra(e.clientInfo,this.cryptoUtils.base64Decode);r={credential:`${t.uid}.${t.utid}`,type:mh}}catch(t){this.logger.verbose(`0wznt3 ${t}`,e.correlationId)}else r=e.ccsCredential;if(this.config.systemOptions.preventCorsPreflight&&r)switch(r.type){case mh:try{ol(t,Ma(r.credential))}catch(t){this.logger.verbose(`1qhtee ${t}`,e.correlationId)}break;case fh:rl(t,r.credential)}return e.embeddedClientId&&Sl(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.extraParameters&&yl(t,e.extraParameters),!e.enableSpaAuthorizationCode||e.extraParameters&&e.extraParameters[Kc]||yl(t,{[Kc]:"1"}),Qc(t,e.correlationId,this.performanceClient),il(t,e.correlationId,e.claims,this.config.authOptions.clientCapabilities,e.skipBrokerClaims),Dc(t)}createLogoutUrlQueryString(e){const t=new Map;return e.postLogoutRedirectUri&&function(e,t){e.set("post_logout_redirect_uri",t)}(t,e.postLogoutRedirectUri),e.correlationId&&sl(t,e.correlationId),e.idTokenHint&&function(e,t){e.set("id_token_hint",t)}(t,e.idTokenHint),e.state&&ll(t,e.state),e.logoutHint&&function(e,t){e.set("logout_hint",t)}(t,e.logoutHint),e.extraQueryParameters&&yl(t,e.extraQueryParameters),this.config.authOptions.instanceAware&&fl(t),Dc(t)}async updateTokenEndpointAuthority(e,t){const r=`https://${e}/${this.authority.tenant}/`,o=await Sh(r,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=o}}function Ah(e){const{skus:t,libraryName:r,libraryVersion:o,extensionName:n,extensionVersion:i}=e,s=new Map([[0,[r,o]],[2,[n,i]]]);let a=[];if(t?.length){if(a=t.split(","),a.length<4)return t}else a=Array.from({length:4},()=>"|");return s.forEach((e,t)=>{2===e.length&&e[0]?.length&&e[1]?.length&&function(e){const{skuArr:t,index:r,skuName:o,skuVersion:n}=e;if(r>=t.length)return;t[r]=[o,n].join("|")}({skuArr:a,index:t,skuName:e[0],skuVersion:e[1]})}),a.join(",")}class _h{constructor(e,t){this.cacheOutcome=Ao,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||"",this.wrapperVer=e.wrapperVer||"",this.telemetryCacheKey=fo+"-"+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${yo}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],r=this.getNativeBrokerErrorCode();r?.length&&t.push(`broker_error=${r}`);const o=t.join(yo),n=[e,this.getRegionDiscoveryFields()].join(yo);return[mo,n,o].join("|")}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=_h.maxErrorsToSend(e),r=e.failedRequests.slice(0,2*t).join(yo),o=e.errors.slice(0,t).join(yo),n=e.errors.length,i=[n,t=50&&(t.failedRequests.shift(),t.failedRequests.shift(),t.errors.shift()),t.failedRequests.push(this.apiId,this.correlationId),e instanceof Error&&e&&e.toString()?e instanceof Mn?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("unknown_error"),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}catch{}}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId),e.cacheHits}getLastRequests(){return this.cacheManager.getServerTelemetry(this.telemetryCacheKey,this.correlationId)||{failedRequests:[],errors:[],cacheHits:0}}clearTelemetryCache(){const e=this.getLastRequests(),t=_h.maxErrorsToSend(e);if(t===e.errors.length)this.cacheManager.removeItem(this.telemetryCacheKey,this.correlationId);else{const r={failedRequests:e.failedRequests.slice(2*t),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,r,this.correlationId)}}static maxErrorsToSend(e){let t,r=0,o=0;const n=e.errors.length;for(t=0;t=0?e.error_uri?.substring(r+t.length):void 0}(e);if(zn(e.error,e.error_description,e.suberror))throw new Fn(e.error||"",e.correlation_id||r,e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.claims||"",t);throw new uh(e.error||"",e.correlation_id||r,e.error_description,e.suberror,t)}}class Bh{constructor(e,t,r,o,n){this.authModule=e,this.browserStorage=t,this.authCodeRequest=r,this.logger=o,this.performanceClient=n}async handleCodeResponse(e,t,r){let o;try{o=function(e,t,r){if(jh(e,t,r),!e.code)throw Jn("authorization_code_missing_from_server_response",r);return e}(e,t.state,t.correlationId)}catch(e){throw e instanceof uh&&e.subError===Bi?Li(Bi,t.correlationId):e}return ua(this.handleCodeResponseFromServer.bind(this),sa,this.logger,this.performanceClient,t.correlationId)(o,t,r)}async handleCodeResponseFromServer(e,t,r,o=!0){if(this.logger.trace("0mf2hb",t.correlationId),this.authCodeRequest.code=e.code,o&&(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 ua(this.authModule.acquireToken.bind(this.authModule),"authClientAcquireToken",this.logger,this.performanceClient,t.correlationId)(this.authCodeRequest,r,e)}createCcsCredentials(e){return e.account?{credential:e.account.homeAccountId,type:mh}:e.loginHint?{credential:e.loginHint,type:fh}:null}}class Kh extends Mn{constructor(e,t,r,o){super(e,t,r||$i(e)),Object.setPrototypeOf(this,Kh.prototype),this.name="NativeAuthError",this.ext=o}}function Wh(e){if(e.ext&&e.ext.status&&"DISABLED"===e.ext.status)return!0;if(e.ext&&e.ext.error&&-2147186943===e.ext.error)return!0;switch(e.errorCode){case"ContentError":case"PageException":return!0;default:return!1}}function Jh(e,t,r,o){let n;if(o&&o.status){switch(o.status){case"ACCOUNT_UNAVAILABLE":n=jn("native_account_unavailable",t,$i(e));break;case"USER_INTERACTION_REQUIRED":n=new Fn(e,t,r);break;case"USER_CANCEL":n=Li(Bi,t);break;case"NO_NETWORK":n=Li(Vi,t);break;case"UI_NOT_ALLOWED":n=jn(Ln,t);break;default:n=new Kh(e,t,r,o)}return n}return n=new Kh(e,t,r,o),n}class Vh{constructor(e,t){this.config=ah(e),this.logger=new Ql(this.config.loggerOptions,Ka,Wa),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}async acquireCachedToken(e){let t=Ao;if(e.forceRefresh||!Hs.isEmptyObj(e.claims))throw this.setCacheOutcome(_o,e.correlationId),Jn(si,e.correlationId);if(!e.account)throw Jn(ri,e.correlationId);const r=e.account.tenantId||function(e,t){const r=new Ws(e,t).getUrlComponents(),o=r.PathSegments.slice(-1)[0]?.toLowerCase();switch(o){case Hr:case Fr:case zr:return;default:return o}}(e.authority,e.correlationId),o=this.cacheManager.getTokenKeys(),n=this.cacheManager.getAccessToken(e.account,e,o,r);if(!n)throw this.setCacheOutcome(Eo,e.correlationId),Jn(si,e.correlationId);if(i=n.cachedAt,Number(i)>fa()||va(n.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(Po,e.correlationId),Jn(si,e.correlationId);if(e.resource){if(n.resource!==e.resource)throw this.setCacheOutcome(Eo,e.correlationId),Jn(si,e.correlationId)}else n.refreshOn&&va(n.refreshOn,0)&&(t=xo);var i;const s=e.authority||this.authority.getPreferredCache(),a={account:this.cacheManager.getAccount(this.cacheManager.generateAccountKey(e.account),e.correlationId),accessToken:n,idToken:this.cacheManager.getIdToken(e.account,e.correlationId,o,r),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(s,e.correlationId)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await ua(this.generateResultFromCacheRecord.bind(this),"silentFlowClientGenerateResultFromCacheRecord",this.logger,this.performanceClient,e.correlationId)(a,e),t]}setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==Ao&&this.logger.info(`09ingz ${e}`,t)}async generateResultFromCacheRecord(e,t){let r;return e.idToken&&(r=pa(e.idToken.secret,this.config.cryptoInterface.base64Decode,t.correlationId)),gh.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,this.performanceClient,r)}}class Gh extends Lh{async acquireToken(e){const t=Oh(fn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),r=await ua(this.getClientConfiguration.bind(this),Ci,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,account:e.account}),o=new Vh(r,this.performanceClient);this.logger.verbose("0wa871",this.correlationId);try{const t=(await ua(o.acquireCachedToken.bind(o),"silentFlowClientAcquireCachedToken",this.logger,this.performanceClient,e.correlationId)(e))[0];return this.performanceClient.addFields({fromCache:!0},e.correlationId),t}catch(e){throw e instanceof Ui&&e.errorCode===Qi&&this.logger.verbose("06wena",this.correlationId),e}}logout(e){this.logger.verbose("1rkurh",this.correlationId);const t=this.initializeLogoutRequest(e);return Mh(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,t.account)}}class Qh extends Ph{constructor(e,t,r,o,n,i,s,a,c,l,h,d){super(e,t,r,o,n,i,a,d,c),this.apiId=s,this.accountId=l,this.platformAuthProvider=c,this.nativeStorageManager=h,this.silentCacheClient=new Gh(e,this.nativeStorageManager,r,o,n,i,a,d,c);const u=this.platformAuthProvider.getExtensionName();this.skus=_h.makeExtraSkuString({libraryName:Uo,libraryVersion:Dl,extensionName:u,extensionVersion:this.platformAuthProvider.getExtensionVersion()})}addRequestSKUs(e){e.extraParameters={...e.extraParameters,[Wc]:this.skus}}async acquireToken(e,t){this.logger.trace("03qeos",this.correlationId);const r=this.performanceClient.startMeasurement(gi,this.correlationId),o=fa(),n=Oh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{const i=await this.initializePlatformRequest(e);try{const e=await this.acquireTokensFromCache(this.accountId,i);return r.end({success:!0,isNativeBroker:!1,fromCache:!0}),e}catch(e){if(t===An)throw this.logger.info("0eitbc",this.correlationId),r.end({success:!1,brokerErrorCode:"cache_request_failed"}),e;this.logger.info("0957j1",this.correlationId)}const s=await this.platformAuthProvider.sendMessage(i);return await this.handleNativeResponse(s,i,o).then(e=>(r.end({success:!0,isNativeBroker:!0,requestId:e.requestId}),n.clearNativeBrokerErrorCode(),e)).catch(e=>{throw r.end({success:!1,errorCode:e.errorCode,subErrorCode:e.subError}),e})}catch(e){throw e instanceof Kh&&n.setNativeBrokerErrorCode(e.errorCode),r.end({success:!1}),e}}createSilentCacheRequest(e,t){return{authority:e.authority,correlationId:this.correlationId,scopes:Ja.fromString(e.scope,this.correlationId).asArray(),account:t,forceRefresh:!1}}async acquireTokensFromCache(e,t){if(!e)throw this.logger.warning("1ndf3e",this.correlationId),Jn(ni,this.correlationId);const r=this.browserStorage.getBaseAccountInfo({nativeAccountId:e},this.correlationId);if(!r)throw Jn(ni,this.correlationId);try{const e=this.createSilentCacheRequest(t,r),o=await this.silentCacheClient.acquireToken(e),n=this.browserStorage.getIdToken(r,this.correlationId,this.browserStorage.getTokenKeys(),r.tenantId),i=pa(n?.secret||"",rs,this.correlationId),s=Ua(r,void 0,i,n?.secret);return{...o,idToken:n?.secret||"",idTokenClaims:i,account:s}}catch(e){throw e}}async acquireTokenRedirect(e,t,r){this.logger.trace("0luikq",this.correlationId);const o=await this.initializePlatformRequest(e),n=r?.navigateToLoginRequestUrl??!0;try{await this.platformAuthProvider.sendMessage(o)}catch(e){if(e instanceof Kh){if(Oh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled).setNativeBrokerErrorCode(e.errorCode),Wh(e))throw e}}this.browserStorage.setTemporaryCache(cn,JSON.stringify(o),!0);const i={apiId:dn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},s=n?Ws.getAbsoluteUrl(e.redirectStartPage||window.location.href,Ol(),this.correlationId):xh(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId);t.end({success:!0}),await this.navigationClient.navigateExternal(s,i)}async handleRedirectPromise(){if(this.logger.trace("1c5lhw",this.correlationId),!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("0le6uv",this.correlationId),null;const e=this.browserStorage.getCachedNativeRequest();if(!e)return this.logger.verbose("0a6zjb",this.correlationId),this.performanceClient?.addFields({errorCode:"no_cached_request"},this.correlationId),null;const{prompt:t,...r}=e;t&&this.logger.verbose("0ac34v",this.correlationId),this.browserStorage.removeItem(this.browserStorage.generateCacheKey(cn));const o=fa();try{this.logger.verbose("003x5a",this.correlationId);const e=await this.platformAuthProvider.sendMessage(r),t=await this.handleNativeResponse(e,r,o);return Oh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled).clearNativeBrokerErrorCode(),this.performanceClient?.addFields({isNativeBroker:!0},this.correlationId),t}catch(e){throw e}}logout(){return this.logger.trace("0u2sjm",this.correlationId),Promise.reject("Logout not implemented yet")}async handleNativeResponse(e,t,r){this.logger.trace("1bojln",this.correlationId);const o=pa(e.id_token,rs,this.correlationId),n=this.createHomeAccountIdentifier(e,o),i=this.browserStorage.getAccountInfoFilteredBy({nativeAccountId:t.accountId},this.correlationId)?.homeAccountId;if(t.extraParameters?.child_client_id&&e.account.id!==t.accountId)this.logger.info("1ub1in",this.correlationId);else if(n!==i&&e.account.id!==t.accountId)throw Jh("user_switch",this.correlationId);const s=await Rh(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,t.authority),a=ph(this.browserStorage,s,n,rs,this.correlationId,o,e.client_info,s.getPreferredCache(),o.tid,void 0,e.account.id,this.logger,this.performanceClient);e.expires_in=Number(e.expires_in);const c=await this.generateAuthenticationResult(e,t,o,a,s.canonicalAuthority,r);return await this.cacheAccount(a,ma(o)),await this.cacheNativeTokens(e,t,n,o,c.tenantId,r,s.getPreferredCache()),c}createHomeAccountIdentifier(e,t){return Da(e.client_info||"",qs,this.logger,this.browserCrypto,this.correlationId,t)}generateScopes(e,t){return t?Ja.fromString(t,this.correlationId):Ja.fromString(e,this.correlationId)}async generatePopAccessToken(e,t){if(t.tokenType===wo.POP&&t.signPopToken){if(e.shr)return this.logger.trace("0coqhu",this.correlationId),e.shr;const r=new dh(this.browserCrypto,this.performanceClient),o={resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,shrNonce:t.shrNonce,correlationId:this.correlationId};if(!t.keyId)throw Jn(ai,this.correlationId);return r.signPopToken(e.access_token,t.keyId,o)}return e.access_token}async generateAuthenticationResult(e,t,r,o,n,i){const s=this.addTelemetryFromNativeResponse(e.properties.MATS),a=this.generateScopes(t.scope,e.scope),c=e.account.properties||{},l=c.UID||r.oid||r.sub||"",h=c.TenantId||r.tid||"",d=Ua(Na(o),void 0,r,e.id_token);if(d.nativeAccountId!==e.account.id){d.nativeAccountId=e.account.id;const t=h||d.tenantId,r=d.tenantProfiles?.get(t);r&&(r.nativeAccountId=e.account.id)}const u=await this.generatePopAccessToken(e,t),g=t.tokenType===wo.POP?wo.POP:wo.BEARER;return{authority:n,uniqueId:l,tenantId:h,scopes:a.asArray(),account:d,idToken:e.id_token,idTokenClaims:r,accessToken:u,fromCache:!!s&&this.isResponseFromCache(s),expiresOn:wa(i+e.expires_in),tokenType:g,correlationId:this.correlationId,state:e.state,fromPlatformBroker:!0,...t.resource&&{resource:t.resource}}}async cacheAccount(e,t){await this.browserStorage.setAccount(e,this.correlationId,t,this.apiId),this.browserStorage.removeAccountContext(Na(e),this.correlationId)}async cacheNativeTokens(e,t,r,o,n,i,s){const a=Ia(r,s,e.id_token||"",t.clientId,o.tid||""),c=i+(t.tokenType===wo.POP?240:("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0),l=this.generateScopes(e.scope,t.scope),h=ba(r,s,e.access_token,t.clientId,o.tid||n,l.printScopes(),c,0,rs,t.correlationId,void 0,t.tokenType,void 0,t.keyId);a&&!1!==t.storeInCache?.idToken&&await this.browserStorage.setIdTokenCredential(a,this.correlationId,ma(o));const d={accessToken:h};return this.nativeStorageManager.saveCacheRecord(d,this.correlationId,ma(o),this.apiId,t.storeInCache)}getExpiresInValue(e,t){return e===wo.POP?240:("string"==typeof t?parseInt(t,10):t)||0}addTelemetryFromNativeResponse(e){const t=this.getMATSFromResponse(e);return t?(this.performanceClient.addFields({extensionId:this.platformAuthProvider.getExtensionId(),extensionVersion:this.platformAuthProvider.getExtensionVersion(),matsBrokerVersion:t.broker_version,matsAccountJoinOnStart:t.account_join_on_start,matsAccountJoinOnEnd:t.account_join_on_end,matsDeviceJoin:t.device_join,matsPromptBehavior:t.prompt_behavior,matsApiErrorCode:t.api_error_code,matsUiVisible:t.ui_visible,matsSilentCode:t.silent_code,matsSilentBiSubCode:t.silent_bi_sub_code,matsSilentMessage:t.silent_message,matsSilentStatus:t.silent_status,matsHttpStatus:t.http_status,matsHttpEventCount:t.http_event_count},this.correlationId),t):null}getMATSFromResponse(e){if(e)try{return JSON.parse(e)}catch(e){this.logger.error("0b3l57",this.correlationId)}return null}isResponseFromCache(e){return void 0===e.is_cached?(this.logger.verbose("1okqev",this.correlationId),!1):!!e.is_cached}async initializePlatformRequest(e){this.logger.trace("1xdm2a",this.correlationId);const t=await this.getCanonicalAuthority(e),r=e.skipBrokerClaims&&e.embeddedClientId?void 0:this.config.auth.clientCapabilities,{scopes:o,claims:n,...i}=e,s=new Ja(o||[],this.correlationId);s.appendScopes(Or);const a={...i,claims:vl(n,r?.length?r:void 0),accountId:this.accountId,clientId:this.config.auth.clientId,authority:t.urlString,scope:s.printScopes(),redirectUri:xh(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId),prompt:this.getPrompt(e.prompt),correlationId:this.correlationId,tokenType:e.authenticationScheme,windowTitleSubstring:document.title,extraParameters:{...e.extraParameters},extendedExpiryToken:!1,keyId:e.popKid};if(a.signPopToken&&e.popKid)throw Li("invalid_pop_token_request",this.correlationId);if(this.handleExtraBrokerParams(a),a.extraParameters=a.extraParameters||{},a.extraParameters.telemetry=Do,e.authenticationScheme===wo.POP){const t={resourceRequestUri:e.resourceRequestUri,resourceRequestMethod:e.resourceRequestMethod,shrClaims:e.shrClaims,shrNonce:e.shrNonce,correlationId:this.correlationId},r=new dh(this.browserCrypto,this.performanceClient);let o;if(a.keyId)o=this.browserCrypto.base64UrlEncode(JSON.stringify({kid:a.keyId})),a.signPopToken=!1;else{const e=await ua(r.generateCnf.bind(r),aa,this.logger,this.performanceClient,this.correlationId)(t,this.logger);o=e.reqCnfString,a.keyId=e.kid,a.signPopToken=!0}a.reqCnf=o}return this.addRequestSKUs(a),a}async getCanonicalAuthority(e){const t=e.authority||this.config.auth.authority,{azureCloudOptions:r,account:o}=e;o&&await Rh(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,t,r,void 0,o);const n=new Ws(t,this.correlationId);return n.validateAsUri(),n}getPrompt(e){switch(this.apiId){case gn:case fn:return this.logger.trace("12n1y2",this.correlationId),Yr}if(e)switch(e){case Yr:case Qr:case Vr:return this.logger.trace("0i0hco",this.correlationId),e;default:throw this.logger.trace(`0w3tpw ${e}`,this.correlationId),Li("native_prompt_not_supported",this.correlationId)}else this.logger.trace("0uid1p",this.correlationId)}handleExtraBrokerParams(e){const t=e.extraParameters&&e.extraParameters.hasOwnProperty(Jc)&&e.extraParameters.hasOwnProperty(Vc)&&e.extraParameters.hasOwnProperty(Fc);if(!e.embeddedClientId&&!t)return;let r="";const o=e.redirectUri;e.embeddedClientId?(e.redirectUri=this.config.auth.redirectUri,r=e.embeddedClientId):e.extraParameters&&(e.redirectUri=e.extraParameters[Vc],r=e.extraParameters[Fc]),e.extraParameters={child_client_id:r,child_redirect_uri:o},this.performanceClient?.addFields({embeddedClientId:r,embeddedRedirectUri:o},this.correlationId)}}const Yh=new Map([["e","AAD"],["m","MSA"]]);function Xh(e,t,r){const o=function(e){if(!e)return null;try{const t=(/%(?:[0-9A-Fa-f]{2})/.test(e)?decodeURIComponent(e):e).split("|");return t.length<5?null:{accountType:Yh.get(t[0]?.trim()||"")||"",error:t[1]?.trim()||"",subError:t[2]?.trim()||"",cloudInstance:t[3]?.trim()||"",callerDataBoundary:t[4]?.trim()||""}}catch{return null}}(e.clientdata);o?.accountType&&r.addFields({accountType:o.accountType},t),o?.error&&r.addFields({serverErrorNo:o.error},t),o?.subError&&r.addFields({serverSubErrorNo:o.subError},t)}async function Zh(e,t,r,o,n){const i=Fh({...e.auth,authority:t},r,o,n);if(al(i,{sku:Uo,version:Dl,os:"",cpu:""}),e.system.protocolMode!==ea&&cl(i,e.telemetry.application),r.platformBroker&&(function(e){e.set("nativebroker","1")}(i),n.addFields({isPlatformAuthorizeRequest:!0},r.correlationId),r.authenticationScheme===wo.POP)){const e=new Ps(o,n),t=new dh(e,n);let s;if(r.popKid)s=e.encodeKid(r.popKid);else{s=(await ua(t.generateCnf.bind(t),aa,o,n,r.correlationId)(r,o)).reqCnfString}Cl(i,s)}return Qc(i,r.correlationId,n),i}async function ed(e,t,r,o,n){if(!r.codeChallenge)throw Ds(zs,r.correlationId);const i=await ua(Zh,"getStandardParams",o,n,r.correlationId)(e,t,r,o,n);return Yc(i,Zr),hl(i,r.codeChallenge,Sr),yl(i,{...r.extraQueryParameters,...r.extraParameters}),zh(t,i)}async function td(e,t,r,o,n,i){if(!o.earJwk)throw Li(Di,o.correlationId);const s=await Zh(t,r,o,n,i);Yc(s,eo),function(e,t){e.set("ear_jwk",encodeURIComponent(t)),e.set("ear_jwe_crypto","eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0")}(s,o.earJwk),hl(s,o.codeChallenge,Sr),yl(s,{...o.extraParameters});const a=new Map;yl(a,o.extraQueryParameters||{}),sl(a,o.correlationId);return od(e,zh(r,a),s)}async function rd(e,t,r,o,n,i){const s=await Zh(t,r,o,n,i);Yc(s,Zr),hl(s,o.codeChallenge,o.codeChallengeMethod||Sr),yl(s,{...o.extraParameters});const a=new Map;yl(a,o.extraQueryParameters||{}),sl(a,o.correlationId);return od(e,zh(r,a),s)}function od(e,t,r){const o=e.createElement("form");return o.method="post",o.action=t,r.forEach((t,r)=>{const n=e.createElement("input");n.hidden=!0,n.name=r,n.value=t,o.appendChild(n)}),e.body.appendChild(o),o}async function nd(e,t,r,o,n,i,s,a,c,l){if(a.verbose("11qcow",e.correlationId),!l)throw Li(Xi,e.correlationId);const h=new Ps(a,c),d=new Qh(o,n,h,a,s,o.system.navigationClient,r,c,l,t,i,e.correlationId),{userRequestState:u}=Uc(h.base64Decode,e.state,e.correlationId);return ua(d.acquireToken.bind(d),gi,a,c,e.correlationId)({...e,state:u,prompt:void 0})}async function id(e,t,r,o,n,i,s,a,c,l,h,d){if(wh.removeThrottle(s,n.auth.clientId,e),Xh(t,e.correlationId,h),t.accountId)return ua(nd,ki,l,h,e.correlationId)(e,t.accountId,o,n,s,a,c,l,h,d);const u={...e,code:t.code||"",codeVerifier:r},g=new Bh(i,s,u,l,h);return await ua(g.handleCodeResponse.bind(g),"handleCodeResponse",l,h,e.correlationId)(t,e,o)}async function sd(e,t,r,o,n,i,s,a,c,l,h){if(wh.removeThrottle(i,o.auth.clientId,e),Xh(t,e.correlationId,l),jh(t,e.state,e.correlationId),!t.ear_jwe)throw Li("ear_jwe_empty",e.correlationId);if(!e.earJwk)throw Li(Di,e.correlationId);const d=JSON.parse(await ua(Cs,"decryptEarResponse",c,l,e.correlationId)(e.earJwk,t.ear_jwe));if(d.accountId)return ua(nd,ki,c,l,e.correlationId)(e,d.accountId,r,o,i,s,a,c,l,h);const u=new gh(o.auth.clientId,i,new Ps(c,l),c,l,null,null);u.validateTokenResponse(d,e.correlationId);const g={code:"",state:e.state,nonce:e.nonce,client_info:d.client_info,cloud_graph_host_name:d.cloud_graph_host_name,cloud_instance_host_name:d.cloud_instance_host_name,cloud_instance_name:d.cloud_instance_name,msgraph_host:d.msgraph_host};return await ua(u.handleServerTokenResponse.bind(u),ca,c,l,e.correlationId)(d,n,fa(),e,r,g,void 0,void 0,void 0,void 0)}async function ad(e,t,r){const o=da(cd,"generateCodeVerifier",t,e,r)(e,t,r);return{verifier:o,challenge:await ua(ld,"generateCodeChallengeFromVerifier",t,e,r)(o,e,t,r)}}function cd(e,t,r){try{const o=new Uint8Array(32);da(ms,"getRandomValues",t,e,r)(o);return Ri(o)}catch(e){throw Li(Ni,r)}}async function ld(e,t,r,o){try{const n=await ua(ps,"sha256Digest",r,t,o)(e);return Ri(new Uint8Array(n))}catch(e){throw Li(Ni,o)}}const hd={sendGetRequestAsync:()=>Promise.reject(Jn(ci,"")),sendPostRequestAsync:()=>Promise.reject(Jn(ci,""))};class dd{navigateInternal(e,t){return dd.defaultNavigateWindow(e,t)}navigateExternal(e,t){return dd.defaultNavigateWindow(e,t)}static defaultNavigateWindow(e,t){return t.noHistory?window.location.replace(e):window.location.assign(e),new Promise((e,r)=>{setTimeout(()=>{r(Li(ts,"","failed_to_redirect"))},t.timeout)})}}class ud{async sendGetRequestAsync(e,t){let r,o={},n=0;const i=gd(t);try{r=await fetch(e,{method:Xo,headers:i})}catch(e){throw Ch(Li(window.navigator.onLine?"get_request_failed":Vi,""),void 0,void 0,e)}o=pd(r.headers);try{return n=r.status,{headers:o,body:await r.json(),status:n}}catch(e){throw Ch(Li(Gi,""),n,o,e)}}async sendPostRequestAsync(e,t){const r=t&&t.body||"",o=gd(t);let n,i=0,s={};try{n=await fetch(e,{method:Zo,headers:o,body:r})}catch(e){throw Ch(Li(window.navigator.onLine?"post_request_failed":Vi,""),void 0,void 0,e)}s=pd(n.headers);try{return i=n.status,{headers:s,body:await n.json(),status:i}}catch(e){throw Ch(Li(Gi,""),i,s,e)}}}function gd(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 Ch(Li("failed_to_build_headers",""),void 0,void 0,e)}}function pd(e){try{const t={};return e.forEach((e,r)=>{t[r]=e}),t}catch(e){throw Li("failed_to_parse_headers","")}}const md="unexpected_error";class fd{constructor(e,t,r,o){this.logger=e,this.handshakeTimeoutMs=t,this.extensionId=o,this.resolvers=new Map,this.handshakeResolvers=new Map,this.messageChannel=new MessageChannel,this.windowListener=this.onWindowMessage.bind(this),this.performanceClient=r,this.handshakeEvent=this.performanceClient.startMeasurement("nativeMessageHandlerHandshake"),this.platformAuthType=Bo}async sendMessage(e){this.logger.trace(`0on4p2 ${this.platformAuthType}`,e.correlationId);const t={method:Jo,request:e},r={channel:Lo,extensionId:this.extensionId,responseId:ys(),body:t};this.logger.trace(`1qadfi ${this.platformAuthType}`,e.correlationId),this.logger.tracePii(`1xm533 ${this.platformAuthType} ${JSON.stringify(r)}`,e.correlationId),this.messageChannel.port1.postMessage(r);const o=await new Promise((e,t)=>{this.resolvers.set(r.responseId,{resolve:e,reject:t})});return this.validatePlatformBrokerResponse(o)}static async createProvider(e,t,r,o){e.trace("15zfnw",o);try{const n=new fd(e,t,r,No);return await n.sendHandshakeRequest(o),n}catch(n){const i=new fd(e,t,r);return await i.sendHandshakeRequest(o),i}}async sendHandshakeRequest(e){this.logger.trace(`1dpg9o ${this.platformAuthType}`,e),window.addEventListener("message",this.windowListener,!1);const t={channel:Lo,extensionId:this.extensionId,responseId:ys(),body:{method:Ko}};return this.handshakeEvent.add({extensionId:this.extensionId,extensionHandshakeTimeoutMs:this.handshakeTimeoutMs}),this.messageChannel.port1.onmessage=e=>{this.onChannelMessage(e)},window.postMessage(t,window.origin,[this.messageChannel.port2]),new Promise((e,r)=>{this.handshakeResolvers.set(t.responseId,{resolve:e,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(Li("native_handshake_timeout","")),this.handshakeResolvers.delete(t.responseId)},this.handshakeTimeoutMs)})}onWindowMessage(e){const t=Ll();if(this.logger.trace(`0jpn5u ${this.platformAuthType}`,t),e.source!==window)return;const r=e.data;if(r.channel&&r.channel===Lo&&(!r.extensionId||r.extensionId===this.extensionId)&&r.body.method===Ko){const e=this.handshakeResolvers.get(r.responseId);if(!e)return void this.logger.trace(`07buhm ${this.platformAuthType} ${r.responseId}`,t);this.logger.verbose(r.extensionId?`0xrkug ${r.extensionId}`:"No extension installed",t),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(Li("native_extension_not_installed",""))}}onChannelMessage(e){const t=Ll();this.logger.trace(`1py8yf ${this.platformAuthType}`,t);const r=e.data,o=this.resolvers.get(r.responseId),n=this.handshakeResolvers.get(r.responseId);try{const e=r.body.method;if(e===Vo){if(!o)return;const e=r.body.response;if(this.logger.trace(`19hpgm ${this.platformAuthType}`,t),this.logger.tracePii(`179a24 ${this.platformAuthType} ${JSON.stringify(e)}`,t),"Success"!==e.status)o.reject(Jh(e.code,t,e.description,e.ext));else{if(!e.result)throw qn(md,t,"Event does not contain result.");e.result.code&&e.result.description?o.reject(Jh(e.result.code,t,e.result.description,e.result.ext)):o.resolve(e.result)}this.resolvers.delete(r.responseId)}else if(e===Wo){if(!n)return void this.logger.trace(`082qnt ${this.platformAuthType} ${r.responseId}`,t);clearTimeout(this.timeoutId),window.removeEventListener("message",this.windowListener,!1),this.extensionId=r.extensionId,this.extensionVersion=r.body.version,this.logger.verbose(`0yf5ib ${this.platformAuthType} ${this.extensionId}`,t),this.handshakeEvent.end({extensionInstalled:!0,success:!0}),n.resolve(),this.handshakeResolvers.delete(r.responseId)}}catch(r){this.logger.error("0xf978",t),this.logger.errorPii(`04i99o ${r}`,t),this.logger.errorPii(`0xdvsy ${e}`,t),o?o.reject(r):n&&n.reject(r)}}validatePlatformBrokerResponse(e){if(e.hasOwnProperty("access_token")&&e.hasOwnProperty("id_token")&&e.hasOwnProperty("client_info")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scope")&&e.hasOwnProperty("expires_in"))return e;throw qn(md,"","Response missing expected properties.")}getExtensionId(){return this.extensionId}getExtensionVersion(){return this.extensionVersion}getExtensionName(){return this.getExtensionId()===No?"chrome":this.getExtensionId()?.length?"unknown":void 0}}class yd{constructor(e,t,r){this.logger=e,this.performanceClient=t,this.correlationId=r,this.platformAuthType=jo}static async createProvider(e,t,r){if(e.trace("12mj4a",r),window.navigator?.platformAuthentication){const o=await window.navigator.platformAuthentication.getSupportedContracts(Ho);if(o?.includes(zo))return e.trace("1h5q1r",r),new yd(e,t,r)}}getExtensionId(){return Ho}getExtensionVersion(){return""}getExtensionName(){return Fo}async sendMessage(e){this.logger.trace(`02bcil ${this.platformAuthType}`,e.correlationId);try{const t=this.initializePlatformDOMRequest(e),r=await window.navigator.platformAuthentication.executeGetToken(t);return this.validatePlatformBrokerResponse(r,e.correlationId)}catch(t){throw this.logger.error(`11im7g ${this.platformAuthType}`,e.correlationId),t}}initializePlatformDOMRequest(e){this.logger.trace(`15d6yv ${this.platformAuthType}`,e.correlationId);const{accountId:t,clientId:r,authority:o,scope:n,redirectUri:i,correlationId:s,state:a,storeInCache:c,embeddedClientId:l,extraParameters:h,...d}=e,u=this.getDOMExtraParams(d,s);return{accountId:t,brokerId:this.getExtensionId(),authority:o,clientId:r,correlationId:s||this.correlationId,extraParameters:{...h,...u},isSecurityTokenService:!1,redirectUri:i,scope:n,state:a,storeInCache:c,embeddedClientId:l}}validatePlatformBrokerResponse(e,t){if(e.hasOwnProperty("isSuccess")){if(e.hasOwnProperty("accessToken")&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("clientInfo")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scopes")&&e.hasOwnProperty("expiresIn"))return this.logger.trace(`0h4vei ${this.platformAuthType}`,t),this.convertToPlatformBrokerResponse(e,t);if(e.hasOwnProperty("error")){const r=e;if(!1===r.isSuccess&&r.error&&r.error.code)throw this.logger.trace(`0g92vm ${this.platformAuthType}`,t),Jh(r.error.code,t,r.error.description,{error:parseInt(r.error.errorCode),protocol_error:r.error.protocolError,status:r.error.status,properties:r.error.properties})}}throw qn(md,t,"Response missing expected properties.")}convertToPlatformBrokerResponse(e,t){this.logger.trace(`14913t ${this.platformAuthType}`,t);return{access_token:e.accessToken,id_token:e.idToken,client_info:e.clientInfo,account:e.account,expires_in:e.expiresIn,scope:e.scopes,state:e.state||"",properties:e.properties||{},extendedLifetimeToken:e.extendedLifetimeToken??!1,shr:e.proofOfPossessionPayload}}getDOMExtraParams(e,t){try{const t={};for(const[r,o]of Object.entries(e))o&&(t[r]="object"==typeof o?JSON.stringify(o):String(o));return t}catch(e){return this.logger.error(`0eu9o3 ${this.platformAuthType}`,t),this.logger.errorPii(`17rpl5 ${this.platformAuthType} ${e}`,t),{}}}}async function wd(e,t,r,o,n){let i;e.trace("134j0v",r),e.trace(`04c81g ${n}`,r);try{n&&(i=await yd.createProvider(e,t,r)),i||(e.trace("0l3na8",r),i=await fd.createProvider(e,o||2e3,t,r))}catch(t){e.trace("0icbd7",t)}return i}function vd(e,t,r,o,n){if(t.trace("0uko3r",r),!e.system.allowPlatformBroker&&e.experimental.allowPlatformBrokerWithDOM)throw Ds("invalid_platform_broker_configuration","");if(!e.system.allowPlatformBroker)return t.trace("04hozs",r),!1;if(!o)return t.trace("0kvv1r",r),!1;if(n)switch(n){case wo.BEARER:case wo.POP:return t.trace("18tev1",r),!0;default:return t.trace("1dd2nh",r),!1}return!0}class Cd extends Lh{constructor(e,t,r,o,n,i,s,a,c,l,h){super(e,t,r,o,n,i,s,c,l),this.nativeStorage=a,this.eventHandler=n,this.waitForPopupResponseHook=h}acquireToken(e,t){let r;try{if(r={popupName:this.generatePopupName(e.scopes||Or,e.authority||this.config.auth.authority),popupWindowAttributes:e.popupWindowAttributes||{},popupWindowParent:e.popupWindowParent??window},this.performanceClient.addFields({isAsyncPopup:!this.config.system.navigatePopups},this.correlationId),this.config.system.navigatePopups){const o={...e,httpMethod:Uh(e,this.config.system.protocolMode)};return this.logger.verbose("1f9ok3",this.correlationId),r.popup=this.openSizedPopup("about:blank",r),this.acquireTokenPopupAsync(o,r,t)}return this.logger.verbose("162h4u",this.correlationId),this.acquireTokenPopupAsync(e,r,t)}catch(e){return Promise.reject(e)}}logout(e){try{this.logger.verbose("068rup",this.correlationId);const t=this.initializeLogoutRequest(e),r={popupName:this.generateLogoutPopupName(t),popupWindowAttributes:e?.popupWindowAttributes||{},popupWindowParent:e?.popupWindowParent??window},o=e&&e.authority,n=e&&e.mainWindowRedirectUri;return this.config.system.navigatePopups?(this.logger.verbose("1a28da",this.correlationId),r.popup=this.openSizedPopup("about:blank",r),this.logoutPopupAsync(t,r,o,n)):(this.logger.verbose("1phd8u",this.correlationId),this.logoutPopupAsync(t,r,o,n))}catch(e){return Promise.reject(e)}}async acquireTokenPopupAsync(e,t,r){this.logger.verbose("1g77pg",this.correlationId);const o=await ua(Nh,Ii,this.logger,this.performanceClient,this.correlationId)(e,In.Popup,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);t.popup&&Ul(o.authority);const n=vd(this.config,this.logger,this.correlationId,this.platformAuthProvider,e.authenticationScheme);return o.platformBroker=n,this.config.system.protocolMode===ta?this.executeEarFlow(o,t,r):this.executeCodeFlow(o,t,r)}async executeCodeFlow(e,t,r){const o=e.correlationId,n=Oh(un,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),i=r||await ua(ad,_i,this.logger,this.performanceClient,o)(this.performanceClient,this.logger,o),s={...e,codeChallenge:i.challenge};try{const r=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,o)({serverTelemetryManager:n,requestAuthority:s.authority,requestAzureCloudOptions:s.azureCloudOptions,requestExtraQueryParameters:s.extraQueryParameters,account:s.account});if(s.httpMethod===xr)return await this.executeCodeFlowWithPost(s,t,r,i.verifier);{const n=await ua(ed,ia,this.logger,this.performanceClient,o)(this.config,r.authority,s,this.logger,this.performanceClient),a=this.initiateAuthRequest(n,t);this.eventHandler.emitEvent(Pc,o,In.Popup,{popupWindow:a},null);const c=await this.waitForPopupResponse(e,a,t.popupWindowParent),l=da(Dh,Ti,this.logger,this.performanceClient,this.correlationId)(c,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);return await ua(id,Si,this.logger,this.performanceClient,o)(e,l,i.verifier,un,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}catch(e){throw t.popup?.close(),e instanceof Mn&&(e.correlationId=this.correlationId,n.cacheFailedRequest(e)),e}}async executeEarFlow(e,t,r){const{correlationId:o,authority:n,azureCloudOptions:i,extraQueryParameters:s,account:a}=e,c=await ua(Rh,ui,this.logger,this.performanceClient,o)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,i,s,a),l=await ua(vs,xi,this.logger,this.performanceClient,o)(),h=r||await ua(ad,_i,this.logger,this.performanceClient,o)(this.performanceClient,this.logger,o),d={...e,earJwk:l,codeChallenge:h.challenge},u=t.popup||this.openPopup("about:blank",t);(await td(u.document,this.config,c,d,this.logger,this.performanceClient)).submit();const g=await ua(this.waitForPopupResponse.bind(this),wi,this.logger,this.performanceClient,o)(d,u,t.popupWindowParent),p=da(Dh,Ti,this.logger,this.performanceClient,this.correlationId)(g,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);if(!p.ear_jwe&&p.code){const t=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,o)({serverTelemetryManager:Oh(un,this.config.auth.clientId,o,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:c});return ua(id,Si,this.logger,this.performanceClient,o)(d,p,h.verifier,un,this.config,t,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}return ua(sd,bi,this.logger,this.performanceClient,o)(d,p,un,this.config,c,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async executeCodeFlowWithPost(e,t,r,o){const n=e.correlationId,i=await ua(Rh,ui,this.logger,this.performanceClient,n)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger),s=t.popup||this.openPopup("about:blank",t);(await rd(s.document,this.config,i,e,this.logger,this.performanceClient)).submit();const a=await ua(this.waitForPopupResponse.bind(this),wi,this.logger,this.performanceClient,n)(e,s,t.popupWindowParent),c=da(Dh,Ti,this.logger,this.performanceClient,this.correlationId)(a,this.config.auth.OIDCOptions.responseMode,this.logger,this.correlationId);return ua(id,Si,this.logger,this.performanceClient,n)(e,c,o,un,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async logoutPopupAsync(e,t,r,o){this.logger.verbose("0b7yrk",this.correlationId),this.eventHandler.emitEvent(xc,this.correlationId,In.Popup,e);const n=Oh(wn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{await Mh(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,e.account);const i=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:r,account:e.account||void 0});try{i.authority.endSessionEndpoint}catch{if(e.account?.homeAccountId&&e.postLogoutRedirectUri&&i.authority.protocolMode===ea){if(this.eventHandler.emitEvent(Oc,e.correlationId,In.Popup,e),o){const e={apiId:wn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=Ws.getAbsoluteUrl(o,Ol(),this.correlationId);await this.navigationClient.navigateInternal(t,e)}return void t.popup?.close()}}e.state=$c(this.browserCrypto,e.state||"",{interactionType:In.Popup},e.correlationId);const s=i.getLogoutUri(e);this.eventHandler.emitEvent(Oc,e.correlationId,In.Popup,e);const a=this.openPopup(s,t);if(this.eventHandler.emitEvent(Pc,e.correlationId,In.Popup,{popupWindow:a},null),await this.waitForPopupResponse(e,a,t.popupWindowParent).catch(()=>{}),o){const e={apiId:wn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=Ws.getAbsoluteUrl(o,Ol(),this.correlationId);this.logger.verbose("0qcur2",this.correlationId),this.logger.verbosePii(`0oj7lk ${t}`,this.correlationId),await this.navigationClient.navigateInternal(t,e)}else this.logger.verbose("03zgcf",this.correlationId)}catch(e){throw t.popup?.close(),e instanceof Mn&&(e.correlationId=this.correlationId,n.cacheFailedRequest(e)),this.eventHandler.emitEvent(Rc,this.correlationId,In.Popup,null,e),this.eventHandler.emitEvent(Mc,this.correlationId,In.Popup),e}this.eventHandler.emitEvent(Mc,this.correlationId,In.Popup)}initiateAuthRequest(e,t){if(e)return this.logger.infoPii(`1kcr9k ${e}`,this.correlationId),this.openPopup(e,t);throw this.logger.error("1l7hyp",this.correlationId),Li(Fi,this.correlationId)}openPopup(e,t){try{let r;if(t.popup?(r=t.popup,this.logger.verbosePii(`0cgeo7 ${e}`,this.correlationId),r.location.assign(e)):void 0===t.popup&&(this.logger.verbosePii(`0c2awd ${e}`,this.correlationId),r=this.openSizedPopup(e,t)),!r)throw Li("empty_window_error",this.correlationId);try{r.document.title="Microsoft Authentication"}catch(e){"undefined"!=typeof DOMException&&e instanceof DOMException&&"SecurityError"===e.name||this.logger.verbose("1s1yfs",this.correlationId)}return r.focus&&r.focus(),this.currentWindow=r,r}catch(e){throw this.logger.error(`0dxfb9 ${e.message}`,this.correlationId),Li("popup_window_error",this.correlationId)}}openSizedPopup(e,{popupName:t,popupWindowAttributes:r,popupWindowParent:o}){const n=o.screenLeft?o.screenLeft:o.screenX,i=o.screenTop?o.screenTop:o.screenY,s=o.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,a=o.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;let c=r.popupSize?.width,l=r.popupSize?.height,h=r.popupPosition?.top,d=r.popupPosition?.left;return(!c||c<0||c>s)&&(this.logger.verbose("08vfmo",this.correlationId),c=Mo),(!l||l<0||l>a)&&(this.logger.verbose("09cxa0",this.correlationId),l=qo),(!h||h<0||h>a)&&(this.logger.verbose("1qh4wo",this.correlationId),h=Math.max(0,a/2-qo/2+i)),(!d||d<0||d>s)&&(this.logger.verbose("1sz3en",this.correlationId),d=Math.max(0,s/2-Mo/2+n)),o.open(e,t,`width=${c}, height=${l}, top=${h}, left=${d}, scrollbars=yes`)}generatePopupName(e,t){return`${$o}.${this.config.auth.clientId}.${e.join("-")}.${t}.${this.correlationId}`}generateLogoutPopupName(e){const t=e.account&&e.account.homeAccountId;return`${$o}.${this.config.auth.clientId}.${t}.${this.correlationId}`}async waitForPopupResponse(e,t,r){return this.waitForPopupResponseHook?this.waitForPopupResponseHook(e,t,r):xl(this.config.system.popupBridgeTimeout,this.logger,e,this.performanceClient)}}class Id extends Lh{constructor(e,t,r,o,n,i,s,a,c,l){super(e,t,r,o,n,i,s,c,l),this.nativeStorage=a}async acquireToken(e){const t=await ua(Nh,Ii,this.logger,this.performanceClient,this.correlationId)(e,In.Redirect,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);t.platformBroker=vd(this.config,this.logger,this.correlationId,this.platformAuthProvider,e.authenticationScheme);const r=e=>{e.persisted&&(this.logger.verbose("0udvtt",this.correlationId),this.browserStorage.resetRequestCache(this.correlationId),this.eventHandler.emitEvent(qc,this.correlationId,In.Redirect))},o=this.getRedirectStartPage(e.redirectStartPage);this.logger.verbosePii(`0zao0a ${o}`,this.correlationId),this.browserStorage.setTemporaryCache(rn,o,!0),window.addEventListener("pageshow",r);try{this.config.system.protocolMode===ta?await this.executeEarFlow(t):await this.executeCodeFlow(t)}catch(e){throw e instanceof Mn&&(e.correlationId=this.correlationId),window.removeEventListener("pageshow",r),e}}async executeCodeFlow(e){const t=e.correlationId,r=Oh(dn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),o=await ua(ad,_i,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),n={...e,codeChallenge:o.challenge};this.browserStorage.cacheAuthorizeRequest(n,this.correlationId,o.verifier);try{if(n.httpMethod===xr)return await this.executeCodeFlowWithPost(n);{const t=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:n.authority,requestAzureCloudOptions:n.azureCloudOptions,requestExtraQueryParameters:n.extraQueryParameters,account:n.account}),o=await ua(ed,ia,this.logger,this.performanceClient,e.correlationId)(this.config,t.authority,n,this.logger,this.performanceClient);return await this.initiateAuthRequest(o)}}catch(e){throw e instanceof Mn&&(e.correlationId=this.correlationId,r.cacheFailedRequest(e)),e}}async executeEarFlow(e){const{correlationId:t,authority:r,azureCloudOptions:o,extraQueryParameters:n,account:i}=e,s=await ua(Rh,ui,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,r,o,n,i),a=await ua(vs,xi,this.logger,this.performanceClient,t)(),c=await ua(ad,_i,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),l={...e,earJwk:a,codeChallenge:c.challenge};this.browserStorage.cacheAuthorizeRequest(l,this.correlationId,c.verifier);return(await td(document,this.config,s,l,this.logger,this.performanceClient)).submit(),new Promise((e,t)=>{setTimeout(()=>{t(Li(ts,"","failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async executeCodeFlowWithPost(e){const t=e.correlationId,r=await ua(Rh,ui,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger);this.browserStorage.cacheAuthorizeRequest(e,this.correlationId);return(await rd(document,this.config,r,e,this.logger,this.performanceClient)).submit(),new Promise((e,t)=>{setTimeout(()=>{t(Li(ts,"","failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async handleRedirectPromise(e,t,r,o){const n=document.title;document.title="Microsoft Authentication";const i=Oh(pn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),s=o?.navigateToLoginRequestUrl??!0;try{const[n,a]=this.getRedirectResponse(o?.hash||"");if(!n)return this.logger.info("1qmv0q",this.correlationId),this.browserStorage.resetRequestCache(this.correlationId),"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}()?r.event.errorCode="no_server_response":this.logger.verbose("1eqegq",this.correlationId),null;const c=this.browserStorage.getTemporaryCache(rn,this.correlationId,!0)||"",l=Hc(c,this.logger,this.correlationId);if(l===Hc(window.location.href,this.logger,this.correlationId)&&s){this.logger.verbose("11yred",this.correlationId),c.indexOf("#")>-1&&function(e){const t=e.split("#");t.shift(),window.location.hash=t.length>0?t.join("#"):""}(c);return await this.handleResponse(n,e,t,i)}if(!s)return this.logger.verbose("0v4sdv",this.correlationId),await this.handleResponse(n,e,t,i);if(!_l()||this.config.system.allowRedirectInIframe){this.browserStorage.setTemporaryCache(on,a,!0);const r={apiId:pn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!0};let o=!0;if(c)this.logger.verbose(`08jpy1 ${c}`,this.correlationId),o=await this.navigationClient.navigateInternal(c,r);else{const e=function(e){const t=new Ws(window.location.href,e||"").getUrlComponents();return`${t.Protocol}//${t.HostNameAndPort}/`}(this.correlationId);this.browserStorage.setTemporaryCache(rn,e,!0),this.logger.warning("1dutq1",this.correlationId),o=await this.navigationClient.navigateInternal(e,r)}if(!o)return await this.handleResponse(n,e,t,i)}return null}catch(e){throw e instanceof Mn&&(e.correlationId=this.correlationId,i.cacheFailedRequest(e)),e}finally{document.title=n}}getRedirectResponse(e){this.logger.verbose("1c5i8m",this.correlationId);let t=e;t||(t=this.config.auth.OIDCOptions.responseMode===to?window.location.search:window.location.hash);let r=Nc(t);if(r){try{Hh(r,this.browserCrypto,In.Redirect,this.correlationId)}catch(e){return e instanceof Mn&&this.logger.error(`0bkq6p ${e.errorCode} ${e.errorMessage}`,this.correlationId),[null,""]}return Al(window),this.logger.verbose("00uvho",this.correlationId),[r,t]}const o=this.browserStorage.getTemporaryCache(on,this.correlationId,!0);return this.browserStorage.removeItem(this.browserStorage.generateCacheKey(on)),o&&(r=Nc(o),r)?(this.logger.verbose("001671",this.correlationId),[r,o]):[null,""]}async handleResponse(e,t,r,o){if(!e.state)throw Li(zi,t.correlationId);const{authority:n,azureCloudOptions:i,extraQueryParameters:s,account:a}=t;if(e.ear_jwe){const r=await ua(Rh,ui,this.logger,this.performanceClient,t.correlationId)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,n,i,s,a);return ua(sd,bi,this.logger,this.performanceClient,t.correlationId)(t,e,dn,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}const c=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:o,requestAuthority:t.authority});return ua(id,Si,this.logger,this.performanceClient,t.correlationId)(t,e,r,dn,this.config,c,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async initiateAuthRequest(e){if(this.logger.verbose("0yaw2e",this.correlationId),e){this.logger.infoPii(`1luf83 ${e}`,this.correlationId);const t={apiId:dn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},r=this.config.auth.onRedirectNavigate;if("function"==typeof r){this.logger.verbose("1nehvl",this.correlationId);return!1!==r(e)?(this.logger.verbose("1a0jxh",this.correlationId),void await this.navigationClient.navigateExternal(e,t)):void this.logger.verbose("09k5h5",this.correlationId)}return this.logger.verbose("0klwf7",this.correlationId),void await this.navigationClient.navigateExternal(e,t)}throw this.logger.info("0rlh4e",this.correlationId),Li(Fi,this.correlationId)}async logout(e){this.logger.verbose("1rkurh",this.correlationId);const t=this.initializeLogoutRequest(e),r=Oh(yn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{this.eventHandler.emitEvent(xc,this.correlationId,In.Redirect,e),await Mh(this.browserStorage,this.browserCrypto,this.logger,this.correlationId,t.account);const o={apiId:yn,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},n=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:e&&e.authority,requestExtraQueryParameters:e?.extraQueryParameters,account:e&&e.account||void 0});if(n.authority.protocolMode===ea)try{n.authority.endSessionEndpoint}catch{if(t.account?.homeAccountId)return void this.eventHandler.emitEvent(Oc,this.correlationId,In.Redirect,t)}t.state=$c(this.browserCrypto,t.state||"",{interactionType:In.Redirect},t.correlationId);const i=n.getLogoutUri(t);t.account?.homeAccountId&&this.eventHandler.emitEvent(Oc,this.correlationId,In.Redirect,t);const s=this.config.auth.onRedirectNavigate;if("function"!=typeof s)return this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,tn),void await this.navigationClient.navigateExternal(i,o);if(!1!==s(i))return this.logger.verbose("06v57e",this.correlationId),this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,tn),void await this.navigationClient.navigateExternal(i,o);this.browserStorage.setInteractionInProgress(!1),this.logger.verbose("0xqes1",this.correlationId)}catch(e){throw e instanceof Mn&&(e.correlationId=this.correlationId,r.cacheFailedRequest(e)),this.eventHandler.emitEvent(Rc,this.correlationId,In.Redirect,null,e),this.eventHandler.emitEvent(Mc,this.correlationId,In.Redirect),e}this.eventHandler.emitEvent(Mc,this.correlationId,In.Redirect)}getRedirectStartPage(e){const t=e||window.location.href,r=Ws.getAbsoluteUrl(t,Ol(),this.correlationId);return function(e,t,r){try{new URL(e)}catch(e){throw t?.error(`1lrjz7 ${e}`,r||""),Ds(Fs,r||"")}}(r,this.logger,this.correlationId),r}}async function bd(e,t,r,o){if(!t)throw r.info("1l7hyp",o),Li(Fi,o);return e.src=t,e}async function kd(e,t,r,o,n,i){if(!e.contentDocument)throw"No document associated with iframe!";return(await rd(e.contentDocument,t,r,o,n,i)).submit(),e}async function Sd(e,t,r,o,n,i){if(!e.contentDocument)throw"No document associated with iframe!";return(await td(e.contentDocument,t,r,o,n,i)).submit(),e}function Td(){const e=document.createElement("iframe");return e.className="msalSilentIframe",e.title="Microsoft Authentication",e.style.visibility="hidden",e.style.position="absolute",e.style.width=e.style.height="0",e.style.border="0",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),e.setAttribute("allow","local-network-access *"),document.body.appendChild(e),e}function Ad(e){document.body===e.parentNode&&document.body.removeChild(e)}class _d extends Lh{constructor(e,t,r,o,n,i,s,a,c,l,h,d){super(e,t,r,o,n,i,a,l,h),this.apiId=s,this.nativeStorage=c,this.waitForIframeResponseHook=d}async acquireToken(e){e.loginHint||e.sid||e.account&&e.account.username||this.logger.warning("1kl318",this.correlationId);const t={...e};t.prompt?t.prompt!==Yr&&t.prompt!==Xr&&(this.logger.warning(`0bmctg ${t.prompt} ${Yr}`,this.correlationId),t.prompt=Yr):t.prompt=Yr;const r=await ua(Nh,Ii,this.logger,this.performanceClient,this.correlationId)(t,In.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId);return r.platformBroker=vd(this.config,this.logger,this.correlationId,this.platformAuthProvider,r.authenticationScheme),Ul(r.authority),this.config.system.protocolMode===ta?this.executeEarFlow(r):this.executeCodeFlow(r)}async executeCodeFlow(e){let t;const r=Oh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{return t=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:r,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),await ua(this.silentTokenHelper.bind(this),fi,this.logger,this.performanceClient,e.correlationId)(t,e)}catch(o){if(o instanceof Mn&&(o.correlationId=this.correlationId,r.cacheFailedRequest(o)),!(t&&o instanceof Mn&&o.errorCode===Ro))throw o;return this.performanceClient.addFields({retryError:o.errorCode},this.correlationId),await ua(this.silentTokenHelper.bind(this),fi,this.logger,this.performanceClient,this.correlationId)(t,e)}}async executeEarFlow(e){const{correlationId:t,authority:r,azureCloudOptions:o,extraQueryParameters:n,account:i}=e,s=await ua(Rh,ui,this.logger,this.performanceClient,t)(this.config,this.correlationId,this.performanceClient,this.browserStorage,this.logger,r,o,n,i),a=await ua(vs,xi,this.logger,this.performanceClient,t)(),c=await ua(ad,_i,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),l={...e,earJwk:a,codeChallenge:c.challenge},h=Td(),d=this.config.auth.OIDCOptions.responseMode;let u;try{const r=ua(this.waitForIframeResponse.bind(this),wi,this.logger,this.performanceClient,t)(h,e);r.catch(()=>{}),await ua(Sd,yi,this.logger,this.performanceClient,t)(h,this.config,s,l,this.logger,this.performanceClient),u=await r}finally{da(Ad,Ai,this.logger,this.performanceClient,t)(h)}const g=da(Dh,Ti,this.logger,this.performanceClient,t)(u,d,this.logger,this.correlationId);if(!g.ear_jwe&&g.code){const r=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,t)({serverTelemetryManager:Oh(this.apiId,this.config.auth.clientId,t,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:s});return ua(id,Si,this.logger,this.performanceClient,t)(l,g,c.verifier,this.apiId,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}return ua(sd,bi,this.logger,this.performanceClient,t)(l,g,this.apiId,this.config,s,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async verifySso(e){const t={...e};t.prompt||(t.prompt=Yr);const r=await ua(Nh,Ii,this.logger,this.performanceClient,this.correlationId)(t,In.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId),o=await ua(this.createAuthCodeClient.bind(this),vi,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:Oh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),requestAuthority:r.authority,requestAzureCloudOptions:r.azureCloudOptions,requestExtraQueryParameters:r.extraQueryParameters,account:r.account}),{serverParams:n}=await this.silentAuthorizeHelper(o,r),i=r.correlationId;return jh(n,r.state,i),n.code?(this.logger.verbose("0kkkcj",i),!0):(this.logger.warning("0y34ti",i),!1)}logout(){return Promise.reject(Li(Ki,""))}async silentTokenHelper(e,t){const{serverParams:r,pkceCodes:o}=await this.silentAuthorizeHelper(e,t);return ua(id,Si,this.logger,this.performanceClient,t.correlationId)(t,r,o.verifier,this.apiId,this.config,e,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async silentAuthorizeHelper(e,t){const r=t.correlationId,o=await ua(ad,_i,this.logger,this.performanceClient,r)(this.performanceClient,this.logger,r),n={...t,codeChallenge:o.challenge},i=Td(),s=this.config.auth.OIDCOptions.responseMode;let a;try{const o=ua(this.waitForIframeResponse.bind(this),wi,this.logger,this.performanceClient,r)(i,t);if(o.catch(()=>{}),t.httpMethod===xr)await ua(kd,yi,this.logger,this.performanceClient,r)(i,this.config,e.authority,n,this.logger,this.performanceClient);else{const t=await ua(ed,ia,this.logger,this.performanceClient,r)(this.config,e.authority,n,this.logger,this.performanceClient);await ua(bd,yi,this.logger,this.performanceClient,r)(i,t,this.logger,r)}a=await o}finally{da(Ad,Ai,this.logger,this.performanceClient,r)(i)}return{serverParams:da(Dh,Ti,this.logger,this.performanceClient,r)(a,s,this.logger,this.correlationId),pkceCodes:o,silentRequest:n}}async waitForIframeResponse(e,t){return this.waitForIframeResponseHook?this.waitForIframeResponseHook(e,t):xl(this.config.system.iframeBridgeTimeout,this.logger,t,this.performanceClient,this.config.experimental)}}class Ed{constructor(e,t){this.config=ah(e),this.logger=new Ql(this.config.loggerOptions,Ka,Wa),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}async acquireToken(e,t){const r=fa(),o=await ua(this.executeTokenRequest.bind(this),"refreshTokenClientExecuteTokenRequest",this.logger,this.performanceClient,e.correlationId)(e,this.authority),n=o.headers?.[Lr],i=new gh(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.performanceClient,this.config.serializableCache,this.config.persistencePlugin);return i.validateTokenResponse(o.body,e.correlationId),ua(i.handleServerTokenResponse.bind(i),ca,this.logger,this.performanceClient,e.correlationId)(o.body,this.authority,r,e,t,void 0,void 0,!0,e.forceCache,n)}async acquireTokenByRefreshToken(e,t){if(!e)throw Ds("token_request_empty","");if(!e.account)throw Jn(ri,e.correlationId);if(this.cacheManager.isAppMetadataFOCI(e.account.environment,e.correlationId))try{return await ua(this.acquireTokenWithCachedRefreshToken.bind(this),na,this.logger,this.performanceClient,e.correlationId)(e,!0,t)}catch(r){const o=r instanceof Fn&&r.errorCode===$n,n=r instanceof uh&&"invalid_grant"===r.errorCode&&"client_mismatch"===r.subError;if(o||n)return ua(this.acquireTokenWithCachedRefreshToken.bind(this),na,this.logger,this.performanceClient,e.correlationId)(e,!1,t);throw r}return ua(this.acquireTokenWithCachedRefreshToken.bind(this),na,this.logger,this.performanceClient,e.correlationId)(e,!1,t)}async acquireTokenWithCachedRefreshToken(e,t,r){const o=da(this.cacheManager.getRefreshToken.bind(this.cacheManager),"cacheManagerGetRefreshToken",this.logger,this.performanceClient,e.correlationId)(e.account,t,e.correlationId,void 0);if(!o)throw jn($n,e.correlationId);if(o.expiresOn){const t=e.refreshTokenExpirationOffsetSeconds||300;if(this.performanceClient?.addFields({cacheRtExpiresOnSeconds:Number(o.expiresOn),rtOffsetSeconds:t},e.correlationId),va(o.expiresOn,t))throw jn(Un,e.correlationId)}const n={...e,refreshToken:o.secret,authenticationScheme:e.authenticationScheme||wo.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:mh}};try{return await ua(this.acquireToken.bind(this),"refreshTokenClientAcquireToken",this.logger,this.performanceClient,e.correlationId)(n,r)}catch(t){if(t instanceof Fn&&t.subError===Nn){this.logger.verbose("1pg3ap",e.correlationId);const t=this.cacheManager.generateCredentialKey(o);this.cacheManager.removeRefreshToken(t,e.correlationId)}throw t}}async executeTokenRequest(e,t){const r=bh(e,this.config.authOptions.clientId,this.config.authOptions.redirectUri,this.performanceClient),o=Ws.appendQueryString(t.tokenEndpoint,r),n=await ua(this.createTokenRequestBody.bind(this),"refreshTokenClientCreateTokenRequestBody",this.logger,this.performanceClient,e.correlationId)(e),i=Ih(this.logger,this.config.systemOptions.preventCorsPreflight,e.ccsCredential),s=Ha(this.config.authOptions.clientId,e);return ua(kh,"refreshTokenClientExecutePostToTokenEndpoint",this.logger,this.performanceClient,e.correlationId)(o,n,i,s,e.correlationId,this.cacheManager,this.networkClient,this.logger,this.performanceClient,this.serverTelemetryManager)}async createTokenRequestBody(e){const t=new Map;if(Zc(t,e.embeddedClientId||e.extraParameters?.[Fc]||this.config.authOptions.clientId),e.redirectUri&&el(t,e.redirectUri),Xc(t,e.scopes,e.correlationId,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),pl(t,no),ml(t),al(t,this.config.libraryInfo),cl(t,this.config.telemetry.application),kl(t),this.serverTelemetryManager&&!ch(this.config)&&bl(t,this.serverTelemetryManager),function(e,t){e.set("refresh_token",t)}(t,e.refreshToken),this.config.clientCredentials.clientSecret&&dl(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;ul(t,await yh(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),gl(t,r.assertionType)}if(e.authenticationScheme===wo.POP){const r=new dh(this.cryptoUtils,this.performanceClient);let o;if(e.popKid)o=this.cryptoUtils.encodeKid(e.popKid);else{o=(await ua(r.generateCnf.bind(r),aa,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}Cl(t,o)}else if(e.authenticationScheme===wo.SSH){if(!e.sshJwk)throw Ds(Bs,e.correlationId);Il(t,e.sshJwk)}if(this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case mh:try{ol(t,Ma(e.ccsCredential.credential))}catch(t){this.logger.verbose(`1qhtee ${t}`,e.correlationId)}break;case fh:rl(t,e.ccsCredential.credential)}return e.embeddedClientId&&Sl(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.extraParameters&&yl(t,{...e.extraParameters}),Qc(t,e.correlationId,this.performanceClient),il(t,e.correlationId,e.claims,this.config.authOptions.clientCapabilities,e.skipBrokerClaims),Dc(t)}}class Pd extends Lh{async acquireToken(e){const t=await ua(qh,mi,this.logger,this.performanceClient,e.correlationId)(e,this.config,this.performanceClient,this.logger,this.correlationId),r={...e,...t};e.redirectUri&&(r.redirectUri=xh(e.redirectUri,this.config.auth.redirectUri,this.logger,this.correlationId));const o=Oh(fn,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled),n=await this.createRefreshTokenClient({serverTelemetryManager:o,authorityUrl:r.authority,azureCloudOptions:r.azureCloudOptions,account:r.account});return ua(n.acquireTokenByRefreshToken.bind(n),"refreshTokenClientAcquireTokenByRefreshToken",this.logger,this.performanceClient,e.correlationId)(r,fn).catch(e=>{throw e.correlationId=this.correlationId,o.cacheFailedRequest(e),e})}logout(){return Promise.reject(Li(Ki,""))}async createRefreshTokenClient(e){const t=await ua(this.getClientConfiguration.bind(this),Ci,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:e.serverTelemetryManager,requestAuthority:e.authorityUrl,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return new Ed(t,this.performanceClient)}}class xd extends Th{constructor(e,t){super(e,t),this.includeRedirectUri=!1}}class Od extends Lh{constructor(e,t,r,o,n,i,s,a,c,l){super(e,t,r,o,n,i,a,c,l),this.apiId=s}async acquireToken(e){if(!e.code)throw Li("auth_code_required",this.correlationId);const t=await ua(Nh,Ii,this.logger,this.performanceClient,this.correlationId)(e,In.Silent,this.config,this.browserCrypto,this.browserStorage,this.logger,this.performanceClient,this.correlationId),r=Oh(this.apiId,this.config.auth.clientId,this.correlationId,this.browserStorage,this.logger,void 0,this.config.system.serverTelemetryEnabled);try{const o={...t,code:e.code},n=await ua(this.getClientConfiguration.bind(this),Ci,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account}),i=new xd(n,this.performanceClient);this.logger.verbose("1uic5e",this.correlationId);const s=new Bh(i,this.browserStorage,o,this.logger,this.performanceClient);return await ua(s.handleCodeResponseFromServer.bind(s),sa,this.logger,this.performanceClient,this.correlationId)({code:e.code,msgraph_host:e.msGraphHost,cloud_graph_host_name:e.cloudGraphHostName,cloud_instance_host_name:e.cloudInstanceHostName},t,this.apiId,!1)}catch(e){throw e instanceof Mn&&(e.correlationId=this.correlationId,r.cacheFailedRequest(e)),e}}logout(){return Promise.reject(Li(Ki,""))}}function Rd(e,t,r,o){try{ql(e),Os(r.auth.isMcp,o)}catch(e){throw t.end({success:!1},e,o.account),e}}class Md{constructor(e){var t,r,o,n;this.operatingContext=e,this.isBrowserEnvironment=this.operatingContext.isBrowserEnvironment(),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 Ps(this.logger,this.performanceClient):Ms,this.eventHandler=new Yl(this.logger),this.browserStorage=this.isBrowserEnvironment?new Kl(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler,function(e){const t=e.cloudDiscoveryMetadata;let r;if(t)try{r=JSON.parse(t)}catch(e){throw Ds(js,"")}return{canonicalAuthority:e.authority?Oa(e.authority):void 0,knownAuthorities:e.knownAuthorities,cloudDiscoveryMetadata:r}}(this.config.auth)):(t=this.config.auth.clientId,r=this.logger,o=this.performanceClient,n=this.eventHandler,new Kl(t,{cacheLocation:Yo,cacheRetentionDays:5},Ms,r,o,n));const i={cacheLocation:Yo,cacheRetentionDays:5};this.nativeInternalStorage=new Kl(this.config.auth.clientId,i,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler),this.activeSilentTokenRequests=new Map,this.trackStateChange=this.trackStateChange.bind(this),this.trackStateChangeWithMeasurement=this.trackStateChangeWithMeasurement.bind(this)}static async createController(e,t){const r=new Md(e);return await r.initialize(t),r}trackStateChange(e,t){e&&("visibilitychange"===t.type?(this.logger.info("16v6hv",e),this.performanceClient.incrementFields({visibilityChangeCount:1},e)):"online"===t.type?(this.logger.info("0zirfd",e),this.performanceClient.incrementFields({onlineStatusChangeCount:1},e)):"offline"===t.type&&(this.logger.info("1xk9ef",e),this.performanceClient.incrementFields({onlineStatusChangeCount:1},e)))}async initialize(e){const t=this.getRequestCorrelationId(e);if(this.logger.trace("1f7joy",t),this.initialized)return void this.logger.info("061m5x",t);if(!this.isBrowserEnvironment)return this.logger.info("19fvpi",t),this.initialized=!0,void this.eventHandler.emitEvent(Cc,t);const r=this.config.system.allowPlatformBroker,o=this.performanceClient.startMeasurement("initializeClientApplication",t);if(this.eventHandler.emitEvent(vc,t),this.logMultipleInstances(o,t),o.add({isMcp:this.config.auth.isMcp}),await ua(this.browserStorage.initialize.bind(this.browserStorage),"initializeCache",this.logger,this.performanceClient,t)(t),r)try{this.platformAuthProvider=await wd(this.logger,this.performanceClient,t,this.config.system.nativeBrokerHandshakeTimeout,this.config.experimental.allowPlatformBrokerWithDOM)}catch(e){this.logger.verbose(e,t)}this.config.cache.cacheLocation===Go&&this.eventHandler.subscribeCrossTab(),!this.config.system.navigatePopups&&await this.preGeneratePkceCodes(t),this.initialized=!0,this.eventHandler.emitEvent(Cc,t),o.end({allowPlatformBroker:r,success:!0})}async handleRedirectPromise(e){if(this.logger.verbose("02l8bm",""),Ml(this.initialized),this.isBrowserEnvironment){const t=e?.hash||"";let r=this.redirectResponse.get(t);return void 0===r?(r=this.handleRedirectPromiseInternal(e),this.redirectResponse.set(t,r),this.logger.verbose("1wn9kp","")):this.logger.verbose("0w0gm3",""),r}return this.logger.verbose("12xi63",""),null}async handleRedirectPromiseInternal(e){if(!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("0le6uv",""),null;const t=this.browserStorage.getInteractionInProgress()?.type;if(t===tn)return this.logger.verbose("1ywcv2",""),this.browserStorage.setInteractionInProgress(!1),Promise.resolve(null);const r=this.getAllAccounts(),o=this.browserStorage.getCachedNativeRequest(),n=o&&!e?.hash;let i,s,a;try{if(n&&this.platformAuthProvider){const e=o?.correlationId||"";this.eventHandler.emitEvent(_c,e,In.Redirect),i=this.performanceClient.startMeasurement(Fa,e),this.logger.trace("12v7is",e),i.add({isPlatformBrokerRequest:!0});const t=new Qh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,pn,this.performanceClient,this.platformAuthProvider,o.accountId,this.nativeInternalStorage,o.correlationId);s=ua(t.handleRedirectPromise.bind(t),"handleNativeRedirectPromise",this.logger,this.performanceClient,i.event.correlationId)()}else{const[t,r]=this.browserStorage.getCachedRequest("");a=t;const o=t.correlationId;this.eventHandler.emitEvent(_c,o,In.Redirect),i=this.performanceClient.startMeasurement(Fa,o),this.logger.trace("0znzs5",o);const n=this.createRedirectClient(o);s=ua(n.handleRedirectPromise.bind(n),"handleRedirectPromise",this.logger,this.performanceClient,i.event.correlationId)(t,r,i,e)}}catch(e){throw this.browserStorage.resetRequestCache(""),e}return s.then(e=>{if(e){this.browserStorage.resetRequestCache(e.correlationId),this.eventHandler.emitEvent(Sc,e.correlationId,In.Redirect,e),this.logger.verbose("0ui8f5",e.correlationId);r.length{this.browserStorage.resetRequestCache(i.event.correlationId);const t=e;throw this.eventHandler.emitEvent(Tc,i.event.correlationId,In.Redirect,null,t),this.eventHandler.emitEvent(Ec,i.event.correlationId,In.Redirect),i.end({success:!1},t),e})}async acquireTokenRedirect(e){const t=this.getRequestCorrelationId(e);this.logger.verbose("0os66p",t),$l(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,en);const r=this.performanceClient.startMeasurement("acquireTokenPreRedirect",t);r.add({scenarioId:e.scenarioId});const o=this.config.auth.onRedirectNavigate;this.config.auth.onRedirectNavigate=t=>{const n="function"==typeof o?o(t):void 0;return r.add({navigateCallbackResult:!1!==n}),r.event=r.end({success:!0},void 0,e.account)||r.event,n};try{let o;if(Os(this.config.auth.isMcp,e),this.eventHandler.emitEvent(kc,t,In.Redirect,e),this.platformAuthProvider&&this.canUsePlatformBroker(e)){const n=new Qh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,dn,this.performanceClient,this.platformAuthProvider,this.getNativeAccountId(e),this.nativeInternalStorage,t);o=ua(n.acquireTokenRedirect.bind(n),"nativeInteractionClientAcquireToken",this.logger,this.performanceClient,t)(e,r).catch(o=>{if(r.add({brokerErrorName:o.name,brokerErrorCode:o.errorCode}),o instanceof Kh&&Wh(o)){this.platformAuthProvider=void 0;return this.createRedirectClient(t).acquireToken(e)}if(o instanceof Fn){this.logger.verbose("1ipyz4",t);return this.createRedirectClient(t).acquireToken(e)}throw o})}else{o=this.createRedirectClient(t).acquireToken(e)}return await o}catch(o){throw this.browserStorage.resetRequestCache(t),2===r.event.status?this.performanceClient.startMeasurement(Fa,t).end({success:!1},o,e.account):r.end({success:!1},o,e.account),this.eventHandler.emitEvent(Tc,t,In.Redirect,null,o),o}}acquireTokenPopup(e){const t=this.getRequestCorrelationId(e),r=this.performanceClient.startMeasurement("acquireTokenPopup",t);r.add({scenarioId:e.scenarioId});try{this.logger.verbose("0ch87b",t),Rd(this.initialized,r,this.config,e),this.browserStorage.setInteractionInProgress(!0,en,e.overrideInteractionInProgress,t)}catch(e){return Promise.reject(e)}const o=this.getAllAccounts();let n;this.eventHandler.emitEvent(kc,t,In.Popup,e);const i=this.getPreGeneratedPkceCodes(t);if(this.canUsePlatformBroker(e))r.add({isPlatformBrokerRequest:!0}),n=this.acquireTokenNative({...e,correlationId:t},un).then(e=>(r.end({success:!0,isNativeBroker:!0},void 0,e.account),e)).catch(o=>{if(r.add({brokerErrorName:o.name,brokerErrorCode:o.errorCode}),o instanceof Kh&&Wh(o)){this.platformAuthProvider=void 0;return this.createPopupClient(t).acquireToken(e,i)}if(o instanceof Fn){this.logger.verbose("0yy5fw",t);return this.createPopupClient(t).acquireToken(e,i)}throw o});else{n=this.createPopupClient(t).acquireToken(e,i)}return n.then(n=>{const i=o.length(this.eventHandler.emitEvent(Tc,t,In.Popup,null,o),r.end({success:!1},o,e.account),Promise.reject(o))).finally(async()=>{this.browserStorage.setInteractionInProgress(!1),this.config.system.navigatePopups||await this.preGeneratePkceCodes(t)})}trackStateChangeWithMeasurement(e){const t=this.ssoSilentMeasurement||this.acquireTokenByCodeAsyncMeasurement;t&&("visibilitychange"===e.type?(this.logger.info(`0yzimq ${t.event.name}`,t.event.correlationId),t.increment({visibilityChangeCount:1})):"online"===e.type?(this.logger.info(`1caf53 ${t.event.name}`,t.event.correlationId),t.increment({onlineStatusChangeCount:1})):"offline"===e.type&&(this.logger.info(`0fdyk7 ${t.event.name}`,t.event.correlationId),t.increment({onlineStatusChangeCount:1})))}addStateChangeListeners(e){document.addEventListener("visibilitychange",e),window.addEventListener("online",e),window.addEventListener("offline",e)}removeStateChangeListeners(e){document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e),window.removeEventListener("offline",e)}getCachedSsoCapable(){try{const e=window.localStorage.getItem(oc);if(e){const t=JSON.parse(e);if(t&&"boolean"==typeof t.ssoCapable&&t.expiresOn&&Date.now(){const i={...e,correlationId:o};this.createSilentIframeClient(o).verifySso(i).then(e=>{this.logger.verbose(`1gd1iv ${t} ${e}`,o);try{const t=JSON.stringify({ssoCapable:e,expiresOn:Date.now()+864e5});window.localStorage.setItem(r,t)}catch{this.logger.warning(`18lmoj ${t}`,o)}n.end({fromCache:!1,success:e},void 0)}).catch(e=>{this.logger.warning(`05g83w ${t} ${e.message}`,o);try{window.localStorage.removeItem(r)}catch{this.logger.warning(`0nlf9q ${t}`,o)}n.end({fromCache:!1,success:!1},e)})},0)}async ssoSilent(e){const t=this.getRequestCorrelationId(e),r={...e,correlationId:t};this.ssoSilentMeasurement=this.performanceClient.startMeasurement("ssoSilent",t),this.ssoSilentMeasurement?.add({scenarioId:e.scenarioId,ssoCapable:this.getCachedSsoCapable()}),Rd(this.initialized,this.ssoSilentMeasurement,this.config,r),this.ssoSilentMeasurement?.increment({visibilityChangeCount:0,onlineStatusChangeCount:0}),this.addStateChangeListeners(this.trackStateChangeWithMeasurement);const o=this.getAllAccounts();let n;if(this.logger.verbose("0w1b45",t),this.eventHandler.emitEvent(kc,t,In.Silent,r),this.canUsePlatformBroker(r))this.ssoSilentMeasurement?.add({isPlatformBrokerRequest:!0}),n=this.acquireTokenNative(r,gn).catch(e=>{if(this.ssoSilentMeasurement?.add({brokerErrorName:e.name,brokerErrorCode:e.errorCode}),e instanceof Kh&&Wh(e)){this.platformAuthProvider=void 0;return this.createSilentIframeClient(r.correlationId).acquireToken(r)}throw e});else{n=this.createSilentIframeClient(r.correlationId).acquireToken(r)}return n.then(e=>{const r=o.length{throw this.eventHandler.emitEvent(Tc,t,In.Silent,null,r),this.ssoSilentMeasurement?.end({success:!1},r,e.account),r}).finally(()=>{this.removeStateChangeListeners(this.trackStateChangeWithMeasurement)})}async acquireTokenByCode(e){const t=this.getRequestCorrelationId(e);this.logger.trace("0ch6ga",t);const r=this.performanceClient.startMeasurement("acquireTokenByCode",t);Rd(this.initialized,r,this.config,e),this.eventHandler.emitEvent(kc,t,In.Silent,e),r.add({scenarioId:e.scenarioId});try{if(e.code&&e.nativeAccountId)throw Li("spa_code_and_nativeAccountId_present",t);if(e.code){const o=e.code;let n=this.hybridAuthCodeResponses.get(o);return n?(this.logger.verbose("0qgp28",t),r.discard()):(this.logger.verbose("06eh73",t),n=this.acquireTokenByCodeAsync({...e,correlationId:t}).then(e=>(this.eventHandler.emitEvent(Sc,t,In.Silent,e),this.hybridAuthCodeResponses.delete(o),r.end({success:!0,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length},void 0,e.account),e)).catch(e=>{throw this.hybridAuthCodeResponses.delete(o),this.eventHandler.emitEvent(Tc,t,In.Silent,null,e),r.end({success:!1},e),e}),this.hybridAuthCodeResponses.set(o,n)),await n}if(e.nativeAccountId){if(this.canUsePlatformBroker(e,e.nativeAccountId)){r.add({isPlatformBrokerRequest:!0});const o=await this.acquireTokenNative({...e,correlationId:t},mn,e.nativeAccountId).catch(e=>{throw r.add({brokerErrorName:e.name,brokerErrorCode:e.errorCode}),e instanceof Kh&&Wh(e)&&(this.platformAuthProvider=void 0),e});return r.end({success:!0},void 0,o.account),o}throw Li("unable_to_acquire_token_from_native_platform",t)}throw Li("auth_code_or_nativeAccountId_required",t)}catch(e){throw this.eventHandler.emitEvent(Tc,t,In.Silent,null,e),r.end({success:!1},e),e}}async acquireTokenByCodeAsync(e){const t=this.getRequestCorrelationId(e);this.logger.trace("10d9hy",t),this.acquireTokenByCodeAsyncMeasurement=this.performanceClient.startMeasurement("acquireTokenByCodeAsync",t),this.acquireTokenByCodeAsyncMeasurement?.increment({visibilityChangeCount:0,onlineStatusChangeCount:0}),this.addStateChangeListeners(this.trackStateChangeWithMeasurement);const r=this.createSilentAuthCodeClient(t);return await r.acquireToken(e).then(e=>(this.acquireTokenByCodeAsyncMeasurement?.end({success:!0,fromCache:e.fromCache}),e)).catch(e=>{throw this.acquireTokenByCodeAsyncMeasurement?.end({success:!1},e),e}).finally(()=>{this.removeStateChangeListeners(this.trackStateChangeWithMeasurement)})}async acquireTokenFromCache(e,t){switch(t){case Tn:case An:case _n:const t=this.createSilentCacheClient(e.correlationId);return ua(t.acquireToken.bind(t),"silentCacheClientAcquireToken",this.logger,this.performanceClient,e.correlationId)(e);default:throw Jn(si,e.correlationId)}}async acquireTokenByRefreshToken(e,t){switch(t){case Tn:case _n:case En:case Pn:const t=this.createSilentRefreshClient(e.correlationId);return ua(t.acquireToken.bind(t),"silentRefreshClientAcquireToken",this.logger,this.performanceClient,e.correlationId)(e);default:throw Jn(si,e.correlationId)}}async acquireTokenBySilentIframe(e){const t=this.createSilentIframeClient(e.correlationId);return ua(t.acquireToken.bind(t),"silentIframeClientAcquireToken",this.logger,this.performanceClient,e.correlationId)(e)}async logoutRedirect(e){const t=this.getRequestCorrelationId(e);$l(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,tn);return this.createRedirectClient(t).logout(e)}logoutPopup(e){try{const t=this.getRequestCorrelationId(e);ql(this.initialized),this.browserStorage.setInteractionInProgress(!0,tn);return this.createPopupClient(t).logout(e).finally(()=>{this.browserStorage.setInteractionInProgress(!1)})}catch(e){return Promise.reject(e)}}async clearCache(e){if(!this.isBrowserEnvironment)return;const t=this.getRequestCorrelationId(e);return this.createSilentCacheClient(t).logout(e)}getAllAccounts(e){return function(e,t,r,o,n){return e.verbose("1yd030",o),r?t.getAllAccounts(n,o):[]}(this.logger,this.browserStorage,this.isBrowserEnvironment,this.getRequestCorrelationId(),e)}getAccount(e){return function(e,t,r,o){t.trace("0u7b90",o);const n=r.getAccountInfoFilteredBy(e,o);return n?(t.verbose("0btgll",o),n):(t.verbose("0ltaj5",o),null)}(e,this.logger,this.browserStorage,this.getRequestCorrelationId())}setActiveAccount(e){!function(e,t,r){t.setActiveAccount(e,r)}(e,this.browserStorage,this.getRequestCorrelationId())}getActiveAccount(){return e=this.browserStorage,t=this.getRequestCorrelationId(),e.getActiveAccount(t);var e,t}async hydrateCache(e,t){this.logger.verbose("16jycr",e.correlationId);const r=function(e,t,r){const o=Array.from(e.tenantProfiles?.values()||[]);if(0===o.length&&e.tenantId&&e.localAccountId)o.push($a(e.homeAccountId,e.localAccountId,e.tenantId,e.nativeAccountId,e.idTokenClaims));else if(e.nativeAccountId){const t=o.find(t=>t.tenantId===e.tenantId);t&&!t.nativeAccountId&&(t.nativeAccountId=e.nativeAccountId)}return{authorityType:e.authorityType||io,homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,nativeAccountId:e.nativeAccountId,realm:e.tenantId,environment:e.environment,username:e.username,loginHint:e.loginHint,name:e.name,cloudGraphHostName:t,msGraphHost:r,tenantProfiles:o,dataBoundary:e.dataBoundary}}(e.account,e.cloudGraphHostName,e.msGraphHost);if(await this.browserStorage.setAccount(r,e.correlationId,ma(e.idTokenClaims),vn),!e.fromPlatformBroker)return this.browserStorage.hydrateCache(e,t);{this.logger.verbose("1i5atf",e.correlationId);const r=Ia(e.account.homeAccountId,e.account.environment,e.idToken,this.config.auth.clientId,e.tenantId),o=ba(e.account.homeAccountId,e.account.environment,e.accessToken,this.config.auth.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?ya(e.expiresOn):0,e.extExpiresOn?ya(e.extExpiresOn):0,rs,t.correlationId||"",void 0,e.tokenType,void 0,t.sshKid);t.resource&&(o.resource=t.resource);const n=ma(e.idTokenClaims);await this.browserStorage.setIdTokenCredential(r,e.correlationId,n),await this.nativeInternalStorage.setAccessTokenCredential(o,e.correlationId,n)}}async acquireTokenNative(e,t,r,o){const n=this.getRequestCorrelationId(e);if(this.logger.trace("0b9y3p",n),!this.platformAuthProvider)throw Li(Xi,n);const i=new Qh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,t,this.performanceClient,this.platformAuthProvider,r||this.getNativeAccountId(e),this.nativeInternalStorage,n);return ua(i.acquireToken.bind(i),gi,this.logger,this.performanceClient,n)(e,o)}canUsePlatformBroker(e,t){const r=this.getRequestCorrelationId(e);if(this.logger.trace("1n9lbl",r),!this.platformAuthProvider)return this.logger.trace("0vnu11",r),!1;if(!vd(this.config,this.logger,r,this.platformAuthProvider,e.authenticationScheme))return this.logger.trace("0yoy1g",r),!1;if(e.prompt)switch(e.prompt){case Yr:case Qr:case Vr:this.logger.trace("0vdv8e",r);break;default:return this.logger.trace(`0pdzw6 ${e.prompt}`,r),!1}return!(!t&&!this.getNativeAccountId(e))||(this.logger.trace("16lbtk",r),!1)}getNativeAccountId(e){const t=e.account||this.getAccount({loginHint:e.loginHint,sid:e.sid})||(e.loginHint||e.sid?null:this.getActiveAccount());return t&&t.nativeAccountId||""}createPopupClient(e){return new Cd(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider,this.operatingContext.getResponseHandlers()?.waitForPopupResponse)}createRedirectClient(e){return new Id(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider)}createSilentIframeClient(e){return new _d(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,gn,this.performanceClient,this.nativeInternalStorage,e,this.platformAuthProvider,this.operatingContext.getResponseHandlers()?.waitForIframeResponse)}createSilentCacheClient(e){return new Gh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,e,this.platformAuthProvider)}createSilentRefreshClient(e){return new Pd(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,e,this.platformAuthProvider)}createSilentAuthCodeClient(e){return new Od(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,mn,this.performanceClient,e,this.platformAuthProvider)}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){return Rl(),this.performanceClient.addPerformanceCallback(e)}removePerformanceCallback(e){return this.performanceClient.removePerformanceCallback(e)}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?ys():""}async loginRedirect(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("0lz9hf",t),this.acquireTokenRedirect({correlationId:t,...e||bn})}loginPopup(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("0qw7v5",t),this.acquireTokenPopup({correlationId:t,...e||bn})}async acquireTokenSilent(e){const t=this.getRequestCorrelationId(e),r=this.performanceClient.startMeasurement("acquireTokenSilent",t);r.add({cacheLookupPolicy:e.cacheLookupPolicy,scenarioId:e.scenarioId,ssoCapable:this.getCachedSsoCapable()}),Rd(this.initialized,r,this.config,e),this.logger.verbose("0x1c4s",t);const o=e.account||this.getActiveAccount();if(!o)throw Li("no_account_error",t);return this.acquireTokenSilentDeduped(e,o,t).then(o=>(r.end({success:!0,fromCache:o.fromCache,accessTokenSize:o.accessToken.length,idTokenSize:o.idToken.length},void 0,o.account),{...o,state:e.state,correlationId:t})).catch(e=>{throw e instanceof Mn&&(e.correlationId=t),r.end({success:!1},e,o),e})}async acquireTokenSilentDeduped(e,t,r){const o=Ha(this.config.auth.clientId,{...e,authority:e.authority||this.config.auth.authority,correlationId:r},t.homeAccountId),n=JSON.stringify(o),i=this.activeSilentTokenRequests.get(n);if(void 0===i){this.logger.verbose("0fcjbk",r),this.performanceClient.addFields({deduped:!1},r);const o=ua(this.acquireTokenSilentAsync.bind(this),"acquireTokenSilentAsync",this.logger,this.performanceClient,r)({...e,correlationId:r},t);return this.activeSilentTokenRequests.set(n,o),o.finally(()=>{this.activeSilentTokenRequests.delete(n)})}return this.logger.verbose("1yq7nb",r),this.performanceClient.addFields({deduped:!0},r),i}async acquireTokenSilentAsync(e,t){const r=t=>this.trackStateChange(e.correlationId,t);this.eventHandler.emitEvent(kc,e.correlationId,In.Silent,e),e.correlationId&&this.performanceClient.incrementFields({visibilityChangeCount:0,onlineStatusChangeCount:0},e.correlationId),this.addStateChangeListeners(r);const o=await ua($h,"initializeSilentRequest",this.logger,this.performanceClient,e.correlationId)(e,t,this.config,this.performanceClient,this.logger),n=e.cacheLookupPolicy||Tn;return this.acquireTokenSilentNoIframe(o,n).catch(async t=>{const r=function(e,t){const r=!(e instanceof Fn&&e.subError!==Nn),o=e.errorCode===Ro||e.errorCode===si,n=r&&o||e.errorCode===$n||e.errorCode===Un,i=On.includes(t);return n&&i}(t,n);if(r){const r=`${t.errorCode}${t.subError?`|${t.subError}`:""}`;if(this.performanceClient.addFields({silentRefreshReason:r},e.correlationId),this.activeIframeRequest){if(n!==xn){const[e,r]=this.activeIframeRequest;this.logger.verbose(`1w8fso ${r}`,o.correlationId);const i=this.performanceClient.startMeasurement("awaitConcurrentIframe",o.correlationId);i.add({awaitIframeCorrelationId:r});const s=await e;if(i.end({success:s}),s)return this.logger.verbose(`0ywzzi ${r}`,o.correlationId),this.acquireTokenSilentNoIframe(o,n);throw this.logger.info(`17y14q ${r}`,o.correlationId),t}return this.logger.warning("1bd4p8",o.correlationId),ua(this.acquireTokenBySilentIframe.bind(this),pi,this.logger,this.performanceClient,o.correlationId)(o)}{let e;return this.activeIframeRequest=[new Promise(t=>{e=t}),o.correlationId],this.logger.verbose("0rh08z",o.correlationId),ua(this.acquireTokenBySilentIframe.bind(this),pi,this.logger,this.performanceClient,o.correlationId)(o).then(t=>(e(!0),t)).catch(t=>{throw e(!1),t}).finally(()=>{this.activeIframeRequest=void 0})}}throw t}).then(t=>(this.eventHandler.emitEvent(Sc,e.correlationId,In.Silent,t),e.correlationId&&this.performanceClient.addFields({fromCache:t.fromCache,isNativeBroker:t.fromPlatformBroker},e.correlationId),t)).catch(t=>{throw this.eventHandler.emitEvent(Tc,e.correlationId,In.Silent,null,t),t}).finally(()=>{this.removeStateChangeListeners(r)})}async acquireTokenSilentNoIframe(e,t){return vd(this.config,this.logger,e.correlationId,this.platformAuthProvider,e.authenticationScheme)&&e.account.nativeAccountId?(this.logger.verbose("0sczo4",e.correlationId),this.performanceClient.addFields({isPlatformBrokerRequest:!0},e.correlationId),this.acquireTokenNative(e,fn,e.account.nativeAccountId,t).catch(async t=>{if(this.performanceClient.addFields({brokerErrorName:t.name,brokerErrorCode:t.errorCode},e.correlationId),t instanceof Kh&&Wh(t))throw this.logger.verbose("07rkmb",e.correlationId),this.platformAuthProvider=void 0,Jn(si,e.correlationId);throw t})):(this.logger.verbose("0ox81t",e.correlationId),t===An&&this.logger.verbose("0fvwxe",e.correlationId),ua(this.acquireTokenFromCache.bind(this),"acquireTokenFromCache",this.logger,this.performanceClient,e.correlationId)(e,t).catch(r=>{if(t===An)throw r;return this.eventHandler.emitEvent(Ac,e.correlationId,In.Silent,e),ua(this.acquireTokenByRefreshToken.bind(this),"acquireTokenByRefreshToken",this.logger,this.performanceClient,e.correlationId)(e,t)}))}async preGeneratePkceCodes(e){return this.logger.verbose("1x6uj6",e),this.pkceCode=await ua(ad,_i,this.logger,this.performanceClient,e)(this.performanceClient,this.logger,e),Promise.resolve()}getPreGeneratedPkceCodes(e){const t=this.pkceCode?{...this.pkceCode}:void 0;return this.pkceCode=void 0,t?this.logger.verbose("12js1o",e):this.logger.verbose("1oe9ci",e),this.performanceClient.addFields({usePreGeneratedPkce:!!t},e),t}logMultipleInstances(e,t){const r=this.config.auth.clientId;if(!window)return;window.msal=window.msal||{},window.msal.clientIds=window.msal.clientIds||[];window.msal.clientIds.length>0&&this.logger.verbose("1qtz3l",t),window.msal.clientIds.push(r),function(e,t,r,o){const n=window.msal?.clientIds||[],i=n.length,s=n.filter(t=>t===e).length;s>1&&r.warning("1e88vg",o),t.add({msalInstanceCount:i,sameClientIdInstanceCount:s})}(r,e,this.logger,t)}}class qd{static loggerCallback(e,t){switch(e){case Jl.Error:return void console.error(t);case Jl.Info:return void console.info(t);case Jl.Verbose:return void console.debug(t);case Jl.Warning:return void console.warn(t);default:return void console.log(t)}}constructor(e,t){let r;this.browserEnvironment="undefined"!=typeof window,this.config=function({auth:e,cache:t,system:r,experimental:o,telemetry:n},i){const s={clientId:"",authority:`${fr}`,knownAuthorities:[],cloudDiscoveryMetadata:"",authorityMetadata:"",redirectUri:"undefined"!=typeof window&&window.location?window.location.href.split("?")[0].split("#")[0]:"",postLogoutRedirectUri:"",clientCapabilities:[],OIDCOptions:{responseMode:ro,defaultScopes:[Ir,br,kr]},azureCloudOptions:{azureCloudInstance:ra,tenant:""},instanceAware:!1,isMcp:!1,verifySSO:!1},a={cacheLocation:Qo,cacheRetentionDays:5},c={loggerCallback:()=>{},logLevel:Jl.Info,piiLoggingEnabled:!1},l={...{...eh,loggerOptions:c,networkClient:i?new ud:hd,navigationClient:new dd,popupBridgeTimeout:r?.popupBridgeTimeout||6e4,iframeBridgeTimeout:r?.iframeBridgeTimeout||1e4,redirectNavigationTimeout:3e4,allowRedirectInIframe:!1,navigatePopups:!0,allowPlatformBroker:!1,nativeBrokerHandshakeTimeout:r?.nativeBrokerHandshakeTimeout||2e3,protocolMode:Zs,serverTelemetryEnabled:!1},...r,loggerOptions:r?.loggerOptions||c},h={application:{appName:"",appVersion:""},client:new Zl};r?.protocolMode!==ea&&e?.OIDCOptions&&new Ql(l.loggerOptions,Nl,Dl).warning(JSON.stringify(Ds("cannot_set_OIDCOptions","")),"");if(r?.protocolMode&&r.protocolMode===ea&&l?.allowPlatformBroker)throw Ds("cannot_allow_platform_broker","");return{auth:{...s,...e,OIDCOptions:{...s.OIDCOptions,...e?.OIDCOptions}},cache:{...a,...t},system:l,experimental:{iframeTimeoutTelemetry:!1,allowPlatformBrokerWithDOM:!1,...o},telemetry:{...h,...n}}}(e,this.browserEnvironment),this.responseHandlers=t;try{r=window[Qo]}catch(e){}const o=r?.getItem(Xa),n=r?.getItem(Za)?.toLowerCase(),i="true"===n||"false"!==n&&void 0,s={...this.config.system.loggerOptions},a=o&&Object.keys(Jl).includes(o)?Jl[o]:void 0;a&&(s.loggerCallback=qd.loggerCallback,s.logLevel=a),void 0!==i&&(s.piiLoggingEnabled=i),this.logger=new Ql(s,Nl,Dl),this.available=!1}getConfig(){return this.config}getResponseHandlers(){return this.responseHandlers}getLogger(){return this.logger}isAvailable(){return this.available}isBrowserEnvironment(){return this.browserEnvironment}}class $d extends qd{getModuleName(){return $d.MODULE_NAME}getId(){return $d.ID}async initialize(e){return this.available="undefined"!=typeof window,this.available}}$d.MODULE_NAME="",$d.ID="StandardOperatingContext";class Ud{constructor(e,t){this.controller=t||new Md(new $d(e,{waitForPopupResponse:this.waitForPopupResponse.bind(this),waitForIframeResponse:this.waitForIframeResponse.bind(this)}))}async waitForPopupResponse(e,t,r){const o=this.controller;return xl(o.getConfiguration().system.popupBridgeTimeout,o.getLogger(),e,o.getPerformanceClient())}async waitForIframeResponse(e,t){const r=this.controller,o=r.getConfiguration();return xl(o.system.iframeBridgeTimeout,r.getLogger(),t,r.getPerformanceClient(),o.experimental)}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)}getAccount(e){return this.controller.getAccount(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)}logoutRedirect(e){return this.controller.logoutRedirect(e)}logoutPopup(e){return this.controller.logoutPopup(e)}ssoSilent(e){return this.controller.ssoSilent(e)}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)}}function Ld(e){return"[Auth] "+e.map(e=>e instanceof Error?e.message:String(e)).join(" ")}class Nd{static info(...e){const r=Ld(e);a.log(t.Info,r),console.info(r)}static warn(...e){const r=Ld(e);a.log(t.Warning,r),console.warn(r)}static error(...e){const r=Ld(e);a.log(t.Error,r),console.error(r)}static debug(...e){const r=Ld(e);a.log(t.Debug,r),console.debug(r)}static trace(...e){const r=Ld(e);a.log(t.Trace,r),console.debug(r)}}var Dd,Hd,Fd,zd=function(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)},jd=function(e,t,r,o,n){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?n.call(e,r):n?n.value=r:t.set(e,r),r};class Bd{constructor(e){Dd.add(this),this._cloudName=e,Hd.set(this,void 0),this._key=`publicClients-${this._cloudName}`,Nd.trace(`Initializing PublicClientApplicationsStorage with key: ${this._key}`),this.get(),Nd.trace(`Initial value loaded: ${JSON.stringify(zd(this,Hd,"f"))}`)}get(){if(zd(this,Hd,"f"))return zd(this,Hd,"f");const e=localStorage.getItem(this._key);if(!e)return;let t;try{if(t=JSON.parse(e),!zd(this,Dd,"m",Fd).call(this,t))return}catch{return}return jd(this,Hd,t,"f"),t}store(e){localStorage.setItem(this._key,JSON.stringify(e)),jd(this,Hd,e,"f")}delete(){localStorage.removeItem(this._key),jd(this,Hd,void 0,"f")}}Hd=new WeakMap,Dd=new WeakSet,Fd=function(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)};class Kd{constructor(e){if(this._set=new Set,e)for(const t of e)this.add(t)}add(e){return this._set.add(e.toLowerCase()),this}clear(){this._set.clear()}delete(e){return this._set.delete(e.toLowerCase())}forEach(e,t){this._set.forEach(r=>{e.call(t,r,r,this)})}has(e){return this._set.has(e.toLowerCase())}get size(){return this._set.size}entries(){return this._set.entries()}keys(){return this._set.keys()}values(){return this._set.values()}[Symbol.iterator](){return this._set[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveSet"}}class Wd{constructor(e){if(this._map=new Map,e)for(const[t,r]of e)this.set(t,r)}set(e,t){return this._map.set(e.toLowerCase(),t),this}get(e){return this._map.get(e.toLowerCase())}has(e){return this._map.has(e.toLowerCase())}delete(e){return this._map.delete(e.toLowerCase())}clear(){this._map.clear()}forEach(e,t){this._map.forEach((r,o)=>{e.call(t,r,o,this)})}get size(){return this._map.size}entries(){return this._map.entries()}keys(){return this._map.keys()}values(){return this._map.values()}[Symbol.iterator](){return this._map[Symbol.iterator]()}get[Symbol.toStringTag](){return"CaseInsensitiveMap"}}class Jd{constructor(e,t){this._token=-1,"function"==typeof e&&"number"==typeof t&&this.setIfNotSet(e,t)}dispose(){this.cancel()}cancel(){-1!==this._token&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){-1===this._token&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}}function Vd(e,t){return e?.toLowerCase()===t?.toLowerCase()}class Gd{constructor(t){this._pcas=new Wd,this._expireWarning=new Wd,this._disposables=[],this._onDidChangeSessionsEmitter=new e,this.onDidAccountsChange=this._onDidChangeSessionsEmitter.event,this._onWillExpireSoonEmitter=new e,this.onWillExpireSoon=this._onWillExpireSoonEmitter.event,this._storage=new Bd(t)}async initialize(){const e=this._storage.get();if(!e)return void Nd.info("No existing PublicClientApplications to initialize.");const t=[],r=new Kd;for(const o of e){(await this.createMsalObj(o)).getAllAccounts().forEach(e=>{r.has(e.homeAccountId)||(r.add(e.homeAccountId),t.push(e))})}this._onDidChangeSessionsEmitter.fire({added:t,changed:[],deleted:[]})}getOrCreate(e){return this._pcas.has(e)?Promise.resolve(this._pcas.get(e)):this.createMsalObj(e)}getAll(){return Array.from(this._pcas.values())}async createMsalObj(e){const t=new Ud({auth:{clientId:e,redirectUri:Gd.REDIRECT_ROUTE},cache:{cacheLocation:"localStorage"},system:{loggerOptions:{loggerCallback:(e,t,r)=>{if(!r)switch(e){case Jl.Error:return void Nd.error(t);case Jl.Info:return void Nd.info(t);case Jl.Verbose:return void Nd.trace(t);case Jl.Warning:return void Nd.warn(t)}},piiLoggingEnabled:!1}}});await t.initialize(),this._pcas.set(e,t),this._storage.store(Array.from(this._pcas.keys()));const r=t.addEventCallback(e=>{switch(e.eventType){case bc:const t=e.payload;this._onDidChangeSessionsEmitter.fire({added:[t],changed:[],deleted:[]});break;case Oc:const r=e.payload;r?.account&&this._onDidChangeSessionsEmitter.fire({added:[],changed:[],deleted:[r.account]});break;case Sc:const o=e.payload;let n=this._expireWarning.get(o.account.homeAccountId);if(n||(n=new Jd,this._expireWarning.set(o.account.homeAccountId,n)),!o.fromCache&&o.refreshOn){Nd.info(`Token acquired for account ${o.account.username} via interaction.`);this.getAll().flatMap(e=>e.getAllAccounts()).find(e=>Vd(e.homeAccountId,o.account.homeAccountId)&&e!==o.account)||this._onDidChangeSessionsEmitter.fire({added:[o.account],changed:[],deleted:[]}),n.cancelAndSet(()=>this._onWillExpireSoonEmitter.fire(o),72e6)}break;default:return}});return this._disposables.push({dispose:()=>t.removeEventCallback(r)}),t}dispose(){this._onDidChangeSessionsEmitter.dispose(),this._disposables.forEach(e=>e.dispose())}}Gd.REDIRECT_ROUTE="/msal";async function Qd(e,t,r,o,n,i){const{clientId:s}=e.getConfiguration().auth,a=new URL(Gd.REDIRECT_ROUTE,window.location.origin);t.length&&a.searchParams.append("scopes",t.join(" ")),a.searchParams.append("clientId",s),a.searchParams.append("authority",o),n&&a.searchParams.append("loginHint",n),i&&a.searchParams.append("claims",i);if(!function(e){const t=Math.floor(window.screenLeft+window.innerWidth/2-390),r=Math.floor(window.screenTop+window.innerHeight/2-320);return window.open(e,"_blank",`width=780,height=640,top=${r},left=${t}`)??void 0}(a.toString()))throw new Error("Could not open popup");const c=function(e,t,r){return new BroadcastChannel(`microsoftAuthPopup#${JSON.stringify({clientId:e,authority:t,scopes:r})}`)}(s,o,t);return await new Promise((n,s)=>{c.onmessage=async a=>{if(a.data)if("message"in a.data)s(a.data);else{const c=5;let l=0;const h=[];for(;lsetTimeout(e,50*Math.pow(2,l-1)))}h.length>0&&s(new AggregateError(h,`Failed to acquire token after ${c} attempts`))}else s("data is undefined");c.onmessage=null,c.postMessage({close:!0}),c.close()}})}function Yd(e){const t=[];for(const r of e)"bearer"===r.scheme.toLowerCase()&&r.params.scope&&t.push(...r.params.scope.split(" "));return t}function Xd(e){for(const t of e)if("bearer"===t.scheme.toLowerCase()&&t.params.claims)try{return JSON.parse(t.params.claims),t.params.claims}catch(e){try{const e=j(t.params.claims);return JSON.parse(e),e}catch(e){Nd.error(`[extractClaimsFromChallenges] failed to decode and parse claims: ${JSON.stringify(e)}`);continue}}}class Zd{constructor(){this.id="microsoft",this.label="Microsoft",this.supportsMultipleAccounts=!0,this._disposables=new Array,this._onDidChangeSessionsEmitter=new e,this.onDidChangeSessions=this._onDidChangeSessionsEmitter.event,this._eventBufferer=new ru;const t=new Gd("Public");this._disposables.push(t),this._disposables.push(this._onDidChangeSessionsEmitter),this._pcaManager=t,this._registerAccountsChangeHandler()}async initialize(){await this._pcaManager.initialize()}getMsalObj(e){return this._pcaManager.getOrCreate(e)}async getSessions(e,t){const r=void 0===e,o=new Kn(e??[]);if(Nd.info(`[getSessions] [${e?o.scopeStr:"all"}] starting`),r){const e=new Map;for(const t of this._pcaManager.getAll())for(const r of t.getAllAccounts())e.has(r.homeAccountId)||e.set(r.homeAccountId,eu(r));const t=Array.from(e.values());return Nd.info(`[getSessions] [all] returned ${t.length} session(s)`),t}const n=await this._pcaManager.getOrCreate(o.clientId),i=await this.getAllSessionsForPca(n,o,t?.account);return Nd.info(`[getSessions] [${o.scopeStr}] returned ${i.length} session(s)`),i}async createSession(e,t){const r=new Kn(e);Nd.info(`[createSession] [${r.scopeStr}] starting`);const o=await this._pcaManager.getOrCreate(r.clientId),n=JSON.stringify({originalScopes:r.originalScopes}),i=new URL(r.tenant,Zd.DEFAULT_AAD_ENDPOINT).toString(),s=await Qd(o,r.scopesToSend,n,i,t.account?.label);o.setActiveAccount(s.account);const a=tu(s,r.originalScopes,t.account?.label);return Nd.info(`[createSession] [${r.scopeStr}] returned a session`),a}async getSessionsFromChallenges(e,t){Nd.info(`[getSessionsFromChallenges] starting with ${e.challenges.length} challenges`);const r=Yd(e.challenges)??e.scopes;if(!r||0===r.length)throw new Error("No scopes found in authentication challenges or fallback scopes");const o=Xd(e.challenges);if(!o)throw new Error("No claims found in authentication challenges");const n=new Kn(r,o);Nd.info(`[getSessions] [${r?n.scopeStr:"all"}] starting`);const i=await this._pcaManager.getOrCreate(n.clientId),s=await this.getAllSessionsForPca(i,n,t?.account);return Nd.info(`[getSessions] [${n.scopeStr}] returned ${s.length} session(s)`),s}async createSessionFromChallenges(e,t){const r=e.scopes?.length?[...e.scopes]:Yd(e.challenges),o=Xd(e.challenges),n=new Kn(r,o);Nd.info(`[createSession] [${n.scopeStr}] starting`);const i=await this._pcaManager.getOrCreate(n.clientId),s=JSON.stringify({originalScopes:n.originalScopes}),a=new URL(n.tenant,Zd.DEFAULT_AAD_ENDPOINT).toString(),c=await Qd(i,n.scopesToSend,s,a,t.account?.label,o);i.setActiveAccount(c.account);const l=tu(c,n.originalScopes,t.account?.label);return Nd.info(`[createSession] [${n.scopeStr}] returned a session`),l}async removeSession(e){Nd.info(`[removeSession] [${e}] starting`);const t=new Array;for(const r of this._pcaManager.getAll()){const o=r.getAllAccounts();for(const n of o)Vd(n.homeAccountId,e)&&(t.push((async()=>(await r.clearCache({account:n}),n))()),Nd.info(`[removeSession] [${e}] [${r.getConfiguration().auth.clientId}] removing session...`))}if(!t.length)return void Nd.info(`[removeSession] [${e}] session not found`);const r=await Promise.allSettled(t),o=new Array;for(const t of r)"rejected"===t.status?Nd.error(`[removeSession] [${e}] error removing session: ${t.reason}`):o.push(t.value);0!==o.length?(this._onDidChangeSessionsEmitter.fire({added:[],changed:[],removed:o.map(eu)}),Nd.info(`[removeSession] [${e}] removed ${o.length} sessions`)):Nd.info(`[removeSession] [${e}] no sessions were removed`)}dispose(){this._disposables.forEach(e=>e.dispose())}_registerAccountsChangeHandler(){this._disposables.push(this._eventBufferer.wrapEvent(this._pcaManager.onDidAccountsChange,(e,t)=>{if(!e)return t;const r={added:[...e.added??[],...t.added??[]],deleted:[...e.deleted??[],...t.deleted??[]],changed:[...e.changed??[],...t.changed??[]]};return{added:Array.from(new Map(r.added.map(e=>[e.username,e])).values()),deleted:Array.from(new Map(r.deleted.map(e=>[e.username,e])).values()),changed:Array.from(new Map(r.changed.map(e=>[e.username,e])).values())}},{added:new Array,deleted:new Array,changed:new Array})(e=>this._handleAccountChange(e)))}_handleAccountChange({added:e,changed:t,deleted:r}){Nd.debug(`[_handleAccountChange] added: ${e.length}, changed: ${t.length}, deleted: ${r.length}`),this._onDidChangeSessionsEmitter.fire({added:e.map(eu),changed:t.map(eu),removed:r.map(eu)})}async getAllSessionsForPca(e,t,r){let o=r?e.getAllAccounts().filter(e=>Vd(e.homeAccountId,r.id)):e.getAllAccounts();const n=new Map;for(const e of o){const t=n.get(e.homeAccountId)||[];t.push(e),n.set(e.homeAccountId,t)}o=Array.from(n.values()).map(e=>{if(1===e.length)return e[0];if(t.tenantId){const r=e.find(e=>Vd(e.tenantId,t.tenantId));if(r)return r}return e.find(e=>Vd(e.tenantId,e.idTokenClaims?.tid))||e[0]});const i=new URL(t.tenant,Zd.DEFAULT_AAD_ENDPOINT).toString(),s=[];return this._eventBufferer.bufferEventsAsync(async()=>{for(const r of o)try{let o,n;t.tenantId?Vd(r.tenantId,t.tenantId)||(o=!0):Vd(r.tenantId,r.idTokenClaims?.tid)||(o=!0),t.claims&&(o=!0,n=t.claims);try{const a=await e.acquireTokenSilent({account:r,refreshTokenExpirationOffsetSeconds:3600,authority:i,scopes:t.scopesToSend,claims:n,forceRefresh:o,cacheLookupPolicy:_n});s.push(tu(a,t.originalScopes))}catch(a){const c=await e.acquireTokenSilent({account:r,authority:i,scopes:t.scopesToSend,claims:n,forceRefresh:o,cacheLookupPolicy:_n});this.informUserOfExpiredSession(c),s.push(tu(c,t.originalScopes))}}catch(e){Nd.info(`[getAllSessionsForPca] [${t.scopeStr}] [${r.username}] failed to acquire token silently, skipping account ${JSON.stringify(e)}`);continue}return s})}async informUserOfExpiredSession(e){const t=de.auth.Refresh.toString(),r=de.auth.MoreInfo.toString(),o=await c.showInformationMessage(de.auth.SessionExpiringSoon.toString(e.account.username),t,r);if(o===t){const t=e.state?JSON.parse(e.state).originalScopes??e.scopes:e.scopes,r=e.idTokenClaims?.login_hint??e.account.idTokenClaims?.login_hint;await this.createSession(t,{account:tu(e,t,r).account})}else o===r&&(window.open("https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens#token-lifetime","_blank"),await this.informUserOfExpiredSession(e))}}function eu(e){return{accessToken:"1234",id:e.homeAccountId,scopes:[],account:{id:e.homeAccountId,label:e.username.toLowerCase()},idToken:e.idToken}}function tu(e,t,r){return{id:e.idToken,scopes:t??e.scopes,account:{label:r??e.account.username,id:e.account.homeAccountId},accessToken:e.accessToken,idToken:e.idToken}}Zd.DEFAULT_AAD_ENDPOINT="https://login.microsoftonline.com/";class ru{constructor(){this.data=[]}wrapEvent(e,t,r){return(o,n,i)=>e(e=>{const i=this.data[this.data.length-1];if(!t)return void(i?i.buffers.push(()=>o.call(n,e)):o.call(n,e));const s=i;s?(s.items??=[],s.items.push(e),0===s.buffers.length&&i.buffers.push(()=>{s.reducedResult??=r?s.items.reduce(t,r):s.items.reduce(t),o.call(n,s.reducedResult)})):o.call(n,t(r,e))},void 0,i)}bufferEvents(e){const t={buffers:new Array};this.data.push(t);const r=e();return this.data.pop(),t.buffers.forEach(e=>e()),r}async bufferEventsAsync(e){const t={buffers:new Array};this.data.push(t);try{return await e()}finally{this.data.pop(),t.buffers.forEach(e=>e())}}}class ou{constructor(e){this.url=e,this.authenticationProvider=new Zd,this._initialized=this.initialize()}async initialize(){await this.authenticationProvider.initialize();const e=window.sessionStorage.getItem("microsoftAuthRedirectData");if(!e)return;const{clientId:t}=JSON.parse(e),r=await this.authenticationProvider.getMsalObj(t);await r.handleRedirectPromise({navigateToLoginRequestUrl:!1}),window.sessionStorage.removeItem("microsoftAuthRedirectData")}async getSessions(e,t){if(t?.forceNewSession&&t?.silent)throw new Error("Invalid options: forceNewSession and silent cannot be used together.");await this._initialized,t?.clientId&&e.push(`VSCODE_CLIENT_ID:${t.clientId}`),t?.tenant&&e.push(`VSCODE_TENANT:${t.tenant}`);const r=new Kn(e);let o;const n=await this.authenticationProvider.getMsalObj(r.clientId),i=new URL(r.tenant,Zd.DEFAULT_AAD_ENDPOINT).toString();if(!t?.forceNewSession){for(const e of n.getAllAccounts()){if(r.tenantId&&!Vd(e.tenantId,r.tenantId))continue;const o={refreshTokenExpirationOffsetSeconds:79200,forceRefresh:!0,scopes:r.scopesToSend,cacheLookupPolicy:_n,account:e,authority:i,state:JSON.stringify({originalScopes:r.originalScopes})};try{await n.acquireTokenSilent(o)}catch(e){if(t?.silent){console.error(e);continue}e instanceof Fn?(window.sessionStorage.setItem("microsoftAuthRedirectData",JSON.stringify({clientId:r.clientId,tenant:r.tenant,redirectUri:window.location.href})),await n.acquireTokenRedirect({...o,claims:e.claims})):console.error(e)}}o=await this.authenticationProvider.getSessions(r.originalScopes,{})}if(!o?.length){if(t?.silent)return[];throw window.sessionStorage.setItem("microsoftAuthRedirectData",JSON.stringify({clientId:r.clientId,tenant:r.tenant,redirectUri:window.location.href})),await n.loginRedirect({scopes:r.scopesToSend,authority:i,state:JSON.stringify({originalScopes:r.originalScopes})}),new Error("Redirecting to authenticate")}return o.map(e=>({...e,getAccessToken:()=>Promise.resolve(e.accessToken)}))}dispose(){this.authenticationProvider.dispose()}async setInitialSessions(e){}tryCompleteAuthExchange(){return Promise.resolve(this.url)}}const nu="stable";new Set(["stable","insider","exploration","dev"]);class iu{constructor(e){this.workspace=e,this.trusted=!0}get payload(){if(void 0===this._payload){let e=null;new URL(window.location.href).searchParams.forEach((t,r)=>{if(r===iu.QUERY_PARAM_PAYLOAD)try{e=JSON.parse(t)}catch(e){console.error(e)}}),this._payload=e}return this._payload??void 0}async open(e,t){let r=ae(e);if(!r&&(void 0===e||se(e).toString()===su.workspaceUri.toString())){const e=new URL(window.location.href);e.pathname="/",r=e.toString()}if(r){if(t?.payload){const e=new URL(r);e.searchParams.set(iu.QUERY_PARAM_PAYLOAD,JSON.stringify(t.payload)),r=e.toString()}if(t?.reuse)return window.location.href=r,!0;let e;return e=window.matchMedia&&window.matchMedia("(display-mode: standalone)").matches?window.open(r,"_blank","toolbar=no"):window.open(r),!!e}throw new Error("Not implemented")}}iu.QUERY_PARAM_PAYLOAD="payload";const su={workspaceUri:o.from({scheme:"tmp",path:"/default.code-workspace"})},au=[{href:"https://aka.ms/vscode-web-docs",label:de.ReadDoc.toString()},{href:"https://go.microsoft.com/fwlink/?LinkId=521839",label:de.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:de.TermsofUse.toString()},{href:"https://code.visualstudio.com/download",label:de.DownloadVSCode.toString()}];function cu(e,t){return r=>{/vscode\.dev$/.test(e.hostname)&&!e.searchParams.get("vscode-quality")?e.hostname="insider"===r?"insiders.vscode.dev":"vscode.dev":r===t?e.searchParams.delete("vscode-quality"):e.searchParams.set("vscode-quality",r),window.location.href=e.toString()}}function lu(e){switch(e.searchParams.get("vscode-log")?.toLowerCase()){case"trace":return t.Trace;case"debug":return t.Debug;case"warning":return t.Warning;case"error":return t.Error;case"critical":return t.Critical;case"off":return t.Off;default:return t.Info}}async function hu(e,t,a){let c=new URL(window.location.href);c=function(e){for(const t of Y)e=t.redirect(e)??e;return e}(c),window.history.replaceState(void 0,"",c.toString());const l=new W(c.host),h=new u(l,e);let d;const g=window.sessionStorage.getItem(`vscode-continueOn-${c.pathname}`);if(g)try{d=JSON.parse(g)}catch(e){console.error("Failed to parse continueOn body",e)}const p=new mr(h,c),m=new ou(c),f=await async function(e){for(const t of te)if(Z(e.url.pathname,t)){const r="string"==typeof t.path?t.path:t.path.prefix;performance.mark(`web/willRoute/${r}`);const o=await t.route(e);return performance.mark(`web/didRoute/${r}`),o&&t.additionalBuiltinExtensions.length&&(o.workbenchOptions={...o.workbenchOptions,additionalBuiltinExtensions:o.workbenchOptions?.additionalBuiltinExtensions?.concat(t.additionalBuiltinExtensions)??t.additionalBuiltinExtensions}),o}}({url:c,githubAuthentication:p,microsoftAuthentication:m,secretStorageProvider:h,quality:e,commit:t,continueOnBody:d});f||(c=new URL(window.location.href),c.pathname="/",window.history.replaceState(void 0,"",c.toString()));const y=function(e,t){const r=[],n=JSON.parse(document.querySelector('meta[name="vscode:additionalBuiltinExtensions"]').content),i=e.searchParams.get("vscode-remotehub-dev");i&&(delete n["github.remotehub"],r.push(o.parse(i)));const s=e.searchParams.get("vscode-azurerepos-dev");s&&(delete n["ms-vscode.azure-repos"],r.push(o.parse(s)));const a=t?.excludeAdditionalBuiltinExtensions?new Set(t?.excludeAdditionalBuiltinExtensions.map(e=>e.toLowerCase())):new Set;for(const[e,t]of Object.entries(n))a.has(e)||r.push("string"==typeof t?o.parse(t):{id:e,preRelease:t});const c=t?.workbenchOptions?.additionalBuiltinExtensions??[];for(const e of c){const t=du(e)?e:"string"==typeof e?{id:e}:void 0;t&&n[t.id.toLowerCase()]||r.push(e)}return r}(c,f),w=f?.workbenchOptions?.enabledExtensions??[];let v=w;f?.excludeAdditionalBuiltinExtensions||(v=[...w,"GitHub.remotehub","ms-vscode.azure-repos"]);const C=f?.workspace??su,I=new iu(C===ee?void 0:C),b=[{id:"vscode.dev:help",label:"Help: Visual Studio Code for the Web",handler:()=>n.executeCommand("vscode.open",o.parse("https://aka.ms/vscode-web-docs"))}];f?.hasOwnProperty("workspace")&&b.push({id:"vscode.dev:close",label:"Close Remote Workspace",menu:[r?.CommandPalette,r?.StatusBarWindowIndicatorMenu],handler:()=>I.open(su,{reuse:!0})});const k=["/+","/tunnel/"];b.push({id:"vscode.dev:openPath",handler:(e,t)=>{k.some(t=>e.startsWith(t))&&(t?.newTab?window.open(e,"_blank"):window.location.pathname=e)}});const S=function(e){const t={enableTelemetry:!0,embedderIdentifier:"vscode.dev",openToWelcomeMainPage:!0,documentationUrl:"https://aka.ms/vscode-web-docs",licenseUrl:"https://www.microsoft.com/en-us/legal/terms-of-use",keyboardShortcutsUrlMac:"https://aka.ms/vscode-dev-shortcuts-macos",keyboardShortcutsUrlLinux:"https://aka.ms/vscode-dev-shortcuts-linux",keyboardShortcutsUrlWin:"https://aka.ms/vscode-dev-shortcuts-win"};return"dev"!==e?t:{...t,extensionsGallery:{nlsBaseUrl:"https://www.vscode-unpkg.net/_lp/",serviceUrl:"https://marketplace.visualstudio.com/_apis/public/gallery",searchUrl:"https://marketplace.visualstudio.com/_apis/public/gallery/searchrelevancy/extensionquery",servicePPEUrl:"https://marketplace.vsallin.net/_apis/public/gallery",cacheUrl:"https://vscode.blob.core.windows.net/gallery/index",itemUrl:"https://marketplace.visualstudio.com/items",resourceUrlTemplate:"https://{publisher}.vscode-unpkg.net/{publisher}/{name}/{version}/{path}",controlUrl:"https://main.vscode-cdn.net/extensions/marketplace.json",publisherUrl:"https://marketplace.visualstudio.com/publishers"},trustedExtensionAuthAccess:["vscode.git","vscode.github","ms-vscode.remote-repositories","github.remotehub","ms-vscode.azure-repos","ms-vscode.remote-server","github.vscode-pull-request-github","github.codespaces","ms-vsliveshare.vsliveshare","github.copilot","github.copilot-chat"]}}(e),T={...f?.workbenchOptions??{},configurationDefaults:{"workbench.colorTheme":"Default Dark Modern",...f?.workbenchOptions?.configurationDefaults??{}},additionalBuiltinExtensions:y,enabledExtensions:v,urlCallbackProvider:new J(l),secretStorageProvider:h,remoteResourceProvider:f?.workbenchOptions?.remoteResourceProvider??(f?.workbenchOptions?.remoteAuthority?fe():void 0),productConfiguration:{...S,...f?.workbenchOptions?.productConfiguration??{},extensionEnabledApiProposals:{...S?.extensionEnabledApiProposals??{},...f?.workbenchOptions?.productConfiguration?.extensionEnabledApiProposals??{}},npsSurveyUrl:void 0,cesSurveyUrl:void 0,surveys:void 0},enableWorkspaceTrust:f?.workbenchOptions?.enableWorkspaceTrust??!0,initialColorTheme:{themeType:"dark"},welcomeBanner:f?.disableWelcomeBanner?void 0:f?.welcomeBanner??{message:de.Anywhere.toString(),actions:au},codeExchangeProxyEndpoints:{microsoft:`${window.location.protocol}//${window.location.host}/codeExchangeProxyEndpoints/microsoft/`,github:`${window.location.protocol}//${window.location.host}/codeExchangeProxyEndpoints/github/`},authenticationProviders:[m.authenticationProvider],resolveExternalUri:async e=>{const t=ae({folderUri:e});if(!t)throw new Error(`Scheme not supported: ${e.scheme}`);return o.parse(t)},commands:f?.workbenchOptions?.commands?.concat(b)??b,workspaceProvider:I,productQualityChangeHandler:cu(c,a),developmentOptions:{logLevel:lu(c)},openerAllowedExternalUrlPrefixes:V,resolveCommonTelemetryProperties:()=>({"common.isPWAInstalled":String(navigator.standalone||window.matchMedia("(display-mode: standalone)").matches)})};if(i(document.body,T),f?.onDidCreateWorkbench?.openUri){const e=f.onDidCreateWorkbench.openUri;s.openUri(o.from({scheme:await s.getUriScheme(),query:window.location.href,...e}))}if(f?.onDidCreateWorkbench?.runCommands)for(const e of f.onDidCreateWorkbench.runCommands)n.executeCommand(e.command,...e.args);if(f?.onWillDisposeWorkbench?.runCommands){const e=f.onWillDisposeWorkbench.runCommands;window.addEventListener("beforeunload",()=>{for(const t of e)n.executeCommand(t.command,...t.args)})}}function du(e){const t=e;return"string"==typeof t?.id&&(void 0===t.preRelease||"boolean"==typeof t.preRelease)}/^de($|-)/i.test(window.navigator.language)&&au.push({href:"https://news.microsoft.com/de-ch/impressum/",label:"Impressum"}),/^it($|-)/i.test(window.navigator.language)&&au.push({href:"https://go.microsoft.com/fwlink/?linkid=2121429",label:"Accessibilità"}),async function(){const{quality:e,commit:t,baseUrl:r,trustedTypesPolicy:o}=globalThis._VSCODE_WEB_BOOTSTRAP_;if(function(e,t={}){const{favicon:r=!0,appleTouchIcon:o=!0,manifest:n=!0}=t;if(e="insider"===e?"insider":"stable",r){const t=document.createElement("link");t.rel="icon",t.href=`/static/${e}/favicon.ico`,t.type="image/x-icon",document.head.append(t)}if(o){const t=document.createElement("link");t.rel="apple-touch-icon",t.href=`/static/${e}/code-192-apple.png`,document.head.append(t)}if(n){const t=document.createElement("link");t.rel="manifest",t.href=`/static/${e}/code.webmanifest`,t.crossOrigin="use-credentials",document.head.append(t)}}(e),function(){const e=navigator.language.split("-")[0];e&&document.documentElement.setAttribute("lang",e)}(),"dev"===e)try{const e=await fetch(`${r}/_builtin`),t=await e.text(),o=document.createElement("meta");o.id="vscode-workbench-builtin-extensions",o.setAttribute("data-settings",t),document.head.append(o)}catch{throw new Error("Failed to load dev sources, make sure you're running 'yarn web'.")}const n=new URL(window.location.href),i=n.searchParams.get("vscode-version");if(i&&!window.confirm(`You are about to load an older version of the VS Code workbench (${i.substring(0,8)}), which might be vulnerable to security issues. Are you sure you want to continue?`))return n.searchParams.delete("vscode-version"),void(window.location.href=n.toString());try{performance.mark("web/willCallMain"),await hu(e,t,nu)}finally{performance.mark("web/didCallMain")}if(location.origin.includes("localhost"))navigator.serviceWorker.getRegistrations().then(e=>{for(const t of e)t.unregister()});else if("serviceWorker"in navigator){const t=o?.createScriptURL("/sw.js")??"/sw.js",r=navigator.serviceWorker.register(t);"dev"!==e&&r.then(async e=>{let t=e.active??e.waiting;t||(t=await new Promise(t=>{if(e.active)return t(e.active);if(!e.installing)throw new Error("Unnexpected service worker state");const r=e.installing,o=e=>{if("activated"===e.target.state)return r.removeEventListener("statechange",o),t(e.target)};r.addEventListener("statechange",o)}));const r={quality:globalThis._VSCODE_WEB_BOOTSTRAP_.quality,version:globalThis._VSCODE_WEB_BOOTSTRAP_.commit};setTimeout(()=>t?.postMessage({type:"preload",preload:r}),2e3)})}}().catch(function(e){console.error(JSON.stringify(e,void 0,2)),console.error(e),document.getElementById("monaco-parts-splash")?.remove();const t=document.createElement("link");t.rel="stylesheet",t.type="text/css",t.href="/static/base.css",document.head.append(t);const r=document.createElement("span");r.className="branding",r.textContent="Visual Studio Code";const o=document.createElement("div");o.className="message-container";const n=document.createElement("div");n.className="message",n.textContent="Fatal Error 🙈 Please check Developer Tools 🐱‍💻",document.body.appendChild(r),o.appendChild(n),document.body.appendChild(o)}).finally(()=>performance.mark("web/didBootstrap"));export{hu as main};