CINXE.COM
<!doctype html><html><head><script>performance.mark('code/didStartRenderer');</script><meta charset="utf-8"/><link rel="stylesheet" href="https://main.vscode-cdn.net/stable/f1a4fb101478ce6ec82fe9627c43efbf9e98c813/out/vs/workbench/workbench.web.main.internal.css"/><link rel="preconnect" href="https://main.vscode-cdn.net/" crossorigin><link rel="dns-prefetch" href="https://main.vscode-cdn.net/"><link rel="preconnect" href="https://main.vscode-cdn.net/" crossorigin><link rel="dns-prefetch" href="https://update.code.visualstudio.com/"><link rel="dns-prefetch" href="https://marketplace.visualstudio.com/"><meta http-equiv="Content-Security-Policy" content=" default-src 'none' ; img-src 'self' https: http://localhost:* https://*.vscode-cdn.net data: blob: vscode-remote-resource: ; media-src 'self' http://localhost:* https://*.vscode-cdn.net data: blob: vscode-remote-resource: ; child-src blob: ; frame-src 'self' https://*.vscode-cdn.net http://localhost:* https://login.microsoftonline.com/ ; script-src 'self' 'sha256-VLdOn1g86SNTcNTJ1ZMOpFZ3qCtT6xfxHelaT0NcTKI=' 'sha256-8Dk7vil/WkVcWs5fuoIfSufZ0vah5Lb7t/iNYcS+ZNY=' 'sha256-pXUMqwqrw0upolqXaaNYQ68XBbwiDFzTWWWLqos0PTU=' 'sha256-up+Z2YerxzwpLIsJG7GiIOGZwAr1pk52qi6YGo6Mphc=' 'unsafe-eval' https://main.vscode-cdn.net https://www.vscode-unpkg.net/nls/ https://ms-vscode.vscode-unpkg.net https://ms-toolsai.vscode-unpkg.net https://ms-azuretools.vscode-unpkg.net https://quantum.vscode-unpkg.net https://SynapseVSCode.vscode-unpkg.net http://localhost:* ; worker-src 'self' blob: ; style-src 'self' https://*.vscode-cdn.net http://localhost:* 'unsafe-inline' ; connect-src 'self' https://main.vscode-cdn.net http://localhost:* https://localhost:* https://login.microsoftonline.com/ https://api.github.com/ https://update.code.visualstudio.com/api/ https://*.vscode-unpkg.net/ https://default.exp-tas.com/vscode/ab https://vscode-sync.trafficmanager.net/ https://vscode-sync-insiders.trafficmanager.net/ https://*.gallerycdn.vsassets.io https://vortex.data.microsoft.com/collect/v1 https://marketplace.visualstudio.com/_apis/public/gallery/ https://vslsdev.azureedge.net/webextension/ https://vscodedotdev.blob.core.windows.net/web-builds/ https://az764295.vo.msecnd.net/experiments/vscode-experiments.json https://vscodeexperiments.azureedge.net/experiments/vscode-experiments.json https://code.visualstudio.com/raw/ https://vscode-auth.github.com https://*.gallery.vsassets.io/_apis/public/gallery/ https://marketplace.visualstudio.com/items/ https://az764295.vo.msecnd.net/extensions/ https://az764295.vo.msecnd.net/profile-templates/ https://mobile.events.data.microsoft.com/ https://auth.vscode.dev https://auth.insiders.vscode.dev https://*.rel.tunnels.api.visualstudio.com wss://*.rel.tunnels.api.visualstudio.com https://vscodeedu.com https://ppe.vscodeedu.com https://management.azure.com https://*.instances.azureml.ms:* wss://*.instances.azureml.ms:* https://api-dogfood.resources.windows-int.net/ https://login.windows-ppe.net/ https://*.servicebus.windows.net/ https://limelight-token-issuer-wrapper.azurewebsites.net/ ; font-src 'self' https://*.vscode-cdn.net https://*.vscode-unpkg.net http://localhost:* vscode-remote-resource: ; manifest-src 'self' ; require-trusted-types-for 'script' ; trusted-types amdLoader cellRendererEditorText defaultWorkerFactory diffEditorWidget diffEditorWidget2 diffReview domLineBreaksComputer dompurify editorGhostText editorViewLayer notebookRenderer stickyScrollViewLayer tokenizeToString ; "/><meta name="mobile-web-app-capable" content="yes"/><meta name="apple-mobile-web-app-capable" content="yes"/><meta name="apple-mobile-web-app-title" content="Code"/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:site" content="@code"/><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/><meta property="og:title" content="Visual Studio Code for the Web"/><meta property="og:description" content="Build with Visual Studio Code, anywhere, anytime, entirely in your browser."/><meta property="og:image" content="/static/stable/social.png"/><meta http-equiv="origin-trial" content="AvfckDxwQpM83MrjWpxpPAZ1SGNko0aeLW1HkPb0B2wVXSt9vhVdVmDWABbeTmWA6T8sGFvjWE9i/AIgA8v1YwUAAABfeyJvcmlnaW4iOiJodHRwczovL2luc2lkZXJzLnZzY29kZS5kZXY6NDQzIiwiZmVhdHVyZSI6IkZpbGVTeXN0ZW1PYnNlcnZlciIsImV4cGlyeSI6MTc0NzE4MDc5OX0="><meta name="vscode:versionInfo" content="stable;1.95.3;f1a4fb101478ce6ec82fe9627c43efbf9e98c813"/><meta name="vscode:baseURL" content="https://main.vscode-cdn.net/stable/f1a4fb101478ce6ec82fe9627c43efbf9e98c813"/><meta name="vscode:additionalBuiltinExtensions" content="{"github.remotehub":"https://GitHub.vscode-unpkg.net/GitHub/remotehub/0.64.0/extension","ms-vscode.azure-repos":"https://ms-vscode.vscode-unpkg.net/ms-vscode/azure-repos/0.40.0/extension","github.codespaces":"https://GitHub.vscode-unpkg.net/GitHub/codespaces/1.17.3/extension","ms-vscode.remote-server":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-server/1.5.2/extension","ms-vscode.anycode":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode/0.0.73/extension","ms-vscode.remote-explorer":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-explorer/0.4.3/extension","ms-vscode.anycode-cpp":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-cpp/0.0.5/extension","ms-vscode.anycode-python":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-python/0.0.5/extension","ms-vscode.anycode-rust":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-rust/0.0.6/extension","ms-vscode.remote-repositories":"https://ms-vscode.vscode-unpkg.net/ms-vscode/remote-repositories/0.42.0/extension","ms-vscode.anycode-typescript":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-typescript/0.0.5/extension","ms-vscode.anycode-go":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-go/0.0.5/extension","ms-vscode.anycode-java":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-java/0.0.5/extension","ms-vscode.anycode-kotlin":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-kotlin/0.0.5/extension","ms-vscode.anycode-php":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-php/0.0.6/extension","ms-vscode.anycode-c-sharp":"https://ms-vscode.vscode-unpkg.net/ms-vscode/anycode-c-sharp/0.0.5/extension"}"/></head><body></body><script>(()=>{var e={972:(e,a,t)=>{var r;void 0===(r=function(e,a){"use strict";!function(){const e=new URL(window.location.href),a=e.searchParams.get("vscode-lang"),t=localStorage.getItem("vscode.nls.locale")||navigator.language.toLowerCase()||"en";t.startsWith("en")&&!a||a!==t&&(t.startsWith("en")?e.searchParams.delete("vscode-lang"):e.searchParams.set("vscode-lang",t),window.location.href=e.href)}()}.apply(a,[t,a]))||(e.exports=r)}},a={};(function t(r){var o=a[r];if(void 0!==o)return o.exports;var s=a[r]={exports:{}};return e[r](s,s.exports,t),s.exports})(972)})();</script><script>(()=>{var t={669:(t,M,e)=>{var o;void 0===(o=function(t,M){"use strict";!function(){performance.mark("code/willShowPartsSplash");(()=>{const t=localStorage.getItem("monaco-parts-splash");if(!t)return!1;let M;try{M=JSON.parse(t)}catch{return!1}if(!M||"object"!=typeof M||!M.layoutInfo)return!1;const e=document.createElement("style");e.className="initialShellColors",document.head.appendChild(e),e.textContent=`\n\t\t\tbody {\n\t\t\t\tbackground-color: ${M.colorInfo.editorBackground};\n\t\t\t\tcolor: ${M.colorInfo.foreground}; margin: 0; padding: 0;\n\t\t\t}\n\t\t\t#monaco-parts-splash {\n\t\t\t\ttransition: opacity 0.35s ease-out;\n\t\t\t\topacity: 0;\n\t\t\t}\n\t\t\t#monaco-parts-splash.loading {\n\t\t\t\topacity: 1;\n\t\t\t}`;const{layoutInfo:o,colorInfo:N}=M,i=document.createElement("div");i.id="monaco-parts-splash",i.className=M.baseTheme??"",o.windowBorder&&(i.style.position="relative",i.style.height="calc(100vh - 2px)",i.style.width="calc(100vw - 2px)",i.style.border="1px solid var(--window-border-color)",i.style.setProperty("--window-border-color",N.windowBorder??null),o.windowBorderRadius&&(i.style.borderRadius=o.windowBorderRadius)),o.sideBarWidth=Math.min(o.sideBarWidth,window.innerWidth-(o.activityBarWidth+o.editorPartMinWidth));const D=document.createElement("div");D.setAttribute("style",`position: absolute; width: 100%; left: 0; top: 0; height: ${o.titleBarHeight}px; background-color: ${N.titleBarBackground}; -webkit-app-region: drag;`),i.appendChild(D);const a=document.createElement("div");a.setAttribute("style",`position: absolute; height: calc(100% - ${o.titleBarHeight}px); top: ${o.titleBarHeight}px; ${o.sideBarSide}: 0; width: ${o.activityBarWidth}px; background-color: ${N.activityBarBackground};`),i.appendChild(a);const n=document.createElement("div");n.setAttribute("style",`position: absolute; height: calc(100% - ${o.titleBarHeight}px); top: ${o.titleBarHeight}px; ${o.sideBarSide}: ${o.activityBarWidth}px; width: ${o.sideBarWidth}px; background-color: ${N.sideBarBackground};`),i.appendChild(n);const c=document.createElement("div");return c.setAttribute("style",`position: absolute; width: 100%; bottom: 0; left: 0; height: ${o.statusBarHeight}px; background-color: ${N.statusBarBackground};`),i.appendChild(c),document.body.appendChild(i),i.classList.add("loading"),!0})()||(()=>{const t=document.createElement("style");t.textContent="\n\t\t\thtml, body, #monaco-parts-splash {\n\t\t\t\tmargin: 0;\n\t\t\t\tpadding: 0;\n\t\t\t\twidth: 100%;\n\t\t\t\theight: 100%;\n\t\t\t}\n\t\t\t#monaco-parts-splash {\n\t\t\t\tposition: absolute;\n\t\t\t\ttop: 0;\n\t\t\t\tleft: 0;\n\t\t\t\ttransition: opacity 0.35s ease-out;\n\t\t\t\topacity: 0;\n\t\t\t\tbackground-color: #1E1E1E; // vscode.dev uses dark theme by default\n\t\t\t\tbackground-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MiIgaGVpZ2h0PSI0MCIgZmlsbD0ibm9uZSIgdmlld0JveD0iMCAwIDQyIDQwIj4KICAgIDxnIG9wYWNpdHk9IjAuMDUiPgogICAgICAgIDxwYXRoIGZpbGw9ImJsYWNrIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0zMC4yMzU0IDM5Ljg4MzZDMjkuOTE5NSAzOS44ODYyIDI5LjYwNTcgMzkuODI4NyAyOS4zMTA5IDM5LjcxMzlDMjguOTg5NiAzOS41ODg1IDI4LjY5NzcgMzkuMzk3OSAyOC40NTM5IDM5LjE1MzlMMTIuNjk5OSAyNC43Nzk5TDkuMjM5MTcgMjcuNDAzN0w1LjgzNDM0IDI5Ljk4NkM1LjcwNDU0IDMwLjA4NDUgNS41NjIwMSAzMC4xNjI2IDUuNDExNjQgMzAuMjE4OUM1LjIwMjU5IDMwLjI5NzYgNC45NzgzIDMwLjMzMzkgNC43NTE5IDMwLjMyMzlDNC4zNjM2MSAzMC4zMDY4IDMuOTkzNTYgMzAuMTU0MyAzLjcwNTg4IDI5Ljg5MjlMMS41MDU4OCAyNy44OTI5QzEuMzM0NTIgMjcuNzM2OCAxLjE5NzYzIDI3LjU0NjYgMS4xMDM5NiAyNy4zMzQ2QzEuMDEwMjkgMjcuMTIyNSAwLjk2MTkxNCAyNi44OTMzIDAuOTYxOTE0IDI2LjY2MTRDMC45NjE5MTQgMjYuNDI5NiAxLjAxMDI5IDI2LjIwMDQgMS4xMDM5NiAyNS45ODgzQzEuMTk3NjMgMjUuNzc2MiAxLjMzNDUyIDI1LjU4NjEgMS41MDU4OCAyNS40Mjk5TDcuNDU3ODggMTkuOTk5OUw0LjY3MDcyIDE3LjQ1MzJMMS41MDczNCAxNC41Njg5QzEuMzM1ODQgMTQuNDEyOSAxLjE5ODgzIDE0LjIyMjcgMS4xMDUwNyAxNC4wMTA3QzEuMDExMzIgMTMuNzk4NiAwLjk2Mjg5MSAxMy41NjkzIDAuOTYyODkxIDEzLjMzNzRDMC45NjI4OTEgMTMuMTA1NiAxLjAxMTMyIDEyLjg3NjMgMS4xMDUwNyAxMi42NjQyQzEuMTk4ODMgMTIuNDUyMSAxLjMzNTg0IDEyLjI2MiAxLjUwNzM0IDEyLjEwNTlMMy43MDczNCAxMC4xMDU5QzMuNzI5MjYgMTAuMDg2IDMuNzUxNjUgMTAuMDY2NyAzLjc3NDUgMTAuMDQ4QzQuMDUyMTMgOS44MjAyNyA0LjM5NjY2IDkuNjg3ODkgNC43NTY5IDkuNjcxOTZDNS4xNDUxOSA5LjY1NDc5IDUuNTI3MjUgOS43NzQwMSA1LjgzNjg4IDEwLjAwODlMMTIuNjk5OSAxNS4yMTc5TDI4LjQ1MTkgMC44NDM5NDJDMjguNTQ1MiAwLjc1MTY4MiAyOC42NDU1IDAuNjY2NzYzIDI4Ljc1MTkgMC41ODk5NDJDMjkuMTE1MyAwLjMyNTYwMSAyOS41NDM2IDAuMTY0NjMzIDI5Ljk5MTEgMC4xMjQxMzdDMzAuMDkxOSAwLjExNTAyIDMwLjE5MjggMC4xMTIwODYgMzAuMjkzMyAwLjExNTIzNEMzMC42NDQ0IDAuMTIzNzQ4IDMwLjk5MTggMC4yMDY0NDMgMzEuMzExNyAwLjM2MDAyN0wzOS41NDc3IDQuMzIxMDNDMzkuOTcxNiA0LjUyNTIyIDQwLjMyOTIgNC44NDQ4NyA0MC41Nzk1IDUuMjQzMjVDNDAuNzc4NyA1LjU2MDIzIDQwLjkwMzUgNS45MTY4IDQwLjk0NjIgNi4yODYyOUM0MC45NTc0IDYuMzgxNDggNDAuOTYzMiA2LjQ3NzU0IDQwLjk2MzMgNi41NzQwMVY2LjY3Mjk1QzQwLjk2MzMgNi42NTc4MSA0MC45NjMxIDYuNjQyNjggNDAuOTYyNyA2LjYyNzU3VjMzLjM3MDRDNDAuOTYzMSAzMy4zNTUyIDQwLjk2MzMgMzMuMzQwMSA0MC45NjMzIDMzLjMyNDlWMzMuNDE5OUM0MC45NjMzIDMzLjUxNDYgNDAuOTU3OSAzMy42MDkgNDAuOTQ3MiAzMy43MDI1QzQwLjkwNTUgMzQuMDc1NCA0MC43ODAyIDM0LjQzNTUgNDAuNTc5MyAzNC43NTUyQzQwLjMyOSAzNS4xNTM0IDM5Ljk3MTQgMzUuNDcyOSAzOS41NDc3IDM1LjY3N0wzMS4zMTE3IDM5LjYzOEMzMS4wMTkxIDM5Ljc3ODUgMzAuNzAzNyAzOS44NTk2IDMwLjM4MzMgMzkuODc5QzMwLjMzNDEgMzkuODgyIDMwLjI4NDggMzkuODgzNSAzMC4yMzU0IDM5Ljg4MzZaTTMwLjk1MDkgMTAuOTM2OUwxOS4wMDI4IDE5Ljk5ODdMMzAuOTU0OSAyOS4wNjM5TDMwLjk1MDkgMTAuOTM2OVoiIGNsaXAtcnVsZT0iZXZlbm9kZCIvPgogICAgPC9nPgo8L3N2Zz4=);\n\t\t\t\tbackground-repeat: no-repeat;\n\t\t\t\tbackground-position: 50% 50%;\n\t\t\t\tbackground-size: 300px;\n\t\t\t\tz-index: 100000000000000;\n\t\t\t\tpointer-events: none;\n\t\t\t}\n\t\t\t@media (prefers-color-scheme: dark) {\n\t\t\t\tbody, #monaco-parts-splash { background-color: #2c2c32; }\n\t\t\t}\n\t\t\t#monaco-parts-splash.loading {\n\t\t\t\topacity: 1;\n\t\t\t}",document.head.appendChild(t);const M=document.createElement("div");M.id="monaco-parts-splash",document.body.appendChild(M),setTimeout((()=>M.classList.add("loading")),20)})(),performance.mark("code/didShowPartsSplash")}()}.apply(M,[e,M]))||(t.exports=o)}},M={};(function e(o){var N=M[o];if(void 0!==N)return N.exports;var i=M[o]={exports:{}};return t[o](i,i.exports,e),i.exports})(669)})();</script><script>(()=>{var t={223:(t,e,r)=>{var o;void 0===(o=function(t,e){"use strict";(function(){const t=document.querySelector('meta[name="vscode:versionInfo"]').content.split(";"),e=document.querySelector('meta[name="vscode:baseURL"]').content,r=t[0],o=t[2]||void 0;let s;const i=window.trustedTypes?.createPolicy("amdLoader",{createScriptURL(t){if(void 0!==e&&t.startsWith(e))return t;if(t.startsWith("/static/")||"/sw.js"===t)return t;if(s&&t.startsWith(s))return t;throw new Error(`Invalid script url: ${t}`)}});globalThis._VSCODE_WEB_BOOTSTRAP_={quality:r,commit:o,baseUrl:e,trustedTypesPolicy:i},globalThis._VSCODE_FILE_ROOT=e+"/out/",globalThis._VSCODE_WEB_PACKAGE_TTP=i,performance.mark("code/willLoadWorkbenchMain")})()}.apply(e,[r,e]))||(t.exports=o)}},e={};(function r(o){var s=e[o];if(void 0!==s)return s.exports;var i=e[o]={exports:{}};return t[o](i,i.exports,r),i.exports})(223)})();</script><script src="https://main.vscode-cdn.net/nlsmetadata/f1a4fb101478ce6ec82fe9627c43efbf9e98c813/nls.messages.js"></script><script src=""></script><script type="module">import*as e from"https://main.vscode-cdn.net/stable/f1a4fb101478ce6ec82fe9627c43efbf9e98c813/out/vs/workbench/workbench.web.main.internal.js";var t={3466:(e,t,r)=>{r.r(t);var o=r(9883),n={};for(const e in o)"default"!==e&&(n[e]=()=>o[e]);r.d(t,n)},6906:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;const r=[];for(let e=0;e<256;++e)r.push((e+256).toString(16).substr(1));var o=function(e,t){const o=t||0,n=r;return(n[e[o+0]]+n[e[o+1]]+n[e[o+2]]+n[e[o+3]]+"-"+n[e[o+4]]+n[e[o+5]]+"-"+n[e[o+6]]+n[e[o+7]]+"-"+n[e[o+8]]+n[e[o+9]]+"-"+n[e[o+10]]+n[e[o+11]]+n[e[o+12]]+n[e[o+13]]+n[e[o+14]]+n[e[o+15]]).toLowerCase()};t.default=o},2107:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"v1",{enumerable:!0,get:function(){return o.default}}),Object.defineProperty(t,"v3",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(t,"v4",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(t,"v5",{enumerable:!0,get:function(){return s.default}});var o=a(r(8610)),n=a(r(3208)),i=a(r(4061)),s=a(r(3358));function a(e){return e&&e.__esModule?e:{default:e}}},882:(e,t)=>{function r(e){return 14+(e+64>>>9<<4)+1}function o(e,t){const r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function n(e,t,r,n,i,s){return o((a=o(o(t,e),o(n,s)))<<(c=i)|a>>>32-c,r);var a,c}function i(e,t,r,o,i,s,a){return n(t&r|~t&o,e,t,i,s,a)}function s(e,t,r,o,i,s,a){return n(t&o|r&~o,e,t,i,s,a)}function a(e,t,r,o,i,s,a){return n(t^r^o,e,t,i,s,a)}function c(e,t,r,o,i,s,a){return n(r^(t|~o),e,t,i,s,a)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var l=function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r)}return function(e){const t=[],r=32*e.length,o="0123456789abcdef";for(let n=0;n<r;n+=8){const r=e[n>>5]>>>n%32&255,i=parseInt(o.charAt(r>>>4&15)+o.charAt(15&r),16);t.push(i)}return t}(function(e,t){e[t>>5]|=128<<t%32,e[r(t)-1]=t;let n=1732584193,l=-271733879,d=-1732584194,u=271733878;for(let t=0;t<e.length;t+=16){const r=n,h=l,g=d,p=u;n=i(n,l,d,u,e[t],7,-680876936),u=i(u,n,l,d,e[t+1],12,-389564586),d=i(d,u,n,l,e[t+2],17,606105819),l=i(l,d,u,n,e[t+3],22,-1044525330),n=i(n,l,d,u,e[t+4],7,-176418897),u=i(u,n,l,d,e[t+5],12,1200080426),d=i(d,u,n,l,e[t+6],17,-1473231341),l=i(l,d,u,n,e[t+7],22,-45705983),n=i(n,l,d,u,e[t+8],7,1770035416),u=i(u,n,l,d,e[t+9],12,-1958414417),d=i(d,u,n,l,e[t+10],17,-42063),l=i(l,d,u,n,e[t+11],22,-1990404162),n=i(n,l,d,u,e[t+12],7,1804603682),u=i(u,n,l,d,e[t+13],12,-40341101),d=i(d,u,n,l,e[t+14],17,-1502002290),l=i(l,d,u,n,e[t+15],22,1236535329),n=s(n,l,d,u,e[t+1],5,-165796510),u=s(u,n,l,d,e[t+6],9,-1069501632),d=s(d,u,n,l,e[t+11],14,643717713),l=s(l,d,u,n,e[t],20,-373897302),n=s(n,l,d,u,e[t+5],5,-701558691),u=s(u,n,l,d,e[t+10],9,38016083),d=s(d,u,n,l,e[t+15],14,-660478335),l=s(l,d,u,n,e[t+4],20,-405537848),n=s(n,l,d,u,e[t+9],5,568446438),u=s(u,n,l,d,e[t+14],9,-1019803690),d=s(d,u,n,l,e[t+3],14,-187363961),l=s(l,d,u,n,e[t+8],20,1163531501),n=s(n,l,d,u,e[t+13],5,-1444681467),u=s(u,n,l,d,e[t+2],9,-51403784),d=s(d,u,n,l,e[t+7],14,1735328473),l=s(l,d,u,n,e[t+12],20,-1926607734),n=a(n,l,d,u,e[t+5],4,-378558),u=a(u,n,l,d,e[t+8],11,-2022574463),d=a(d,u,n,l,e[t+11],16,1839030562),l=a(l,d,u,n,e[t+14],23,-35309556),n=a(n,l,d,u,e[t+1],4,-1530992060),u=a(u,n,l,d,e[t+4],11,1272893353),d=a(d,u,n,l,e[t+7],16,-155497632),l=a(l,d,u,n,e[t+10],23,-1094730640),n=a(n,l,d,u,e[t+13],4,681279174),u=a(u,n,l,d,e[t],11,-358537222),d=a(d,u,n,l,e[t+3],16,-722521979),l=a(l,d,u,n,e[t+6],23,76029189),n=a(n,l,d,u,e[t+9],4,-640364487),u=a(u,n,l,d,e[t+12],11,-421815835),d=a(d,u,n,l,e[t+15],16,530742520),l=a(l,d,u,n,e[t+2],23,-995338651),n=c(n,l,d,u,e[t],6,-198630844),u=c(u,n,l,d,e[t+7],10,1126891415),d=c(d,u,n,l,e[t+14],15,-1416354905),l=c(l,d,u,n,e[t+5],21,-57434055),n=c(n,l,d,u,e[t+12],6,1700485571),u=c(u,n,l,d,e[t+3],10,-1894986606),d=c(d,u,n,l,e[t+10],15,-1051523),l=c(l,d,u,n,e[t+1],21,-2054922799),n=c(n,l,d,u,e[t+8],6,1873313359),u=c(u,n,l,d,e[t+15],10,-30611744),d=c(d,u,n,l,e[t+6],15,-1560198380),l=c(l,d,u,n,e[t+13],21,1309151649),n=c(n,l,d,u,e[t+4],6,-145523070),u=c(u,n,l,d,e[t+11],10,-1120210379),d=c(d,u,n,l,e[t+2],15,718787259),l=c(l,d,u,n,e[t+9],21,-343485551),n=o(n,r),l=o(l,h),d=o(d,g),u=o(u,p)}return[n,l,d,u]}(function(e){if(0===e.length)return[];const t=8*e.length,o=new Uint32Array(r(t));for(let r=0;r<t;r+=8)o[r>>5]|=(255&e[r/8])<<r%32;return o}(e),8*e.length))};t.default=l},5975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){if(!r)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return r(o)};const r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),o=new Uint8Array(16)},8135:(e,t)=>{function r(e,t,r,o){switch(e){case 0:return t&r^~t&o;case 1:case 3:return t^r^o;case 2:return t&r^t&o^r&o}}function o(e,t){return e<<t|e>>>32-t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=function(e){const t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r))}e.push(128);const i=e.length/4+2,s=Math.ceil(i/16),a=new Array(s);for(let t=0;t<s;++t){const r=new Uint32Array(16);for(let o=0;o<16;++o)r[o]=e[64*t+4*o]<<24|e[64*t+4*o+1]<<16|e[64*t+4*o+2]<<8|e[64*t+4*o+3];a[t]=r}a[s-1][14]=8*(e.length-1)/Math.pow(2,32),a[s-1][14]=Math.floor(a[s-1][14]),a[s-1][15]=8*(e.length-1)&4294967295;for(let e=0;e<s;++e){const i=new Uint32Array(80);for(let t=0;t<16;++t)i[t]=a[e][t];for(let e=16;e<80;++e)i[e]=o(i[e-3]^i[e-8]^i[e-14]^i[e-16],1);let s=n[0],c=n[1],l=n[2],d=n[3],u=n[4];for(let e=0;e<80;++e){const n=Math.floor(e/20),a=o(s,5)+r(n,c,l,d)+u+t[n]+i[e]>>>0;u=d,d=l,l=o(c,30)>>>0,c=s,s=a}n[0]=n[0]+s>>>0,n[1]=n[1]+c>>>0,n[2]=n[2]+l>>>0,n[3]=n[3]+d>>>0,n[4]=n[4]+u>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]};t.default=n},8610:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=i(r(5975)),n=i(r(6906));function i(e){return e&&e.__esModule?e:{default:e}}let s,a,c=0,l=0;var d=function(e,t,r){let i=t&&r||0;const d=t||[];let u=(e=e||{}).node||s,h=void 0!==e.clockseq?e.clockseq:a;if(null==u||null==h){const t=e.random||(e.rng||o.default)();null==u&&(u=s=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==h&&(h=a=16383&(t[6]<<8|t[7]))}let g=void 0!==e.msecs?e.msecs:Date.now(),p=void 0!==e.nsecs?e.nsecs:l+1;const m=g-c+(p-l)/1e4;if(m<0&&void 0===e.clockseq&&(h=h+1&16383),(m<0||g>c)&&void 0===e.nsecs&&(p=0),p>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");c=g,l=p,a=h,g+=122192928e5;const f=(1e4*(268435455&g)+p)%4294967296;d[i++]=f>>>24&255,d[i++]=f>>>16&255,d[i++]=f>>>8&255,d[i++]=255&f;const y=g/4294967296*1e4&268435455;d[i++]=y>>>8&255,d[i++]=255&y,d[i++]=y>>>24&15|16,d[i++]=y>>>16&255,d[i++]=h>>>8|128,d[i++]=255&h;for(let e=0;e<6;++e)d[i+e]=u[e];return t||(0,n.default)(d)};t.default=d},3208:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=i(r(1525)),n=i(r(882));function i(e){return e&&e.__esModule?e:{default:e}}var s=(0,o.default)("v3",48,n.default);t.default=s},1525:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){function o(e,o,i,s){const a=i&&s||0;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}(e)),"string"==typeof o&&(o=function(e){const t=[];return e.replace(/[a-fA-F0-9]{2}/g,(function(e){t.push(parseInt(e,16))})),t}(o)),!Array.isArray(e))throw TypeError("value must be an array of bytes");if(!Array.isArray(o)||16!==o.length)throw TypeError("namespace must be uuid string or an Array of 16 byte values");const c=r(o.concat(e));if(c[6]=15&c[6]|t,c[8]=63&c[8]|128,i)for(let e=0;e<16;++e)i[a+e]=c[e];return i||(0,n.default)(c)}try{o.name=e}catch(e){}return o.DNS=i,o.URL=s,o},t.URL=t.DNS=void 0;var o,n=(o=r(6906))&&o.__esModule?o:{default:o};const i="6ba7b810-9dad-11d1-80b4-00c04fd430c8";t.DNS=i;const s="6ba7b811-9dad-11d1-80b4-00c04fd430c8";t.URL=s},4061:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=i(r(5975)),n=i(r(6906));function i(e){return e&&e.__esModule?e:{default:e}}var s=function(e,t,r){"string"==typeof e&&(t="binary"===e?new Uint8Array(16):null,e=null);const i=(e=e||{}).random||(e.rng||o.default)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){const e=r||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return(0,n.default)(i)};t.default=s},3358:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var o=i(r(1525)),n=i(r(8135));function i(e){return e&&e.__esModule?e:{default:e}}var s=(0,o.default)("v5",80,n.default);t.default=s},7322:(e,t,r)=>{function o(){return"object"==typeof navigator&&"userAgent"in navigator?navigator.userAgent:"object"==typeof process&&"version"in process?`Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`:"<environment undetectable>"}r.r(t),r.d(t,{Octokit:()=>L});var n=r(3015);function i(e){return"[object Object]"===Object.prototype.toString.call(e)}function s(e){var t,r;return!1!==i(e)&&(void 0===(t=e.constructor)||!1!==i(r=t.prototype)&&!1!==r.hasOwnProperty("isPrototypeOf"))}function a(e,t){const r=Object.assign({},e);return Object.keys(t).forEach((o=>{s(t[o])?o in e?r[o]=a(e[o],t[o]):Object.assign(r,{[o]:t[o]}):Object.assign(r,{[o]:t[o]})})),r}function c(e){for(const t in e)void 0===e[t]&&delete e[t];return e}function l(e,t,r){if("string"==typeof t){let[e,o]=t.split(" ");r=Object.assign(o?{method:e,url:o}:{url:e},r)}else r=Object.assign({},t);var o;r.headers=(o=r.headers)?Object.keys(o).reduce(((e,t)=>(e[t.toLowerCase()]=o[t],e)),{}):{},c(r),c(r.headers);const n=a(e||{},r);return e&&e.mediaType.previews.length&&(n.mediaType.previews=e.mediaType.previews.filter((e=>!n.mediaType.previews.includes(e))).concat(n.mediaType.previews)),n.mediaType.previews=n.mediaType.previews.map((e=>e.replace(/-preview/,""))),n}const d=/\{[^}]+\}/g;function u(e){return e.replace(/^\W+|\W+$/g,"").split(/,/)}function h(e,t){return Object.keys(e).filter((e=>!t.includes(e))).reduce(((t,r)=>(t[r]=e[r],t)),{})}function g(e){return e.split(/(%[0-9A-Fa-f]{2})/g).map((function(e){return/%[0-9A-Fa-f]/.test(e)||(e=encodeURI(e).replace(/%5B/g,"[").replace(/%5D/g,"]")),e})).join("")}function p(e){return encodeURIComponent(e).replace(/[!'()*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function m(e,t,r){return t="+"===e||"#"===e?g(t):p(t),r?p(r)+"="+t:t}function f(e){return null!=e}function y(e){return";"===e||"&"===e||"?"===e}function v(e,t){var r=["+","#",".","/",";","?","&"];return e.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g,(function(e,o,n){if(o){let e="";const n=[];if(-1!==r.indexOf(o.charAt(0))&&(e=o.charAt(0),o=o.substr(1)),o.split(/,/g).forEach((function(r){var o=/([^:\*]*)(?::(\d+)|(\*))?/.exec(r);n.push(function(e,t,r,o){var n=e[r],i=[];if(f(n)&&""!==n)if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)n=n.toString(),o&&"*"!==o&&(n=n.substring(0,parseInt(o,10))),i.push(m(t,n,y(t)?r:""));else if("*"===o)Array.isArray(n)?n.filter(f).forEach((function(e){i.push(m(t,e,y(t)?r:""))})):Object.keys(n).forEach((function(e){f(n[e])&&i.push(m(t,n[e],e))}));else{const e=[];Array.isArray(n)?n.filter(f).forEach((function(r){e.push(m(t,r))})):Object.keys(n).forEach((function(r){f(n[r])&&(e.push(p(r)),e.push(m(t,n[r].toString())))})),y(t)?i.push(p(r)+"="+e.join(",")):0!==e.length&&i.push(e.join(","))}else";"===t?f(n)&&i.push(p(r)):""!==n||"&"!==t&&"?"!==t?""===n&&i.push(""):i.push(p(r)+"=");return i}(t,e,o[1],o[2]||o[3]))})),e&&"+"!==e){var i=",";return"?"===e?i="&":"#"!==e&&(i=e),(0!==n.length?e:"")+n.join(i)}return n.join(",")}return g(n)}))}function C(e){let t,r=e.method.toUpperCase(),o=(e.url||"/").replace(/:([a-z]\w+)/g,"{$1}"),n=Object.assign({},e.headers),i=h(e,["method","baseUrl","url","headers","request","mediaType"]);const s=function(e){const t=e.match(d);return t?t.map(u).reduce(((e,t)=>e.concat(t)),[]):[]}(o);var a;o=(a=o,{expand:v.bind(null,a)}).expand(i),/^http/.test(o)||(o=e.baseUrl+o);const c=h(i,Object.keys(e).filter((e=>s.includes(e))).concat("baseUrl"));if(!/application\/octet-stream/i.test(n.accept)&&(e.mediaType.format&&(n.accept=n.accept.split(/,/).map((t=>t.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,`application/vnd$1$2.${e.mediaType.format}`))).join(",")),e.mediaType.previews.length)){const t=n.accept.match(/[\w-]+(?=-preview)/g)||[];n.accept=t.concat(e.mediaType.previews).map((t=>`application/vnd.github.${t}-preview${e.mediaType.format?`.${e.mediaType.format}`:"+json"}`)).join(",")}return["GET","HEAD"].includes(r)?o=function(e,t){const r=/\?/.test(e)?"&":"?",o=Object.keys(t);return 0===o.length?e:e+r+o.map((e=>"q"===e?"q="+t.q.split("+").map(encodeURIComponent).join("+"):`${e}=${encodeURIComponent(t[e])}`)).join("&")}(o,c):"data"in c?t=c.data:Object.keys(c).length?t=c:n["content-length"]=0,n["content-type"]||void 0===t||(n["content-type"]="application/json; charset=utf-8"),["PATCH","PUT"].includes(r)&&void 0===t&&(t=""),Object.assign({method:r,url:o,headers:n},void 0!==t?{body:t}:null,e.request?{request:e.request}:null)}function w(e,t,r){return C(l(e,t,r))}const T=function e(t,r){const o=l(t,r),n=w.bind(null,o);return Object.assign(n,{DEFAULTS:o,defaults:e.bind(null,o),merge:l.bind(null,o),parse:C})}(null,{method:"GET",baseUrl:"https://api.github.com",headers:{accept:"application/vnd.github.v3+json","user-agent":`octokit-endpoint.js/6.0.12 ${o()}`},mediaType:{format:"",previews:[]}});var k=r(5440),I=r.n(k),A=r(3798);function b(e){const t=e.request&&e.request.log?e.request.log:console;(s(e.body)||Array.isArray(e.body))&&(e.body=JSON.stringify(e.body));let r,o,n={};return(e.request&&e.request.fetch||I())(e.url,Object.assign({method:e.method,body:e.body,headers:e.headers,redirect:e.redirect},e.request)).then((async i=>{o=i.url,r=i.status;for(const e of i.headers)n[e[0]]=e[1];if("deprecation"in n){const r=n.link&&n.link.match(/<([^>]+)>; rel="deprecation"/),o=r&&r.pop();t.warn(`[@octokit/request] "${e.method} ${e.url}" is deprecated. It is scheduled to be removed on ${n.sunset}${o?`. See ${o}`:""}`)}if(204!==r&&205!==r){if("HEAD"===e.method){if(r<400)return;throw new A.RequestError(i.statusText,r,{response:{url:o,status:r,headers:n,data:void 0},request:e})}if(304===r)throw new A.RequestError("Not modified",r,{response:{url:o,status:r,headers:n,data:await S(i)},request:e});if(r>=400){const t=await S(i),s=new A.RequestError(function(e){if("string"==typeof e)return e;if("message"in e)return Array.isArray(e.errors)?`${e.message}: ${e.errors.map(JSON.stringify).join(", ")}`:e.message;return`Unknown error: ${JSON.stringify(e)}`}(t),r,{response:{url:o,status:r,headers:n,data:t},request:e});throw s}return S(i)}})).then((e=>({status:r,url:o,headers:n,data:e}))).catch((t=>{if(t instanceof A.RequestError)throw t;throw new A.RequestError(t.message,500,{request:e})}))}async function S(e){const t=e.headers.get("content-type");return/application\/json/.test(t)?e.json():!t||/^text\/|charset=utf-8$/.test(t)?e.text():function(e){return e.arrayBuffer()}(e)}const E=function e(t,r){const o=t.defaults(r);return Object.assign((function(t,r){const n=o.merge(t,r);if(!n.request||!n.request.hook)return b(o.parse(n));const i=(e,t)=>b(o.parse(o.merge(e,t)));return Object.assign(i,{endpoint:o,defaults:e.bind(null,o)}),n.request.hook(i,n)}),{endpoint:o,defaults:e.bind(null,o)})}(T,{headers:{"user-agent":`octokit-request.js/5.6.0 ${o()}`}});class R extends Error{constructor(e,t){super(t.data.errors[0].message),Object.assign(this,t.data),Object.assign(this,{headers:t.headers}),this.name="GraphqlError",this.request=e,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}const _=["method","baseUrl","url","headers","request","query","mediaType"],P=["query","method","url"],M=/\/api\/v3\/?$/;function O(e,t){const r=e.defaults(t);return Object.assign(((e,t)=>function(e,t,r){if(r){if("string"==typeof t&&"query"in r)return Promise.reject(new Error('[@octokit/graphql] "query" cannot be used as variable name'));for(const e in r)if(P.includes(e))return Promise.reject(new Error(`[@octokit/graphql] "${e}" cannot be used as variable name`))}const o="string"==typeof t?Object.assign({query:t},r):t,n=Object.keys(o).reduce(((e,t)=>_.includes(t)?(e[t]=o[t],e):(e.variables||(e.variables={}),e.variables[t]=o[t],e)),{}),i=o.baseUrl||e.endpoint.DEFAULTS.baseUrl;return M.test(i)&&(n.url=i.replace(M,"/api/graphql")),e(n).then((e=>{if(e.data.errors){const t={};for(const r of Object.keys(e.headers))t[r]=e.headers[r];throw new R(n,{headers:t,data:e.data})}return e.data.data}))}(r,e,t)),{defaults:O.bind(null,r),endpoint:E.endpoint})}O(E,{headers:{"user-agent":`octokit-graphql.js/4.6.4 ${o()}`},method:"POST",url:"/graphql"});async function N(e){const t=3===e.split(/\./).length?"app":/^v\d+\./.test(e)?"installation":"oauth";return{type:"token",token:e,tokenType:t}}async function q(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)}const U=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(N.bind(null,e),{hook:q.bind(null,e)})},x="3.5.1";class L{constructor(e={}){const t=new n.Collection,r={baseUrl:E.endpoint.DEFAULTS.baseUrl,headers:{},request:Object.assign({},e.request,{hook:t.bind(null,"request")}),mediaType:{previews:[],format:""}};var i;if(r.headers["user-agent"]=[e.userAgent,`octokit-core.js/${x} ${o()}`].filter(Boolean).join(" "),e.baseUrl&&(r.baseUrl=e.baseUrl),e.previews&&(r.mediaType.previews=e.previews),e.timeZone&&(r.headers["time-zone"]=e.timeZone),this.request=E.defaults(r),this.graphql=(i=this.request,O(i,{method:"POST",url:"/graphql"})).defaults(r),this.log=Object.assign({debug:()=>{},info:()=>{},warn:console.warn.bind(console),error:console.error.bind(console)},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=U(e.auth);t.wrap("request",r.hook),this.auth=r}else this.auth=async()=>({type:"unauthenticated"});this.constructor.plugins.forEach((t=>{Object.assign(this,t(this,e))}))}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 plugin(...e){var t;const r=this.plugins;return(t=class extends(this){}).plugins=r.concat(e.filter((e=>!r.includes(e)))),t}}L.VERSION=x,L.plugins=[]},3798:(e,t,r)=>{r.r(t),r.d(t,{RequestError:()=>c});class o extends Error{constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="Deprecation"}}var n=r(9819),i=r.n(n);const s=i()((e=>console.warn(e))),a=i()((e=>console.warn(e)));class c extends Error{constructor(e,t,r){let n;super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="HttpError",this.status=t,"headers"in r&&void 0!==r.headers&&(n=r.headers),"response"in r&&(this.response=r.response,n=r.response.headers);const i=Object.assign({},r.request);r.request.headers.authorization&&(i.headers=Object.assign({},r.request.headers,{authorization:r.request.headers.authorization.replace(/ .*$/," [REDACTED]")})),i.url=i.url.replace(/\bclient_secret=\w+/g,"client_secret=[REDACTED]").replace(/\baccess_token=\w+/g,"access_token=[REDACTED]"),this.request=i,Object.defineProperty(this,"code",{get:()=>(s(new o("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")),t)}),Object.defineProperty(this,"headers",{get:()=>(a(new o("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")),n||{})})}}},3015:(e,t,r)=>{var o=r(3878),n=r(4252),i=r(5179),s=Function.bind,a=s.bind(s);function c(e,t,r){var o=a(i,null).apply(null,r?[t,r]:[t]);e.api={remove:o},e.remove=o,["before","error","after","wrap"].forEach((function(o){var i=r?[t,o,r]:[t,o];e[o]=e.api[o]=a(n,null).apply(null,i)}))}function l(){var e={registry:{}},t=o.bind(null,e);return c(t,e),t}var d=!1;function u(){return d||(console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4'),d=!0),l()}u.Singular=function(){var e={registry:{}},t=o.bind(null,e,"h");return c(t,e,"h"),t}.bind(),u.Collection=l.bind(),e.exports=u,e.exports.Hook=u,e.exports.Singular=u.Singular,e.exports.Collection=u.Collection},4252:e=>{e.exports=function(e,t,r,o){var n=o;e.registry[r]||(e.registry[r]=[]);"before"===t&&(o=function(e,t){return Promise.resolve().then(n.bind(null,t)).then(e.bind(null,t))});"after"===t&&(o=function(e,t){var r;return Promise.resolve().then(e.bind(null,t)).then((function(e){return n(r=e,t)})).then((function(){return r}))});"error"===t&&(o=function(e,t){return Promise.resolve().then(e.bind(null,t)).catch((function(e){return n(e,t)}))});e.registry[r].push({hook:o,orig:n})}},3878:e=>{e.exports=function e(t,r,o,n){if("function"!=typeof o)throw new Error("method for before hook must be a function");n||(n={});if(Array.isArray(r))return r.reverse().reduce((function(r,o){return e.bind(null,t,o,r,n)}),o)();return Promise.resolve().then((function(){return t.registry[r]?t.registry[r].reduce((function(e,t){return t.hook.bind(null,e,n)}),o)():o(n)}))}},5179:e=>{e.exports=function(e,t,r){if(!e.registry[t])return;var o=e.registry[t].map((function(e){return e.orig})).indexOf(r);if(-1===o)return;e.registry[t].splice(o,1)}},8235:function(e,t,r){"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==r.g&&r.g,e.exports=function(){var e,t="3.7.1",r=t,o="function"==typeof atob,n="function"==typeof btoa,i="function"==typeof Buffer,s="function"==typeof TextDecoder?new TextDecoder:void 0,a="function"==typeof TextEncoder?new TextEncoder:void 0,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=Array.prototype.slice.call(c),d=(e={},l.forEach((function(t,r){return e[t]=r})),e),u=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,h=String.fromCharCode.bind(String),g="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(e,t){return void 0===t&&(t=function(e){return e}),new Uint8Array(Array.prototype.slice.call(e,0).map(t))},p=function(e){return e.replace(/[+\/]/g,(function(e){return"+"==e?"-":"_"})).replace(/=+$/m,"")},m=function(e){return e.replace(/[^A-Za-z0-9\+\/]/g,"")},f=function(e){for(var t,r,o,n,i="",s=e.length%3,a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw new TypeError("invalid character found");i+=l[(t=r<<16|o<<8|n)>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}return s?i.slice(0,s-3)+"===".substring(s):i},y=n?function(e){return btoa(e)}:i?function(e){return Buffer.from(e,"binary").toString("base64")}:f,v=i?function(e){return Buffer.from(e).toString("base64")}:function(e){for(var t=4096,r=[],o=0,n=e.length;o<n;o+=t)r.push(h.apply(null,e.subarray(o,o+t)));return y(r.join(""))},C=function(e,t){return void 0===t&&(t=!1),t?p(v(e)):v(e)},w=function(e){if(e.length<2)return(t=e.charCodeAt(0))<128?e:t<2048?h(192|t>>>6)+h(128|63&t):h(224|t>>>12&15)+h(128|t>>>6&63)+h(128|63&t);var t=65536+1024*(e.charCodeAt(0)-55296)+(e.charCodeAt(1)-56320);return h(240|t>>>18&7)+h(128|t>>>12&63)+h(128|t>>>6&63)+h(128|63&t)},T=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,k=function(e){return e.replace(T,w)},I=i?function(e){return Buffer.from(e,"utf8").toString("base64")}:a?function(e){return v(a.encode(e))}:function(e){return y(k(e))},A=function(e,t){return void 0===t&&(t=!1),t?p(I(e)):I(e)},b=function(e){return A(e,!0)},S=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,E=function(e){switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return h(55296+(t>>>10))+h(56320+(1023&t));case 3:return h((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return h((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},R=function(e){return e.replace(S,E)},_=function(e){if(e=e.replace(/\s+/g,""),!u.test(e))throw new TypeError("malformed base64.");e+="==".slice(2-(3&e.length));for(var t,r,o,n="",i=0;i<e.length;)t=d[e.charAt(i++)]<<18|d[e.charAt(i++)]<<12|(r=d[e.charAt(i++)])<<6|(o=d[e.charAt(i++)]),n+=64===r?h(t>>16&255):64===o?h(t>>16&255,t>>8&255):h(t>>16&255,t>>8&255,255&t);return n},P=o?function(e){return atob(m(e))}:i?function(e){return Buffer.from(e,"base64").toString("binary")}:_,M=i?function(e){return g(Buffer.from(e,"base64"))}:function(e){return g(P(e),(function(e){return e.charCodeAt(0)}))},O=function(e){return M(q(e))},N=i?function(e){return Buffer.from(e,"base64").toString("utf8")}:s?function(e){return s.decode(M(e))}:function(e){return R(P(e))},q=function(e){return m(e.replace(/[-_]/g,(function(e){return"-"==e?"+":"/"})))},U=function(e){return N(q(e))},x=function(e){return{value:e,enumerable:!1,writable:!0,configurable:!0}},L=function(){var e=function(e,t){return Object.defineProperty(String.prototype,e,x(t))};e("fromBase64",(function(){return U(this)})),e("toBase64",(function(e){return A(this,e)})),e("toBase64URI",(function(){return A(this,!0)})),e("toBase64URL",(function(){return A(this,!0)})),e("toUint8Array",(function(){return O(this)}))},D=function(){var e=function(e,t){return Object.defineProperty(Uint8Array.prototype,e,x(t))};e("toBase64",(function(e){return C(this,e)})),e("toBase64URI",(function(){return C(this,!0)})),e("toBase64URL",(function(){return C(this,!0)}))},H=function(){L(),D()},B={version:t,VERSION:r,atob:P,atobPolyfill:_,btoa:y,btoaPolyfill:f,fromBase64:U,toBase64:A,encode:A,encodeURI:b,encodeURL:b,utob:k,btou:R,decode:U,isValid:function(e){if("string"!=typeof e)return!1;var t=e.replace(/\s+/g,"").replace(/=+$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},fromUint8Array:C,toUint8Array:O,extendString:L,extendUint8Array:D,extendBuiltins:H,Base64:{}};return Object.keys(B).forEach((function(e){return B.Base64[e]=B[e]})),B}()},5440:(e,t)=>{var r=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==r)return r;throw new Error("unable to locate global object")}();e.exports=t=r.fetch,r.fetch&&(t.default=r.fetch.bind(r)),t.Headers=r.Headers,t.Request=r.Request,t.Response=r.Response},9819:(e,t,r)=>{var o=r(1591);function n(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},r=e.name||"Function wrapped with `once`";return t.onceError=r+" shouldn't be called more than once",t.called=!1,t}e.exports=o(n),e.exports.strict=o(i),n.proto=n((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return n(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return i(this)},configurable:!0})}))},7467:function(e,t,r){var o,n,i=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r),Object.defineProperty(e,o,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return s(t,e),t},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};o=[r,t,r(3466),r(6877),r(9685),r(9804),r(586),r(1052)],n=function(e,t,r,o,n,i,s,l){Object.defineProperty(t,"__esModule",{value:!0}),r=a(r),i=c(i);const d=new Set(["ms-vscode","ms-toolsai","ms-azuretools","quantum","synapsevscode"]),u=new Set(i.default.map((e=>e.toLowerCase()))),h=new Set(["vscode-quality","vscode-version"]),g=new Set(["localhost","127.0.0.1","[::1]"]),p=new Map([["ms-vscode.remote-server","tunnel"],["quantum.qsharp-lang-vscode","quantum"]]),m=new Map([...p].map((([e,t])=>[t,e]))),f=/\.code-workspace$/i,y=/^([a-z0-9][a-z0-9\-]*)\.([a-z0-9][a-z0-9\-]*)(?:@([0-9]+\.[0-9]+\.[0-9]+))?$/;const v=new class{constructor(e){this.maxSize=e}save(e,t){const r=this.getAuthorityKey(e),o=this.getValue();o.delete(r),o.set(r,t);for(const e of o.keys()){if(o.size<this.maxSize)break;o.delete(e)}localStorage.setItem("anything.cache",JSON.stringify([...o]))}getExtensionFor(e){return this.getValue().get(this.getAuthorityKey(e))}getAuthorityKey(e){let t=e.indexOf("+");return-1===t?e:e.slice(0,t)}getValue(){if(!this._value){const e=localStorage.getItem("anything.cache");this._value=new Map(e?JSON.parse(e):void 0),this._value.set("tunnel","ms-vscode.remote-server")}return this._value}}(100);class C{async route({url:e,microsoftAuthentication:t,githubAuthentication:i,quality:a,commit:c,continueOnBody:g}){const y=function(e){let t=e.indexOf("/",1);-1===t&&(t=e.length);const r=e.slice(1,-1===t?void 0:t),o=m.get(r);let n;if(o)n=o;else{if("+"!==e[1])return;n=r.slice(1)}return{extensionPathPart:r,extensionId:n,folderUri:t+1<e.length?e.slice(t+1):void 0}}(e.pathname);if(!y)return;const w="stable"!==a,T=await this.getExtensionUrl(w,y.extensionId);if(!T)return;const k=await this.readPackageJson(T.url),I=T.publisher||k.publisher||"unknown",A=T.name||k.name||"unnamed",b=k.contributes?.webOpener;if(!d.has(I.toLowerCase()))return;g?.authentication?.microsoft?.length&&await t.setInitialSessions(g.authentication.microsoft),e=await t.tryCompleteAuthExchange(),e=function(e,t){if("+"!==t[0])return e;const r=p.get(t.slice(1));if(!r)return e;const o=new URL(e);return o.pathname=o.pathname.replace(/^\/[^/]+/,`/${r}`),window.history.replaceState(void 0,document.title,o.toString()),o}(e=await i.tryCompleteAuthExchange(),y.extensionPathPart);const S=`${I}.${A}`;let E,R={workspaceUri:r.URI.from({scheme:"tmp",path:"/default.code-workspace"})};if(b?.scheme&&y.folderUri){const t=y.folderUri.indexOf("/"),o=new URLSearchParams(document.location.search);for(const e of h)o.delete(e);E=r.URI.from({scheme:b.scheme,authority:-1===t?y.folderUri:y.folderUri.slice(0,t),fragment:e.hash.slice(1),query:o.toString(),path:-1===t?void 0:this.sanitizePathForUri(y.folderUri.slice(t))}),R=f.test(E.path)?{workspaceUri:E}:{folderUri:E}}const _=await this.collectExtensionDependencies(w,k),P={workspace:R,workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},additionalBuiltinExtensions:[r.URI.parse(T.url),..._.map((e=>e.uri))],enabledExtensions:[S]},excludeAdditionalBuiltinExtensions:[S],onDidCreateWorkbench:{runCommands:this.processRunCommands(b?.runCommands)}},M={commands:{executeCommand:r.commands.executeCommand},logger:{log:r.logger.log},window:{withProgress:r.window.withProgress}};if(u.has(I.toLowerCase())&&b?.import){const e=await import(`${T.url}/${b.import}`),r={version:{quality:a,commit:c},registerLoopbackResponder:s.registerLoopbackResponder,microsoftAuthentication:t,githubAuthentication:i,workbench:M,withProgress:l.withProgress,...this.makeExportsApi(w)};await e.default(P,r)}if("object"==typeof P.workspace){const e=(0,n.getWorkspaceUri)(P.workspace);v.save(e.authority,S),e.path||(P.workspace=o.EmptyWorkspace)}return C.lastRouted={extensionPathPart:y.extensionPathPart,uri:E},P}sanitizePathForUri(e){return e.replace(/%20/g," ")}async readPackageJson(e){const t=await fetch(`${e}/package.json`);if(!t.ok)throw new Error(`Unexpected ${t.status} from ${e}/package.json`);return await t.json()}processRunCommands(e){return e?.map((e=>({...e,args:e.args.map((e=>"$url"===e?document.location.href:e))})))??[]}async getExtension(e,t){const o=await this.getExtensionUrl(e,t);if(!o)return;const n=await this.readPackageJson(o.url);return{id:t,extensionUri:r.URI.parse(o.url),packageJSON:n,isActive:!1,activate:()=>o.publisher&&u.has(o.publisher.toLowerCase())&&n.contributes.webOpener?.import?import(`${o.url}/${n.contributes.webOpener.import}`).then((async t=>await(t.exports?.(this.makeExportsApi(e))))):Promise.resolve(void 0)}}makeExportsApi(e){return{getExtension:t=>this.getExtension(e,t)}}async getExtensionUrl(e,t){const r=y.exec(t);if(r){const[,o,n,i=await this.getLatestExtensionVersion(t,e)]=r;return{url:`https://${o}.vscode-unpkg.net/${o}/${n}/${i}/extension`,publisher:o,name:n}}try{const e=atob(t),r=new URL(e);if(g.has(r.hostname))return{url:r.toString(),publisher:void 0,name:void 0}}catch{}}async getLatestExtensionVersion(e,t){const r=await fetch("https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery",{method:"POST",headers:{"Content-Type":"application/json",accept:"application/json;api-version=3.0-preview.1","x-market-client-id":"vscode-dev"},body:JSON.stringify({filters:[{criteria:[{filterType:7,value:e}]}],pageNumber:1,flags:1|(t?512:16)})});if(!r.ok)throw new Error(`Unexpected ${r.status} from marketplace search: ${await r.text()}`);const o=await r.json();let n=o.results[0].extensions[0]?.versions;if(!n?.length)return;const i=n.filter((e=>"web"===e.targetPlatform));let s="";if(i.length&&(n=i,s="+web"),t)return n[0].version+s;const a=n.find((e=>!e.properties.some((e=>"Microsoft.VisualStudio.Code.PreRelease"===e.key&&"true"===e.value))));return a?a.version+s:void 0}async collectExtensionDependencies(e,t){const o=[],n=[t],i=new Set;for(;n.length;){const t=n.pop(),s=[...t.extensionDependencies??[],...t.extensionPack??[]];s.length&&await Promise.all(s.map((async t=>{if(i.has(t))return;i.add(t);const s=await this.getExtensionUrl(e,t);if(!s)return;const a=await this.readPackageJson(s.url);o.push({uri:r.URI.parse(s.url),packageJson:a,name:s.name,publisher:s.publisher}),n.push(a)})))}return o}}for(const e of m.keys())(0,o.registerRouter)(new class extends C{constructor(){super(...arguments),this.path=e,this.additionalBuiltinExtensions=[]}});(0,o.registerRouter)(new class extends C{constructor(){super(...arguments),this.path={prefix:"+"},this.additionalBuiltinExtensions=[]}}),(0,n.registerWorkspaceResolver)(new class{resolveWorkspace(e){if(void 0===e&&C.lastRouted?.uri){const e=new URL(document.location.href);return e.pathname=`/${C.lastRouted.extensionPathPart}/${C.lastRouted.uri.authority}`,e.toString()}const t=e&&(0,n.getWorkspaceUri)(e);if(!t)return;let r=t.authority.split("@");const o=r[r.length-1];o.includes("+")&&(r[r.length-1]=o.slice(o.indexOf("+")+1));const i=t&&v.getExtensionFor(o);if(!i)return;const s=p.get(i)||`+${i}`,a=new URL(document.location.href);a.search=t?.query?`?${t.query}`:"",a.hash=t?.fragment?`#${t?.fragment}`:"",a.pathname=`/${s}/${r.join("@")}${t?.path||""}`;const c=new URLSearchParams(document.location.search);for(const e of h)c.has(e)&&a.searchParams.set(e,c.get(e));return a.toString()}})}.apply(t,o),void 0===n||(e.exports=n)},9573:function(e,t,r){var o,n,i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};o=[r,t,r(6201),r(3466),r(4595),r(1895)],n=function(e,t,r,o,n,s){Object.defineProperty(t,"__esModule",{value:!0}),t.MsalAuthentication=void 0,n=i(n);t.MsalAuthentication=class{constructor(e){this.url=e,this.authenticationProvider=new a,this._initialized=this.initialize()}async initialize(){const e=window.sessionStorage.getItem("microsoftAuthRedirectData");if(!e)return;const{clientId:t,tenant:r}=JSON.parse(e),o=await this.authenticationProvider.getMsalObj(t,r);await o.handleRedirectPromise(),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 o=new u(e);let n;const i=await this.authenticationProvider.getMsalObj(o.clientId,o.tenant);if(!t?.forceNewSession){for(const e of i.getAllAccounts({tenantId:o.tenantId})){const n={refreshTokenExpirationOffsetSeconds:79200,forceRefresh:!0,scopes:o.msalScopes,account:e,state:JSON.stringify({originalScopes:o.originalScopes})};try{await i.acquireTokenSilent(n)}catch(e){if(t?.silent){console.error(e);continue}e instanceof r.InteractionRequiredAuthError?(window.sessionStorage.setItem("microsoftAuthRedirectData",JSON.stringify({clientId:o.clientId,tenant:o.tenant,redirectUri:window.location.href})),await i.acquireTokenRedirect({...n,claims:e.claims})):console.error(e)}}n=await this.authenticationProvider.getSessions(o.originalScopes)}if(!n?.length){if(t?.silent)return[];throw window.sessionStorage.setItem("microsoftAuthRedirectData",JSON.stringify({clientId:o.clientId,tenant:o.tenant,redirectUri:window.location.href})),await i.loginRedirect({scopes:o.msalScopes,state:JSON.stringify({originalScopes:o.originalScopes})}),new Error("Redirecting to authenticate")}return n.map((e=>({...e,getAccessToken:()=>Promise.resolve(e.accessToken)})))}dispose(){this.authenticationProvider.dispose()}async setInitialSessions(e){}tryCompleteAuthExchange(){return Promise.resolve(this.url)}};class a{constructor(){this.id="microsoft",this.label="Microsoft",this.supportsMultipleAccounts=!0,this._msalInstances=new Map,this._sessionIdToContext=new Map,this._expireWarning=new Map,this._disposables=new Array,this._onDidChangeSessionsEmitter=new o.Emitter,this.onDidChangeSessions=this._onDidChangeSessionsEmitter.event,this._disposables.push(this._onDidChangeSessionsEmitter)}async getSessions(e,t){const n=new u(e??[]);o.logger.log(o.LogLevel.Info,`[getSessions] [${e?n.scopeStr:"all"}] starting`);let i=this._msalInstances.get(`${n.clientId}:${n.tenant}`);i||(i=await this.createMsalObj(n.clientId,n.tenant));const s=i.getAllAccounts({tenantId:n.tenantId,loginHint:t?.account?.label});if(!s.length)return o.logger.log(o.LogLevel.Info,`[getSessions] [${e?n.scopeStr:"all"}] no accounts found`),[];const a=new Array;for(const e of s)try{const t=await i.acquireTokenSilent({scopes:n.msalScopes,cacheLookupPolicy:r.CacheLookupPolicy.AccessTokenAndRefreshToken,account:e,state:JSON.stringify({originalScopes:n.originalScopes})});a.push(t)}catch(e){o.logger.log(o.LogLevel.Error,e.toString()),console.error(e)}const c=a.map((e=>d(e,n.originalScopes)));return o.logger.log(o.LogLevel.Info,`[getSessions] [${e?n.scopeStr:"all"}] returned ${c.length} sessions`),c}async createSession(e,t){const r=new u(e);o.logger.log(o.LogLevel.Info,`[createSession] [${r.scopeStr}] starting`);const n=this._msalInstances.get(`${r.clientId}:${r.tenant}`)??await this.createMsalObj(r.clientId,r.tenant),i=JSON.stringify({originalScopes:r.originalScopes}),s=await this.getAuthenticationResultFromRedirectInPopup(n,r.msalScopes,i,t.account?.label);n.setActiveAccount(s.account);const a=d(s,r.originalScopes);return o.logger.log(o.LogLevel.Info,`[createSession] [${r.scopeStr}] returned a session`),a}async removeSession(e){const t=this._sessionIdToContext.get(e);if(o.logger.log(o.LogLevel.Info,`[removeSession] [${e}] starting`),!t)return void o.logger.log(o.LogLevel.Info,`[removeSession] [${e}] session not found`);const{msalObj:r,authResult:n,scopes:i}=t;await r.clearCache({account:n.account}),this._sessionIdToContext.delete(e),o.logger.log(o.LogLevel.Info,`[removeSession] [${e}] session removed`),this._onDidChangeSessionsEmitter.fire({removed:[d(n,i)]})}dispose(){this._disposables.forEach((e=>e.dispose())),this._disposables=[]}async getMsalObj(e,t){const r=this._msalInstances.get(`${e}:${t}`);return r||await this.createMsalObj(e,t)}async createMsalObj(e,t){const n=new r.PublicClientApplication({auth:{clientId:e,authority:`${a._DEFAULT_AAD_ENDPOINT}${t}`,redirectUri:a._REDIRECT_ROUTE},cache:{cacheLocation:"localStorage"},system:{loggerOptions:{loggerCallback:(e,t,n)=>{if(!n)switch(e){case r.LogLevel.Error:return o.logger.log(o.LogLevel.Error,t),void console.error(t);case r.LogLevel.Info:return o.logger.log(o.LogLevel.Info,t),void console.info(t);case r.LogLevel.Verbose:return o.logger.log(o.LogLevel.Trace,t),void console.debug(t);case r.LogLevel.Warning:return o.logger.log(o.LogLevel.Warning,t),void console.warn(t)}},piiLoggingEnabled:!1}}});this._msalInstances.set(`${e}:${t}`,n),await n.initialize();const i=n.addEventCallback((e=>{if(e.eventType!==r.EventType.ACQUIRE_TOKEN_SUCCESS)return;const t=e.payload;if(this._sessionIdToContext.has(t.idToken)){if(!t.fromCache){const e=this._sessionIdToContext.get(t.idToken);this._sessionIdToContext.set(t.idToken,{msalObj:n,authResult:t,scopes:e.scopes}),this._onDidChangeSessionsEmitter.fire({changed:[d(t,e.scopes)]})}}else{const e=t.state?JSON.parse(t.state).originalScopes??t.scopes:t.scopes;this._sessionIdToContext.set(t.idToken,{msalObj:n,authResult:t,scopes:e}),this._onDidChangeSessionsEmitter.fire({added:[d(t,e)]})}let o=this._expireWarning.get(t.account.homeAccountId);o&&t.fromCache||(o||(t.account.homeAccountId,o=new h,this._expireWarning.set(t.account.homeAccountId,o)),o.cancelAndSet((()=>this.informUserOfExpiredSession(t)),72e6))}));return i&&this._disposables.push({dispose:()=>n.removeEventCallback(i)}),n}async getAuthenticationResultFromRedirectInPopup(e,t,o,n,i){const{clientId:a,authority:d}=e.getConfiguration().auth,u=new URL("/msal",window.location.origin);u.searchParams.append("scopes",t.join(" ")),u.searchParams.append("clientId",a),u.searchParams.append("authority",d),n&&u.searchParams.append("loginHint",n),i&&u.searchParams.append("claims",i);if(!function(e){const t=Math.floor(window.screenLeft+window.innerWidth/2-c/2),r=Math.floor(window.screenTop+window.innerHeight/2-l/2);return window.open(e,"_blank",`width=${c},height=${l},top=${r},left=${t}`)??void 0}(u.toString()))throw new Error("Could not open popup");const h=(0,s.createMicrosoftAuthBroadcastChannel)(a,d,t);return await new Promise(((n,i)=>{h.onmessage=async s=>{if(s.data)if("message"in s.data)i(s.data);else{const i=await e.acquireTokenSilent({scopes:t,account:s.data.account,cacheLookupPolicy:r.CacheLookupPolicy.AccessTokenAndRefreshToken,forceRefresh:!1,state:o});n(i)}else i("data is undefined");h.onmessage=null,h.postMessage({close:!0}),h.close()}}))}async informUserOfExpiredSession(e){const t=n.default.auth.Refresh.toString(),r=n.default.auth.MoreInfo.toString(),i=await o.window.showInformationMessage(n.default.auth.SessionExpiringSoon.toString(e.account.username),t,r);if(i===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:d(e,t,r).account})}else i===r&&(window.open("https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens#token-lifetime","_blank"),await this.informUserOfExpiredSession(e))}}a._REDIRECT_ROUTE="/msal",a._DEFAULT_AAD_ENDPOINT="https://login.microsoftonline.com/";const c=780,l=640;function d(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}}class u{constructor(e){this.DEFAULT_CLIENT_ID="aebc6443-996d-45c2-90f0-388ff96faa56",this.DEFAULT_TENANT="organizations",this.originalScopes=e,this.scopeStr=this.originalScopes.join(" "),this.msalScopes=this.getFullScopeList(e),this.tenant=this.getTenantId(e),this.tenantId=["common","organizations","consumers"].includes(this.tenant)?void 0:this.tenant,this.clientId=this.getClientId(e)}getFullScopeList(e){e??=[],e=e.filter((e=>!e.startsWith("VSCODE_")));let t=[...e];return t.includes("openid")||t.push("openid"),t.includes("email")||t.push("email"),t.includes("profile")||t.push("profile"),t.includes("offline_access")||t.push("offline_access"),t.sort()}getClientId(e){return e?e.reduce(((e,t)=>t.startsWith("VSCODE_CLIENT_ID:")?t.split("VSCODE_CLIENT_ID:")[1]:e),void 0)??this.DEFAULT_CLIENT_ID:this.DEFAULT_CLIENT_ID}getTenantId(e){return e?e.reduce(((e,t)=>t.startsWith("VSCODE_TENANT:")?t.split("VSCODE_TENANT:")[1]:e),void 0)??this.DEFAULT_TENANT:this.DEFAULT_TENANT}}class h{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))}}}.apply(t,o),void 0===n||(e.exports=n)},438:(e,t,r)=>{var o,n;o=[r,t,r(3466),r(6877),r(1895),r(1052)],n=function(e,t,r,o,n,i){Object.defineProperty(t,"__esModule",{value:!0});const s="https://management.azure.com/";function a(e){const t="tunnel+",r=e.lastIndexOf("@");return-1===r?t+e:e.slice(0,r+1)+t+e.slice(r+1)}async function c(e,t){if(!e.ok){const o=(await e.json()).error.message;throw console.error(t+o),r.window.showInformationMessage(t+o),new Error(o)}}async function l(e){const t=`${s}subscriptions?api-version=2020-01-01`,r=await fetch(t,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${e}`}});return await c(r,"Failed to list subscriptions: "),r.json()}async function d(e,t=50,r=500){for(let o=0;o<t;o++)try{return await e()}catch(e){if(!e.message.includes("not found"))throw e;if(!(o<t-1))throw e;await new Promise((e=>setTimeout(e,r)))}}async function u(e){return new Promise((async(t,r)=>{await Promise.allSettled(e.map((async e=>{"Registered"===(await async function(e,t){const r=`${s}subscriptions/${e}/providers/Microsoft.Features/providers/Microsoft.CloudShell/features/vscode?api-version=2021-07-01`,o=await fetch(r,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${t}`,"Content-Type":"application/json"}});return await c(o,"Failed to get feature: "),o.json()}(e.subscriptionId,e.accessToken)).properties.state&&t(e)}))),r("No subscription found with Cloud Shell feature registered")}))}(0,o.registerRouter)(new class{constructor(){this.path="azure",this.additionalBuiltinExtensions=["ms-vscode.remote-server"],this.excludeDefaultExtensions=!0}async route({url:e,microsoftAuthentication:t}){try{if(!/^\/azure\/?$/i.test(e.pathname))return;return(0,i.withProgress)({title:"Connecting to vscode.dev/azure"},(async o=>{o.report({message:"Authenticating with Azure..."}),e=await t.tryCompleteAuthExchange();const i=await t.getSessions(["https://management.core.windows.net//.default"]),h=await t.getSessions(["46da2f7e-b5ef-422a-88d4-2a7f9de6a0b2/.default","email"]),g=h[0]?.accessToken,p=i[0]?.accessToken;if(!p)return void r.window.showInformationMessage("Couldn't get ARM access token.");if(!g)return void r.window.showInformationMessage("Couldn't get Dev Tunnels access token.");o.report({message:"Getting Azure Subscriptions..."});const m=await async function(e){const t=`${s}tenants?api-version=2022-12-01`,r=await fetch(t,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${e}`}});return await c(r,"Failed to list tenants: "),(await r.json()).value}(p),f=[];for(const e of m){const r=(await t.getSessions(["https://management.azure.com//.default"],{tenant:e.tenantId,silent:!0}))[0];if(r){const e=(await l(r.accessToken)).value.map((e=>({...e,accessToken:r.accessToken})));f.push(...e)}}const y=await u(f);o.report({message:"Creating Azure Cloud Shell instance..."});const v=C?`${s}providers/Microsoft.Portal/locations/${C}`:`${s}providers/Microsoft.Portal`;var C;const w=await async function(e,t,r,o){const n=`${e}/userSettings/cloudconsole?api-version=2023-02-01-preview`,i=await fetch(n,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({properties:{preferredOsType:"Linux",preferredLocation:o||"westus",terminalSettings:{fontSize:"Medium",fontStyle:"Monospace"},preferredShellType:"bash",networkType:"Default",userSubscription:r,sessionType:"Ephemeral"}})});return await c(i,"Failed to update Cloud Shell settings: "),(await i.json()).properties}(v,p,y.subscriptionId),T=await async function(e,t,r){let o={properties:{provisioningState:""}};for(;"Succeeded"!==o.properties.provisioningState;){const n="https://management.azure.com/providers/Microsoft.Portal/consoles/default?api-version=2023-02-01-preview",i=await fetch(r||n,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${e}`,"x-ms-console-preferred-location":t.preferredLocation},body:JSON.stringify({properties:{osType:"linux"}})});await c(i,"Failed to create Cloud Shell: "),o=await i.json()}return o}(p,w),k=T.properties.uri,I=await async function(e,t){const r=new URL(t),o=await fetch(t+"/terminals?cols=80&rows=24&shell=bash",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${e.resource}`,Referer:r.protocol+"//"+r.hostname+"/$hc"+r.pathname+"/terminals"},body:JSON.stringify({tokens:[]})});return await c(o,"Failed to initialize terminal: "),o.json()}({resource:p},k),A=I.id,b=e.searchParams.get("azdTemplateUrl");if(b&&!function(e){let t;try{t=new URL(e)}catch(e){return!1}return"http:"===t.protocol||"https:"===t.protocol}(b)){const e=`Invalid azdTemplateUrl: ${b}`;throw r.window.showInformationMessage(e),new Error(e)}const S=function(e){if(!e)return"azuredev-"+crypto.randomUUID().slice(0,4);const t=new URL(e).pathname.split("/");return(t.pop()||t.pop()||"")+"-"+crypto.randomUUID().slice(0,4)}(b),E=await async function(e,t,r,o,n){const i=await fetch(t+"/tunnel",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${e.resource}`},body:JSON.stringify({token:r,folderPath:o,tunnelName:n,extensions:["ms-azuretools.azure-dev","ms-azuretools.vscode-azureresourcegroups","ms-azuretools.vscode-azurefunctions","ms-azuretools.vscode-azurestaticwebapps","ms-azuretools.vscode-azurestorage","ms-azuretools.vscode-azurevirtualmachines","ms-azuretools.vscode-cosmosdb","GitHub.vscode-pull-request-github","GitHub.copilot","GitHub.copilot-chat"]})});return await c(i,"Failed to create tunnel: "),i.json()}({resource:p},k,g,S,"cloudshell"),R=E.tunnelName,_=E.directory;return r.workspace.didResolveRemoteAuthority().then((async()=>{console.log("Resolved remote authority..."),b&&await d((async()=>{console.log("Calling azd init..."),await r.commands.executeCommand("azure-dev.commands.cli.init",void 0,void 0,{templateUrl:b,environmentName:"vscode-dev-"+crypto.randomUUID().slice(0,6)})})),await d((async()=>{console.log("Calling maintainCloudShellConnection..."),await r.commands.executeCommand("azureResourceGroups.maintainCloudShellConnection",{consoleUri:k,terminalId:A})}))})),{workspace:{folderUri:r.URI.from({scheme:"vscode-remote",authority:`tunnel+${R}`,path:_})},workbenchOptions:{enableWorkspaceTrust:!1,remoteAuthority:a(R),additionalTrustedDomains:[],enabledExtensions:[],windowIndicator:{onDidChange:n.NullEvent,label:"Azure",tooltip:"Use Azure online"}}}}))}catch(e){return void console.error(e)}}})}.apply(t,o),void 0===n||(e.exports=n)},7117:(e,t,r)=>{var o,n;o=[r,t,r(3466),r(4336),r(6877),r(2808),r(5132)],n=function(e,t,r,o,n,i,s){Object.defineProperty(t,"__esModule",{value:!0});const a=/^\/(?<service>azurerepos)(?<indexed>\+idx=?(?<idx>latest|[0-9a-fA-F]{40})?)?(?:\/defaultcollection)?\/(?<organization>[^/]+)(?:\/(?<project>[^_/][^/]*))?(?:\/_git)?\/(?<repo>[^/]+)(?:\/commit\/(?<commit>[0-9a-f]{40})|\/pullrequest\/(?<pull>\d+))?/i;(0,n.registerRouter)(new class{constructor(){this.path="azurerepos",this.additionalBuiltinExtensions=["ms-vscode.azure-repos"]}async route({url:e,quality:t}){const o=a.exec(e.pathname);if(void 0===o?.groups)return;const{indexed:n,idx:i,organization:c,project:l,repo:d,commit:u,pull:h}=o.groups,g=/^GC(?<commit>[0-9a-f]{40})/i.exec(e.searchParams.get("version")??""),p=/^GB(?<branchName>.+)/i.exec(e.searchParams.get("version")??""),m=/^GT(?<tagName>.+)/i.exec(e.searchParams.get("version")??"");let f,y,v={};if(p&&p.groups){const{branchName:e}=p.groups;f={v:1,ref:{type:s.RepositoryRefType.Branch,id:e}}}else if(m&&m.groups){const{tagName:e}=m.groups;f={v:1,ref:{type:s.RepositoryRefType.Tag,id:e}}}else if(u)f={v:1,ref:{type:s.RepositoryRefType.Commit,id:u}};else if(g&&g.groups){const{commit:e}=g.groups;f={v:1,ref:{type:s.RepositoryRefType.Commit,id:e}}}else h?f={v:1,ref:{type:s.RepositoryRefType.PullRequest,id:h}}:v={"workbench.startupEditor":"readme"};n&&(f||(f={v:1}),f.idx=i||"latest");const C=e.searchParams.get("path");if(C){let t;if(e.searchParams.get("line")){const r=Number(e.searchParams.get("line"));t={startColumn:Number(e.searchParams.get("lineStartColumn")??0),startLineNumber:r,endColumn:Number(e.searchParams.get("lineEndColumn")??0),endLineNumber:Number(e.searchParams.get("lineEnd")??r+1)}}y={force:!0,editors:[{uri:{scheme:"vscode-vfs",authority:(0,s.encodeAuthority)("azurerepos",f),path:`/${c}/${l??d}/${d}${C.startsWith("/")?C:`/${C}`}`},options:{selection:t},openOnlyIfExists:!0}]}}const w=e.searchParams.get("editSessionId")??void 0;return e.searchParams.delete("editSessionId"),window.history.replaceState(void 0,document.title,e.toString()),{workspace:{folderUri:r.URI.from({scheme:"vscode-vfs",authority:(0,s.encodeAuthority)("azurerepos",f),path:`/${c}/${l??d}/${d}`})},workbenchOptions:{configurationDefaults:{"remoteHub.richNavigation.enabled":!0,"workbench.startupEditor":"none",...v},editSessionId:w,defaultLayout:y,commands:[{id:"_remotehub.getLfsProxyEndpoint",handler:()=>({"dev.azure.com":`https://${"stable"===t?"vscode.dev":"insiders.vscode.dev"}/indexes/lfs`})}]}}}}),(0,s.registerRemoteHubWorkspaceResolver)("azurerepos",new class{resolveRemoteHubWorkspace(e,t){const r=new URL(document.location.href),o=a.exec(`/azurerepos${e.path}`);if(void 0===o?.groups)throw new Error(`RemoteHub uri not supported: ${e.toString()}`);const{organization:n,project:i,repo:c}=o.groups,l=new URLSearchParams(e.query);let d=l.get("vscode-experience")??"azurerepos";void 0!==t&&("latest"===t.idx?d+="+idx":(0,s.isSha)(t.idx)&&(d+=`+idx=${t.idx}`));let u=`/${d}/${n}/${i}/${c}`;switch(t?.ref?.type){case s.RepositoryRefType.Commit:l.set("version",`GC${t.ref.id}`);break;case s.RepositoryRefType.Branch:l.set("version",`GB${t.ref.id}`);break;case s.RepositoryRefType.Tag:l.set("version",`GT${t.ref.id}`);break;case s.RepositoryRefType.PullRequest:u=`${u}/pullrequest/${t.ref.id}`}return r.pathname=u,r.search=l.toString(),r.toString()}}),(0,o.registerRedirect)(new i.DomainRedirect("dev.azure.com","azurerepos")),(0,o.registerRedirect)(new class{constructor(e,t){this.service=t,this.regexp=new RegExp(`^/(?:https?://)?(?<organization>[^.]+)${e.replace(/\./g,"\\.")}(?:/defaultcollection)?/(?<rest>.*)`,"i")}redirect(e){const t=this.regexp.exec(e.pathname);if(!t?.groups||!t.groups.organization)return;const r=new URL(e.toString());return r.pathname=`/${this.service}/${t.groups.organization}/${t.groups.rest}`,r}}(".visualstudio.com","azurerepos")),(0,o.registerRedirect)(new class{redirect(e){const t=a.exec(e.pathname);if(void 0===t?.groups)return;const{organization:r,project:o,repo:n,commit:i,pull:s}=t.groups,c=new URL(e.toString());return c.pathname=`/azurerepos/${r}/${o??n}/${n}${i?`/commit/${i}`:s?`/pullrequest/${s}`:""}`,c}})}.apply(t,o),void 0===n||(e.exports=n)},4174:(e,t,r)=>{var o,n;o=[r,t,r(7322),r(3798),r(3466),r(4336),r(6877),r(2808),r(5132)],n=function(e,t,r,o,n,i,s,a,c){Object.defineProperty(t,"__esModule",{value:!0});const l=["repo","workflow","user:email","read:user"];class d{constructor(){this.path="github",this.additionalBuiltinExtensions=["GitHub.vscode-pull-request-github"]}async route({url:e,githubAuthentication:t,quality:i}){const s=d.RX.exec(e.pathname);if(void 0===s?.groups)return;let a,h,{service:g,indexed:p,idx:m,owner:f,repo:y,blob:v,commit:C,tree:w,pull:T}=s.groups,k={};const I=await async function(e,t,n,i){try{const e=new r.Octokit;return await u(e,t,n,i)}catch(e){if(!i||e instanceof o.RequestError&&404!==e.status)return{owner:t,repo:n}}const s=(await e.login(l)).accessToken;try{if(void 0!==s){const e=new r.Octokit({auth:`token ${s}`});return await u(e,t,n,i)}}catch(e){console.error(e)}return{owner:t,repo:n}}(t,f,y,w??v);if(void 0===I)return;let A,b;if(({owner:f,repo:y,ref:b,path:A}=I),w||v){if(!b&&!A){const t=new URL(e);t.pathname=`/${g}/${f}/${y}`,window.location.href=t.toString(),await new Promise((()=>{}))}if(h={v:1,ref:b},A&&v){let t,r;if(e.hash){const o=/(L(?<start>\d+)(?:-L(?<end>\d+))?)|(C(?<cell>\d+)(\:L(?<cell_line_start>\d+)(?:-L(?<cell_line_end>\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}}})}}a={force:!0,editors:[{uri:{scheme:"vscode-vfs",authority:(0,c.encodeAuthority)("github",h),path:`/${f}/${y}${A?.startsWith("/")?A:A?`/${A}`:""}`},options:{...r,selection:t},openOnlyIfExists:!0}]}}}else C?h={v:1,ref:{type:c.RepositoryRefType.Commit,id:C}}:T?h={v:1,ref:{type:c.RepositoryRefType.PullRequest,id:T}}:b?h={v:1,ref:b}:k={"workbench.startupEditor":"readme"};p&&(h||(h={v:1}),h.idx=m||"latest");const S=e.searchParams.get("editSessionId")??void 0;e.searchParams.delete("editSessionId"),window.history.replaceState(void 0,document.title,e.toString());let E={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},...k},_tarballProxyEndpoints:{"github.com":`https://${"stable"===i?"vscode.dev":"insiders.vscode.dev"}/indexes/github2/{owner}/{repo}/{sha}`},editSessionId:S,defaultLayout:a,commands:[{id:"_remotehub.getTarballProxyEndpoints",handler:()=>({"github.com":`https://${"stable"===i?"vscode.dev":"insiders.vscode.dev"}/indexes/github2/{owner}/{repo}/{sha}`})}],welcomeDialog:T?void 0:{id:"github/repo",title:"View and commit changes to your GitHub repositories",message:"Your uncommitted changes are persisted in your browser until you commit using the Source Control view. You can also access your changes across devices using [Cloud Changes](command:workbench.editSessions.actions.signIn).\n [Read our documentation to learn more about VS Code for the Web.](https://aka.ms/vscode-web-docs)",buttonText:"Open Source Control",buttonCommand:"workbench.view.scm",media:{altText:"Source Control view",path:"git.svg"}}},R={};return"codetour"===g&&(E={...E,configurationDefaults:{...E.configurationDefaults,"workbench.startupEditor":"none"},enabledExtensions:["vsls-contrib.codetour"]},R={...R,openUri:{authority:"vsls-contrib.codetour",path:"/startDefaultTour"}}),{workspace:{folderUri:n.URI.from({scheme:"vscode-vfs",authority:(0,c.encodeAuthority)("github",h),path:`/${f}/${y}`})},workbenchOptions:E,onDidCreateWorkbench:R}}}d.RX=/^\/(?<service>github|codetour)(?<indexed>\+idx=?(?<idx>latest|[0-9a-fA-F]{40})?)?\/(?<owner>[^/]+)\/(?<repo>[^/?#]+)(?:|\.git|\/tree\/(?<tree>.+)|\/blob\/(?<blob>.+)|\/commit\/(?<commit>[0-9a-f]{40})|\/pull\/(?<pull>[0-9]+))?/i;async function u(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:c.RepositoryRefType.Tree,id:n.data.ref},path:n.data.path}:{owner:t,repo:r}}(0,s.registerRouter)(new d),(0,s.registerRouter)(new class extends d{constructor(){super(...arguments),this.path="codetour",this.additionalBuiltinExtensions=["GitHub.vscode-pull-request-github","vsls-contrib.codetour"]}}),(0,c.registerRemoteHubWorkspaceResolver)("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":(0,c.isSha)(t.idx)&&(o+=`+idx=${t.idx}`)),r.pathname=`/${o}${e.path}`,t?.ref?.type){case c.RepositoryRefType.PullRequest:r.pathname+=`/pull/${t.ref.id}`;break;case c.RepositoryRefType.Tree:r.pathname+=`/tree/${t.ref.id}`;break;case c.RepositoryRefType.Commit:r.pathname+=`/commit/${t.ref.id}`}return r.toString()}}),(0,i.registerRedirect)(new a.DomainRedirect("github.com","github")),(0,i.registerRedirect)(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}})}.apply(t,o),void 0===n||(e.exports=n)},6712:(e,t,r)=>{var o,n;o=[r,t,r(2107)],n=function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.GitHubAuthentication=void 0;t.GitHubAuthentication=class{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 o=await this.getAuthSessions(),n={id:(0,r.v4)(),accessToken:e,scopes:t};o.push(n),await this.secretStorageProvider.set(this.SECRET_STORAGE_PROVIDER_KEY,JSON.stringify(o))}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}}}.apply(t,o),void 0===n||(e.exports=n)},2808:(e,t,r)=>{var o,n;o=[r,t,r(4336)],n=function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.DomainRedirect=void 0;t.DomainRedirect=class{constructor(e,t){this.service=t,this.regexp=new RegExp(`^/(?:https?://)?${e.replace(/\./g,"\\.")}/(?<rest>.*)`,"i")}redirect(e){const t=this.regexp.exec(e.pathname);if(!t?.groups)return;const r=new URL(e.toString());return r.pathname=`/${this.service}/${t.groups.rest}`,r}};(0,r.registerRedirect)(new class{redirect(e){const t=/^#(?<rest>https?:\/\/.*)/i.exec(e.hash);if(!t?.groups)return;const r=new URL(e.toString());return r.pathname=t.groups.rest,r.hash="",r}})}.apply(t,o),void 0===n||(e.exports=n)},3493:(e,t,r)=>{var o,n;o=[r,t,r(4336)],n=function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0});(0,r.registerRedirect)(new class{redirect(e){const t=e.searchParams.get("idx");if(null===t)return;const r=/\/(?<service>[^/]+)\/(?<rest>.*)/.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}})}.apply(t,o),void 0===n||(e.exports=n)},5032:(e,t,r)=>{var o,n;o=[r,t,r(3466),r(6877),r(9685),r(4336)],n=function(e,t,r,o,n,i){Object.defineProperty(t,"__esModule",{value:!0});class s{constructor(){this.path="editor/liveshare",this.additionalBuiltinExtensions=["MS-vsliveshare.vsliveshare"]}async route({url:e}){const t=s.RX.exec(e.pathname);if(!t?.groups?.sessionId)return;const o=new URLSearchParams(e.searchParams);return o.set("sessionId",t.groups.sessionId),{workspace:{workspaceUri:r.URI.from({scheme:"vsls",authority:"",path:"/Live Share.code-workspace",query:o.toString()})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},enabledExtensions:this.additionalBuiltinExtensions},onWillDisposeWorkbench:{runCommands:[{command:"liveshare.workbench.dispose",args:[]}]}}}}s.RX=/^\/editor\/liveshare\/(?<sessionId>[^/]+)/i;(0,o.registerRouter)(new s),(0,i.registerRedirect)({redirect(e){if(!/^\/liveshare\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}}),(0,n.registerWorkspaceResolver)(new class{resolveWorkspace(e){if(!(0,n.isFolderWorkspace)(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()}})}.apply(t,o),void 0===n||(e.exports=n)},7590:function(e,t,r){var o,n,i=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r),Object.defineProperty(e,o,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return s(t,e),t},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};o=[r,t,r(3466),r(6877),r(4595),r(4336)],n=function(e,t,r,o,n,i){Object.defineProperty(t,"__esModule",{value:!0}),r=a(r),n=c(n);const s="https://arcade.makecode.com";class l{constructor(){this.path="edu/makecode",this.additionalBuiltinExtensions=[{id:"ms-edu.pxt-vscode-web",preRelease:!0}]}async route({url:e}){const t=l.routeRegex.exec(e.pathname);if(!t)return;const o=[],i=t.groups?.projectId;return i&&(o.push({command:"makecodeActions.focus",args:[]}),o.push({command:"makecode.importUrl",args:[i]})),{workspace:{workspaceUri:r.URI.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:s},windowIndicator:{onDidChange:()=>({dispose:()=>{}}),label:"MakeCode Arcade",tooltip:n.default.MakeCodePrompt.toString()},additionalTrustedDomains:[s]},onDidCreateWorkbench:{runCommands:o}}}}l.routeRegex=/^\/edu\/makecode(\/(?<projectId>(S?\d{4}[\d\-]+|_[a-zA-Z0-9]{10,}))\/?)?$/i,(0,o.registerRouter)(new l),(0,i.registerRedirect)({redirect(e){if(!/^\/makecode\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/edu${e.pathname}`,t}})}.apply(t,o),void 0===n||(e.exports=n)},810:(e,t,r)=>{var o,n;o=[r,t,r(3466),r(6877),r(4336)],n=function(e,t,r,o,n){Object.defineProperty(t,"__esModule",{value:!0});class i{constructor(){this.path="editor/marketplace",this.additionalBuiltinExtensions=["ms-vscode.vscode-marketplace-extension-browser"]}async route({url:e}){const t=i.RX.exec(e.pathname);if(t?.groups)return{workspace:{folderUri:r.URI.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"}}}}}i.RX=/^\/editor\/marketplace\/(?<owner>[^/]+)\/(?<repo>[^/]+)\/(?<version>\d+\.\d+\.\d+(-.*)?)$/i,(0,o.registerRouter)(new i),(0,n.registerRedirect)({redirect(e){if(!/^\/marketplace\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}})}.apply(t,o),void 0===n||(e.exports=n)},5855:(e,t,r)=>{var o,n;o=[r,t,r(6877),r(3466),r(4336)],n=function(e,t,r,o,n){Object.defineProperty(t,"__esModule",{value:!0});class i{constructor(){this.path="power",this.additionalBuiltinExtensions=["microsoft-IsvExpTools.powerplatform-vscode"]}async route({url:e}){const t=i.RX1.exec(e.pathname),r=i.RX2.exec(e.pathname);if(void 0===t?.groups&&void 0===r?.groups)return;const n=t?.groups?.appName??r?.groups?.appName,s=t?.groups?.entity,a=t?.groups?.entityId;let c=e.search,l="";l=!n||"portal"!==n&&"pages"!==n?"PowerPlatform":"PowerPages";const d=new URLSearchParams(c),u=d.get("enableMultifile"),h=d.get("websiteId")?.replace(/\//g,""),g="true"===u?.toLowerCase()&&h;return{workspace:{workspaceUri:o.URI.from({scheme:"powerplatform-vfs",authority:"",path:!g&&s&&a?`/${s}/${a}/${l}`:`/${h}/${l}`})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none","files.autoSave":"off"},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{runCommands:[{command:"microsoft-powerapps-portals.webExtension.init",args:s&&a?[{appName:n,entity:s,entityId:a,searchParams:c}]:[{appName:n,searchParams:c}]}]}}}}i.RX1=/^\/(?<path>power)\/(?<appName>[^/]+)\/?(?<entity>[^/]+)?\/?(?<entityId>[^/?]+)?([?])?(?<queryString>[^#]+)?/i,i.RX2=/^\/(?<path>power)\/(?<appName>[^/]+)(?:\/(?<queryString>[^#]+))?/i,(0,r.registerRouter)(new i),(0,n.registerRedirect)({redirect(e){if(!/^\/powerplatform\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=t.pathname.replace(/^\/powerplatform/,"/power"),t}})}.apply(t,o),void 0===n||(e.exports=n)},8516:(e,t,r)=>{var o,n;o=[r,t,r(2107),r(3466),r(6877),r(4336)],n=function(e,t,r,o,n,i){Object.defineProperty(t,"__esModule",{value:!0});class s{constructor(){this.path="editor/profile",this.additionalBuiltinExtensions=[]}async route({url:e,quality:t}){const n=s.RX.exec(e.pathname),i=n?.groups?.path;if(!i)return;let a="code-oss";switch(t){case"stable":a="vscode";break;case"insider":a="vscode-insiders"}return{workspace:{workspaceUri:o.URI.from({scheme:"tmp",path:`/${(0,r.v4)()}`})},workbenchOptions:{profileToPreview:o.URI.from({scheme:a,authority:"profile",path:`/${i}`})}}}}s.RX=/^\/editor\/profile\/(?<path>.+)$/i,(0,n.registerRouter)(new s),(0,i.registerRedirect)({redirect(e){if(!/^\/profile\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}})}.apply(t,o),void 0===n||(e.exports=n)},5132:(e,t,r)=>{var o,n;o=[r,t,r(9685),r(1080)],n=function(e,t,r,o){Object.defineProperty(t,"__esModule",{value:!0}),t.registerRemoteHubWorkspaceResolver=t.encodeAuthority=t.isSha=t.RepositoryRefType=void 0,function(e){e[e.Branch=0]="Branch",e[e.Tag=1]="Tag",e[e.Commit=2]="Commit",e[e.PullRequest=3]="PullRequest",e[e.Tree=4]="Tree"}(t.RepositoryRefType||(t.RepositoryRefType={}));const n=/^[0-9a-f]{40}$/i;t.isSha=function(e){return void 0!==e&&n.test(e)};function i(e){const[t,r]=e.split("+");let o;if(r)try{o=JSON.parse(function(e){const t=e.match(/(\w{2})/g);if(null===t)return"";const r=new Uint8Array(t.map((e=>parseInt(e,16))));return c.decode(r)}(r))}catch{}return{scheme:t,metadata:o}}t.encodeAuthority=function(e,t){return`${e}${t?`+${function(e){const t=a.encode(e),r=new Array(t.length);for(let e=0;e<t.length;++e)r[e]=s[t[e]];return r.join("")}(JSON.stringify(t))}`:""}`};const s=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],a=new TextEncoder;const c=new TextDecoder;const l=new o.MapRegistry;t.registerRemoteHubWorkspaceResolver=function(e,t){return l.register(e,t)};(0,r.registerWorkspaceResolver)(new class{resolveWorkspace(e){if(!(0,r.isFolderWorkspace)(e))return;const t=e.folderUri;if("vscode-vfs"!==t.scheme)return;const{scheme:o,metadata:n}=i(t.authority),s=l.get(o);if(!s)throw new Error(`RemoteHub authority not supported: ${t.authority}`);return s.resolveRemoteHubWorkspace(t,n)}})}.apply(t,o),void 0===n||(e.exports=n)},8788:(e,t,r)=>{var o,n;o=[r,t,r(3466),r(6877),r(4336)],n=function(e,t,r,o,n){Object.defineProperty(t,"__esModule",{value:!0});class i{constructor(){this.path="editor/theme",this.additionalBuiltinExtensions=["ms-vscode.theme-tester"]}async route({url:e}){if(i.RX.exec(e.pathname))return{workspace:{folderUri:r.URI.from({scheme:"vscode-theme-tester",authority:"",path:"/"})},workbenchOptions:{configurationDefaults:{"workbench.startupEditor":"none"},enabledExtensions:this.additionalBuiltinExtensions},onDidCreateWorkbench:{openUri:{authority:this.additionalBuiltinExtensions[0],path:"/open"}}}}}i.RX=/^\/editor\/theme\//i,(0,o.registerRouter)(new i),(0,n.registerRedirect)({redirect(e){if(!/^\/theme\//i.test(e.pathname))return;const t=new URL(e.toString());return t.pathname=`/editor${e.pathname}`,t}})}.apply(t,o),void 0===n||(e.exports=n)},5967:function(e,t,r){var o,n,i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};o=[r,t,r(6877),r(4595)],n=function(e,t,r,o){Object.defineProperty(t,"__esModule",{value:!0}),o=i(o);(0,r.registerRouter)(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:r.EmptyWorkspace,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:o.default.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:o.default.TermsofUse.toString()}]}}}})}.apply(t,o),void 0===n||(e.exports=n)},6613:(e,t,r)=>{var o,n;o=[r,t,r(2107),r(3466),r(6877),r(1895),r(7322),r(5132)],n=function(e,t,r,o,n,i,s,a){Object.defineProperty(t,"__esModule",{value:!0});const c={homepageBase:"https://vscodeedu.com",signInUrl:"https://vscodeedu.com/signin",apiBase:"https://vscodeedu.com"},l={homepageBase:"https://vscodeedu.com/beta",signInUrl:"https://vscodeedu.com/beta/signin",apiBase:"https://vscodeedu.com"},d={homepageBase:"https://ppe.vscodeedu.com",signInUrl:"https://ppe.vscodeedu.com/signin",apiBase:"https://ppe.vscodeedu.com"};function u(e){return"ppe"===e?d:"beta"===e?l:c}const h="requestId",g="otac",p="redirectUri",m="codeChallenge",f="codeVerifier",y="VSCE_SESSIONTOKEN";const v=e=>e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");function C(e){return`treehouse.auth.state.${e}`}function w(){return JSON.stringify({extensionId:"ms-edu.vscode-learning",key:y})}(0,n.registerRouter)(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:n}){if(!/^\/edu\/?$/i.test(e.pathname))return;const l=e.searchParams.get("env")?.match(/^(ppe|prod|beta)$/i)?.[0]?.toLowerCase()??"prod",y="ppe"===l,T=y?d.apiBase:c.apiBase;!!e.searchParams.get("sign-out")?.match(/^(true|1)$/i)?.[0]&&await t.delete(w()),await this.redirectToHomePageIfNecessary(e,u(l).homepageBase);if(!e.searchParams.get("auth")?.match(/^(false|0)$/i)?.[0]){const r=e.searchParams.get(h),o=e.searchParams.get(g),n=e.searchParams.get("region"),i=u(l).signInUrl;r&&o?await async function(e,t,r,o,n){try{if(await e.get(w()))return;const i=C(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(g,r),a.searchParams.set(f,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(w(),l)}catch(e){console.error("Error completing VSCode Edu sign-in flow"),console.error(e)}}(t,r,o,n,T):await async function(e,t,r){try{const o=w();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=v(btoa(String.fromCharCode(...new Uint8Array(t))));return{codeVerifier:e,codeChallenge:r}}(),r=crypto.randomUUID(),o=new URL(t);o.searchParams.set(p,window.location.href),o.searchParams.set(h,r),o.searchParams.set(m,e.codeChallenge),sessionStorage.setItem(C(r),e.codeVerifier),window.location.href=o.toString()}}catch(e){console.error("Error starting VSCode Edu sign-in flow"),console.error(e)}}(t,i,e.hash)}const k=await this.getConfig(T),I=e.searchParams.get("extension")?.match(/^([0-9a-z]{7})$/i)?.[0]?.toLowerCase()??k[`${l}.extension`],A=o.URI.parse(`${T}/extension/${I}/extension`),b=e.searchParams.get("profile")??"default-dark",S=b.includes("/")?b:`${k[`${l}.profile`]??""}/${b}`,E=o.URI.parse(`${T}/profile/${S}.code-profile`),R=await this.getProfileName(E,b);let _,P=e.searchParams.get("workspace-scheme")??"vscode-edu-workspace",M=e.searchParams.get("workspace-path")??"/";const O=e.searchParams.get("courseId"),N=e.searchParams.get("curriculumId"),q={};e.searchParams.forEach(((e,t)=>{q[t]=e}));const U=e.hash.slice(1),x=[{command:"vscode-learning.handleRouteOptions",args:[q,U]}];if((O||N)&&x.push({command:"workbench.view.extension.learningView",args:[]}),N&&!O){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 s.Octokit({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:a.RepositoryRefType.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}(n,t),P="vscode-vfs",_="github",M=`/${t}`}return{workspace:P?{folderUri:o.URI.from({scheme:P,authority:_,path:M})}:{workspaceUri:o.URI.from({scheme:"tmp",path:`/${(0,r.v4)()}`})},workbenchOptions:{enableWorkspaceTrust:!1,additionalBuiltinExtensions:[A],additionalTrustedDomains:[T],enabledExtensions:["ms-edu.vscode-learning",...this.additionalBuiltinExtensions.map((e=>e.id))],configurationDefaults:{"workbench.startupEditor":"none","vscode-learning.usePPEHost":y,"vscode-learning.env":l},windowIndicator:{onDidChange:i.NullEvent,label:"Education",tooltip:"Learn to code"},profile:{name:R,contents:E},commands:this.createCommands()},onDidCreateWorkbench:{runCommands:x},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!==d.homepageBase&&t.origin!==c.homepageBase)throw new Error(`URL must be of origin ${d.homepageBase} or ${c.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():{}}})}.apply(t,o),void 0===n||(e.exports=n)},9645:function(e,t,r){var o,n,i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};o=[r,t,r(3466),r(6877),r(4595)],n=function(e,t,r,o,n){Object.defineProperty(t,"__esModule",{value:!0}),n=i(n);(0,o.registerRouter)(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:r.URI.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:n.default.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:n.default.TermsofUse.toString()}]}}}})}.apply(t,o),void 0===n||(e.exports=n)},4222:(e,t,r)=>{var o,n;o=[r,t,r(8235)],n=function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.AESGCMCrypto=void 0;class o{constructor(e){this.authEndpoint=function(e){return"vscode.dev"===e||"insiders.vscode.dev"===e?`https://auth.${e}`:"/_auth"}(e)}async encrypt(e){const t=window.crypto.getRandomValues(new Uint8Array(o.IV_LENGTH)),n=await window.crypto.subtle.generateKey({name:o.ALGORITHM,length:o.KEY_LENGTH},!0,["encrypt","decrypt"]),i=new Uint8Array(await window.crypto.subtle.exportKey("raw",n)),s=await this.getKey(i),a=r.Base64.encode(e),c=r.Base64.toUint8Array(a),l=await window.crypto.subtle.encrypt({name:o.ALGORITHM,iv:t},s,c),d=new Uint8Array(function*(...e){for(const t of e)for(const e of t)yield e}(i,t,new Uint8Array(l)));return r.Base64.fromUint8Array(d)}async decrypt(e){const t=r.Base64.toUint8Array(e);if(t.byteLength<60)throw Error("Invalid length for the value for credentials.crypto");const n=o.KEY_LENGTH/8,i=t.slice(0,n),s=t.slice(n,n+o.IV_LENGTH),a=t.slice(n+o.IV_LENGTH),c=await this.getKey(i),l=await window.crypto.subtle.decrypt({name:o.ALGORITHM,iv:s},c,a),d=r.Base64.fromUint8Array(new Uint8Array(l));return r.Base64.decode(d)}async getKey(e){if(!e||e.byteLength!=o.KEY_LENGTH/8)throw Error("Invalid length for clientKey");const t=await this.getServerKeyPart(),r=new Uint8Array(o.KEY_LENGTH/8);for(let o=0;o<r.byteLength;o++)r[o]=e[o]^t[o];return window.crypto.subtle.importKey("raw",r,{name:o.ALGORITHM,length:o.KEY_LENGTH},!0,["encrypt","decrypt"])}async getServerKeyPart(){if(this._serverKey)return this._serverKey;let e,t=0;for(;t<=3;)try{const e=await fetch(this.authEndpoint,{credentials:"include",method:"POST"});if(!e.ok)throw new Error(e.statusText);const t=await e.text(),n=r.Base64.toUint8Array(t);if(n.byteLength!=o.KEY_LENGTH/8)throw Error(`The key retrieved by the server is not ${o.KEY_LENGTH} bit long.`);return this._serverKey=n,this._serverKey}catch(r){e=r,t++,await new Promise((e=>setTimeout(e,t*t*100)))}throw e}}t.AESGCMCrypto=o,o.ALGORITHM="AES-GCM",o.KEY_LENGTH=256,o.IV_LENGTH=12}.apply(t,o),void 0===n||(e.exports=n)},4336:(e,t,r)=>{var o,n;o=[r,t,r(1080)],n=function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.registerRedirect=void 0;const o=new r.SetRegistry;t.registerRedirect=function(e){return o.register(e)},t.default=function(e){for(const t of o)e=t.redirect(e)??e;return e}}.apply(t,o),void 0===n||(e.exports=n)},6877:(e,t,r)=>{var o,n;o=[r,t,r(1080),r(9739)],n=function(e,t,r,o){Object.defineProperty(t,"__esModule",{value:!0}),t.registerRouter=t.EmptyWorkspace=void 0,t.EmptyWorkspace=Symbol("EmptyWorkspace");const n=new r.SetRegistry;t.registerRouter=function(e){return n.register(e)},t.default=async function(e){for(const t of n)if((0,o.matchRoute)(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}}}.apply(t,o),void 0===n||(e.exports=n)},9685:(e,t,r)=>{var o,n;o=[r,t,r(3466),r(1080)],n=function(e,t,r,o){Object.defineProperty(t,"__esModule",{value:!0}),t.getWorkspaceUri=t.isFileWorkspace=t.isFolderWorkspace=t.registerWorkspaceResolver=void 0;const n=new o.SetRegistry;function i(e){return!!e&&e.workspaceUri instanceof r.URI}t.registerWorkspaceResolver=function(e){return n.register(e)},t.isFolderWorkspace=function(e){return!!e&&e.folderUri instanceof r.URI},t.isFileWorkspace=i;t.getWorkspaceUri=e=>i(e)?e.workspaceUri:e.folderUri,t.default=function(e){for(const t of n){const r=t.resolveWorkspace(e);if(r)return r}}}.apply(t,o),void 0===n||(e.exports=n)},8571:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.showFatalError=void 0,t.showFatalError=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)}}.apply(t,[r,t]),void 0===o||(e.exports=o)},4595:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=["cs","de","en","es","fr","it","ja","ko","pl","pt","ru","tr","zh-Hans","zh-Hant"];const o=/{(\d+)}/g;class n{constructor(e){this.strings=e}toString(...e){const t=function(e,t){for(;;){const o=r.indexOf(e);if(o>-1)return t[o];let n=e.replace(/-[^-]*$/,"");n===e&&(n="en"),e=n}}(window.navigator.language,this.strings);return 0===e.length?t:function(e,...t){return 0===t.length?e:e.replace(o,(function(e,r){const o=parseInt(r,10);return isNaN(o)||o<0||o>=t.length?e:t[o]}))}(t,...e)}}t.default={Anywhere:new n(["Visual Studio Code (Preview). Kdekoli, kdykoli a výhradně v prohlížeči.","Visual Studio Code (Vorschau). Überall, jederzeit, vollständig in Ihrem Browser.","Visual Studio Code (Preview). Anywhere, anytime, entirely in your browser.","Visual Studio Code (Versión preliminar). En cualquier lugar, en cualquier momento y plenamente en el explorador.","Visual Studio Code (préversion). N’importe où, à tout moment, entièrement dans votre navigateur.","Visual Studio Code (anteprima). Ovunque, in qualsiasi momento, interamente nel browser.","Visual Studio Code (プレビュー)。いつでもどこでも、すべてをブラウザーで。","Visual Studio Code(미리 보기). 언제 어디서나 브라우저에서 사용할 수 있습니다.","Visual Studio Code (wersja zapoznawcza). W dowolnym miejscu i czasie, wyłącznie w przeglądarce.","Visual Studio Code (Pré-visualização). Em qualquer lugar, a qualquer momento, totalmente em seu navegador.","Visual Studio Code (предварительная версия). В любом месте, в любое время, полностью в вашем браузере.","Visual Studio Code (Önizleme). Her yerde, her zaman, tamamen tarayıcınızda.","Visual Studio Code(预览版)。随时随地,尽在浏览器中。","Visual Studio Code (預覽)。隨時隨地,完全在瀏覽器中。"]),LearnMore:new n(["Další informace","Weitere Informationen","Learn More","Más información","En savoir plus","Altre informazioni","詳細情報","더 알아보기","Dowiedz się więcej","Saiba Mais","Дополнительные сведения","Daha Fazla Bilgi","了解详细信息","深入了解"]),ReadDoc:new n(["Přečtěte si dokumentaci","Lesen Sie die Dokumentation","Read the Documentation","Leer la documentación","Lire la documentation","Leggere la documentazione","ドキュメントを読む","문서 읽기","Przeczytaj dokumentację","Leia a documentação","Прочитать документацию","Belgeleri okuyun","阅读文档","閱讀文檔"]),Privacy:new n(["Ochrana osobních údajů a soubory cookie","Datenschutz und Cookies","Privacy & Cookies","Privacidad y cookies","Confidentialité et cookies","Privacy e cookie","プライバシーと Cookie","개인정보처리방침 및 위치정보이용약관","Prywatność i pliki cookie","Privacidade e Cookies","Конфиденциальность и файлы cookie","Gizlilik ve Tanımlama Bilgileri","隐私和 Cookie","隱私權與 Cookie"]),TermsofUse:new n(["Podmínky použití","Nutzungsbedingungen","Terms of Use","Términos de uso","Conditions d'utilisation","Condizioni per l'utilizzo","利用規約","사용 약관","Warunki użytkowania","Termos de Uso","Условия использования","Kullanım Koşulları","使用条款","使用規定"]),DownloadVSCode:new n(["Stáhnout VS Code","VS Code herunterladen","Download VS Code","Descargar VS Code","Télécharger VS Code","Scaricare Visual Studio Code","VS Code をダウンロードする","VS Code 다운로드","Pobierz program VS Code","Baixar o Visual Studio Code","Загрузить VS Code","VS Code’u indirin","下载 VS 代码","下載 VS 代碼"]),MakeCodePrompt:new n(["Použijte MakeCode k vytvoření vlastních arkádových her.","Verwenden Sie MakeCode, um eigene Arcade-Spiele zu erstellen.","Use MakeCode to create arcade games of your own.","Utilice MakeCode para crear sus propios juegos de arcade.","Utilisez MakeCode pour créer vos propres jeux d’arcade.","Usa MakeCode per creare giochi arcade personalizzati.","MakeCode を使用して、独自のアーケード ゲームを作成します。","MakeCode를 사용하여 자신만의 아케이드 게임을 만들 수 있습니다.","Użyj MakeCode, aby tworzyć własne gry zręcznościowe.","Use o MakeCode para criar seus próprios jogos de arcade.","Используйте MakeCode для создания собственных аркадных игр.","Kendi arcade oyunlarınızı oluşturmak için MakeCode'u kullanın.","使用MakeCode创建自己的街机游戏。","使用MakeCode創建自己的街機遊戲。"]),auth:{SessionExpiringSoon:new n(["Sessie pro {0} brzy vyprší. Chcete obnovit svou relaci? (otevře se vyskakovací okno)","Die Sitzung für {0} läuft in Kürze ab. Möchten Sie Ihre Sitzung aktualisieren? (Ein Popup wird geöffnet)","The session for {0} is expiring soon. Would you like to refresh your session? (a popup will be launched)","La sesión de {0} está a punto de caducar. ¿Desea actualizar su sesión? (se abrirá una ventana emergente)","La session pour {0} expire bientôt. Souhaitez-vous actualiser votre session ? (une fenêtre contextuelle sera ouverte)","La sessione per {0} sta per scadere. Vuoi aggiornare la sessione? (verrà aperto un popup)","{0} のセッションがまもなく期限切れになります。セッションを更新しますか? (ポップアップが開きます)","{0} 세션이 곧 만료됩니다. 세션을 새로 고치시겠습니까? (팝업이 열립니다)","Sesja dla {0} wygasa wkrótce. Czy chcesz odświeżyć swoją sesję? (otworzy się okno)","A sessão para {0} está prestes a expirar. Deseja atualizar sua sessão? (uma janela pop-up será aberta)","Сессия для {0} скоро истечет. Хотите обновить сессию? (будет открыто всплывающее окно)","{0} oturumu yakında sona erecek. Oturumu yenilemek ister misiniz? (bir açılır pencere açılacak)","{0} 的会话即将过期。是否要刷新会话?(将弹出一个弹出窗口)","{0} 的會話即將到期。是否要重新整理您的會話?(將開啟彈出視窗)"]),Refresh:new n(["Obnovit","Aktualisieren","Refresh","Refrescar","Actualiser","Aggiorna","更新","새로 고침","Odśwież","Atualizar","Обновить","Yenile","刷新","重新整理"]),MoreInfo:new n(["Více informací","Weitere Informationen","More Info","Más información","Plus d’informations","Ulteriori informazioni","詳細情報","더 알아보기","Więcej informacji","Mais informações","Дополнительные сведения","Daha Fazla Bilgi","更多信息","更多資訊"])}}}.apply(t,[r,t]),void 0===o||(e.exports=o)},586:(e,t,r)=>{var o,n;o=[r,t,r(3466)],n=function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.getLoopbackRemoteResourceProvider=t.registerLoopbackResponder=void 0;let o=!1;const n=[];t.registerLoopbackResponder=e=>{n.push(e),o||(console.warn("registerLoopbackResponder will soon stop working. VS Code proposed.resolvers.d.ts now work in the web, please use those instead."),o=!0,navigator.serviceWorker.addEventListener("message",(async e=>{if(e.origin!==window.location.origin||"loopback"!==e.data.type||!e.source)return;const t={uri:r.URI.parse(e.data.uri),headers:e.data.headers,method:e.data.method},o=t=>e.source.postMessage({type:"loopback",id:e.data.id,status:t.status,body:t.body,headers:t.headers},{targetOrigin:e.origin,transfer:[t.body]});try{for(const e of n){const r=await e(t);if(r)return o(r)}o({status:404,body:(new TextEncoder).encode("Not found")})}catch(e){o({status:504,body:(new TextEncoder).encode(String(e))})}})))};t.getLoopbackRemoteResourceProvider=()=>{if(o)return;let e;return navigator.serviceWorker.addEventListener("message",(async t=>{t.origin===window.location.origin&&"loopback"===t.data.type&&t.source&&e?.({uri:r.URI.parse(t.data.uri),respondWith(e,r,o){const n=r.byteLength===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);t.source.postMessage({type:"loopback",id:t.data.id,status:e,body:n,headers:o},{targetOrigin:t.origin,transfer:[n]})}})})),{path:"/loopback",onDidReceiveRequest:t=>(e=t,{dispose:()=>{e=void 0}})}}}.apply(t,o),void 0===n||(e.exports=n)},6268:function(e,t,r){var o,n,i=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r),Object.defineProperty(e,o,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&i(t,e,r);return s(t,e),t},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};o=[r,t,r(3466),r(2567),r(4222),r(560),r(4336),r(6877),r(9685),r(4595),r(586),r(6712),r(9573),r(896),r(8571),r(1422),r(7467),r(7117),r(4174),r(2808),r(3493),r(5032),r(7590),r(810),r(5132),r(8788),r(8516),r(9645),r(5855),r(6613),r(438),r(5967)],n=function(e,t,r,o,n,i,s,l,d,u,h,g,p,m,f,y){Object.defineProperty(t,"__esModule",{value:!0}),t.main=void 0,r=a(r),s=c(s),l=a(l),d=a(d),u=c(u);class v{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===v.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=(0,d.default)(e);if(!r&&(void 0===e||(0,d.getWorkspaceUri)(e).toString()===w.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(v.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")}}v.QUERY_PARAM_PAYLOAD="payload";const C=["https://github.com/login/oauth/authorize","https://app.vssps.visualstudio.com/oauth2/authorize","https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize","https://login.microsoftonline.com/common/oauth2/v2.0/authorize","https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize","https://vscodeedu.com/signin","https://vscodeedu.com/beta/signin","https://ppe.vscodeedu.com/signin"],w={workspaceUri:r.URI.from({scheme:"tmp",path:"/default.code-workspace"})},T=[{href:"https://aka.ms/vscode-web-docs",label:u.default.ReadDoc.toString()},{href:"https://go.microsoft.com/fwlink/?LinkId=521839",label:u.default.Privacy.toString()},{href:"https://www.microsoft.com/en-us/legal/terms-of-use",label:u.default.TermsofUse.toString()},{href:"https://code.visualstudio.com/download",label:u.default.DownloadVSCode.toString()}];function k(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 I(e){switch(e.searchParams.get("vscode-log")?.toLowerCase()){case"trace":return r.LogLevel.Trace;case"debug":return r.LogLevel.Debug;case"warning":return r.LogLevel.Warning;case"error":return r.LogLevel.Error;case"critical":return r.LogLevel.Critical;case"off":return r.LogLevel.Off;default:return r.LogLevel.Info}}async function A(e,t,a){let c=new URL(window.location.href);c=(0,s.default)(c),window.history.replaceState(void 0,"",c.toString());const m=new n.AESGCMCrypto(c.host),f=new o.LocalStorageSecretStorageProvider(m,e);let y;const A=window.sessionStorage.getItem(`vscode-continueOn-${c.pathname}`);if(A)try{y=JSON.parse(A)}catch(e){console.error("Failed to parse continueOn body",e)}const S=new g.GitHubAuthentication(f,c),E=new p.MsalAuthentication(c),R=await(0,l.default)({url:c,githubAuthentication:S,microsoftAuthentication:E,secretStorageProvider:f,quality:e,commit:t,continueOnBody:y});R||(c=new URL(window.location.href),c.pathname="/",window.history.replaceState(void 0,"",c.toString()));const _=function(e,t){const o=[],n=JSON.parse(document.querySelector('meta[name="vscode:additionalBuiltinExtensions"]').content),i=e.searchParams.get("vscode-remotehub-dev");i&&(delete n["github.remotehub"],o.push(r.URI.parse(i)));const s=e.searchParams.get("vscode-azurerepos-dev");s&&(delete n["ms-vscode.azure-repos"],o.push(r.URI.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)||o.push("string"==typeof t?r.URI.parse(t):{id:e,preRelease:t});const c=t?.workbenchOptions?.additionalBuiltinExtensions??[];for(const e of c){const t=b(e)?e:"string"==typeof e?{id:e}:void 0;t&&n[t.id.toLowerCase()]||o.push(e)}return o}(c,R),P=R?.workbenchOptions?.enabledExtensions??[];let M=P;R?.excludeAdditionalBuiltinExtensions||(M=[...P,"GitHub.remotehub","ms-vscode.azure-repos"]);const O=R?.workspace??w,N=new v(O===l.EmptyWorkspace?void 0:O),q=[{id:"vscode.dev:help",label:"Help: Visual Studio Code for the Web",handler:()=>r.commands.executeCommand("vscode.open",r.URI.parse("https://aka.ms/vscode-web-docs"))}];R?.hasOwnProperty("workspace")&&q.push({id:"vscode.dev:close",label:"Close Remote Workspace",menu:[r.Menu?.CommandPalette,r.Menu?.StatusBarWindowIndicatorMenu],handler:()=>N.open(w,{reuse:!0})});const U=["/+","/tunnel/"];q.push({id:"vscode.dev:openPath",handler:(e,t)=>{U.some((t=>e.startsWith(t)))&&(t?.newTab?window.open(e,"_blank"):window.location.pathname=e)}});const x=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://az764295.vo.msecnd.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),L={...R?.workbenchOptions??{},configurationDefaults:{"workbench.colorTheme":"Default Dark Modern",...R?.workbenchOptions?.configurationDefaults??{}},additionalBuiltinExtensions:_,enabledExtensions:M,urlCallbackProvider:new i.LocalStorageURLCallbackProvider(m),secretStorageProvider:f,remoteResourceProvider:R?.workbenchOptions?.remoteResourceProvider??(R?.workbenchOptions?.remoteAuthority?(0,h.getLoopbackRemoteResourceProvider)():void 0),productConfiguration:{...x,...R?.workbenchOptions?.productConfiguration??{},extensionEnabledApiProposals:{...x?.extensionEnabledApiProposals??{},...R?.workbenchOptions?.productConfiguration?.extensionEnabledApiProposals??{}},npsSurveyUrl:void 0,cesSurveyUrl:void 0,surveys:void 0},enableWorkspaceTrust:R?.workbenchOptions?.enableWorkspaceTrust??!0,initialColorTheme:{themeType:"dark"},welcomeBanner:R?.disableWelcomeBanner?void 0:R?.welcomeBanner??{message:u.default.Anywhere.toString(),actions:T},codeExchangeProxyEndpoints:{microsoft:`${window.location.protocol}//${window.location.host}/codeExchangeProxyEndpoints/microsoft/`,github:`${window.location.protocol}//${window.location.host}/codeExchangeProxyEndpoints/github/`},authenticationProviders:[E.authenticationProvider],resolveExternalUri:async e=>{const t=(0,d.default)({folderUri:e});if(!t)throw new Error(`Scheme not supported: ${e.scheme}`);return r.URI.parse(t)},commands:R?.workbenchOptions?.commands?.concat(q)??q,workspaceProvider:N,productQualityChangeHandler:k(c,a),developmentOptions:{logLevel:I(c)},openerAllowedExternalUrlPrefixes:C,resolveCommonTelemetryProperties:()=>({"common.isPWAInstalled":String(navigator.standalone||window.matchMedia("(display-mode: standalone)").matches)})};if(r.create(document.body,L),R?.onDidCreateWorkbench?.openUri){const e=R.onDidCreateWorkbench.openUri;r.env.openUri(r.URI.from({scheme:await r.env.getUriScheme(),query:window.location.href,...e}))}if(R?.onDidCreateWorkbench?.runCommands)for(const e of R.onDidCreateWorkbench.runCommands)r.commands.executeCommand(e.command,...e.args);if(R?.onWillDisposeWorkbench?.runCommands){const e=R.onWillDisposeWorkbench.runCommands;window.addEventListener("beforeunload",(()=>{for(const t of e)r.commands.executeCommand(t.command,...t.args)}))}}function b(e){const t=e;return"string"==typeof t?.id&&(void 0===t.preRelease||"boolean"==typeof t.preRelease)}/^de($|-)/i.test(window.navigator.language)&&T.push({href:"https://news.microsoft.com/de-ch/impressum/",label:"Impressum"}),/^it($|-)/i.test(window.navigator.language)&&T.push({href:"https://go.microsoft.com/fwlink/?linkid=2121429",label:"Accessibilità"}),t.main=A,async function(){const{quality:e,commit:t,baseUrl:r,trustedTypesPolicy:o}=globalThis._VSCODE_WEB_BOOTSTRAP_;if((0,y.setupQualityHeadLinks)(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 A(e,t,m.DefaultQuality)}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(f.showFatalError).finally((()=>performance.mark("web/didBootstrap")))}.apply(t,o),void 0===n||(e.exports=n)},1052:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.withProgress=void 0;let r=!1;t.withProgress=async function(e,t){if(!r){r=!0;const e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href="/static/progress.css",document.head.append(e)}const o=document.createElement("div");o.classList.add("vscode-dev-progress");const n=document.createElement("h2");let i;n.textContent=e.title,o.appendChild(n),document.body.appendChild(o);try{return await t({report:e=>{e.message&&(i||(i=document.createElement("p"),o.appendChild(i)),i.textContent=e.message)}})}finally{o.remove()}}}.apply(t,[r,t]),void 0===o||(e.exports=o)},1422:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.setupQualityHeadLinks=void 0,t.setupQualityHeadLinks=function(e){e="insider"===e?"insider":"stable";const t=document.createElement("link");t.rel="icon",t.href=`/static/${e}/favicon.ico`,t.type="image/x-icon",document.head.append(t);const r=document.createElement("link");r.rel="apple-touch-icon",r.href=`/static/${e}/code-192-apple.png`,document.head.append(r);const o=document.createElement("link");o.rel="manifest",o.href=`/static/${e}/code.webmanifest`,o.crossOrigin="use-credentials",document.head.append(o)}}.apply(t,[r,t]),void 0===o||(e.exports=o)},1080:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MapRegistry=t.SetRegistry=void 0;class r{constructor(){this.set=new Set}register(e){return this.set.add(e),{dispose:()=>this.set.delete(e)}}[Symbol.iterator](){return this.set.values()}}t.SetRegistry=r;class o{constructor(){this.map=new Map}register(e,t){return this.map.set(e,t),{dispose:()=>this.map.delete(e)}}get(e){return this.map.get(e)}[Symbol.iterator](){return this.map.values()}}t.MapRegistry=o}.apply(t,[r,t]),void 0===o||(e.exports=o)},2567:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.LocalStorageSecretStorageProvider=void 0;t.LocalStorageSecretStorageProvider=class{constructor(e,t){this.crypto=e,this.quality=t,this._storageKey=`${this.quality}.secrets.provider`,this._secretsPromise=this.load(),this.type="persisted"}async load(){const e=window.localStorage.getItem(this._storageKey);if(e)try{return JSON.parse(await this.crypto.decrypt(e))}catch(e){console.error("Failed to decrypt secrets from localStorage",e),window.localStorage.removeItem(this._storageKey)}return{}}async get(e){return(await this._secretsPromise)[e]}async set(e,t){const r=await this._secretsPromise;r[e]=t,this._secretsPromise=Promise.resolve(r),this.save()}async delete(e){const t=await this._secretsPromise;delete t[e],this._secretsPromise=Promise.resolve(t),this.save()}async save(){try{const e=await this.crypto.encrypt(JSON.stringify(await this._secretsPromise));window.localStorage.setItem(this._storageKey,e)}catch(e){console.error(e)}}}}.apply(t,[r,t]),void 0===o||(e.exports=o)},560:(e,t,r)=>{var o,n;o=[r,t,r(3466)],n=function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.LocalStorageURLCallbackProvider=void 0;class o{constructor(e){this.crypto=e,this._onCallback=new r.Emitter,this.onCallback=this._onCallback.event,this.pendingCallbacks=new Set,this.lastTimeChecked=Date.now(),this.checkCallbacksTimeout=void 0}create(e={}){const t=++o.REQUEST_ID,n=[`vscode-reqid=${t}`];for(const t of o.KEYS){const r=e[t];r&&n.push(`vscode-${t}=${encodeURIComponent(r)}`)}if("vscode.github-authentication"!==e.authority||"/dummy"!==e.path){const e=`vscode-dev.url-callbacks[${t}]`;window.localStorage.removeItem(e),this.pendingCallbacks.add(t),this.startListening()}return r.URI.parse(window.location.href).with({path:"/callback",query:n.join("&")})}startListening(){if(this.onDidChangeLocalStorageDisposable)return;const e=()=>this.onDidChangeLocalStorage();window.addEventListener("storage",e),this.onDidChangeLocalStorageDisposable={dispose:()=>window.removeEventListener("storage",e)}}stopListening(){this.onDidChangeLocalStorageDisposable?.dispose(),this.onDidChangeLocalStorageDisposable=void 0}async onDidChangeLocalStorage(){const e=Date.now()-this.lastTimeChecked;e>1e3?this.checkCallbacks():void 0===this.checkCallbacksTimeout&&(this.checkCallbacksTimeout=setTimeout((()=>{this.checkCallbacksTimeout=void 0,this.checkCallbacks()}),1e3-e))}async checkCallbacks(){let e;for(const t of this.pendingCallbacks){const o=`vscode-dev.url-callbacks[${t}]`,n=window.localStorage.getItem(o);if(null!==n){try{this._onCallback.fire(r.URI.revive(JSON.parse(await this.crypto.decrypt(n))))}catch(e){console.error(e)}e=e??new Set(this.pendingCallbacks),e.delete(t),window.localStorage.removeItem(o)}}e&&(this.pendingCallbacks=e,0===this.pendingCallbacks.size&&this.stopListening()),this.lastTimeChecked=Date.now()}}t.LocalStorageURLCallbackProvider=o,o.REQUEST_ID=0,o.KEYS=["scheme","query","authority","path","fragment"]}.apply(t,o),void 0===n||(e.exports=n)},1895:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.createMicrosoftAuthBroadcastChannel=t.NullEvent=t.NullDisposable=t.combinedDisposable=void 0,t.combinedDisposable=function(...e){return{dispose(){for(const t of e)t.dispose()}}},t.NullDisposable={dispose(){}};t.NullEvent=()=>t.NullDisposable,t.createMicrosoftAuthBroadcastChannel=function(e,t,r){return new BroadcastChannel(`microsoftAuthPopup#${JSON.stringify({clientId:e,authority:t,scopes:r})}`)}}.apply(t,[r,t]),void 0===o||(e.exports=o)},896:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.getQuality=t.DefaultQuality=void 0,t.DefaultQuality="stable";const r=new Set(["stable","insider","dev"]);t.getQuality=function(e){let o=e.searchParams.get("vscode-quality");return o||"vscode.dev"!==e.hostname?o||"localhost"!==e.hostname||(o="insider"):o=t.DefaultQuality,o||(o=/^(?<quality>[^.]+)\.vscode\.dev$/.exec(e.hostname)?.groups?.quality),o||(o=t.DefaultQuality),"insiders"===o?o="insider":r.has(o)||(o=t.DefaultQuality),o}}.apply(t,[r,t]),void 0===o||(e.exports=o)},9739:(e,t,r)=>{var o;o=function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.ROUTES=t.matchRoute=void 0,t.matchRoute=function(e,t){const r=("string"==typeof t.path?t.path:t.path.prefix).replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g,"\\$&");return new RegExp("string"==typeof t.path?`^/${r}/`:`^/${r}`,"i").test(e.endsWith("/")?e:`${e}/`)},t.ROUTES=[]}.apply(t,[r,t]),void 0===o||(e.exports=o)},1591:e=>{e.exports=function e(t,r){if(t&&r)return e(t)(r);if("function"!=typeof t)throw new TypeError("need wrapper function");return Object.keys(t).forEach((function(e){o[e]=t[e]})),o;function o(){for(var e=new Array(arguments.length),r=0;r<e.length;r++)e[r]=arguments[r];var o=t.apply(this,e),n=e[e.length-1];return"function"==typeof o&&o!==n&&Object.keys(n).forEach((function(e){o[e]=n[e]})),o}}},9883:t=>{t.exports=e},6201:(e,t)=>{const r={LIBRARY_NAME:"MSAL.JS",SKU:"msal.js.common",CACHE_PREFIX:"msal",DEFAULT_AUTHORITY:"https://login.microsoftonline.com/common/",DEFAULT_AUTHORITY_HOST:"login.microsoftonline.com",DEFAULT_COMMON_TENANT:"common",ADFS:"adfs",DSTS:"dstsv2",AAD_INSTANCE_DISCOVERY_ENDPT:"https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=",CIAM_AUTH_URL:".ciamlogin.com",AAD_TENANT_DOMAIN_SUFFIX:".onmicrosoft.com",RESOURCE_DELIM:"|",NO_ACCOUNT:"NO_ACCOUNT",CLAIMS:"claims",CONSUMER_UTID:"9188040d-6c67-4c5b-b112-36a304b66dad",OPENID_SCOPE:"openid",PROFILE_SCOPE:"profile",OFFLINE_ACCESS_SCOPE:"offline_access",EMAIL_SCOPE:"email",CODE_RESPONSE_TYPE:"code",CODE_GRANT_TYPE:"authorization_code",RT_GRANT_TYPE:"refresh_token",FRAGMENT_RESPONSE_MODE:"fragment",S256_CODE_CHALLENGE_METHOD:"S256",URL_FORM_CONTENT_TYPE:"application/x-www-form-urlencoded;charset=utf-8",AUTHORIZATION_PENDING:"authorization_pending",NOT_DEFINED:"not_defined",EMPTY_STRING:"",NOT_APPLICABLE:"N/A",NOT_AVAILABLE:"Not Available",FORWARD_SLASH:"/",IMDS_ENDPOINT:"http://169.254.169.254/metadata/instance/compute/location",IMDS_VERSION:"2020-06-01",IMDS_TIMEOUT:2e3,AZURE_REGION_AUTO_DISCOVER_FLAG:"TryAutoDetect",REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX:"login.microsoft.com",KNOWN_PUBLIC_CLOUDS:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],TOKEN_RESPONSE_TYPE:"token",ID_TOKEN_RESPONSE_TYPE:"id_token",SHR_NONCE_VALIDITY:240,INVALID_INSTANCE:"invalid_instance"},o=400,n=499,i=500,s=599,a=[r.OPENID_SCOPE,r.PROFILE_SCOPE,r.OFFLINE_ACCESS_SCOPE],c=[...a,r.EMAIL_SCOPE],l="Content-Type",d="Retry-After",u="X-AnchorMailbox",h="WWW-Authenticate",g="Authentication-Info",p="x-ms-request-id",m="x-ms-httpver",f="idtoken",y="client.info",v="adal.idtoken",C="error",w="error.description",T="active-account",k="active-account-filters",I="common",A="organizations",b="consumers",S="access_token",E="xms_cc",R={LOGIN:"login",SELECT_ACCOUNT:"select_account",CONSENT:"consent",NONE:"none",CREATE:"create",NO_SESSION:"no_session"},_={PLAIN:"plain",S256:"S256"},P={QUERY:"query",FRAGMENT:"fragment"},M={...P,FORM_POST:"form_post"},O="authorization_code",N="refresh_token",q="MSSTS",U="ADFS",x="Generic",L={CACHE_KEY_SEPARATOR:"-",CLIENT_INFO_SEPARATOR:"."},D={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},H="appmetadata",B="1",$="authority-metadata",F=86400,z="config",K="cache",j="network",G="hardcoded_values",W={SCHEMA_VERSION:5,MAX_CUR_HEADER_BYTES:80,MAX_LAST_HEADER_BYTES:330,MAX_CACHED_ERRORS:50,CACHE_KEY:"server-telemetry",CATEGORY_SEPARATOR:"|",VALUE_SEPARATOR:",",OVERFLOW_TRUE:"1",OVERFLOW_FALSE:"0",UNKNOWN_ERROR:"unknown_error"},V={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},Q=60,Y=3600,J="throttling",X="retry-after, h429",Z="invalid_grant",ee="client_mismatch",te="username",re="password",oe=200,ne=400,ie="1",se="3",ae="4",ce="2",le="4",de="5",ue="0",he="1",ge="2",pe="3",me="4",fe={Jwt:"JWT",Jwk:"JWK",Pop:"pop"},ye="unexpected_error",ve="post_request_failed";var Ce=Object.freeze({__proto__:null,postRequestFailed:ve,unexpectedError:ye});const we={[ye]:"Unexpected error in authentication.",[ve]:"Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details."},Te={unexpectedError:{code:ye,desc:we[ye]},postRequestFailed:{code:ve,desc:we[ve]}};class ke extends Error{constructor(e,t,o){super(t?`${e}: ${t}`:e),Object.setPrototypeOf(this,ke.prototype),this.errorCode=e||r.EMPTY_STRING,this.errorMessage=t||r.EMPTY_STRING,this.subError=o||r.EMPTY_STRING,this.name="AuthError"}setCorrelationId(e){this.correlationId=e}}function Ie(e,t){return new ke(e,t?`${we[e]} ${t}`:we[e])}const Ae="client_info_decoding_error",be="client_info_empty_error",Se="token_parsing_error",Ee="null_or_empty_token",Re="endpoints_resolution_error",_e="network_error",Pe="openid_config_error",Me="hash_not_deserialized",Oe="invalid_state",Ne="state_mismatch",qe="state_not_found",Ue="nonce_mismatch",xe="auth_time_not_found",Le="max_age_transpired",De="multiple_matching_tokens",He="multiple_matching_accounts",Be="multiple_matching_appMetadata",$e="request_cannot_be_made",Fe="cannot_remove_empty_scope",ze="cannot_append_scopeset",Ke="empty_input_scopeset",je="device_code_polling_cancelled",Ge="device_code_expired",We="device_code_unknown_error",Ve="no_account_in_silent_request",Qe="invalid_cache_record",Ye="invalid_cache_environment",Je="no_account_found",Xe="no_crypto_object",Ze="unexpected_credential_type",et="invalid_assertion",tt="invalid_client_credential",rt="token_refresh_required",ot="user_timeout_reached",nt="token_claims_cnf_required_for_signedjwt",it="authorization_code_missing_from_server_response",st="binding_key_not_removed",at="end_session_endpoint_not_supported",ct="key_id_missing",lt="no_network_connectivity",dt="user_canceled",ut="missing_tenant_id_error",ht="method_not_implemented",gt="nested_app_auth_bridge_disabled";var pt=Object.freeze({__proto__:null,authTimeNotFound:xe,authorizationCodeMissingFromServerResponse:it,bindingKeyNotRemoved:st,cannotAppendScopeSet:ze,cannotRemoveEmptyScope:Fe,clientInfoDecodingError:Ae,clientInfoEmptyError:be,deviceCodeExpired:Ge,deviceCodePollingCancelled:je,deviceCodeUnknownError:We,emptyInputScopeSet:Ke,endSessionEndpointNotSupported:at,endpointResolutionError:Re,hashNotDeserialized:Me,invalidAssertion:et,invalidCacheEnvironment:Ye,invalidCacheRecord:Qe,invalidClientCredential:tt,invalidState:Oe,keyIdMissing:ct,maxAgeTranspired:Le,methodNotImplemented:ht,missingTenantIdError:ut,multipleMatchingAccounts:He,multipleMatchingAppMetadata:Be,multipleMatchingTokens:De,nestedAppAuthBridgeDisabled:gt,networkError:_e,noAccountFound:Je,noAccountInSilentRequest:Ve,noCryptoObject:Xe,noNetworkConnectivity:lt,nonceMismatch:Ue,nullOrEmptyToken:Ee,openIdConfigError:Pe,requestCannotBeMade:$e,stateMismatch:Ne,stateNotFound:qe,tokenClaimsCnfRequiredForSignedJwt:nt,tokenParsingError:Se,tokenRefreshRequired:rt,unexpectedCredentialType:Ze,userCanceled:dt,userTimeoutReached:ot});const mt={[Ae]:"The client info could not be parsed/decoded correctly",[be]:"The client info was empty",[Se]:"Token cannot be parsed",[Ee]:"The token is null or empty",[Re]:"Endpoints cannot be resolved",[_e]:"Network request failed",[Pe]:"Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",[Me]:"The hash parameters could not be deserialized",[Oe]:"State was not the expected format",[Ne]:"State mismatch error",[qe]:"State not found",[Ue]:"Nonce mismatch error",[xe]:"Max Age was requested and the ID token is missing the auth_time variable. auth_time is an optional claim and is not enabled by default - it must be enabled. See https://aka.ms/msaljs/optional-claims for more information.",[Le]:"Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",[De]:"The cache contains multiple tokens satisfying the requirements. Call AcquireToken again providing more requirements such as authority or account.",[He]:"The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",[Be]:"The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",[$e]:"Token request cannot be made without authorization code or refresh token.",[Fe]:"Cannot remove null or empty scope from ScopeSet",[ze]:"Cannot append ScopeSet",[Ke]:"Empty input ScopeSet cannot be processed",[je]:"Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",[Ge]:"Device code is expired.",[We]:"Device code stopped polling for unknown reasons.",[Ve]:"Please pass an account object, silent flow is not supported without account information",[Qe]:"Cache record object was null or undefined.",[Ye]:"Invalid environment when attempting to create cache entry",[Je]:"No account found in cache for given key.",[Xe]:"No crypto object detected.",[Ze]:"Unexpected credential type.",[et]:"Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515",[tt]:"Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",[rt]:"Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.",[ot]:"User defined timeout for device code polling reached",[nt]:"Cannot generate a POP jwt if the token_claims are not populated",[it]:"Server response does not contain an authorization code to proceed",[st]:"Could not remove the credential's binding key from storage.",[at]:"The provided authority does not support logout",[ct]:"A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.",[lt]:"No network connectivity. Check your internet connection.",[dt]:"User cancelled the flow.",[ut]:"A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",[ht]:"This method has not been implemented",[gt]:"The nested app auth bridge is disabled"},ft={clientInfoDecodingError:{code:Ae,desc:mt[Ae]},clientInfoEmptyError:{code:be,desc:mt[be]},tokenParsingError:{code:Se,desc:mt[Se]},nullOrEmptyToken:{code:Ee,desc:mt[Ee]},endpointResolutionError:{code:Re,desc:mt[Re]},networkError:{code:_e,desc:mt[_e]},unableToGetOpenidConfigError:{code:Pe,desc:mt[Pe]},hashNotDeserialized:{code:Me,desc:mt[Me]},invalidStateError:{code:Oe,desc:mt[Oe]},stateMismatchError:{code:Ne,desc:mt[Ne]},stateNotFoundError:{code:qe,desc:mt[qe]},nonceMismatchError:{code:Ue,desc:mt[Ue]},authTimeNotFoundError:{code:xe,desc:mt[xe]},maxAgeTranspired:{code:Le,desc:mt[Le]},multipleMatchingTokens:{code:De,desc:mt[De]},multipleMatchingAccounts:{code:He,desc:mt[He]},multipleMatchingAppMetadata:{code:Be,desc:mt[Be]},tokenRequestCannotBeMade:{code:$e,desc:mt[$e]},removeEmptyScopeError:{code:Fe,desc:mt[Fe]},appendScopeSetError:{code:ze,desc:mt[ze]},emptyInputScopeSetError:{code:Ke,desc:mt[Ke]},DeviceCodePollingCancelled:{code:je,desc:mt[je]},DeviceCodeExpired:{code:Ge,desc:mt[Ge]},DeviceCodeUnknownError:{code:We,desc:mt[We]},NoAccountInSilentRequest:{code:Ve,desc:mt[Ve]},invalidCacheRecord:{code:Qe,desc:mt[Qe]},invalidCacheEnvironment:{code:Ye,desc:mt[Ye]},noAccountFound:{code:Je,desc:mt[Je]},noCryptoObj:{code:Xe,desc:mt[Xe]},unexpectedCredentialType:{code:Ze,desc:mt[Ze]},invalidAssertion:{code:et,desc:mt[et]},invalidClientCredential:{code:tt,desc:mt[tt]},tokenRefreshRequired:{code:rt,desc:mt[rt]},userTimeoutReached:{code:ot,desc:mt[ot]},tokenClaimsRequired:{code:nt,desc:mt[nt]},noAuthorizationCodeFromServer:{code:it,desc:mt[it]},bindingKeyNotRemovedError:{code:st,desc:mt[st]},logoutNotSupported:{code:at,desc:mt[at]},keyIdMissing:{code:ct,desc:mt[ct]},noNetworkConnectivity:{code:lt,desc:mt[lt]},userCanceledError:{code:dt,desc:mt[dt]},missingTenantIdError:{code:ut,desc:mt[ut]},nestedAppAuthBridgeDisabled:{code:gt,desc:mt[gt]}};class yt extends ke{constructor(e,t){super(e,t?`${mt[e]}: ${t}`:mt[e]),this.name="ClientAuthError",Object.setPrototypeOf(this,yt.prototype)}}function vt(e,t){return new yt(e,t)}const Ct={createNewGuid:()=>{throw vt(ht)},base64Decode:()=>{throw vt(ht)},base64Encode:()=>{throw vt(ht)},base64UrlEncode:()=>{throw vt(ht)},encodeKid:()=>{throw vt(ht)},async getPublicKeyThumbprint(){throw vt(ht)},async removeTokenBindingKey(){throw vt(ht)},async clearKeystore(){throw vt(ht)},async signJwt(){throw vt(ht)},async hashString(){throw vt(ht)}};var wt;t.LogLevel=void 0,(wt=t.LogLevel||(t.LogLevel={}))[wt.Error=0]="Error",wt[wt.Warning=1]="Warning",wt[wt.Info=2]="Info",wt[wt.Verbose=3]="Verbose",wt[wt.Trace=4]="Trace";class Tt{constructor(e,o,n){this.level=t.LogLevel.Info;const i=e||Tt.createDefaultLoggerOptions();this.localCallback=i.loggerCallback||(()=>{}),this.piiLoggingEnabled=i.piiLoggingEnabled||!1,this.level="number"==typeof i.logLevel?i.logLevel:t.LogLevel.Info,this.correlationId=i.correlationId||r.EMPTY_STRING,this.packageName=o||r.EMPTY_STRING,this.packageVersion=n||r.EMPTY_STRING}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:t.LogLevel.Info}}clone(e,t,r){return new Tt({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level,correlationId:r||this.correlationId},e,t)}logMessage(e,r){if(r.logLevel>this.level||!this.piiLoggingEnabled&&r.containsPii)return;const o=`${`[${(new Date).toUTCString()}] : [${r.correlationId||this.correlationId||""}]`} : ${this.packageName}@${this.packageVersion} : ${t.LogLevel[r.logLevel]} - ${e}`;this.executeCallback(r.logLevel,o,r.containsPii||!1)}executeCallback(e,t,r){this.localCallback&&this.localCallback(e,t,r)}error(e,o){this.logMessage(e,{logLevel:t.LogLevel.Error,containsPii:!1,correlationId:o||r.EMPTY_STRING})}errorPii(e,o){this.logMessage(e,{logLevel:t.LogLevel.Error,containsPii:!0,correlationId:o||r.EMPTY_STRING})}warning(e,o){this.logMessage(e,{logLevel:t.LogLevel.Warning,containsPii:!1,correlationId:o||r.EMPTY_STRING})}warningPii(e,o){this.logMessage(e,{logLevel:t.LogLevel.Warning,containsPii:!0,correlationId:o||r.EMPTY_STRING})}info(e,o){this.logMessage(e,{logLevel:t.LogLevel.Info,containsPii:!1,correlationId:o||r.EMPTY_STRING})}infoPii(e,o){this.logMessage(e,{logLevel:t.LogLevel.Info,containsPii:!0,correlationId:o||r.EMPTY_STRING})}verbose(e,o){this.logMessage(e,{logLevel:t.LogLevel.Verbose,containsPii:!1,correlationId:o||r.EMPTY_STRING})}verbosePii(e,o){this.logMessage(e,{logLevel:t.LogLevel.Verbose,containsPii:!0,correlationId:o||r.EMPTY_STRING})}trace(e,o){this.logMessage(e,{logLevel:t.LogLevel.Trace,containsPii:!1,correlationId:o||r.EMPTY_STRING})}tracePii(e,o){this.logMessage(e,{logLevel:t.LogLevel.Trace,containsPii:!0,correlationId:o||r.EMPTY_STRING})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}}const kt="@azure/msal-common",It="14.15.0",At={None:"none",AzurePublic:"https://login.microsoftonline.com",AzurePpe:"https://login.windows-ppe.net",AzureChina:"https://login.chinacloudapi.cn",AzureGermany:"https://login.microsoftonline.de",AzureUsGovernment:"https://login.microsoftonline.us"};function bt(e,t){const r=function(e){if(!e)throw vt(Ee);const t=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(e);if(!t||t.length<4)throw vt(Se);return t[2]}(e);try{const e=t(r);return JSON.parse(e)}catch(e){throw vt(Se)}}function St(e,t){if(0===t||Date.now()-3e5>e+t)throw vt(Le)}function Et(){return Math.round((new Date).getTime()/1e3)}function Rt(e,t){const r=Number(e)||0;return Et()+t>r}function _t(e){return Number(e)>Et()}function Pt(e){return[Dt(e),Ht(e),Bt(e),$t(e),Ft(e)].join(L.CACHE_KEY_SEPARATOR).toLowerCase()}function Mt(e,t,r,o,n){return{credentialType:D.ID_TOKEN,homeAccountId:e,environment:t,clientId:o,secret:r,realm:n}}function Ot(e,t,r,o,n,i,s,a,c,l,d,u,h,g,p){const m={homeAccountId:e,credentialType:D.ACCESS_TOKEN,secret:r,cachedAt:Et().toString(),expiresOn:s.toString(),extendedExpiresOn:a.toString(),environment:t,clientId:o,realm:n,target:i,tokenType:d||V.BEARER};if(u&&(m.userAssertionHash=u),l&&(m.refreshOn=l.toString()),g&&(m.requestedClaims=g,m.requestedClaimsHash=p),m.tokenType?.toLowerCase()!==V.BEARER.toLowerCase())switch(m.credentialType=D.ACCESS_TOKEN_WITH_AUTH_SCHEME,m.tokenType){case V.POP:const e=bt(r,c);if(!e?.cnf?.kid)throw vt(nt);m.keyId=e.cnf.kid;break;case V.SSH:m.keyId=h}return m}function Nt(e,t,r,o,n,i,s){const a={credentialType:D.REFRESH_TOKEN,homeAccountId:e,environment:t,clientId:o,secret:r};return i&&(a.userAssertionHash=i),n&&(a.familyId=n),s&&(a.expiresOn=s.toString()),a}function qt(e){return e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("credentialType")&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("secret")}function Ut(e){return!!e&&(qt(e)&&e.hasOwnProperty("realm")&&e.hasOwnProperty("target")&&(e.credentialType===D.ACCESS_TOKEN||e.credentialType===D.ACCESS_TOKEN_WITH_AUTH_SCHEME))}function xt(e){return!!e&&(qt(e)&&e.hasOwnProperty("realm")&&e.credentialType===D.ID_TOKEN)}function Lt(e){return!!e&&(qt(e)&&e.credentialType===D.REFRESH_TOKEN)}function Dt(e){return[e.homeAccountId,e.environment].join(L.CACHE_KEY_SEPARATOR).toLowerCase()}function Ht(e){const t=e.credentialType===D.REFRESH_TOKEN&&e.familyId||e.clientId;return[e.credentialType,t,e.realm||""].join(L.CACHE_KEY_SEPARATOR).toLowerCase()}function Bt(e){return(e.target||"").toLowerCase()}function $t(e){return(e.requestedClaimsHash||"").toLowerCase()}function Ft(e){return e.tokenType&&e.tokenType.toLowerCase()!==V.BEARER.toLowerCase()?e.tokenType.toLowerCase():""}function zt(){return Et()+F}function Kt(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 jt(e,t,r){e.aliases=t.aliases,e.preferred_cache=t.preferred_cache,e.preferred_network=t.preferred_network,e.aliasesFromNetwork=r}function Gt(e){return e.expiresAt<=Et()}const Wt="redirect_uri_empty",Vt="claims_request_parsing_error",Qt="authority_uri_insecure",Yt="url_parse_error",Jt="empty_url_error",Xt="empty_input_scopes_error",Zt="invalid_prompt_value",er="invalid_claims",tr="token_request_empty",rr="logout_request_empty",or="invalid_code_challenge_method",nr="pkce_params_missing",ir="invalid_cloud_discovery_metadata",sr="invalid_authority_metadata",ar="untrusted_authority",cr="missing_ssh_jwk",lr="missing_ssh_kid",dr="missing_nonce_authentication_header",ur="invalid_authentication_header",hr="cannot_set_OIDCOptions",gr="cannot_allow_native_broker",pr="authority_mismatch";var mr=Object.freeze({__proto__:null,authorityMismatch:pr,authorityUriInsecure:Qt,cannotAllowNativeBroker:gr,cannotSetOIDCOptions:hr,claimsRequestParsingError:Vt,emptyInputScopesError:Xt,invalidAuthenticationHeader:ur,invalidAuthorityMetadata:sr,invalidClaims:er,invalidCloudDiscoveryMetadata:ir,invalidCodeChallengeMethod:or,invalidPromptValue:Zt,logoutRequestEmpty:rr,missingNonceAuthenticationHeader:dr,missingSshJwk:cr,missingSshKid:lr,pkceParamsMissing:nr,redirectUriEmpty:Wt,tokenRequestEmpty:tr,untrustedAuthority:ar,urlEmptyError:Jt,urlParseError:Yt});const fr={[Wt]:"A redirect URI is required for all calls, and none has been set.",[Vt]:"Could not parse the given claims request object.",[Qt]:"Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options",[Yt]:"URL could not be parsed into appropriate segments.",[Jt]:"URL was empty or null.",[Xt]:"Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",[Zt]:"Please see here for valid configuration options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_common.html#commonauthorizationurlrequest",[er]:"Given claims parameter must be a stringified JSON object.",[tr]:"Token request was empty and not found in cache.",[rr]:"The logout request was null or undefined.",[or]:'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',[nr]:"Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",[ir]:"Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",[sr]:"Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",[ar]:"The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",[cr]:"Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",[lr]:"Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",[dr]:"Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.",[ur]:"Invalid authentication header provided",[hr]:"Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",[gr]:"Cannot set allowNativeBroker parameter to true when not in AAD protocol mode.",[pr]:"Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority."},yr={redirectUriNotSet:{code:Wt,desc:fr[Wt]},claimsRequestParsingError:{code:Vt,desc:fr[Vt]},authorityUriInsecure:{code:Qt,desc:fr[Qt]},urlParseError:{code:Yt,desc:fr[Yt]},urlEmptyError:{code:Jt,desc:fr[Jt]},emptyScopesError:{code:Xt,desc:fr[Xt]},invalidPrompt:{code:Zt,desc:fr[Zt]},invalidClaimsRequest:{code:er,desc:fr[er]},tokenRequestEmptyError:{code:tr,desc:fr[tr]},logoutRequestEmptyError:{code:rr,desc:fr[rr]},invalidCodeChallengeMethod:{code:or,desc:fr[or]},invalidCodeChallengeParams:{code:nr,desc:fr[nr]},invalidCloudDiscoveryMetadata:{code:ir,desc:fr[ir]},invalidAuthorityMetadata:{code:sr,desc:fr[sr]},untrustedAuthority:{code:ar,desc:fr[ar]},missingSshJwk:{code:cr,desc:fr[cr]},missingSshKid:{code:lr,desc:fr[lr]},missingNonceAuthenticationHeader:{code:dr,desc:fr[dr]},invalidAuthenticationHeader:{code:ur,desc:fr[ur]},cannotSetOIDCOptions:{code:hr,desc:fr[hr]},cannotAllowNativeBroker:{code:gr,desc:fr[gr]},authorityMismatch:{code:pr,desc:fr[pr]}};class vr extends ke{constructor(e){super(e,fr[e]),this.name="ClientConfigurationError",Object.setPrototypeOf(this,vr.prototype)}}function Cr(e){return new vr(e)}class wr{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}}static matchPattern(e,t){return new RegExp(e.replace(/\\/g,"\\\\").replace(/\*/g,"[^ ]*").replace(/\?/g,"\\?")).test(t)}}class Tr{constructor(e){const t=e?wr.trimArrayEntries([...e]):[],r=t?wr.removeEmptyStringsFromArray(t):[];this.validateInputScopes(r),this.scopes=new Set,r.forEach((e=>this.scopes.add(e)))}static fromString(e){const t=(e||r.EMPTY_STRING).split(" ");return new Tr(t)}static createSearchScopes(e){const t=new Tr(e);return t.containsOnlyOIDCScopes()?t.removeScope(r.OFFLINE_ACCESS_SCOPE):t.removeOIDCScopes(),t}validateInputScopes(e){if(!e||e.length<1)throw Cr(Xt)}containsScope(e){const t=this.printScopesLowerCase().split(" "),r=new Tr(t);return!!e&&r.scopes.has(e.toLowerCase())}containsScopeSet(e){return!(!e||e.scopes.size<=0)&&(this.scopes.size>=e.scopes.size&&e.asArray().every((e=>this.containsScope(e))))}containsOnlyOIDCScopes(){let e=0;return c.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 vt(ze)}}removeScope(e){if(!e)throw vt(Fe);this.scopes.delete(e.trim())}removeOIDCScopes(){c.forEach((e=>{this.scopes.delete(e)}))}unionScopeSets(e){if(!e)throw vt(Ke);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 vt(Ke);e.containsOnlyOIDCScopes()||e.removeOIDCScopes();const t=this.unionScopeSets(e),r=e.getScopeCount(),o=this.getScopeCount();return t.size<o+r}getScopeCount(){return this.scopes.size}asArray(){const e=[];return this.scopes.forEach((t=>e.push(t))),e}printScopes(){if(this.scopes){return this.asArray().join(" ")}return r.EMPTY_STRING}printScopesLowerCase(){return this.printScopes().toLowerCase()}}function kr(e,t){if(!e)throw vt(be);try{const r=t(e);return JSON.parse(r)}catch(e){throw vt(Ae)}}function Ir(e){if(!e)throw vt(Ae);const t=e.split(L.CLIENT_INFO_SEPARATOR,2);return{uid:t[0],utid:t.length<2?r.EMPTY_STRING:t[1]}}function Ar(e,t){return!!e&&!!t&&e===t.split(".")[1]}function br(e,t,r,o){if(o){const{oid:t,sub:r,tid:n,name:i,tfp:s,acr:a}=o,c=n||s||a||"";return{tenantId:c,localAccountId:t||r||"",name:i,isHomeTenant:Ar(c,e)}}return{tenantId:r,localAccountId:t,isHomeTenant:Ar(r,e)}}function Sr(e,t,r,o){let n=e;if(t){const{isHomeTenant:r,...o}=t;n={...e,...o}}if(r){const{isHomeTenant:t,...i}=br(e.homeAccountId,e.localAccountId,e.tenantId,r);return n={...n,...i,idTokenClaims:r,idToken:o},n}return n}const Er=0,Rr=1,_r=2,Pr=3;function Mr(e){if(e){return e.tid||e.tfp||e.acr||null}return null}const Or={AAD:"AAD",OIDC:"OIDC"};class Nr{generateAccountId(){return[this.homeAccountId,this.environment].join(L.CACHE_KEY_SEPARATOR).toLowerCase()}generateAccountKey(){return Nr.generateAccountCacheKey({homeAccountId:this.homeAccountId,environment:this.environment,tenantId:this.realm,username:this.username,localAccountId:this.localAccountId})}getAccountInfo(){return{homeAccountId:this.homeAccountId,environment:this.environment,tenantId:this.realm,username:this.username,localAccountId:this.localAccountId,name:this.name,nativeAccountId:this.nativeAccountId,authorityType:this.authorityType,tenantProfiles:new Map((this.tenantProfiles||[]).map((e=>[e.tenantId,e])))}}isSingleTenant(){return!this.tenantProfiles}static generateAccountCacheKey(e){const t=e.homeAccountId.split(".")[1];return[e.homeAccountId,e.environment||"",t||e.tenantId||""].join(L.CACHE_KEY_SEPARATOR).toLowerCase()}static createAccount(e,t,r){const o=new Nr;let n;t.authorityType===Rr?o.authorityType=U:t.protocolMode===Or.AAD?o.authorityType=q:o.authorityType=x,e.clientInfo&&r&&(n=kr(e.clientInfo,r)),o.clientInfo=e.clientInfo,o.homeAccountId=e.homeAccountId,o.nativeAccountId=e.nativeAccountId;const i=e.environment||t&&t.getPreferredCache();if(!i)throw vt(Ye);o.environment=i,o.realm=n?.utid||Mr(e.idTokenClaims)||"",o.localAccountId=n?.uid||e.idTokenClaims?.oid||e.idTokenClaims?.sub||"";const s=e.idTokenClaims?.preferred_username||e.idTokenClaims?.upn,a=e.idTokenClaims?.emails?e.idTokenClaims.emails[0]:null;if(o.username=s||a||"",o.name=e.idTokenClaims?.name||"",o.cloudGraphHostName=e.cloudGraphHostName,o.msGraphHost=e.msGraphHost,e.tenantProfiles)o.tenantProfiles=e.tenantProfiles;else{const t=br(e.homeAccountId,o.localAccountId,o.realm,e.idTokenClaims);o.tenantProfiles=[t]}return o}static createFromAccountInfo(e,t,r){const o=new Nr;return o.authorityType=e.authorityType||x,o.homeAccountId=e.homeAccountId,o.localAccountId=e.localAccountId,o.nativeAccountId=e.nativeAccountId,o.realm=e.tenantId,o.environment=e.environment,o.username=e.username,o.name=e.name,o.cloudGraphHostName=t,o.msGraphHost=r,o.tenantProfiles=Array.from(e.tenantProfiles?.values()||[]),o}static generateHomeAccountId(e,t,r,o,n){if(t!==Rr&&t!==_r){if(e)try{const t=kr(e,o.base64Decode);if(t.uid&&t.utid)return`${t.uid}.${t.utid}`}catch(e){}r.warning("No client info in response")}return n?.sub||""}static isAccountEntity(e){return!!e&&(e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("realm")&&e.hasOwnProperty("localAccountId")&&e.hasOwnProperty("username")&&e.hasOwnProperty("authorityType"))}static accountInfoIsEqual(e,t,r){if(!e||!t)return!1;let o=!0;if(r){const r=e.idTokenClaims||{},n=t.idTokenClaims||{};o=r.iat===n.iat&&r.nonce===n.nonce}return e.homeAccountId===t.homeAccountId&&e.localAccountId===t.localAccountId&&e.username===t.username&&e.tenantId===t.tenantId&&e.environment===t.environment&&e.nativeAccountId===t.nativeAccountId&&o}}function qr(e){return e.startsWith("#/")?e.substring(2):e.startsWith("#")||e.startsWith("?")?e.substring(1):e}function Ur(e){if(!e||e.indexOf("=")<0)return null;try{const t=qr(e),r=Object.fromEntries(new URLSearchParams(t));if(r.code||r.error||r.error_description||r.state)return r}catch(e){throw vt(Me)}return null}class xr{get urlString(){return this._urlString}constructor(e){if(this._urlString=e,!this._urlString)throw Cr(Jt);e.includes("#")||(this._urlString=xr.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return wr.endsWith(t,"?")?t=t.slice(0,-1):wr.endsWith(t,"?/")&&(t=t.slice(0,-2)),wr.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch(e){throw Cr(Yt)}if(!e.HostNameAndPort||!e.PathSegments)throw Cr(Yt);if(!e.Protocol||"https:"!==e.Protocol.toLowerCase())throw Cr(Qt)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return xr.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),r=t.PathSegments;return!e||0===r.length||r[0]!==I&&r[0]!==A||(r[0]=e),xr.constructAuthorityUriFromObject(t)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw Cr(Yt);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){const t=RegExp("^([^:/?#]+://)?([^/?#]*)"),r=e.match(t);if(!r)throw Cr(Yt);return r[2]}static getAbsoluteUrl(e,t){if(e[0]===r.FORWARD_SLASH){const r=new xr(t).getUrlComponents();return r.Protocol+"//"+r.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e){return new xr(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"))}static hashContainsKnownProperties(e){return!!Ur(e)}}const Lr={"login.microsoftonline.com":{token_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys",issuer:"https://login.microsoftonline.com/{tenantid}/v2.0",authorization_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/logout"},"login.chinacloudapi.cn":{token_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.chinacloudapi.cn/{tenantid}/discovery/v2.0/keys",issuer:"https://login.partner.microsoftonline.cn/{tenantid}/v2.0",authorization_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/logout"},"login.microsoftonline.us":{token_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.microsoftonline.us/{tenantid}/discovery/v2.0/keys",issuer:"https://login.microsoftonline.us/{tenantid}/v2.0",authorization_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/logout"}},Dr={tenant_discovery_endpoint:"https://{canonicalAuthority}/v2.0/.well-known/openid-configuration",metadata:[{preferred_network:"login.microsoftonline.com",preferred_cache:"login.windows.net",aliases:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"]},{preferred_network:"login.partner.microsoftonline.cn",preferred_cache:"login.partner.microsoftonline.cn",aliases:["login.partner.microsoftonline.cn","login.chinacloudapi.cn"]},{preferred_network:"login.microsoftonline.de",preferred_cache:"login.microsoftonline.de",aliases:["login.microsoftonline.de"]},{preferred_network:"login.microsoftonline.us",preferred_cache:"login.microsoftonline.us",aliases:["login.microsoftonline.us","login.usgovcloudapi.net"]},{preferred_network:"login-us.microsoftonline.com",preferred_cache:"login-us.microsoftonline.com",aliases:["login-us.microsoftonline.com"]}]},Hr=new Set;function Br(e,t,r,o){if(o?.trace(`getAliasesFromMetadata called with source: ${r}`),e&&t){const n=$r(t,e);if(n)return o?.trace(`getAliasesFromMetadata: found cloud discovery metadata in ${r}, returning aliases`),n.aliases;o?.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in ${r}`)}return null}function $r(e,t){for(let r=0;r<e.length;r++){const o=e[r];if(o.aliases.includes(t))return o}return null}Dr.metadata.forEach((e=>{e.aliases.forEach((e=>{Hr.add(e)}))}));const Fr="cache_quota_exceeded",zr="cache_error_unknown",Kr={[Fr]:"Exceeded cache storage capacity.",[zr]:"Unexpected error occurred when using cache storage."};class jr extends Error{constructor(e,t){const r=t||(Kr[e]?Kr[e]:Kr[zr]);super(`${e}: ${r}`),Object.setPrototypeOf(this,jr.prototype),this.name="CacheError",this.errorCode=e,this.errorMessage=r}}class Gr{constructor(e,t,r,o){this.clientId=e,this.cryptoImpl=t,this.commonLogger=r.clone(kt,It),this.staticAuthorityOptions=o}getAllAccounts(e){return this.buildTenantProfiles(this.getAccountsFilteredBy(e||{}),e)}getAccountInfoFilteredBy(e){const t=this.getAllAccounts(e);if(t.length>1){return t.sort((e=>e.idTokenClaims?-1:1))[0]}return 1===t.length?t[0]:null}getBaseAccountInfo(e){const t=this.getAccountsFilteredBy(e);return t.length>0?t[0].getAccountInfo():null}buildTenantProfiles(e,t){return e.flatMap((e=>this.getTenantProfilesFromAccountEntity(e,t?.tenantId,t)))}getTenantedAccountInfoByFilter(e,t,r,o){let n,i=null;if(o&&!this.tenantProfileMatchesFilter(r,o))return null;const s=this.getIdToken(e,t,r.tenantId);return s&&(n=bt(s.secret,this.cryptoImpl.base64Decode),!this.idTokenClaimsMatchTenantProfileFilter(n,o))?null:(i=Sr(e,r,n,s?.secret),i)}getTenantProfilesFromAccountEntity(e,t,r){const o=e.getAccountInfo();let n=o.tenantProfiles||new Map;const i=this.getTokenKeys();if(t){const e=n.get(t);if(!e)return[];n=new Map([[t,e]])}const s=[];return n.forEach((e=>{const t=this.getTenantedAccountInfoByFilter(o,i,e,r);t&&s.push(t)})),s}tenantProfileMatchesFilter(e,t){return!(t.localAccountId&&!this.matchLocalAccountIdFromTenantProfile(e,t.localAccountId))&&((!t.name||e.name===t.name)&&(void 0===t.isHomeTenant||e.isHomeTenant===t.isHomeTenant))}idTokenClaimsMatchTenantProfileFilter(e,t){if(t){if(t.localAccountId&&!this.matchLocalAccountIdFromTokenClaims(e,t.localAccountId))return!1;if(t.loginHint&&!this.matchLoginHintFromTokenClaims(e,t.loginHint))return!1;if(t.username&&!this.matchUsername(e.preferred_username,t.username))return!1;if(t.name&&!this.matchName(e,t.name))return!1;if(t.sid&&!this.matchSid(e,t.sid))return!1}return!0}async saveCacheRecord(e,t,r){if(!e)throw vt(Qe);try{e.account&&this.setAccount(e.account),e.idToken&&!1!==t?.idToken&&this.setIdTokenCredential(e.idToken),e.accessToken&&!1!==t?.accessToken&&await this.saveAccessToken(e.accessToken),e.refreshToken&&!1!==t?.refreshToken&&this.setRefreshTokenCredential(e.refreshToken),e.appMetadata&&this.setAppMetadata(e.appMetadata)}catch(e){throw this.commonLogger?.error("CacheManager.saveCacheRecord: failed"),e instanceof Error?(this.commonLogger?.errorPii(`CacheManager.saveCacheRecord: ${e.message}`,r),"QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||e.message.includes("exceeded the quota")?(this.commonLogger?.error("CacheManager.saveCacheRecord: exceeded storage quota",r),new jr(Fr)):new jr(e.name,e.message)):(this.commonLogger?.errorPii(`CacheManager.saveCacheRecord: ${e}`,r),new jr(zr))}}async saveAccessToken(e){const t={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType,requestedClaimsHash:e.requestedClaimsHash},r=this.getTokenKeys(),o=Tr.fromString(e.target),n=[];r.accessToken.forEach((e=>{if(!this.accessTokenKeyMatchesFilter(e,t,!1))return;const r=this.getAccessTokenCredential(e);if(r&&this.credentialMatchesFilter(r,t)){Tr.fromString(r.target).intersectingScopeSets(o)&&n.push(this.removeAccessToken(e))}})),await Promise.all(n),this.setAccessTokenCredential(e)}getAccountsFilteredBy(e){const t=this.getAccountKeys(),r=[];return t.forEach((t=>{if(!this.isAccountKey(t,e.homeAccountId))return;const o=this.getAccount(t,this.commonLogger);if(!o)return;if(e.homeAccountId&&!this.matchHomeAccountId(o,e.homeAccountId))return;if(e.username&&!this.matchUsername(o.username,e.username))return;if(e.environment&&!this.matchEnvironment(o,e.environment))return;if(e.realm&&!this.matchRealm(o,e.realm))return;if(e.nativeAccountId&&!this.matchNativeAccountId(o,e.nativeAccountId))return;if(e.authorityType&&!this.matchAuthorityType(o,e.authorityType))return;const n={localAccountId:e?.localAccountId,name:e?.name},i=o.tenantProfiles?.filter((e=>this.tenantProfileMatchesFilter(e,n)));i&&0===i.length||r.push(o)})),r}isAccountKey(e,t,r){return!(e.split(L.CACHE_KEY_SEPARATOR).length<3)&&(!(t&&!e.toLowerCase().includes(t.toLowerCase()))&&!(r&&!e.toLowerCase().includes(r.toLowerCase())))}isCredentialKey(e){if(e.split(L.CACHE_KEY_SEPARATOR).length<6)return!1;const t=e.toLowerCase();if(-1===t.indexOf(D.ID_TOKEN.toLowerCase())&&-1===t.indexOf(D.ACCESS_TOKEN.toLowerCase())&&-1===t.indexOf(D.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase())&&-1===t.indexOf(D.REFRESH_TOKEN.toLowerCase()))return!1;if(t.indexOf(D.REFRESH_TOKEN.toLowerCase())>-1){const e=`${D.REFRESH_TOKEN}${L.CACHE_KEY_SEPARATOR}${this.clientId}${L.CACHE_KEY_SEPARATOR}`,r=`${D.REFRESH_TOKEN}${L.CACHE_KEY_SEPARATOR}${B}${L.CACHE_KEY_SEPARATOR}`;if(-1===t.indexOf(e.toLowerCase())&&-1===t.indexOf(r.toLowerCase()))return!1}else if(-1===t.indexOf(this.clientId.toLowerCase()))return!1;return!0}credentialMatchesFilter(e,t){if(t.clientId&&!this.matchClientId(e,t.clientId))return!1;if(t.userAssertionHash&&!this.matchUserAssertionHash(e,t.userAssertionHash))return!1;if("string"==typeof t.homeAccountId&&!this.matchHomeAccountId(e,t.homeAccountId))return!1;if(t.environment&&!this.matchEnvironment(e,t.environment))return!1;if(t.realm&&!this.matchRealm(e,t.realm))return!1;if(t.credentialType&&!this.matchCredentialType(e,t.credentialType))return!1;if(t.familyId&&!this.matchFamilyId(e,t.familyId))return!1;if(t.target&&!this.matchTarget(e,t.target))return!1;if((t.requestedClaimsHash||e.requestedClaimsHash)&&e.requestedClaimsHash!==t.requestedClaimsHash)return!1;if(e.credentialType===D.ACCESS_TOKEN_WITH_AUTH_SCHEME){if(t.tokenType&&!this.matchTokenType(e,t.tokenType))return!1;if(t.tokenType===V.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId))return!1}return!0}getAppMetadataFilteredBy(e){const t=this.getKeys(),r={};return t.forEach((t=>{if(!this.isAppMetadata(t))return;const o=this.getAppMetadata(t);o&&(e.environment&&!this.matchEnvironment(o,e.environment)||e.clientId&&!this.matchClientId(o,e.clientId)||(r[t]=o))})),r}getAuthorityMetadataByAlias(e){const t=this.getAuthorityMetadataKeys();let r=null;return t.forEach((t=>{if(!this.isAuthorityMetadata(t)||-1===t.indexOf(this.clientId))return;const o=this.getAuthorityMetadata(t);o&&-1!==o.aliases.indexOf(e)&&(r=o)})),r}async removeAllAccounts(){const e=this.getAccountKeys(),t=[];e.forEach((e=>{t.push(this.removeAccount(e))})),await Promise.all(t)}async removeAccount(e){const t=this.getAccount(e,this.commonLogger);t&&(await this.removeAccountContext(t),this.removeItem(e))}async removeAccountContext(e){const t=this.getTokenKeys(),r=e.generateAccountId(),o=[];t.idToken.forEach((e=>{0===e.indexOf(r)&&this.removeIdToken(e)})),t.accessToken.forEach((e=>{0===e.indexOf(r)&&o.push(this.removeAccessToken(e))})),t.refreshToken.forEach((e=>{0===e.indexOf(r)&&this.removeRefreshToken(e)})),await Promise.all(o)}updateOutdatedCachedAccount(e,t,r){if(t&&t.isSingleTenant()){this.commonLogger?.verbose("updateOutdatedCachedAccount: Found a single-tenant (outdated) account entity in the cache, migrating to multi-tenant account entity");const o=this.getAccountKeys().filter((e=>e.startsWith(t.homeAccountId))),n=[];o.forEach((e=>{const t=this.getCachedAccountEntity(e);t&&n.push(t)}));const i=n.find((e=>Ar(e.realm,e.homeAccountId)))||n[0];i.tenantProfiles=n.map((e=>({tenantId:e.realm,localAccountId:e.localAccountId,name:e.name,isHomeTenant:Ar(e.realm,e.homeAccountId)})));const s=Gr.toObject(new Nr,{...i}),a=s.generateAccountKey();return o.forEach((t=>{t!==a&&this.removeOutdatedAccount(e)})),this.setAccount(s),r?.verbose("Updated an outdated account entity in the cache"),s}return t}async removeAccessToken(e){const t=this.getAccessTokenCredential(e);if(t){if(t.credentialType.toLowerCase()===D.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()&&t.tokenType===V.POP){const e=t.keyId;if(e)try{await this.cryptoImpl.removeTokenBindingKey(e)}catch(e){throw vt(st)}}return this.removeItem(e)}}removeAppMetadata(){return this.getKeys().forEach((e=>{this.isAppMetadata(e)&&this.removeItem(e)})),!0}readAccountFromCache(e){const t=Nr.generateAccountCacheKey(e);return this.getAccount(t,this.commonLogger)}getIdToken(e,t,r,o,n){this.commonLogger.trace("CacheManager - getIdToken called");const i={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:D.ID_TOKEN,clientId:this.clientId,realm:r},s=this.getIdTokensByFilter(i,t),a=s.size;if(a<1)return this.commonLogger.info("CacheManager:getIdToken - No token found"),null;if(a>1){let t=s;if(!r){const r=new Map;s.forEach(((t,o)=>{t.realm===e.tenantId&&r.set(o,t)}));const o=r.size;if(o<1)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result"),s.values().next().value;if(1===o)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile"),r.values().next().value;t=r}return this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them"),t.forEach(((e,t)=>{this.removeIdToken(t)})),o&&n&&o.addFields({multiMatchedID:s.size},n),null}return this.commonLogger.info("CacheManager:getIdToken - Returning ID token"),s.values().next().value}getIdTokensByFilter(e,t){const r=t&&t.idToken||this.getTokenKeys().idToken,o=new Map;return r.forEach((t=>{if(!this.idTokenKeyMatchesFilter(t,{clientId:this.clientId,...e}))return;const r=this.getIdTokenCredential(t);r&&this.credentialMatchesFilter(r,e)&&o.set(t,r)})),o}idTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.clientId||-1!==r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase()))}removeIdToken(e){this.removeItem(e)}removeRefreshToken(e){this.removeItem(e)}getAccessToken(e,t,r,o,n,i){this.commonLogger.trace("CacheManager - getAccessToken called");const s=Tr.createSearchScopes(t.scopes),a=t.authenticationScheme||V.BEARER,c=a&&a.toLowerCase()!==V.BEARER.toLowerCase()?D.ACCESS_TOKEN_WITH_AUTH_SCHEME:D.ACCESS_TOKEN,l={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:c,clientId:this.clientId,realm:o||e.tenantId,target:s,tokenType:a,keyId:t.sshKid,requestedClaimsHash:t.requestedClaimsHash},d=r&&r.accessToken||this.getTokenKeys().accessToken,u=[];d.forEach((e=>{if(this.accessTokenKeyMatchesFilter(e,l,!0)){const t=this.getAccessTokenCredential(e);t&&this.credentialMatchesFilter(t,l)&&u.push(t)}}));const h=u.length;return h<1?(this.commonLogger.info("CacheManager:getAccessToken - No token found"),null):h>1?(this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them"),u.forEach((e=>{this.removeAccessToken(Pt(e))})),n&&i&&n.addFields({multiMatchedAT:u.length},i),null):(this.commonLogger.info("CacheManager:getAccessToken - Returning access token"),u[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.requestedClaimsHash&&-1===o.indexOf(t.requestedClaimsHash.toLowerCase()))return!1;if(t.target){const e=t.target.asArray();for(let t=0;t<e.length;t++){if(r&&!o.includes(e[t].toLowerCase()))return!1;if(!r&&o.includes(e[t].toLowerCase()))return!0}}return!0}getAccessTokensByFilter(e){const t=this.getTokenKeys(),r=[];return t.accessToken.forEach((t=>{if(!this.accessTokenKeyMatchesFilter(t,e,!0))return;const o=this.getAccessTokenCredential(t);o&&this.credentialMatchesFilter(o,e)&&r.push(o)})),r}getRefreshToken(e,t,r,o,n){this.commonLogger.trace("CacheManager - getRefreshToken called");const i=t?B:void 0,s={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:D.REFRESH_TOKEN,clientId:this.clientId,familyId:i},a=r&&r.refreshToken||this.getTokenKeys().refreshToken,c=[];a.forEach((e=>{if(this.refreshTokenKeyMatchesFilter(e,s)){const t=this.getRefreshTokenCredential(e);t&&this.credentialMatchesFilter(t,s)&&c.push(t)}}));const l=c.length;return l<1?(this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found."),null):(l>1&&o&&n&&o.addFields({multiMatchedRT:l},n),this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token"),c[0])}refreshTokenKeyMatchesFilter(e,t){const r=e.toLowerCase();return(!t.familyId||-1!==r.indexOf(t.familyId.toLowerCase()))&&(!(!t.familyId&&t.clientId&&-1===r.indexOf(t.clientId.toLowerCase()))&&(!t.homeAccountId||-1!==r.indexOf(t.homeAccountId.toLowerCase())))}readAppMetadataFromCache(e){const t={environment:e,clientId:this.clientId},r=this.getAppMetadataFilteredBy(t),o=Object.keys(r).map((e=>r[e])),n=o.length;if(n<1)return null;if(n>1)throw vt(Be);return o[0]}isAppMetadataFOCI(e){const t=this.readAppMetadataFromCache(e);return!(!t||t.familyId!==B)}matchHomeAccountId(e,t){return!("string"!=typeof e.homeAccountId||t!==e.homeAccountId)}matchLocalAccountIdFromTokenClaims(e,t){return t===(e.oid||e.sub)}matchLocalAccountIdFromTenantProfile(e,t){return e.localAccountId===t}matchName(e,t){return!(t.toLowerCase()!==e.name?.toLowerCase())}matchUsername(e,t){return!(!e||"string"!=typeof e||t?.toLowerCase()!==e.toLowerCase())}matchUserAssertionHash(e,t){return!(!e.userAssertionHash||t!==e.userAssertionHash)}matchEnvironment(e,t){if(this.staticAuthorityOptions){const r=function(e,t){let r;const o=e.canonicalAuthority;if(o){const n=new xr(o).getUrlComponents().HostNameAndPort;r=Br(n,e.cloudDiscoveryMetadata?.metadata,z,t)||Br(n,Dr.metadata,G,t)||e.knownAuthorities}return r||[]}(this.staticAuthorityOptions,this.commonLogger);if(r.includes(t)&&r.includes(e.environment))return!0}const r=this.getAuthorityMetadataByAlias(t);return!!(r&&r.aliases.indexOf(e.environment)>-1)}matchCredentialType(e,t){return e.credentialType&&t.toLowerCase()===e.credentialType.toLowerCase()}matchClientId(e,t){return!(!e.clientId||t!==e.clientId)}matchFamilyId(e,t){return!(!e.familyId||t!==e.familyId)}matchRealm(e,t){return!(e.realm?.toLowerCase()!==t.toLowerCase())}matchNativeAccountId(e,t){return!(!e.nativeAccountId||t!==e.nativeAccountId)}matchLoginHintFromTokenClaims(e,t){return e.login_hint===t||(e.preferred_username===t||e.upn===t)}matchSid(e,t){return e.sid===t}matchAuthorityType(e,t){return!(!e.authorityType||t.toLowerCase()!==e.authorityType.toLowerCase())}matchTarget(e,t){if(e.credentialType!==D.ACCESS_TOKEN&&e.credentialType!==D.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target)return!1;return Tr.fromString(e.target).containsScopeSet(t)}matchTokenType(e,t){return!(!e.tokenType||e.tokenType!==t)}matchKeyId(e,t){return!(!e.keyId||e.keyId!==t)}isAppMetadata(e){return-1!==e.indexOf(H)}isAuthorityMetadata(e){return-1!==e.indexOf($)}generateAuthorityMetadataCacheKey(e){return`${$}-${this.clientId}-${e}`}static toObject(e,t){for(const r in t)e[r]=t[r];return e}}class Wr extends Gr{setAccount(){throw vt(ht)}getAccount(){throw vt(ht)}getCachedAccountEntity(){throw vt(ht)}setIdTokenCredential(){throw vt(ht)}getIdTokenCredential(){throw vt(ht)}setAccessTokenCredential(){throw vt(ht)}getAccessTokenCredential(){throw vt(ht)}setRefreshTokenCredential(){throw vt(ht)}getRefreshTokenCredential(){throw vt(ht)}setAppMetadata(){throw vt(ht)}getAppMetadata(){throw vt(ht)}setServerTelemetry(){throw vt(ht)}getServerTelemetry(){throw vt(ht)}setAuthorityMetadata(){throw vt(ht)}getAuthorityMetadata(){throw vt(ht)}getAuthorityMetadataKeys(){throw vt(ht)}setThrottlingCache(){throw vt(ht)}getThrottlingCache(){throw vt(ht)}removeItem(){throw vt(ht)}getKeys(){throw vt(ht)}getAccountKeys(){throw vt(ht)}getTokenKeys(){throw vt(ht)}async clear(){throw vt(ht)}updateCredentialCacheKey(){throw vt(ht)}removeOutdatedAccount(){throw vt(ht)}}const Vr={tokenRenewalOffsetSeconds:300,preventCorsPreflight:!1},Qr={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:t.LogLevel.Info,correlationId:r.EMPTY_STRING},Yr={claimsBasedCachingEnabled:!1},Jr={async sendGetRequestAsync(){throw vt(ht)},async sendPostRequestAsync(){throw vt(ht)}},Xr={sku:r.SKU,version:It,cpu:r.EMPTY_STRING,os:r.EMPTY_STRING},Zr={clientSecret:r.EMPTY_STRING,clientAssertion:void 0},eo={azureCloudInstance:At.None,tenant:`${r.DEFAULT_COMMON_TENANT}`},to={application:{appName:"",appVersion:""}};function ro(e){return e.authOptions.authority.options.protocolMode===Or.OIDC}class oo extends ke{constructor(e,t,r,o,n){super(e,t,r),this.name="ServerError",this.errorNo=o,this.status=n,Object.setPrototypeOf(this,oo.prototype)}}class no{static generateThrottlingStorageKey(e){return`${J}.${JSON.stringify(e)}`}static preProcess(e,t){const o=no.generateThrottlingStorageKey(t),n=e.getThrottlingCache(o);if(n){if(n.throttleTime<Date.now())return void e.removeItem(o);throw new oo(n.errorCodes?.join(" ")||r.EMPTY_STRING,n.errorMessage,n.subError)}}static postProcess(e,t,r){if(no.checkResponseStatus(r)||no.checkResponseForRetryAfter(r)){const o={throttleTime:no.calculateThrottleTime(parseInt(r.headers[d])),error:r.body.error,errorCodes:r.body.error_codes,errorMessage:r.body.error_description,subError:r.body.suberror};e.setThrottlingCache(no.generateThrottlingStorageKey(t),o)}}static checkResponseStatus(e){return 429===e.status||e.status>=500&&e.status<600}static checkResponseForRetryAfter(e){return!!e.headers&&(e.headers.hasOwnProperty(d)&&(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||Q),r+Y))}static removeThrottle(e,t,r,o){const n={clientId:t,authority:r.authority,scopes:r.scopes,homeAccountIdentifier:o,claims:r.claims,authenticationScheme:r.authenticationScheme,resourceRequestMethod:r.resourceRequestMethod,resourceRequestUri:r.resourceRequestUri,shrClaims:r.shrClaims,sshKid:r.sshKid},i=this.generateThrottlingStorageKey(n);e.removeItem(i)}}class io{constructor(e,t){this.networkClient=e,this.cacheManager=t}async sendPostRequest(e,t,r){let o;no.preProcess(this.cacheManager,e);try{o=await this.networkClient.sendPostRequestAsync(t,r)}catch(e){throw e instanceof ke?e:vt(_e)}return no.postProcess(this.cacheManager,e,o),o}}const so="home_account_id",ao="UPN",co="client_id",lo="response_type",uo="token_type",ho="req_cnf",go="return_spa_code",po="x-client-xtra-sku";class mo{static validateRedirectUri(e){if(!e)throw Cr(Wt)}static validatePrompt(e){const t=[];for(const e in R)t.push(R[e]);if(t.indexOf(e)<0)throw Cr(Zt)}static validateClaims(e){try{JSON.parse(e)}catch(e){throw Cr(er)}}static validateCodeChallengeParams(e,t){if(!e||!t)throw Cr(nr);this.validateCodeChallengeMethod(t)}static validateCodeChallengeMethod(e){if([_.PLAIN,_.S256].indexOf(e)<0)throw Cr(or)}}class fo{constructor(){this.parameters=new Map}addResponseTypeCode(){this.parameters.set(lo,encodeURIComponent(r.CODE_RESPONSE_TYPE))}addResponseTypeForTokenAndIdToken(){this.parameters.set(lo,encodeURIComponent(`${r.TOKEN_RESPONSE_TYPE} ${r.ID_TOKEN_RESPONSE_TYPE}`))}addResponseMode(e){this.parameters.set("response_mode",encodeURIComponent(e||M.QUERY))}addNativeBroker(){this.parameters.set("nativebroker",encodeURIComponent("1"))}addScopes(e,t=!0,r=a){!t||r.includes("openid")||e.includes("openid")||r.push("openid");const o=t?[...e||[],...r]:e||[],n=new Tr(o);this.parameters.set("scope",encodeURIComponent(n.printScopes()))}addClientId(e){this.parameters.set(co,encodeURIComponent(e))}addRedirectUri(e){mo.validateRedirectUri(e),this.parameters.set("redirect_uri",encodeURIComponent(e))}addPostLogoutRedirectUri(e){mo.validateRedirectUri(e),this.parameters.set("post_logout_redirect_uri",encodeURIComponent(e))}addIdTokenHint(e){this.parameters.set("id_token_hint",encodeURIComponent(e))}addDomainHint(e){this.parameters.set("domain_hint",encodeURIComponent(e))}addLoginHint(e){this.parameters.set("login_hint",encodeURIComponent(e))}addCcsUpn(e){this.parameters.set(u,encodeURIComponent(`UPN:${e}`))}addCcsOid(e){this.parameters.set(u,encodeURIComponent(`Oid:${e.uid}@${e.utid}`))}addSid(e){this.parameters.set("sid",encodeURIComponent(e))}addClaims(e,t){const r=this.addClientCapabilitiesToClaims(e,t);mo.validateClaims(r),this.parameters.set("claims",encodeURIComponent(r))}addCorrelationId(e){this.parameters.set("client-request-id",encodeURIComponent(e))}addLibraryInfo(e){this.parameters.set("x-client-SKU",e.sku),this.parameters.set("x-client-VER",e.version),e.os&&this.parameters.set("x-client-OS",e.os),e.cpu&&this.parameters.set("x-client-CPU",e.cpu)}addApplicationTelemetry(e){e?.appName&&this.parameters.set("x-app-name",e.appName),e?.appVersion&&this.parameters.set("x-app-ver",e.appVersion)}addPrompt(e){mo.validatePrompt(e),this.parameters.set("prompt",encodeURIComponent(e))}addState(e){e&&this.parameters.set("state",encodeURIComponent(e))}addNonce(e){this.parameters.set("nonce",encodeURIComponent(e))}addCodeChallengeParams(e,t){if(mo.validateCodeChallengeParams(e,t),!e||!t)throw Cr(nr);this.parameters.set("code_challenge",encodeURIComponent(e)),this.parameters.set("code_challenge_method",encodeURIComponent(t))}addAuthorizationCode(e){this.parameters.set("code",encodeURIComponent(e))}addDeviceCode(e){this.parameters.set("device_code",encodeURIComponent(e))}addRefreshToken(e){this.parameters.set("refresh_token",encodeURIComponent(e))}addCodeVerifier(e){this.parameters.set("code_verifier",encodeURIComponent(e))}addClientSecret(e){this.parameters.set("client_secret",encodeURIComponent(e))}addClientAssertion(e){e&&this.parameters.set("client_assertion",encodeURIComponent(e))}addClientAssertionType(e){e&&this.parameters.set("client_assertion_type",encodeURIComponent(e))}addOboAssertion(e){this.parameters.set("assertion",encodeURIComponent(e))}addRequestTokenUse(e){this.parameters.set("requested_token_use",encodeURIComponent(e))}addGrantType(e){this.parameters.set("grant_type",encodeURIComponent(e))}addClientInfo(){this.parameters.set("client_info","1")}addExtraQueryParameters(e){Object.entries(e).forEach((([e,t])=>{!this.parameters.has(e)&&t&&this.parameters.set(e,t)}))}addClientCapabilitiesToClaims(e,t){let r;if(e)try{r=JSON.parse(e)}catch(e){throw Cr(er)}else r={};return t&&t.length>0&&(r.hasOwnProperty(S)||(r[S]={}),r[S][E]={values:t}),JSON.stringify(r)}addUsername(e){this.parameters.set(te,encodeURIComponent(e))}addPassword(e){this.parameters.set(re,encodeURIComponent(e))}addPopToken(e){e&&(this.parameters.set(uo,V.POP),this.parameters.set(ho,encodeURIComponent(e)))}addSshJwk(e){e&&(this.parameters.set(uo,V.SSH),this.parameters.set(ho,encodeURIComponent(e)))}addServerTelemetry(e){this.parameters.set("x-client-current-telemetry",e.generateCurrentRequestHeaderValue()),this.parameters.set("x-client-last-telemetry",e.generateLastRequestHeaderValue())}addThrottling(){this.parameters.set("x-ms-lib-capability",X)}addLogoutHint(e){this.parameters.set("logout_hint",encodeURIComponent(e))}createQueryString(){const e=new Array;return this.parameters.forEach(((t,r)=>{e.push(`${r}=${t}`)})),e.join("&")}}const yo={AcquireTokenByCode:"acquireTokenByCode",AcquireTokenByRefreshToken:"acquireTokenByRefreshToken",AcquireTokenSilent:"acquireTokenSilent",AcquireTokenSilentAsync:"acquireTokenSilentAsync",AcquireTokenPopup:"acquireTokenPopup",AcquireTokenPreRedirect:"acquireTokenPreRedirect",AcquireTokenRedirect:"acquireTokenRedirect",CryptoOptsGetPublicKeyThumbprint:"cryptoOptsGetPublicKeyThumbprint",CryptoOptsSignJwt:"cryptoOptsSignJwt",SilentCacheClientAcquireToken:"silentCacheClientAcquireToken",SilentIframeClientAcquireToken:"silentIframeClientAcquireToken",AwaitConcurrentIframe:"awaitConcurrentIframe",SilentRefreshClientAcquireToken:"silentRefreshClientAcquireToken",SsoSilent:"ssoSilent",StandardInteractionClientGetDiscoveredAuthority:"standardInteractionClientGetDiscoveredAuthority",FetchAccountIdWithNativeBroker:"fetchAccountIdWithNativeBroker",NativeInteractionClientAcquireToken:"nativeInteractionClientAcquireToken",BaseClientCreateTokenRequestHeaders:"baseClientCreateTokenRequestHeaders",RefreshTokenClientExecutePostToTokenEndpoint:"refreshTokenClientExecutePostToTokenEndpoint",AuthorizationCodeClientExecutePostToTokenEndpoint:"authorizationCodeClientExecutePostToTokenEndpoint",BrokerHandhshake:"brokerHandshake",AcquireTokenByRefreshTokenInBroker:"acquireTokenByRefreshTokenInBroker",AcquireTokenByBroker:"acquireTokenByBroker",RefreshTokenClientExecuteTokenRequest:"refreshTokenClientExecuteTokenRequest",RefreshTokenClientAcquireToken:"refreshTokenClientAcquireToken",RefreshTokenClientAcquireTokenWithCachedRefreshToken:"refreshTokenClientAcquireTokenWithCachedRefreshToken",RefreshTokenClientAcquireTokenByRefreshToken:"refreshTokenClientAcquireTokenByRefreshToken",RefreshTokenClientCreateTokenRequestBody:"refreshTokenClientCreateTokenRequestBody",AcquireTokenFromCache:"acquireTokenFromCache",SilentFlowClientAcquireCachedToken:"silentFlowClientAcquireCachedToken",SilentFlowClientGenerateResultFromCacheRecord:"silentFlowClientGenerateResultFromCacheRecord",AcquireTokenBySilentIframe:"acquireTokenBySilentIframe",InitializeBaseRequest:"initializeBaseRequest",InitializeSilentRequest:"initializeSilentRequest",InitializeClientApplication:"initializeClientApplication",SilentIframeClientTokenHelper:"silentIframeClientTokenHelper",SilentHandlerInitiateAuthRequest:"silentHandlerInitiateAuthRequest",SilentHandlerMonitorIframeForHash:"silentHandlerMonitorIframeForHash",SilentHandlerLoadFrame:"silentHandlerLoadFrame",SilentHandlerLoadFrameSync:"silentHandlerLoadFrameSync",StandardInteractionClientCreateAuthCodeClient:"standardInteractionClientCreateAuthCodeClient",StandardInteractionClientGetClientConfiguration:"standardInteractionClientGetClientConfiguration",StandardInteractionClientInitializeAuthorizationRequest:"standardInteractionClientInitializeAuthorizationRequest",StandardInteractionClientInitializeAuthorizationCodeRequest:"standardInteractionClientInitializeAuthorizationCodeRequest",GetAuthCodeUrl:"getAuthCodeUrl",HandleCodeResponseFromServer:"handleCodeResponseFromServer",HandleCodeResponse:"handleCodeResponse",UpdateTokenEndpointAuthority:"updateTokenEndpointAuthority",AuthClientAcquireToken:"authClientAcquireToken",AuthClientExecuteTokenRequest:"authClientExecuteTokenRequest",AuthClientCreateTokenRequestBody:"authClientCreateTokenRequestBody",AuthClientCreateQueryString:"authClientCreateQueryString",PopTokenGenerateCnf:"popTokenGenerateCnf",PopTokenGenerateKid:"popTokenGenerateKid",HandleServerTokenResponse:"handleServerTokenResponse",DeserializeResponse:"deserializeResponse",AuthorityFactoryCreateDiscoveredInstance:"authorityFactoryCreateDiscoveredInstance",AuthorityResolveEndpointsAsync:"authorityResolveEndpointsAsync",AuthorityResolveEndpointsFromLocalSources:"authorityResolveEndpointsFromLocalSources",AuthorityGetCloudDiscoveryMetadataFromNetwork:"authorityGetCloudDiscoveryMetadataFromNetwork",AuthorityUpdateCloudDiscoveryMetadata:"authorityUpdateCloudDiscoveryMetadata",AuthorityGetEndpointMetadataFromNetwork:"authorityGetEndpointMetadataFromNetwork",AuthorityUpdateEndpointMetadata:"authorityUpdateEndpointMetadata",AuthorityUpdateMetadataWithRegionalInformation:"authorityUpdateMetadataWithRegionalInformation",RegionDiscoveryDetectRegion:"regionDiscoveryDetectRegion",RegionDiscoveryGetRegionFromIMDS:"regionDiscoveryGetRegionFromIMDS",RegionDiscoveryGetCurrentVersion:"regionDiscoveryGetCurrentVersion",AcquireTokenByCodeAsync:"acquireTokenByCodeAsync",GetEndpointMetadataFromNetwork:"getEndpointMetadataFromNetwork",GetCloudDiscoveryMetadataFromNetworkMeasurement:"getCloudDiscoveryMetadataFromNetworkMeasurement",HandleRedirectPromiseMeasurement:"handleRedirectPromise",HandleNativeRedirectPromiseMeasurement:"handleNativeRedirectPromise",UpdateCloudDiscoveryMetadataMeasurement:"updateCloudDiscoveryMetadataMeasurement",UsernamePasswordClientAcquireToken:"usernamePasswordClientAcquireToken",NativeMessageHandlerHandshake:"nativeMessageHandlerHandshake",NativeGenerateAuthResult:"nativeGenerateAuthResult",RemoveHiddenIframe:"removeHiddenIframe",ClearTokensAndKeysWithClaims:"clearTokensAndKeysWithClaims",CacheManagerGetRefreshToken:"cacheManagerGetRefreshToken",GeneratePkceCodes:"generatePkceCodes",GenerateCodeVerifier:"generateCodeVerifier",GenerateCodeChallengeFromVerifier:"generateCodeChallengeFromVerifier",Sha256Digest:"sha256Digest",GetRandomValues:"getRandomValues"},vo=new Map([[yo.AcquireTokenByCode,"ATByCode"],[yo.AcquireTokenByRefreshToken,"ATByRT"],[yo.AcquireTokenSilent,"ATS"],[yo.AcquireTokenSilentAsync,"ATSAsync"],[yo.AcquireTokenPopup,"ATPopup"],[yo.AcquireTokenRedirect,"ATRedirect"],[yo.CryptoOptsGetPublicKeyThumbprint,"CryptoGetPKThumb"],[yo.CryptoOptsSignJwt,"CryptoSignJwt"],[yo.SilentCacheClientAcquireToken,"SltCacheClientAT"],[yo.SilentIframeClientAcquireToken,"SltIframeClientAT"],[yo.SilentRefreshClientAcquireToken,"SltRClientAT"],[yo.SsoSilent,"SsoSlt"],[yo.StandardInteractionClientGetDiscoveredAuthority,"StdIntClientGetDiscAuth"],[yo.FetchAccountIdWithNativeBroker,"FetchAccIdWithNtvBroker"],[yo.NativeInteractionClientAcquireToken,"NtvIntClientAT"],[yo.BaseClientCreateTokenRequestHeaders,"BaseClientCreateTReqHead"],[yo.RefreshTokenClientExecutePostToTokenEndpoint,"RTClientExecPost"],[yo.AuthorizationCodeClientExecutePostToTokenEndpoint,"AuthCodeClientExecPost"],[yo.BrokerHandhshake,"BrokerHandshake"],[yo.AcquireTokenByRefreshTokenInBroker,"ATByRTInBroker"],[yo.AcquireTokenByBroker,"ATByBroker"],[yo.RefreshTokenClientExecuteTokenRequest,"RTClientExecTReq"],[yo.RefreshTokenClientAcquireToken,"RTClientAT"],[yo.RefreshTokenClientAcquireTokenWithCachedRefreshToken,"RTClientATWithCachedRT"],[yo.RefreshTokenClientAcquireTokenByRefreshToken,"RTClientATByRT"],[yo.RefreshTokenClientCreateTokenRequestBody,"RTClientCreateTReqBody"],[yo.AcquireTokenFromCache,"ATFromCache"],[yo.SilentFlowClientAcquireCachedToken,"SltFlowClientATCached"],[yo.SilentFlowClientGenerateResultFromCacheRecord,"SltFlowClientGenResFromCache"],[yo.AcquireTokenBySilentIframe,"ATBySltIframe"],[yo.InitializeBaseRequest,"InitBaseReq"],[yo.InitializeSilentRequest,"InitSltReq"],[yo.InitializeClientApplication,"InitClientApplication"],[yo.SilentIframeClientTokenHelper,"SIClientTHelper"],[yo.SilentHandlerInitiateAuthRequest,"SHandlerInitAuthReq"],[yo.SilentHandlerMonitorIframeForHash,"SltHandlerMonitorIframeForHash"],[yo.SilentHandlerLoadFrame,"SHandlerLoadFrame"],[yo.SilentHandlerLoadFrameSync,"SHandlerLoadFrameSync"],[yo.StandardInteractionClientCreateAuthCodeClient,"StdIntClientCreateAuthCodeClient"],[yo.StandardInteractionClientGetClientConfiguration,"StdIntClientGetClientConf"],[yo.StandardInteractionClientInitializeAuthorizationRequest,"StdIntClientInitAuthReq"],[yo.StandardInteractionClientInitializeAuthorizationCodeRequest,"StdIntClientInitAuthCodeReq"],[yo.GetAuthCodeUrl,"GetAuthCodeUrl"],[yo.HandleCodeResponseFromServer,"HandleCodeResFromServer"],[yo.HandleCodeResponse,"HandleCodeResp"],[yo.UpdateTokenEndpointAuthority,"UpdTEndpointAuth"],[yo.AuthClientAcquireToken,"AuthClientAT"],[yo.AuthClientExecuteTokenRequest,"AuthClientExecTReq"],[yo.AuthClientCreateTokenRequestBody,"AuthClientCreateTReqBody"],[yo.AuthClientCreateQueryString,"AuthClientCreateQueryStr"],[yo.PopTokenGenerateCnf,"PopTGenCnf"],[yo.PopTokenGenerateKid,"PopTGenKid"],[yo.HandleServerTokenResponse,"HandleServerTRes"],[yo.DeserializeResponse,"DeserializeRes"],[yo.AuthorityFactoryCreateDiscoveredInstance,"AuthFactCreateDiscInst"],[yo.AuthorityResolveEndpointsAsync,"AuthResolveEndpointsAsync"],[yo.AuthorityResolveEndpointsFromLocalSources,"AuthResolveEndpointsFromLocal"],[yo.AuthorityGetCloudDiscoveryMetadataFromNetwork,"AuthGetCDMetaFromNet"],[yo.AuthorityUpdateCloudDiscoveryMetadata,"AuthUpdCDMeta"],[yo.AuthorityGetEndpointMetadataFromNetwork,"AuthUpdCDMetaFromNet"],[yo.AuthorityUpdateEndpointMetadata,"AuthUpdEndpointMeta"],[yo.AuthorityUpdateMetadataWithRegionalInformation,"AuthUpdMetaWithRegInfo"],[yo.RegionDiscoveryDetectRegion,"RegDiscDetectReg"],[yo.RegionDiscoveryGetRegionFromIMDS,"RegDiscGetRegFromIMDS"],[yo.RegionDiscoveryGetCurrentVersion,"RegDiscGetCurrentVer"],[yo.AcquireTokenByCodeAsync,"ATByCodeAsync"],[yo.GetEndpointMetadataFromNetwork,"GetEndpointMetaFromNet"],[yo.GetCloudDiscoveryMetadataFromNetworkMeasurement,"GetCDMetaFromNet"],[yo.HandleRedirectPromiseMeasurement,"HandleRedirectPromise"],[yo.HandleNativeRedirectPromiseMeasurement,"HandleNtvRedirectPromise"],[yo.UpdateCloudDiscoveryMetadataMeasurement,"UpdateCDMeta"],[yo.UsernamePasswordClientAcquireToken,"UserPassClientAT"],[yo.NativeMessageHandlerHandshake,"NtvMsgHandlerHandshake"],[yo.NativeGenerateAuthResult,"NtvGenAuthRes"],[yo.RemoveHiddenIframe,"RemoveHiddenIframe"],[yo.ClearTokensAndKeysWithClaims,"ClearTAndKeysWithClaims"],[yo.CacheManagerGetRefreshToken,"CacheManagerGetRT"],[yo.GeneratePkceCodes,"GenPkceCodes"],[yo.GenerateCodeVerifier,"GenCodeVerifier"],[yo.GenerateCodeChallengeFromVerifier,"GenCodeChallengeFromVerifier"],[yo.Sha256Digest,"Sha256Digest"],[yo.GetRandomValues,"GetRandomValues"]]),Co=1,wo=2,To=new Set(["accessTokenSize","durationMs","idTokenSize","matsSilentStatus","matsHttpStatus","refreshTokenSize","queuedTimeMs","startTimeMs","status","multiMatchedAT","multiMatchedID","multiMatchedRT"]),ko=(e,t,r,o,n)=>(...i)=>{r.trace(`Executing function ${t}`);const s=o?.startMeasurement(t,n);if(n){const e=t+"CallCount";o?.incrementFields({[e]:1},n)}try{const o=e(...i);return s?.end({success:!0}),r.trace(`Returning result from ${t}`),o}catch(e){r.trace(`Error occurred in ${t}`);try{r.trace(JSON.stringify(e))}catch(e){r.trace("Unable to print error message.")}throw s?.end({success:!1},e),e}},Io=(e,t,r,o,n)=>(...i)=>{r.trace(`Executing function ${t}`);const s=o?.startMeasurement(t,n);if(n){const e=t+"CallCount";o?.incrementFields({[e]:1},n)}return o?.setPreQueueTime(t,n),e(...i).then((e=>(r.trace(`Returning result from ${t}`),s?.end({success:!0}),e))).catch((e=>{r.trace(`Error occurred in ${t}`);try{r.trace(JSON.stringify(e))}catch(e){r.trace("Unable to print error message.")}throw s?.end({success:!1},e),e}))};class Ao{constructor(e,t,r,o){this.networkInterface=e,this.logger=t,this.performanceClient=r,this.correlationId=o}async detectRegion(e,t){this.performanceClient?.addQueueMeasurement(yo.RegionDiscoveryDetectRegion,this.correlationId);let o=e;if(o)t.region_source=se;else{const e=Ao.IMDS_OPTIONS;try{const n=await Io(this.getRegionFromIMDS.bind(this),yo.RegionDiscoveryGetRegionFromIMDS,this.logger,this.performanceClient,this.correlationId)(r.IMDS_VERSION,e);if(n.status===oe&&(o=n.body,t.region_source=ae),n.status===ne){const r=await Io(this.getCurrentVersion.bind(this),yo.RegionDiscoveryGetCurrentVersion,this.logger,this.performanceClient,this.correlationId)(e);if(!r)return t.region_source=ie,null;const n=await Io(this.getRegionFromIMDS.bind(this),yo.RegionDiscoveryGetRegionFromIMDS,this.logger,this.performanceClient,this.correlationId)(r,e);n.status===oe&&(o=n.body,t.region_source=ae)}}catch(e){return t.region_source=ie,null}}return o||(t.region_source=ie),o||null}async getRegionFromIMDS(e,t){return this.performanceClient?.addQueueMeasurement(yo.RegionDiscoveryGetRegionFromIMDS,this.correlationId),this.networkInterface.sendGetRequestAsync(`${r.IMDS_ENDPOINT}?api-version=${e}&format=text`,t,r.IMDS_TIMEOUT)}async getCurrentVersion(e){this.performanceClient?.addQueueMeasurement(yo.RegionDiscoveryGetCurrentVersion,this.correlationId);try{const t=await this.networkInterface.sendGetRequestAsync(`${r.IMDS_ENDPOINT}?format=json`,e);return t.status===ne&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch(e){return null}}}Ao.IMDS_OPTIONS={headers:{Metadata:"true"}};class bo{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 Ao(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(r.CIAM_AUTH_URL))return Pr;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case r.ADFS:return Rr;case r.DSTS:return _r}return Er}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 xr(e),this._canonicalAuthority.validateAsUri(),this._canonicalAuthorityUrlComponents=null}get canonicalAuthorityUrlComponents(){return this._canonicalAuthorityUrlComponents||(this._canonicalAuthorityUrlComponents=this._canonicalAuthority.getUrlComponents()),this._canonicalAuthorityUrlComponents}get hostnameAndPort(){return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase()}get tenant(){return this.canonicalAuthorityUrlComponents.PathSegments[0]}get authorizationEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.authorization_endpoint);throw vt(Re)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw vt(Re)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw vt(Re)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw vt(at);return this.replacePath(this.metadata.end_session_endpoint)}throw vt(Re)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw vt(Re)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw vt(Re)}canReplaceTenant(e){return 1===e.PathSegments.length&&!bo.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===Er&&this.protocolMode===Or.AAD}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const r=new xr(this.metadata.canonical_authority).getUrlComponents(),o=r.PathSegments;return this.canonicalAuthorityUrlComponents.PathSegments.forEach(((e,n)=>{let i=o[n];if(0===n&&this.canReplaceTenant(r)){const e=new xr(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];i!==e&&(this.logger.verbose(`Replacing tenant domain name ${i} with id ${e}`),i=e)}e!==i&&(t=t.replace(`/${i}/`,`/${e}/`))})),this.replaceTenant(t)}get defaultOpenIdConfigurationEndpoint(){const e=this.hostnameAndPort;return this.canonicalAuthority.endsWith("v2.0/")||this.authorityType===Rr||this.protocolMode!==Or.AAD&&!this.isAliasOfKnownMicrosoftAuthority(e)?`${this.canonicalAuthority}.well-known/openid-configuration`:`${this.canonicalAuthority}v2.0/.well-known/openid-configuration`}discoveryComplete(){return!!this.metadata}async resolveEndpointsAsync(){this.performanceClient?.addQueueMeasurement(yo.AuthorityResolveEndpointsAsync,this.correlationId);const e=this.getCurrentMetadataEntity(),t=await Io(this.updateCloudDiscoveryMetadata.bind(this),yo.AuthorityUpdateCloudDiscoveryMetadata,this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const r=await Io(this.updateEndpointMetadata.bind(this),yo.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);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:zt(),jwks_uri:""}),e}updateCachedMetadata(e,t,r){t!==K&&r?.source!==K&&(e.expiresAt=zt(),e.canonical_authority=this.canonicalAuthority);const o=this.cacheManager.generateAuthorityMetadataCacheKey(e.preferred_cache);this.cacheManager.setAuthorityMetadata(o,e),this.metadata=e}async updateEndpointMetadata(e){this.performanceClient?.addQueueMeasurement(yo.AuthorityUpdateEndpointMetadata,this.correlationId);const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===G&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){Kt(e,await Io(this.updateMetadataWithRegionalInformation.bind(this),yo.AuthorityUpdateMetadataWithRegionalInformation,this.logger,this.performanceClient,this.correlationId)(t.metadata),!1),e.canonical_authority=this.canonicalAuthority}return t.source}let r=await Io(this.getEndpointMetadataFromNetwork.bind(this),yo.AuthorityGetEndpointMetadataFromNetwork,this.logger,this.performanceClient,this.correlationId)();if(r)return this.authorityOptions.azureRegionConfiguration?.azureRegion&&(r=await Io(this.updateMetadataWithRegionalInformation.bind(this),yo.AuthorityUpdateMetadataWithRegionalInformation,this.logger,this.performanceClient,this.correlationId)(r)),Kt(e,r,!0),j;throw vt(Pe,this.defaultOpenIdConfigurationEndpoint)}updateEndpointMetadataFromLocalSources(e){this.logger.verbose("Attempting to get endpoint metadata from authority configuration");const t=this.getEndpointMetadataFromConfig();if(t)return this.logger.verbose("Found endpoint metadata in authority configuration"),Kt(e,t,!1),{source:z};if(this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values."),this.authorityOptions.skipAuthorityMetadataCache)this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache.");else{const t=this.getEndpointMetadataFromHardcodedValues();if(t)return Kt(e,t,!1),{source:G,metadata:t};this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.")}const r=Gt(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!r?(this.logger.verbose("Found endpoint metadata in the cache."),{source:K}):(r&&this.logger.verbose("The metadata entity is expired."),null)}isAuthoritySameType(e){return new xr(e.canonical_authority).getUrlComponents().PathSegments.length===this.canonicalAuthorityUrlComponents.PathSegments.length}getEndpointMetadataFromConfig(){if(this.authorityOptions.authorityMetadata)try{return JSON.parse(this.authorityOptions.authorityMetadata)}catch(e){throw Cr(sr)}return null}async getEndpointMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(yo.AuthorityGetEndpointMetadataFromNetwork,this.correlationId);const e={},t=this.defaultOpenIdConfigurationEndpoint;this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${t}`);try{const r=await this.networkInterface.sendGetRequestAsync(t,e),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("Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration"),null)}catch(e){return this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`),null}}getEndpointMetadataFromHardcodedValues(){return this.hostnameAndPort in Lr?Lr[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){this.performanceClient?.addQueueMeasurement(yo.AuthorityUpdateMetadataWithRegionalInformation,this.correlationId);const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if(t!==r.AZURE_REGION_AUTO_DISCOVER_FLAG)return this.regionDiscoveryMetadata.region_outcome=ce,this.regionDiscoveryMetadata.region_used=t,bo.replaceWithRegionalInformation(e,t);const o=await Io(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),yo.RegionDiscoveryDetectRegion,this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(o)return this.regionDiscoveryMetadata.region_outcome=le,this.regionDiscoveryMetadata.region_used=o,bo.replaceWithRegionalInformation(e,o);this.regionDiscoveryMetadata.region_outcome=de}return e}async updateCloudDiscoveryMetadata(e){this.performanceClient?.addQueueMeasurement(yo.AuthorityUpdateCloudDiscoveryMetadata,this.correlationId);const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const r=await Io(this.getCloudDiscoveryMetadataFromNetwork.bind(this),yo.AuthorityGetCloudDiscoveryMetadataFromNetwork,this.logger,this.performanceClient,this.correlationId)();if(r)return jt(e,r,!0),j;throw Cr(ar)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration"),this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities||r.NOT_APPLICABLE}`),this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata||r.NOT_APPLICABLE}`),this.logger.verbosePii(`Canonical Authority: ${e.canonical_authority||r.NOT_APPLICABLE}`);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("Found cloud discovery metadata in authority configuration"),jt(e,t,!1),z;if(this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values."),this.options.skipAuthorityMetadataCache)this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache.");else{const t=(o=this.hostnameAndPort,$r(Dr.metadata,o));if(t)return this.logger.verbose("Found cloud discovery metadata from hardcoded values."),jt(e,t,!1),G;this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.")}var o;const n=Gt(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!n?(this.logger.verbose("Found cloud discovery metadata in the cache."),K):(n&&this.logger.verbose("The metadata entity is expired."),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===Pr)return this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host."),bo.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);if(this.authorityOptions.cloudDiscoveryMetadata){this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.");try{this.logger.verbose("Attempting to parse the cloud discovery metadata.");const e=$r(JSON.parse(this.authorityOptions.cloudDiscoveryMetadata).metadata,this.hostnameAndPort);if(this.logger.verbose("Parsed the cloud discovery metadata."),e)return this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata."),e;this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.")}catch(e){throw this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error."),Cr(ir)}}return this.isInKnownAuthorities()?(this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host."),bo.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(yo.AuthorityGetCloudDiscoveryMetadataFromNetwork,this.correlationId);const e=`${r.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let o=null;try{const n=await this.networkInterface.sendGetRequestAsync(e,t);let i,s;if(function(e){return e.hasOwnProperty("tenant_discovery_endpoint")&&e.hasOwnProperty("metadata")}(n.body))i=n.body,s=i.metadata,this.logger.verbosePii(`tenant_discovery_endpoint is: ${i.tenant_discovery_endpoint}`);else{if(!function(e){return e.hasOwnProperty("error")&&e.hasOwnProperty("error_description")}(n.body))return this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse"),null;if(this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${n.status}`),i=n.body,i.error===r.INVALID_INSTANCE)return this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance."),null;this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${i.error}`),this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${i.error_description}`),this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []"),s=[]}this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request."),o=$r(s,this.hostnameAndPort)}catch(e){if(e instanceof ke)this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: ${e.errorCode}\nError Description: ${e.errorMessage}`);else{const t=e;this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: ${t.name}\nError Description: ${t.message}`)}return null}return o||(this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request."),this.logger.verbose("Creating custom Authority for custom domain scenario."),o=bo.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),o}isInKnownAuthorities(){return this.authorityOptions.knownAuthorities.filter((e=>e&&xr.getDomainFromUrl(e).toLowerCase()===this.hostnameAndPort)).length>0}static generateAuthority(e,t){let o;if(t&&t.azureCloudInstance!==At.None){const e=t.tenant?t.tenant:r.DEFAULT_COMMON_TENANT;o=`${t.azureCloudInstance}/${e}/`}return o||e}static createCloudDiscoveryMetadataFromHost(e){return{preferred_network:e,preferred_cache:e,aliases:[e]}}getPreferredCache(){if(this.managedIdentity)return r.DEFAULT_AUTHORITY_HOST;if(this.discoveryComplete())return this.metadata.preferred_cache;throw vt(Re)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return Hr.has(e)}static isPublicCloudAuthority(e){return r.KNOWN_PUBLIC_CLOUDS.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,o){const n=new xr(e);n.validateAsUri();const i=n.getUrlComponents();let s=`${t}.${i.HostNameAndPort}`;this.isPublicCloudAuthority(i.HostNameAndPort)&&(s=`${t}.${r.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`);const a=xr.constructAuthorityUriFromObject({...n.getUrlComponents(),HostNameAndPort:s}).urlString;return o?`${a}?${o}`:a}static replaceWithRegionalInformation(e,t){const r={...e};return r.authorization_endpoint=bo.buildRegionalAuthorityString(r.authorization_endpoint,t),r.token_endpoint=bo.buildRegionalAuthorityString(r.token_endpoint,t),r.end_session_endpoint&&(r.end_session_endpoint=bo.buildRegionalAuthorityString(r.end_session_endpoint,t)),r}static transformCIAMAuthority(e){let t=e;const o=new xr(e).getUrlComponents();if(0===o.PathSegments.length&&o.HostNameAndPort.endsWith(r.CIAM_AUTH_URL)){t=`${t}${o.HostNameAndPort.split(".")[0]}${r.AAD_TENANT_DOMAIN_SUFFIX}`}return t}}function So(e){return e.endsWith(r.FORWARD_SLASH)?e:`${e}${r.FORWARD_SLASH}`}function Eo(e){const t=e.cloudDiscoveryMetadata;let r;if(t)try{r=JSON.parse(t)}catch(e){throw Cr(ir)}return{canonicalAuthority:e.authority?So(e.authority):void 0,knownAuthorities:e.knownAuthorities,cloudDiscoveryMetadata:r}}async function Ro(e,t,r,o,n,i,s){s?.addQueueMeasurement(yo.AuthorityFactoryCreateDiscoveredInstance,i);const a=bo.transformCIAMAuthority(So(e)),c=new bo(a,t,r,o,n,i,s);try{return await Io(c.resolveEndpointsAsync.bind(c),yo.AuthorityResolveEndpointsAsync,n,s,i)(),c}catch(e){throw vt(Re)}}bo.reservedTenantDomains=new Set(["{tenant}","{tenantid}",I,b,A]);class _o{constructor(e,t){this.config=function({authOptions:e,systemOptions:t,loggerOptions:r,cacheOptions:o,storageInterface:n,networkInterface:i,cryptoInterface:s,clientCredentials:a,libraryInfo:c,telemetry:l,serverTelemetryManager:d,persistencePlugin:u,serializableCache:h}){const g={...Qr,...r};return{authOptions:(p=e,{clientCapabilities:[],azureCloudOptions:eo,skipAuthorityMetadataCache:!1,instanceAware:!1,...p}),systemOptions:{...Vr,...t},loggerOptions:g,cacheOptions:{...Yr,...o},storageInterface:n||new Wr(e.clientId,Ct,new Tt(g)),networkInterface:i||Jr,cryptoInterface:s||Ct,clientCredentials:a||Zr,libraryInfo:{...Xr,...c},telemetry:{...to,...l},serverTelemetryManager:d||null,persistencePlugin:u||null,serializableCache:h||null};var p}(e),this.logger=new Tt(this.config.loggerOptions,kt,It),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.networkManager=new io(this.networkClient,this.cacheManager),this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}createTokenRequestHeaders(e){const t={};if(t[l]=r.URL_FORM_CONTENT_TYPE,!this.config.systemOptions.preventCorsPreflight&&e)switch(e.type){case so:try{const r=Ir(e.credential);t[u]=`Oid:${r.uid}@${r.utid}`}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case ao:t[u]=`UPN: ${e.credential}`}return t}async executePostToTokenEndpoint(e,t,r,o,n,i){i&&this.performanceClient?.addQueueMeasurement(i,n);const s=await this.networkManager.sendPostRequest(o,e,{body:t,headers:r});return this.performanceClient?.addFields({refreshTokenSize:s.body.refresh_token?.length||0,httpVerToken:s.headers?.[m]||""},n),this.config.serverTelemetryManager&&s.status<500&&429!==s.status&&this.config.serverTelemetryManager.clearTelemetryCache(),s}async updateAuthority(e,t){this.performanceClient?.addQueueMeasurement(yo.UpdateTokenEndpointAuthority,t);const r=`https://${e}/${this.authority.tenant}/`,o=await Ro(r,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=o}createTokenQueryParameters(e){const t=new fo;return e.tokenQueryParameters&&t.addExtraQueryParameters(e.tokenQueryParameters),t.createQueryString()}}const Po="no_tokens_found",Mo="native_account_unavailable",Oo="refresh_token_expired",No="interaction_required",qo="consent_required",Uo="login_required",xo="bad_token";var Lo=Object.freeze({__proto__:null,badToken:xo,consentRequired:qo,interactionRequired:No,loginRequired:Uo,nativeAccountUnavailable:Mo,noTokensFound:Po,refreshTokenExpired:Oo});const Do=[No,qo,Uo,xo],Ho=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token"],Bo={[Po]:"No refresh token found in the cache. Please sign-in.",[Mo]:"The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API.",[Oo]:"Refresh token has expired.",[xo]:"Identity provider returned bad_token due to an expired or invalid refresh token. Please invoke an interactive API to resolve."},$o={noTokensFoundError:{code:Po,desc:Bo[Po]},native_account_unavailable:{code:Mo,desc:Bo[Mo]},bad_token:{code:xo,desc:Bo[xo]}};class Fo extends ke{constructor(e,t,o,n,i,s,a,c){super(e,t,o),Object.setPrototypeOf(this,Fo.prototype),this.timestamp=n||r.EMPTY_STRING,this.traceId=i||r.EMPTY_STRING,this.correlationId=s||r.EMPTY_STRING,this.claims=a||r.EMPTY_STRING,this.name="InteractionRequiredAuthError",this.errorNo=c}}function zo(e,t,r){const o=!!e&&Do.indexOf(e)>-1,n=!!r&&Ho.indexOf(r)>-1,i=!!t&&Do.some((e=>t.indexOf(e)>-1));return o||i||n}function Ko(e){return new Fo(e,Bo[e])}class jo{static setRequestState(e,t,o){const n=jo.generateLibraryState(e,o);return t?`${n}${r.RESOURCE_DELIM}${t}`:n}static generateLibraryState(e,t){if(!e)throw vt(Xe);const r={id:e.createNewGuid()};t&&(r.meta=t);const o=JSON.stringify(r);return e.base64Encode(o)}static parseRequestState(e,t){if(!e)throw vt(Xe);if(!t)throw vt(Oe);try{const o=t.split(r.RESOURCE_DELIM),n=o[0],i=o.length>1?o.slice(1).join(r.RESOURCE_DELIM):r.EMPTY_STRING,s=e.base64Decode(n),a=JSON.parse(s);return{userRequestState:i||r.EMPTY_STRING,libraryState:a}}catch(e){throw vt(Oe)}}}const Go="sw";class Wo{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){this.performanceClient?.addQueueMeasurement(yo.PopTokenGenerateCnf,e.correlationId);const r=await Io(this.generateKid.bind(this),yo.PopTokenGenerateCnf,t,this.performanceClient,e.correlationId)(e),o=this.cryptoUtils.base64UrlEncode(JSON.stringify(r));return{kid:r.kid,reqCnfString:o}}async generateKid(e){this.performanceClient?.addQueueMeasurement(yo.PopTokenGenerateKid,e.correlationId);return{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:Go}}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 xr(i):void 0,d=l?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:Et(),m:n?.toUpperCase(),u:d?.HostNameAndPort,nonce:a||this.cryptoUtils.createNewGuid(),p:d?.AbsolutePath,q:d?.QueryString?[[],d.QueryString]:void 0,client_claims:s||void 0,...o},t,c,r.correlationId)}}class Vo{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}class Qo{constructor(e,t,r,o,n,i,s){this.clientId=e,this.cacheStorage=t,this.cryptoObj=r,this.logger=o,this.serializableCache=n,this.persistencePlugin=i,this.performanceClient=s}validateServerAuthorizationCodeResponse(e,t){if(!e.state||!t)throw e.state?vt(qe,"Cached State"):vt(qe,"Server State");let r,o;try{r=decodeURIComponent(e.state)}catch(t){throw vt(Oe,e.state)}try{o=decodeURIComponent(t)}catch(t){throw vt(Oe,e.state)}if(r!==o)throw vt(Ne);if(e.error||e.error_description||e.suberror){const t=function(e){const t="code=",r=e.error_uri?.lastIndexOf(t);return r&&r>=0?e.error_uri?.substring(r+5):void 0}(e);if(zo(e.error,e.error_description,e.suberror))throw new Fo(e.error||"",e.error_description,e.suberror,e.timestamp||"",e.trace_id||"",e.correlation_id||"",e.claims||"",t);throw new oo(e.error||"",e.error_description,e.suberror,t)}}validateTokenResponse(e,t){if(e.error||e.error_description||e.suberror){const a=`Error(s): ${e.error_codes||r.NOT_AVAILABLE} - Timestamp: ${e.timestamp||r.NOT_AVAILABLE} - Description: ${e.error_description||r.NOT_AVAILABLE} - Correlation ID: ${e.correlation_id||r.NOT_AVAILABLE} - Trace ID: ${e.trace_id||r.NOT_AVAILABLE}`,c=e.error_codes?.length?e.error_codes[0]:void 0,l=new oo(e.error,a,e.suberror,c,e.status);if(t&&e.status&&e.status>=i&&e.status<=s)return void this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.\n${l}`);if(t&&e.status&&e.status>=o&&e.status<=n)return void this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.\n${l}`);if(zo(e.error,e.error_description,e.suberror))throw new Fo(e.error,e.error_description,e.suberror,e.timestamp||r.EMPTY_STRING,e.trace_id||r.EMPTY_STRING,e.correlation_id||r.EMPTY_STRING,e.claims||r.EMPTY_STRING,c);throw l}}async handleServerTokenResponse(e,t,o,n,i,s,a,c,l){let d,u;if(this.performanceClient?.addQueueMeasurement(yo.HandleServerTokenResponse,e.correlation_id),e.id_token){if(d=bt(e.id_token||r.EMPTY_STRING,this.cryptoObj.base64Decode),i&&i.nonce&&d.nonce!==i.nonce)throw vt(Ue);if(n.maxAge||0===n.maxAge){const e=d.auth_time;if(!e)throw vt(xe);St(e,n.maxAge)}}this.homeAccountIdentifier=Nr.generateHomeAccountId(e.client_info||r.EMPTY_STRING,t.authorityType,this.logger,this.cryptoObj,d),i&&i.state&&(u=jo.parseRequestState(this.cryptoObj,i.state)),e.key_id=e.key_id||n.sshKid||void 0;const h=this.generateCacheRecord(e,t,o,n,d,s,i);let g;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("Persistence enabled, calling beforeCacheAccess"),g=new Vo(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(g)),a&&!c&&h.account){const e=h.account.generateAccountKey();if(!this.cacheStorage.getAccount(e,this.logger))return this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache"),await Qo.generateAuthenticationResult(this.cryptoObj,t,h,!1,n,d,u,void 0,l)}await this.cacheStorage.saveCacheRecord(h,n.storeInCache,n.correlationId)}finally{this.persistencePlugin&&this.serializableCache&&g&&(this.logger.verbose("Persistence enabled, calling afterCacheAccess"),await this.persistencePlugin.afterCacheAccess(g))}return Qo.generateAuthenticationResult(this.cryptoObj,t,h,!1,n,d,u,e,l)}generateCacheRecord(e,t,r,o,n,i,s){const a=t.getPreferredCache();if(!a)throw vt(Ye);const c=Mr(n);let l,d;e.id_token&&n&&(l=Mt(this.homeAccountIdentifier,a,e.id_token,this.clientId,c||""),d=Yo(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,n,e.client_info,a,c,s,void 0,this.logger));let u=null;if(e.access_token){const n=e.scope?Tr.fromString(e.scope):new Tr(o.scopes||[]),s=("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0,l=("string"==typeof e.ext_expires_in?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,d=("string"==typeof e.refresh_in?parseInt(e.refresh_in,10):e.refresh_in)||void 0,h=r+s,g=h+l,p=d&&d>0?r+d:void 0;u=Ot(this.homeAccountIdentifier,a,e.access_token,this.clientId,c||t.tenant||"",n.printScopes(),h,g,this.cryptoObj.base64Decode,p,e.token_type,i,e.key_id,o.claims,o.requestedClaimsHash)}let h=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)}h=Nt(this.homeAccountIdentifier,a,e.refresh_token,this.clientId,e.foci,i,t)}let g=null;return e.foci&&(g={clientId:this.clientId,environment:a,familyId:e.foci}),{account:d,idToken:l,accessToken:u,refreshToken:h,appMetadata:g}}static async generateAuthenticationResult(e,t,o,n,i,s,a,c,l){let d,u,h=r.EMPTY_STRING,g=[],p=null,m=r.EMPTY_STRING;if(o.accessToken){if(o.accessToken.tokenType!==V.POP||i.popKid)h=o.accessToken.secret;else{const t=new Wo(e),{secret:r,keyId:n}=o.accessToken;if(!n)throw vt(ct);h=await t.signPopToken(r,n,i)}g=Tr.fromString(o.accessToken.target).asArray(),p=new Date(1e3*Number(o.accessToken.expiresOn)),d=new Date(1e3*Number(o.accessToken.extendedExpiresOn)),o.accessToken.refreshOn&&(u=new Date(1e3*Number(o.accessToken.refreshOn)))}o.appMetadata&&(m=o.appMetadata.familyId===B?B:"");const f=s?.oid||s?.sub||"",y=s?.tid||"";c?.spa_accountid&&o.account&&(o.account.nativeAccountId=c?.spa_accountid);const v=o.account?Sr(o.account.getAccountInfo(),void 0,s,o.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:f,tenantId:y,scopes:g,account:v,idToken:o?.idToken?.secret||"",idTokenClaims:s||{},accessToken:h,fromCache:n,expiresOn:p,extExpiresOn:d,refreshOn:u,correlationId:i.correlationId,requestId:l||r.EMPTY_STRING,familyId:m,tokenType:o.accessToken?.tokenType||r.EMPTY_STRING,state:a?a.userRequestState:r.EMPTY_STRING,cloudGraphHostName:o.account?.cloudGraphHostName||r.EMPTY_STRING,msGraphHost:o.account?.msGraphHost||r.EMPTY_STRING,code:c?.spa_code,fromNativeBroker:!1}}}function Yo(e,t,r,o,n,i,s,a,c,l,d){d?.verbose("setCachedAccount called");const u=e.getAccountKeys().find((e=>e.startsWith(r)));let h=null;u&&(h=e.getAccount(u,d));const g=h||Nr.createAccount({homeAccountId:r,idTokenClaims:n,clientInfo:i,environment:s,cloudGraphHostName:c?.cloud_graph_host_name,msGraphHost:c?.msgraph_host,nativeAccountId:l},t,o),p=g.tenantProfiles||[],m=a||g.realm;if(m&&!p.find((e=>e.tenantId===m))){const e=br(r,g.localAccountId,m,n);p.push(e)}return g.tenantProfiles=p,g}async function Jo(e,t,r){if("string"==typeof e)return e;return e({clientId:t,tokenEndpoint:r})}class Xo extends _o{constructor(e,t){super(e,t),this.includeRedirectUri=!0,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async getAuthCodeUrl(e){this.performanceClient?.addQueueMeasurement(yo.GetAuthCodeUrl,e.correlationId);const t=await Io(this.createAuthCodeUrlQueryString.bind(this),yo.AuthClientCreateQueryString,this.logger,this.performanceClient,e.correlationId)(e);return xr.appendQueryString(this.authority.authorizationEndpoint,t)}async acquireToken(e,t){if(this.performanceClient?.addQueueMeasurement(yo.AuthClientAcquireToken,e.correlationId),!e.code)throw vt($e);const r=Et(),o=await Io(this.executeTokenRequest.bind(this),yo.AuthClientExecuteTokenRequest,this.logger,this.performanceClient,e.correlationId)(this.authority,e),n=o.headers?.[p],i=new Qo(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin,this.performanceClient);return i.validateTokenResponse(o.body),Io(i.handleServerTokenResponse.bind(i),yo.HandleServerTokenResponse,this.logger,this.performanceClient,e.correlationId)(o.body,this.authority,r,e,t,void 0,void 0,void 0,n)}handleFragmentResponse(e,t){if(new Qo(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,null,null).validateServerAuthorizationCodeResponse(e,t),!e.code)throw vt(it);return e}getLogoutUri(e){if(!e)throw Cr(rr);const t=this.createLogoutUrlQueryString(e);return xr.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(yo.AuthClientExecuteTokenRequest,t.correlationId);const r=this.createTokenQueryParameters(t),o=xr.appendQueryString(e.tokenEndpoint,r),n=await Io(this.createTokenRequestBody.bind(this),yo.AuthClientCreateTokenRequestBody,this.logger,this.performanceClient,t.correlationId)(t);let i;if(t.clientInfo)try{const e=kr(t.clientInfo,this.cryptoUtils.base64Decode);i={credential:`${e.uid}${L.CLIENT_INFO_SEPARATOR}${e.utid}`,type:so}}catch(e){this.logger.verbose("Could not parse client info for CCS Header: "+e)}const s=this.createTokenRequestHeaders(i||t.ccsCredential),a={clientId:t.tokenBodyParameters?.clientId||this.config.authOptions.clientId,authority:e.canonicalAuthority,scopes:t.scopes,claims:t.claims,authenticationScheme:t.authenticationScheme,resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,sshKid:t.sshKid};return Io(this.executePostToTokenEndpoint.bind(this),yo.AuthorizationCodeClientExecutePostToTokenEndpoint,this.logger,this.performanceClient,t.correlationId)(o,n,s,a,t.correlationId,yo.AuthorizationCodeClientExecutePostToTokenEndpoint)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(yo.AuthClientCreateTokenRequestBody,e.correlationId);const t=new fo;if(t.addClientId(e.tokenBodyParameters?.[co]||this.config.authOptions.clientId),this.includeRedirectUri?t.addRedirectUri(e.redirectUri):mo.validateRedirectUri(e.redirectUri),t.addScopes(e.scopes,!0,this.oidcDefaultScopes),t.addAuthorizationCode(e.code),t.addLibraryInfo(this.config.libraryInfo),t.addApplicationTelemetry(this.config.telemetry.application),t.addThrottling(),this.serverTelemetryManager&&!ro(this.config)&&t.addServerTelemetry(this.serverTelemetryManager),e.codeVerifier&&t.addCodeVerifier(e.codeVerifier),this.config.clientCredentials.clientSecret&&t.addClientSecret(this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;t.addClientAssertion(await Jo(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),t.addClientAssertionType(r.assertionType)}if(t.addGrantType(O),t.addClientInfo(),e.authenticationScheme===V.POP){const r=new Wo(this.cryptoUtils,this.performanceClient);let o;if(e.popKid)o=this.cryptoUtils.encodeKid(e.popKid);else{o=(await Io(r.generateCnf.bind(r),yo.PopTokenGenerateCnf,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}t.addPopToken(o)}else if(e.authenticationScheme===V.SSH){if(!e.sshJwk)throw Cr(cr);t.addSshJwk(e.sshJwk)}const r=e.correlationId||this.config.cryptoInterface.createNewGuid();let o;if(t.addCorrelationId(r),(!wr.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&t.addClaims(e.claims,this.config.authOptions.clientCapabilities),e.clientInfo)try{const t=kr(e.clientInfo,this.cryptoUtils.base64Decode);o={credential:`${t.uid}${L.CLIENT_INFO_SEPARATOR}${t.utid}`,type:so}}catch(e){this.logger.verbose("Could not parse client info for CCS Header: "+e)}else o=e.ccsCredential;if(this.config.systemOptions.preventCorsPreflight&&o)switch(o.type){case so:try{const e=Ir(o.credential);t.addCcsOid(e)}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case ao:t.addCcsUpn(o.credential)}return e.tokenBodyParameters&&t.addExtraQueryParameters(e.tokenBodyParameters),!e.enableSpaAuthorizationCode||e.tokenBodyParameters&&e.tokenBodyParameters[go]||t.addExtraQueryParameters({[go]:"1"}),t.createQueryString()}async createAuthCodeUrlQueryString(e){this.performanceClient?.addQueueMeasurement(yo.AuthClientCreateQueryString,e.correlationId);const t=new fo;t.addClientId(e.extraQueryParameters?.[co]||this.config.authOptions.clientId);const r=[...e.scopes||[],...e.extraScopesToConsent||[]];t.addScopes(r,!0,this.oidcDefaultScopes),t.addRedirectUri(e.redirectUri);const o=e.correlationId||this.config.cryptoInterface.createNewGuid();if(t.addCorrelationId(o),t.addResponseMode(e.responseMode),t.addResponseTypeCode(),t.addLibraryInfo(this.config.libraryInfo),ro(this.config)||t.addApplicationTelemetry(this.config.telemetry.application),t.addClientInfo(),e.codeChallenge&&e.codeChallengeMethod&&t.addCodeChallengeParams(e.codeChallenge,e.codeChallengeMethod),e.prompt&&t.addPrompt(e.prompt),e.domainHint&&t.addDomainHint(e.domainHint),e.prompt!==R.SELECT_ACCOUNT)if(e.sid&&e.prompt===R.NONE)this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request"),t.addSid(e.sid);else if(e.account){const r=this.extractAccountSid(e.account);let o=this.extractLoginHint(e.account);if(o&&e.domainHint&&(this.logger.warning('AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint'),o=null),o){this.logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account"),t.addLoginHint(o);try{const r=Ir(e.account.homeAccountId);t.addCcsOid(r)}catch(e){this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(r&&e.prompt===R.NONE){this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account"),t.addSid(r);try{const r=Ir(e.account.homeAccountId);t.addCcsOid(r)}catch(e){this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(e.loginHint)this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from request"),t.addLoginHint(e.loginHint),t.addCcsUpn(e.loginHint);else if(e.account.username){this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from account"),t.addLoginHint(e.account.username);try{const r=Ir(e.account.homeAccountId);t.addCcsOid(r)}catch(e){this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}}else e.loginHint&&(this.logger.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request"),t.addLoginHint(e.loginHint),t.addCcsUpn(e.loginHint));else this.logger.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints");if(e.nonce&&t.addNonce(e.nonce),e.state&&t.addState(e.state),(e.claims||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&t.addClaims(e.claims,this.config.authOptions.clientCapabilities),this.addExtraQueryParams(e,t),e.nativeBroker&&(t.addNativeBroker(),e.authenticationScheme===V.POP)){const r=new Wo(this.cryptoUtils);let o;if(e.popKid)o=this.cryptoUtils.encodeKid(e.popKid);else{o=(await Io(r.generateCnf.bind(r),yo.PopTokenGenerateCnf,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}t.addPopToken(o)}return t.createQueryString()}createLogoutUrlQueryString(e){const t=new fo;return e.postLogoutRedirectUri&&t.addPostLogoutRedirectUri(e.postLogoutRedirectUri),e.correlationId&&t.addCorrelationId(e.correlationId),e.idTokenHint&&t.addIdTokenHint(e.idTokenHint),e.state&&t.addState(e.state),e.logoutHint&&t.addLogoutHint(e.logoutHint),this.addExtraQueryParams(e,t),t.createQueryString()}addExtraQueryParams(e,t){!(e.extraQueryParameters&&e.extraQueryParameters.hasOwnProperty("instance_aware"))&&this.config.authOptions.instanceAware&&(e.extraQueryParameters=e.extraQueryParameters||{},e.extraQueryParameters.instance_aware="true"),e.extraQueryParameters&&t.addExtraQueryParameters(e.extraQueryParameters)}extractAccountSid(e){return e.idTokenClaims?.sid||null}extractLoginHint(e){return e.idTokenClaims?.login_hint||null}}class Zo extends _o{constructor(e,t){super(e,t)}async acquireToken(e){this.performanceClient?.addQueueMeasurement(yo.RefreshTokenClientAcquireToken,e.correlationId);const t=Et(),r=await Io(this.executeTokenRequest.bind(this),yo.RefreshTokenClientExecuteTokenRequest,this.logger,this.performanceClient,e.correlationId)(e,this.authority),o=r.headers?.[p],n=new Qo(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return n.validateTokenResponse(r.body),Io(n.handleServerTokenResponse.bind(n),yo.HandleServerTokenResponse,this.logger,this.performanceClient,e.correlationId)(r.body,this.authority,t,e,void 0,void 0,!0,e.forceCache,o)}async acquireTokenByRefreshToken(e){if(!e)throw Cr(tr);if(this.performanceClient?.addQueueMeasurement(yo.RefreshTokenClientAcquireTokenByRefreshToken,e.correlationId),!e.account)throw vt(Ve);if(this.cacheManager.isAppMetadataFOCI(e.account.environment))try{return await Io(this.acquireTokenWithCachedRefreshToken.bind(this),yo.RefreshTokenClientAcquireTokenWithCachedRefreshToken,this.logger,this.performanceClient,e.correlationId)(e,!0)}catch(t){const r=t instanceof Fo&&t.errorCode===Po,o=t instanceof oo&&t.errorCode===Z&&t.subError===ee;if(r||o)return Io(this.acquireTokenWithCachedRefreshToken.bind(this),yo.RefreshTokenClientAcquireTokenWithCachedRefreshToken,this.logger,this.performanceClient,e.correlationId)(e,!1);throw t}return Io(this.acquireTokenWithCachedRefreshToken.bind(this),yo.RefreshTokenClientAcquireTokenWithCachedRefreshToken,this.logger,this.performanceClient,e.correlationId)(e,!1)}async acquireTokenWithCachedRefreshToken(e,t){this.performanceClient?.addQueueMeasurement(yo.RefreshTokenClientAcquireTokenWithCachedRefreshToken,e.correlationId);const r=ko(this.cacheManager.getRefreshToken.bind(this.cacheManager),yo.CacheManagerGetRefreshToken,this.logger,this.performanceClient,e.correlationId)(e.account,t,void 0,this.performanceClient,e.correlationId);if(!r)throw Ko(Po);if(r.expiresOn&&Rt(r.expiresOn,e.refreshTokenExpirationOffsetSeconds||300))throw Ko(Oo);const o={...e,refreshToken:r.secret,authenticationScheme:e.authenticationScheme||V.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:so}};try{return await Io(this.acquireToken.bind(this),yo.RefreshTokenClientAcquireToken,this.logger,this.performanceClient,e.correlationId)(o)}catch(e){if(e instanceof Fo&&e.subError===xo){this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache");const e=Pt(r);this.cacheManager.removeRefreshToken(e)}throw e}}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(yo.RefreshTokenClientExecuteTokenRequest,e.correlationId);const r=this.createTokenQueryParameters(e),o=xr.appendQueryString(t.tokenEndpoint,r),n=await Io(this.createTokenRequestBody.bind(this),yo.RefreshTokenClientCreateTokenRequestBody,this.logger,this.performanceClient,e.correlationId)(e),i=this.createTokenRequestHeaders(e.ccsCredential),s={clientId:e.tokenBodyParameters?.clientId||this.config.authOptions.clientId,authority:t.canonicalAuthority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid};return Io(this.executePostToTokenEndpoint.bind(this),yo.RefreshTokenClientExecutePostToTokenEndpoint,this.logger,this.performanceClient,e.correlationId)(o,n,i,s,e.correlationId,yo.RefreshTokenClientExecutePostToTokenEndpoint)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(yo.RefreshTokenClientCreateTokenRequestBody,e.correlationId);const t=e.correlationId,r=new fo;if(r.addClientId(e.tokenBodyParameters?.[co]||this.config.authOptions.clientId),e.redirectUri&&r.addRedirectUri(e.redirectUri),r.addScopes(e.scopes,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),r.addGrantType(N),r.addClientInfo(),r.addLibraryInfo(this.config.libraryInfo),r.addApplicationTelemetry(this.config.telemetry.application),r.addThrottling(),this.serverTelemetryManager&&!ro(this.config)&&r.addServerTelemetry(this.serverTelemetryManager),r.addCorrelationId(t),r.addRefreshToken(e.refreshToken),this.config.clientCredentials.clientSecret&&r.addClientSecret(this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const t=this.config.clientCredentials.clientAssertion;r.addClientAssertion(await Jo(t.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),r.addClientAssertionType(t.assertionType)}if(e.authenticationScheme===V.POP){const t=new Wo(this.cryptoUtils,this.performanceClient);let o;if(e.popKid)o=this.cryptoUtils.encodeKid(e.popKid);else{o=(await Io(t.generateCnf.bind(t),yo.PopTokenGenerateCnf,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString}r.addPopToken(o)}else if(e.authenticationScheme===V.SSH){if(!e.sshJwk)throw Cr(cr);r.addSshJwk(e.sshJwk)}if((!wr.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&r.addClaims(e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case so:try{const t=Ir(e.ccsCredential.credential);r.addCcsOid(t)}catch(e){this.logger.verbose("Could not parse home account ID for CCS Header: "+e)}break;case ao:r.addCcsUpn(e.ccsCredential.credential)}return e.tokenBodyParameters&&r.addExtraQueryParameters(e.tokenBodyParameters),r.createQueryString()}}class en extends _o{constructor(e,t){super(e,t)}async acquireToken(e){try{const[t,r]=await this.acquireCachedToken({...e,scopes:e.scopes?.length?e.scopes:[...a]});if(r===me){this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.");new Zo(this.config,this.performanceClient).acquireTokenByRefreshToken(e).catch((()=>{}))}return t}catch(t){if(t instanceof yt&&t.errorCode===rt){return new Zo(this.config,this.performanceClient).acquireTokenByRefreshToken(e)}throw t}}async acquireCachedToken(e){this.performanceClient?.addQueueMeasurement(yo.SilentFlowClientAcquireCachedToken,e.correlationId);let t=ue;if(e.forceRefresh||!this.config.cacheOptions.claimsBasedCachingEnabled&&!wr.isEmptyObj(e.claims))throw this.setCacheOutcome(he,e.correlationId),vt(rt);if(!e.account)throw vt(Ve);const r=e.account.tenantId||function(e){const t=new xr(e).getUrlComponents(),r=t.PathSegments.slice(-1)[0]?.toLowerCase();switch(r){case I:case A:case b:return;default:return r}}(e.authority),o=this.cacheManager.getTokenKeys(),n=this.cacheManager.getAccessToken(e.account,e,o,r,this.performanceClient,e.correlationId);if(!n)throw this.setCacheOutcome(ge,e.correlationId),vt(rt);if(_t(n.cachedAt)||Rt(n.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(pe,e.correlationId),vt(rt);n.refreshOn&&Rt(n.refreshOn,0)&&(t=me);const i=e.authority||this.authority.getPreferredCache(),s={account:this.cacheManager.readAccountFromCache(e.account),accessToken:n,idToken:this.cacheManager.getIdToken(e.account,o,r,this.performanceClient,e.correlationId),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(i)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await Io(this.generateResultFromCacheRecord.bind(this),yo.SilentFlowClientGenerateResultFromCacheRecord,this.logger,this.performanceClient,e.correlationId)(s,e),t]}setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==ue&&this.logger.info(`Token refresh is required due to cache outcome: ${e}`)}async generateResultFromCacheRecord(e,t){let r;if(this.performanceClient?.addQueueMeasurement(yo.SilentFlowClientGenerateResultFromCacheRecord,t.correlationId),e.idToken&&(r=bt(e.idToken.secret,this.config.cryptoInterface.base64Decode)),t.maxAge||0===t.maxAge){const e=r?.auth_time;if(!e)throw vt(xe);St(e,t.maxAge)}return Qo.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,r)}}const tn={sendGetRequestAsync:()=>Promise.reject(vt(ht)),sendPostRequestAsync:()=>Promise.reject(vt(ht))};const rn="|";function on(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},(()=>rn));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(rn)}({skuArr:a,index:t,skuName:e[0],skuVersion:e[1]})})),a.join(",")}class nn{constructor(e,t){this.cacheOutcome=ue,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||r.EMPTY_STRING,this.wrapperVer=e.wrapperVer||r.EMPTY_STRING,this.telemetryCacheKey=W.CACHE_KEY+L.CACHE_KEY_SEPARATOR+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${W.VALUE_SEPARATOR}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],r=this.getNativeBrokerErrorCode();r?.length&&t.push(`broker_error=${r}`);const o=t.join(W.VALUE_SEPARATOR),n=[e,this.getRegionDiscoveryFields()].join(W.VALUE_SEPARATOR);return[W.SCHEMA_VERSION,n,o].join(W.CATEGORY_SEPARATOR)}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=nn.maxErrorsToSend(e),r=e.failedRequests.slice(0,2*t).join(W.VALUE_SEPARATOR),o=e.errors.slice(0,t).join(W.VALUE_SEPARATOR),n=e.errors.length,i=[n,t<n?W.OVERFLOW_TRUE:W.OVERFLOW_FALSE].join(W.VALUE_SEPARATOR);return[W.SCHEMA_VERSION,e.cacheHits,r,o,i].join(W.CATEGORY_SEPARATOR)}cacheFailedRequest(e){const t=this.getLastRequests();t.errors.length>=W.MAX_CACHED_ERRORS&&(t.failedRequests.shift(),t.failedRequests.shift(),t.errors.shift()),t.failedRequests.push(this.apiId,this.correlationId),e instanceof Error&&e&&e.toString()?e instanceof ke?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(W.UNKNOWN_ERROR),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t)}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e),e.cacheHits}getLastRequests(){return this.cacheManager.getServerTelemetry(this.telemetryCacheKey)||{failedRequests:[],errors:[],cacheHits:0}}clearTelemetryCache(){const e=this.getLastRequests(),t=nn.maxErrorsToSend(e);if(t===e.errors.length)this.cacheManager.removeItem(this.telemetryCacheKey);else{const r={failedRequests:e.failedRequests.slice(2*t),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,r)}}static maxErrorsToSend(e){let t,o=0,n=0;const i=e.errors.length;for(t=0;t<i;t++){const i=e.failedRequests[2*t]||r.EMPTY_STRING,s=e.failedRequests[2*t+1]||r.EMPTY_STRING,a=e.errors[t]||r.EMPTY_STRING;if(n+=i.toString().length+s.toString().length+a.length+3,!(n<W.MAX_LAST_HEADER_BYTES))break;o+=1}return o}getRegionDiscoveryFields(){const e=[];return e.push(this.regionUsed||r.EMPTY_STRING),e.push(this.regionSource||r.EMPTY_STRING),e.push(this.regionOutcome||r.EMPTY_STRING),e.join(",")}updateRegionDiscoveryMetadata(e){this.regionUsed=e.region_used,this.regionSource=e.region_source,this.regionOutcome=e.region_outcome}setCacheOutcome(e){this.cacheOutcome=e}setNativeBrokerErrorCode(e){const t=this.getLastRequests();t.nativeBrokerErrorCode=e,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t)}getNativeBrokerErrorCode(){return this.getLastRequests().nativeBrokerErrorCode}clearNativeBrokerErrorCode(){const e=this.getLastRequests();delete e.nativeBrokerErrorCode,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e)}static makeExtraSkuString(e){return on(e)}}const sn="missing_kid_error",an="missing_alg_error",cn={[sn]:"The JOSE Header for the requested JWT, JWS or JWK object requires a keyId to be configured as the 'kid' header claim. No 'kid' value was provided.",[an]:"The JOSE Header for the requested JWT, JWS or JWK object requires an algorithm to be specified as the 'alg' header claim. No 'alg' value was provided."};class ln extends ke{constructor(e,t){super(e,t),this.name="JoseHeaderError",Object.setPrototypeOf(this,ln.prototype)}}function dn(e){return new ln(e,cn[e])}class un{constructor(e){this.typ=e.typ,this.alg=e.alg,this.kid=e.kid}static getShrHeaderString(e){if(!e.kid)throw dn(sn);if(!e.alg)throw dn(an);const t=new un({typ:e.typ||fe.Pop,kid:e.kid,alg:e.alg});return JSON.stringify(t)}}class hn{startMeasurement(){}endMeasurement(){}flushMeasurement(){return null}}class gn{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:Co,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""},measurement:new hn}}startPerformanceMeasurement(){return new hn}calculateQueuedTime(){return 0}addQueueMeasurement(){}setPreQueueTime(){}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}incrementFields(){}cacheEventByCorrelationId(){}}function pn(e,t,r,o=5){if(e instanceof Error)return e instanceof ke?(r.errorCode=e.errorCode,r.subErrorCode=e.subError,void((e instanceof oo||e instanceof Fo)&&(r.serverErrorNo=e.errorNo))):void(e instanceof jr?r.errorCode=e.errorCode:r.errorStack?.length?t.trace("PerformanceClient.addErrorStack: Stack already exist",r.correlationId):e.stack?.length?(e.stack&&(r.errorStack=function(e,t){if(t<0)return[];const r=e.split("\n")||[];if(r.length<2)return[];const o=[];for(let e=Math.max(r.length-t-1,1);e<r.length;e++){const n=r[e];if(o.length>=t)break;o.push(mn(n))}return o}(e.stack,o)),r.errorName=e.name):t.trace("PerformanceClient.addErrorStack: Input stack is empty",r.correlationId));t.trace("PerformanceClient.addErrorStack: Input error is not instance of Error",r.correlationId)}function mn(e){const t=e.lastIndexOf(" ")+1;if(t<1)return e;const r=e.substring(t);let o=r.lastIndexOf("/");return o=o<0?r.lastIndexOf("\\"):o,o>=0?(e.substring(0,t)+"("+r.substring(o+1)+(")"===r.charAt(r.length-1)?"":")")).trimStart():e.trimStart()}class fn{constructor(e,t,r,o,n,i,s,a){this.authority=t,this.libraryName=o,this.libraryVersion=n,this.applicationTelemetry=i,this.clientId=e,this.logger=r,this.callbacks=new Map,this.eventsByCorrelationId=new Map,this.eventStack=new Map,this.queueMeasurements=new Map,this.preQueueTimeByCorrelationId=new Map,this.intFields=s||new Set;for(const e of To)this.intFields.add(e);this.abbreviations=a||new Map;for(const[e,t]of vo)this.abbreviations.set(e,t)}startPerformanceMeasurement(e,t){return{}}getPreQueueTime(e,t){const r=this.preQueueTimeByCorrelationId.get(t);if(r){if(r.name===e)return r.time;this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue time found for ${e}, unable to add queue measurement`)}else this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue times found for correlationId: ${t}, unable to add queue measurement`)}calculateQueuedTime(e,t){return e<1?(this.logger.trace(`PerformanceClient: preQueueTime should be a positive integer and not ${e}`),0):t<1?(this.logger.trace(`PerformanceClient: currentTime should be a positive integer and not ${t}`),0):t<e?(this.logger.trace("PerformanceClient: currentTime is less than preQueueTime, check how time is being retrieved"),0):t-e}addQueueMeasurement(e,t,r,o){if(!t)return void this.logger.trace(`PerformanceClient.addQueueMeasurement: correlationId not provided for ${e}, cannot add queue measurement`);if(0===r)this.logger.trace(`PerformanceClient.addQueueMeasurement: queue time provided for ${e} is ${r}`);else if(!r)return void this.logger.trace(`PerformanceClient.addQueueMeasurement: no queue time provided for ${e}`);const n={eventName:e,queueTime:o?0:r,manuallyCompleted:o},i=this.queueMeasurements.get(t);if(i)i.push(n),this.queueMeasurements.set(t,i);else{this.logger.trace(`PerformanceClient.addQueueMeasurement: adding correlationId ${t} to queue measurements`);const e=[n];this.queueMeasurements.set(t,e)}this.preQueueTimeByCorrelationId.delete(t)}startMeasurement(e,t){const r=t||this.generateId();t||this.logger.info(`PerformanceClient: No correlation id provided for ${e}, generating`,r),this.logger.trace(`PerformanceClient: Performance measurement started for ${e}`,r);const o={eventId:this.generateId(),status:Co,authority:this.authority,libraryName:this.libraryName,libraryVersion:this.libraryVersion,clientId:this.clientId,name:e,startTimeMs:Date.now(),correlationId:r,appName:this.applicationTelemetry?.appName,appVersion:this.applicationTelemetry?.appVersion};var n,i,s;return this.cacheEventByCorrelationId(o),n=o,i=this.abbreviations,(s=this.eventStack.get(r))&&s.push({name:i.get(n.name)||n.name}),{end:(e,t)=>this.endMeasurement({...o,...e},t),discard:()=>this.discardMeasurements(o.correlationId),add:e=>this.addFields(e,o.correlationId),increment:e=>this.incrementFields(e,o.correlationId),event:o,measurement:new hn}}endMeasurement(e,t){const r=this.eventsByCorrelationId.get(e.correlationId);if(!r)return this.logger.trace(`PerformanceClient: Measurement not found for ${e.eventId}`,e.correlationId),null;const o=e.eventId===r.eventId;let n={totalQueueTime:0,totalQueueCount:0,manuallyCompletedCount:0};e.durationMs=Math.round(e.durationMs||this.getDurationMs(e.startTimeMs));const i=JSON.stringify(function(e,t,r,o){if(!r?.length)return;const n=e=>e.length?e[e.length-1]:void 0,i=t.get(e.name)||e.name,s=n(r);if(s?.name!==i)return;const a=r?.pop();if(!a)return;const c=o instanceof ke?o.errorCode:o instanceof Error?o.name:void 0,l=o instanceof ke?o.subError:void 0;c&&a.childErr!==c&&(a.err=c,l&&(a.subErr=l)),delete a.name,delete a.childErr;const d={...a,dur:e.durationMs};e.success||(d.fail=1);const u=n(r);if(!u)return{[i]:d};let h;if(c&&(u.childErr=c),u[i]){const e=Object.keys(u).filter((e=>e.startsWith(i))).length;h=`${i}_${e+1}`}else h=i;return u[h]=d,u}(e,this.abbreviations,this.eventStack.get(r.correlationId),t));if(o?(n=this.getQueueInfo(e.correlationId),this.discardMeasurements(r.correlationId)):r.incompleteSubMeasurements?.delete(e.eventId),this.logger.trace(`PerformanceClient: Performance measurement ended for ${e.name}: ${e.durationMs} ms`,e.correlationId),!o)return r[e.name+"DurationMs"]=Math.floor(e.durationMs),{...r};t&&pn(t,this.logger,r);let s={...r,...e},a=0;return s.incompleteSubMeasurements?.forEach((t=>{this.logger.trace(`PerformanceClient: Incomplete submeasurement ${t.name} found for ${e.name}`,s.correlationId),a++})),s.incompleteSubMeasurements=void 0,s={...s,queuedTimeMs:n.totalQueueTime,queuedCount:n.totalQueueCount,queuedManuallyCompletedCount:n.manuallyCompletedCount,status:wo,incompleteSubsCount:a,context:i},this.truncateIntegralFields(s),this.emitEvents([s],e.correlationId),s}addFields(e,t){this.logger.trace("PerformanceClient: Updating static fields");const r=this.eventsByCorrelationId.get(t);r?this.eventsByCorrelationId.set(t,{...r,...e}):this.logger.trace("PerformanceClient: Event not found for",t)}incrementFields(e,t){this.logger.trace("PerformanceClient: Updating counters");const r=this.eventsByCorrelationId.get(t);if(r)for(const t in e){if(r.hasOwnProperty(t)){if(isNaN(Number(r[t])))return}else r[t]=0;r[t]+=e[t]}else this.logger.trace("PerformanceClient: Event not found for",t)}cacheEventByCorrelationId(e){const t=this.eventsByCorrelationId.get(e.correlationId);t?(this.logger.trace(`PerformanceClient: Performance measurement for ${e.name} added/updated`,e.correlationId),t.incompleteSubMeasurements=t.incompleteSubMeasurements||new Map,t.incompleteSubMeasurements.set(e.eventId,{name:e.name,startTimeMs:e.startTimeMs})):(this.logger.trace(`PerformanceClient: Performance measurement for ${e.name} started`,e.correlationId),this.eventsByCorrelationId.set(e.correlationId,{...e}),this.eventStack.set(e.correlationId,[]))}getQueueInfo(e){const t=this.queueMeasurements.get(e);t||this.logger.trace(`PerformanceClient: no queue measurements found for for correlationId: ${e}`);let r=0,o=0,n=0;return t?.forEach((e=>{r+=e.queueTime,o++,n+=e.manuallyCompleted?1:0})),{totalQueueTime:r,totalQueueCount:o,manuallyCompletedCount:n}}discardMeasurements(e){this.logger.trace("PerformanceClient: Performance measurements discarded",e),this.eventsByCorrelationId.delete(e),this.logger.trace("PerformanceClient: QueueMeasurements discarded",e),this.queueMeasurements.delete(e),this.logger.trace("PerformanceClient: Pre-queue times discarded",e),this.preQueueTimeByCorrelationId.delete(e),this.logger.trace("PerformanceClient: Event stack discarded",e),this.eventStack.delete(e)}addPerformanceCallback(e){for(const[t,r]of this.callbacks)if(r.toString()===e.toString())return this.logger.warning(`PerformanceClient: Performance callback is already registered with id: ${t}`),t;const t=this.generateId();return this.callbacks.set(t,e),this.logger.verbose(`PerformanceClient: Performance callback registered with id: ${t}`),t}removePerformanceCallback(e){const t=this.callbacks.delete(e);return t?this.logger.verbose(`PerformanceClient: Performance callback ${e} removed.`):this.logger.verbose(`PerformanceClient: Performance callback ${e} not removed.`),t}emitEvents(e,t){this.logger.verbose("PerformanceClient: Emitting performance events",t),this.callbacks.forEach(((r,o)=>{this.logger.trace(`PerformanceClient: Emitting event to callback ${o}`,t),r.apply(null,[e])}))}truncateIntegralFields(e){this.intFields.forEach((t=>{t in e&&"number"==typeof e[t]&&(e[t]=Math.floor(e[t]))}))}getDurationMs(e){const t=Date.now()-e;return t<0?t:0}}const yn="pkce_not_created",vn="crypto_nonexistent",Cn="empty_navigate_uri",wn="hash_empty_error",Tn="no_state_in_hash",kn="hash_does_not_contain_known_properties",In="unable_to_parse_state",An="state_interaction_type_mismatch",bn="interaction_in_progress",Sn="popup_window_error",En="empty_window_error",Rn="user_cancelled",_n="monitor_popup_timeout",Pn="monitor_window_timeout",Mn="redirect_in_iframe",On="block_iframe_reload",Nn="block_nested_popups",qn="iframe_closed_prematurely",Un="silent_logout_unsupported",xn="no_account_error",Ln="silent_prompt_value_error",Dn="no_token_request_cache_error",Hn="unable_to_parse_token_request_cache_error",Bn="no_cached_authority_error",$n="auth_request_not_set_error",Fn="invalid_cache_type",zn="non_browser_environment",Kn="database_not_open",jn="no_network_connectivity",Gn="post_request_failed",Wn="get_request_failed",Vn="failed_to_parse_response",Qn="unable_to_load_token",Yn="crypto_key_not_found",Jn="auth_code_required",Xn="auth_code_or_nativeAccountId_required",Zn="spa_code_and_nativeAccountId_present",ei="database_unavailable",ti="unable_to_acquire_token_from_native_platform",ri="native_handshake_timeout",oi="native_extension_not_installed",ni="native_connection_not_established",ii="uninitialized_public_client_application",si="native_prompt_not_supported",ai="invalid_base64_string",ci="invalid_pop_token_request";var li=Object.freeze({__proto__:null,authCodeOrNativeAccountIdRequired:Xn,authCodeRequired:Jn,authRequestNotSetError:$n,blockIframeReload:On,blockNestedPopups:Nn,cryptoKeyNotFound:Yn,cryptoNonExistent:vn,databaseNotOpen:Kn,databaseUnavailable:ei,emptyNavigateUri:Cn,emptyWindowError:En,failedToParseResponse:Vn,getRequestFailed:Wn,hashDoesNotContainKnownProperties:kn,hashEmptyError:wn,iframeClosedPrematurely:qn,interactionInProgress:bn,invalidBase64String:ai,invalidCacheType:Fn,invalidPopTokenRequest:ci,monitorPopupTimeout:_n,monitorWindowTimeout:Pn,nativeConnectionNotEstablished:ni,nativeExtensionNotInstalled:oi,nativeHandshakeTimeout:ri,nativePromptNotSupported:si,noAccountError:xn,noCachedAuthorityError:Bn,noNetworkConnectivity:jn,noStateInHash:Tn,noTokenRequestCacheError:Dn,nonBrowserEnvironment:zn,pkceNotCreated:yn,popupWindowError:Sn,postRequestFailed:Gn,redirectInIframe:Mn,silentLogoutUnsupported:Un,silentPromptValueError:Ln,spaCodeAndNativeAccountIdPresent:Zn,stateInteractionTypeMismatch:An,unableToAcquireTokenFromNativePlatform:ti,unableToLoadToken:Qn,unableToParseState:In,unableToParseTokenRequestCacheError:Hn,uninitializedPublicClientApplication:ii,userCancelled:Rn});const di="For more visit: aka.ms/msaljs/browser-errors",ui={[yn]:"The PKCE code challenge and verifier could not be generated.",[vn]:"The crypto object or function is not available.",[Cn]:"Navigation URI is empty. Please check stack trace for more info.",[wn]:`Hash value cannot be processed because it is empty. Please verify that your redirectUri is not clearing the hash. ${di}`,[Tn]:"Hash does not contain state. Please verify that the request originated from msal.",[kn]:`Hash does not contain known properites. Please verify that your redirectUri is not changing the hash. ${di}`,[In]:"Unable to parse state. Please verify that the request originated from msal.",[An]:"Hash contains state but the interaction type does not match the caller.",[bn]:`Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API. ${di}`,[Sn]:"Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser.",[En]:"window.open returned null or undefined window object.",[Rn]:"User cancelled the flow.",[_n]:`Token acquisition in popup failed due to timeout. ${di}`,[Pn]:`Token acquisition in iframe failed due to timeout. ${di}`,[Mn]:"Redirects are not supported for iframed or brokered applications. Please ensure you are using MSAL.js in a top frame of the window if using the redirect APIs, or use the popup APIs.",[On]:`Request was blocked inside an iframe because MSAL detected an authentication response. ${di}`,[Nn]:"Request was blocked inside a popup because MSAL detected it was running in a popup.",[qn]:"The iframe being monitored was closed prematurely.",[Un]:"Silent logout not supported. Please call logoutRedirect or logoutPopup instead.",[xn]:"No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the request.",[Ln]:"The value given for the prompt value is not valid for silent requests - must be set to 'none' or 'no_session'.",[Dn]:"No token request found in cache.",[Hn]:"The cached token request could not be parsed.",[Bn]:"No cached authority found.",[$n]:"Auth Request not set. Please ensure initiateAuthRequest was called from the InteractionHandler",[Fn]:"Invalid cache type",[zn]:"Login and token requests are not supported in non-browser environments.",[Kn]:"Database is not open!",[jn]:"No network connectivity. Check your internet connection.",[Gn]:"Network request failed: If the browser threw a CORS error, check that the redirectUri is registered in the Azure App Portal as type 'SPA'",[Wn]:"Network request failed. Please check the network trace to determine root cause.",[Vn]:"Failed to parse network response. Check network trace.",[Qn]:"Error loading token to cache.",[Yn]:"Cryptographic Key or Keypair not found in browser storage.",[Jn]:"An authorization code must be provided (as the `code` property on the request) to this flow.",[Xn]:"An authorization code or nativeAccountId must be provided to this flow.",[Zn]:"Request cannot contain both spa code and native account id.",[ei]:"IndexedDB, which is required for persistent cryptographic key storage, is unavailable. This may be caused by browser privacy features which block persistent storage in third-party contexts.",[ti]:`Unable to acquire token from native platform. ${di}`,[ri]:"Timed out while attempting to establish connection to browser extension",[oi]:"Native extension is not installed. If you think this is a mistake call the initialize function.",[ni]:`Connection to native platform has not been established. Please install a compatible browser extension and run initialize(). ${di}`,[ii]:`You must call and await the initialize function before attempting to call any other MSAL API. ${di}`,[si]:"The provided prompt is not supported by the native platform. This request should be routed to the web based flow.",[ai]:"Invalid base64 encoded string.",[ci]:"Invalid PoP token request. The request should not have both a popKid value and signPopToken set to true."},hi={pkceNotGenerated:{code:yn,desc:ui[yn]},cryptoDoesNotExist:{code:vn,desc:ui[vn]},emptyNavigateUriError:{code:Cn,desc:ui[Cn]},hashEmptyError:{code:wn,desc:ui[wn]},hashDoesNotContainStateError:{code:Tn,desc:ui[Tn]},hashDoesNotContainKnownPropertiesError:{code:kn,desc:ui[kn]},unableToParseStateError:{code:In,desc:ui[In]},stateInteractionTypeMismatchError:{code:An,desc:ui[An]},interactionInProgress:{code:bn,desc:ui[bn]},popupWindowError:{code:Sn,desc:ui[Sn]},emptyWindowError:{code:En,desc:ui[En]},userCancelledError:{code:Rn,desc:ui[Rn]},monitorPopupTimeoutError:{code:_n,desc:ui[_n]},monitorIframeTimeoutError:{code:Pn,desc:ui[Pn]},redirectInIframeError:{code:Mn,desc:ui[Mn]},blockTokenRequestsInHiddenIframeError:{code:On,desc:ui[On]},blockAcquireTokenInPopupsError:{code:Nn,desc:ui[Nn]},iframeClosedPrematurelyError:{code:qn,desc:ui[qn]},silentLogoutUnsupportedError:{code:Un,desc:ui[Un]},noAccountError:{code:xn,desc:ui[xn]},silentPromptValueError:{code:Ln,desc:ui[Ln]},noTokenRequestCacheError:{code:Dn,desc:ui[Dn]},unableToParseTokenRequestCacheError:{code:Hn,desc:ui[Hn]},noCachedAuthorityError:{code:Bn,desc:ui[Bn]},authRequestNotSet:{code:$n,desc:ui[$n]},invalidCacheType:{code:Fn,desc:ui[Fn]},notInBrowserEnvironment:{code:zn,desc:ui[zn]},databaseNotOpen:{code:Kn,desc:ui[Kn]},noNetworkConnectivity:{code:jn,desc:ui[jn]},postRequestFailed:{code:Gn,desc:ui[Gn]},getRequestFailed:{code:Wn,desc:ui[Wn]},failedToParseNetworkResponse:{code:Vn,desc:ui[Vn]},unableToLoadTokenError:{code:Qn,desc:ui[Qn]},signingKeyNotFoundInStorage:{code:Yn,desc:ui[Yn]},authCodeRequired:{code:Jn,desc:ui[Jn]},authCodeOrNativeAccountRequired:{code:Xn,desc:ui[Xn]},spaCodeAndNativeAccountPresent:{code:Zn,desc:ui[Zn]},databaseUnavailable:{code:ei,desc:ui[ei]},unableToAcquireTokenFromNativePlatform:{code:ti,desc:ui[ti]},nativeHandshakeTimeout:{code:ri,desc:ui[ri]},nativeExtensionNotInstalled:{code:oi,desc:ui[oi]},nativeConnectionNotEstablished:{code:ni,desc:ui[ni]},uninitializedPublicClientApplication:{code:ii,desc:ui[ii]},nativePromptNotSupported:{code:si,desc:ui[si]},invalidBase64StringError:{code:ai,desc:ui[ai]},invalidPopTokenRequest:{code:ci,desc:ui[ci]}};class gi extends ke{constructor(e){super(e,ui[e]),Object.setPrototypeOf(this,gi.prototype),this.name="BrowserAuthError"}}function pi(e){return new gi(e)}const mi={INTERACTION_IN_PROGRESS_VALUE:"interaction_in_progress",INVALID_GRANT_ERROR:"invalid_grant",POPUP_WIDTH:483,POPUP_HEIGHT:600,POPUP_NAME_PREFIX:"msal",DEFAULT_POLL_INTERVAL_MS:30,MSAL_SKU:"msal.js.browser"},fi="53ee284d-920a-4b59-9d30-a60315b26836",yi="ppnbnpeolgkicgegkbkbjmhlideopiji",vi="MATS",Ci="Handshake",wi="HandshakeResponse",Ti="GetToken",ki="Response",Ii={LocalStorage:"localStorage",SessionStorage:"sessionStorage",MemoryStorage:"memoryStorage"},Ai="GET",bi="POST",Si="authority",Ei="request.state",Ri="nonce.id_token",_i="request.origin",Pi="urlHash",Mi="request.params",Oi="interaction.status",Ni="ccs.credential",qi="request.correlationId",Ui="request.native",xi="msal.account.keys",Li="msal.token.keys",Di="wrapper.sku",Hi="wrapper.version",Bi={acquireTokenRedirect:861,acquireTokenPopup:862,ssoSilent:863,acquireTokenSilent_authCode:864,handleRedirectPromise:865,acquireTokenByCode:866,acquireTokenSilent_silentFlow:61,logout:961,logoutPopup:962};var $i;t.InteractionType=void 0,($i=t.InteractionType||(t.InteractionType={})).Redirect="redirect",$i.Popup="popup",$i.Silent="silent",$i.None="none";const Fi={Startup:"startup",Login:"login",Logout:"logout",AcquireToken:"acquireToken",SsoSilent:"ssoSilent",HandleRedirect:"handleRedirect",None:"none"},zi={scopes:a},Ki="msal.db",ji=`${Ki}.keys`,Gi={Default:0,AccessToken:1,AccessTokenAndRefreshToken:2,RefreshToken:3,RefreshTokenAndNetwork:4,Skip:5},Wi=[Gi.Default,Gi.Skip,Gi.RefreshTokenAndNetwork];function Vi(e){return encodeURIComponent(Yi(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"))}function Qi(e){return Ji(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Yi(e){return Ji((new TextEncoder).encode(e))}function Ji(e){const t=Array.from(e,(e=>String.fromCodePoint(e))).join("");return btoa(t)}const Xi="SHA-256",Zi=new Uint8Array([1,0,1]),es="0123456789abcdef",ts=new Uint32Array(1),rs={name:"RSASSA-PKCS1-v1_5",hash:Xi,modulusLength:2048,publicExponent:Zi};async function os(e,t,r){t?.addQueueMeasurement(yo.Sha256Digest,r);const o=(new TextEncoder).encode(e);return window.crypto.subtle.digest(Xi,o)}function ns(e){return window.crypto.getRandomValues(e)}function is(){return window.crypto.getRandomValues(ts),ts[0]}function ss(){const e=Date.now(),t=1024*is()+(1023&is()),r=new Uint8Array(16),o=Math.trunc(t/2**30),n=t&2**30-1,i=is();r[0]=e/2**40,r[1]=e/2**32,r[2]=e/2**24,r[3]=e/65536,r[4]=e/256,r[5]=e,r[6]=112|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<r.length;e++)s+=es.charAt(r[e]>>>4),s+=es.charAt(15&r[e]),3!==e&&5!==e&&7!==e&&9!==e||(s+="-");return s}async function as(e){return window.crypto.subtle.exportKey("jwk",e)}async function cs(e){const t=await os(e);return Qi(new Uint8Array(t))}const ls="storage_not_supported",ds="stubbed_public_client_application_called",us="in_mem_redirect_unavailable";var hs=Object.freeze({__proto__:null,inMemRedirectUnavailable:us,storageNotSupported:ls,stubbedPublicClientApplicationCalled:ds});const gs={[ls]:"Given storage configuration option was not supported.",[ds]:"Stub instance of Public Client Application was called. If using msal-react, please ensure context is not used without a provider. For more visit: aka.ms/msaljs/browser-errors",[us]:"Redirect cannot be supported. In-memory storage was selected and storeAuthStateInCookie=false, which would cause the library to be unable to handle the incoming hash. If you would like to use the redirect API, please use session/localStorage or set storeAuthStateInCookie=true."},ps={storageNotSupportedError:{code:ls,desc:gs[ls]},stubPcaInstanceCalled:{code:ds,desc:gs[ds]},inMemRedirectUnavailable:{code:us,desc:gs[us]}};class ms extends ke{constructor(e,t){super(e,t),this.name="BrowserConfigurationAuthError",Object.setPrototypeOf(this,ms.prototype)}}function fs(e){return new ms(e,gs[e])}function ys(e){e.location.hash="","function"==typeof e.history.replaceState&&e.history.replaceState(null,"",`${e.location.origin}${e.location.pathname}${e.location.search}`)}function vs(e){const t=e.split("#");t.shift(),window.location.hash=t.length>0?t.join("#"):""}function Cs(){return window.parent!==window}function ws(){return"undefined"!=typeof window&&!!window.opener&&window.opener!==window&&"string"==typeof window.name&&0===window.name.indexOf(`${mi.POPUP_NAME_PREFIX}.`)}function Ts(){return window.location.href.split("?")[0].split("#")[0]}function ks(){const e=new xr(window.location.href).getUrlComponents();return`${e.Protocol}//${e.HostNameAndPort}/`}function Is(){if(xr.hashContainsKnownProperties(window.location.hash)&&Cs())throw pi(On)}function As(e){if(Cs()&&!e)throw pi(Mn)}function bs(){if(ws())throw pi(Nn)}function Ss(){if("undefined"==typeof window)throw pi(zn)}function Es(e){if(!e)throw pi(ii)}function Rs(e){Ss(),Is(),bs(),Es(e)}function _s(e,t){if(Rs(e),As(t.system.allowRedirectInIframe),t.cache.cacheLocation===Ii.MemoryStorage&&!t.cache.storeAuthStateInCookie)throw fs(us)}function Ps(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 Ms(){return ss()}var Os=Object.freeze({__proto__:null,blockAPICallsBeforeInitialize:Es,blockAcquireTokenInPopups:bs,blockNonBrowserEnvironment:Ss,blockRedirectInIframe:As,blockReloadInHiddenIframes:Is,clearHash:ys,createGuid:Ms,getCurrentUri:Ts,getHomepage:ks,invoke:ko,invokeAsync:Io,isInIframe:Cs,isInPopup:ws,preconnect:Ps,preflightCheck:Rs,redirectPreflightCheck:_s,replaceHash:vs});class Ns{navigateInternal(e,t){return Ns.defaultNavigateWindow(e,t)}navigateExternal(e,t){return Ns.defaultNavigateWindow(e,t)}static defaultNavigateWindow(e,t){return t.noHistory?window.location.replace(e):window.location.assign(e),new Promise((e=>{setTimeout((()=>{e(!0)}),t.timeout)}))}}class qs{async sendGetRequestAsync(e,t){let r;try{r=await fetch(e,{method:Ai,headers:this.getFetchHeaders(t)})}catch(e){throw window.navigator.onLine?pi(Wn):pi(jn)}try{return{headers:this.getHeaderDict(r.headers),body:await r.json(),status:r.status}}catch(e){throw pi(Vn)}}async sendPostRequestAsync(e,t){const o=t&&t.body||r.EMPTY_STRING;let n;try{n=await fetch(e,{method:bi,headers:this.getFetchHeaders(t),body:o})}catch(e){throw window.navigator.onLine?pi(Gn):pi(jn)}try{return{headers:this.getHeaderDict(n.headers),body:await n.json(),status:n.status}}catch(e){throw pi(Vn)}}getFetchHeaders(e){const t=new Headers;if(!e||!e.headers)return t;const r=e.headers;return Object.keys(r).forEach((e=>{t.append(e,r[e])})),t}getHeaderDict(e){const t={};return e.forEach(((e,r)=>{t[r]=e})),t}}const Us=1e4;const xs="@azure/msal-browser",Ls="3.26.1";class Ds{static loggerCallback(e,r){switch(e){case t.LogLevel.Error:return void console.error(r);case t.LogLevel.Info:return void console.info(r);case t.LogLevel.Verbose:return void console.debug(r);case t.LogLevel.Warning:return void console.warn(r);default:return void console.log(r)}}constructor(e){let o;this.browserEnvironment="undefined"!=typeof window,this.config=function({auth:e,cache:o,system:n,telemetry:i},s){const a={clientId:r.EMPTY_STRING,authority:`${r.DEFAULT_AUTHORITY}`,knownAuthorities:[],cloudDiscoveryMetadata:r.EMPTY_STRING,authorityMetadata:r.EMPTY_STRING,redirectUri:r.EMPTY_STRING,postLogoutRedirectUri:r.EMPTY_STRING,navigateToLoginRequestUrl:!0,clientCapabilities:[],protocolMode:Or.AAD,OIDCOptions:{serverResponseType:P.FRAGMENT,defaultScopes:[r.OPENID_SCOPE,r.PROFILE_SCOPE,r.OFFLINE_ACCESS_SCOPE]},azureCloudOptions:{azureCloudInstance:At.None,tenant:r.EMPTY_STRING},skipAuthorityMetadataCache:!1,supportsNestedAppAuth:!1,instanceAware:!1},c={cacheLocation:Ii.SessionStorage,temporaryCacheLocation:Ii.SessionStorage,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!(!o||o.cacheLocation!==Ii.LocalStorage),claimsBasedCachingEnabled:!1},l={loggerCallback:()=>{},logLevel:t.LogLevel.Info,piiLoggingEnabled:!1},d={...{...Vr,loggerOptions:l,networkClient:s?new qs:tn,navigationClient:new Ns,loadFrameTimeout:0,windowHashTimeout:n?.loadFrameTimeout||6e4,iframeHashTimeout:n?.loadFrameTimeout||Us,navigateFrameWait:0,redirectNavigationTimeout:3e4,asyncPopups:!1,allowRedirectInIframe:!1,allowNativeBroker:!1,nativeBrokerHandshakeTimeout:n?.nativeBrokerHandshakeTimeout||2e3,pollIntervalMilliseconds:mi.DEFAULT_POLL_INTERVAL_MS},...n,loggerOptions:n?.loggerOptions||l},u={application:{appName:r.EMPTY_STRING,appVersion:r.EMPTY_STRING},client:new gn};e?.protocolMode!==Or.OIDC&&e?.OIDCOptions&&new Tt(d.loggerOptions).warning(JSON.stringify(Cr(hr)));if(e?.protocolMode&&e.protocolMode!==Or.AAD&&d?.allowNativeBroker)throw Cr(gr);return{auth:{...a,...e,OIDCOptions:{...a.OIDCOptions,...e?.OIDCOptions}},cache:{...c,...o},system:d,telemetry:{...u,...i}}}(e,this.browserEnvironment);try{o=window[Ii.SessionStorage]}catch(e){}const n=o?.getItem("msal.browser.log.level"),i=o?.getItem("msal.browser.log.pii")?.toLowerCase(),s="true"===i||"false"!==i&&void 0,a={...this.config.system.loggerOptions},c=n&&Object.keys(t.LogLevel).includes(n)?t.LogLevel[n]:void 0;c&&(a.loggerCallback=Ds.loggerCallback,a.logLevel=c),void 0!==s&&(a.piiLoggingEnabled=s),this.logger=new Tt(a,xs,Ls),this.available=!1}getConfig(){return this.config}getLogger(){return this.logger}isAvailable(){return this.available}isBrowserEnvironment(){return this.browserEnvironment}}const Hs="USER_INTERACTION_REQUIRED",Bs="USER_CANCEL",$s="NO_NETWORK",Fs="TRANSIENT_ERROR",zs="PERSISTENT_ERROR",Ks="DISABLED",js="ACCOUNT_UNAVAILABLE",Gs="NESTED_APP_AUTH_UNAVAILABLE";class Ws{static async initializeNestedAppAuthBridge(){if(void 0===window)throw new Error("window is undefined");if(void 0===window.nestedAppAuthBridge)throw new Error("window.nestedAppAuthBridge is undefined");try{window.nestedAppAuthBridge.addEventListener("message",(e=>{const t="string"==typeof e?e:e.data,r=JSON.parse(t),o=Ws.bridgeRequests.find((e=>e.requestId===r.requestId));void 0!==o&&(Ws.bridgeRequests.splice(Ws.bridgeRequests.indexOf(o),1),r.success?o.resolve(r):o.reject(r.error))}));const e=await new Promise(((e,t)=>{const r=Ws.buildRequest("GetInitContext"),o={requestId:r.requestId,method:r.method,resolve:e,reject:t};Ws.bridgeRequests.push(o),window.nestedAppAuthBridge.postMessage(JSON.stringify(r))}));return Ws.validateBridgeResultOrThrow(e.initContext)}catch(e){throw window.console.log(e),e}}getTokenInteractive(e){return this.getToken("GetTokenPopup",e)}getTokenSilent(e){return this.getToken("GetToken",e)}async getToken(e,t){const r=await this.sendRequest(e,{tokenParams:t});return{token:Ws.validateBridgeResultOrThrow(r.token),account:Ws.validateBridgeResultOrThrow(r.account)}}getHostCapabilities(){return this.capabilities??null}getAccountContext(){return this.accountContext?this.accountContext:null}static buildRequest(e,t){return{messageType:"NestedAppAuthRequest",method:e,requestId:ss(),sendTime:Date.now(),clientLibrary:mi.MSAL_SKU,clientLibraryVersion:Ls,...t}}sendRequest(e,t){const r=Ws.buildRequest(e,t);return new Promise(((e,t)=>{const o={requestId:r.requestId,method:r.method,resolve:e,reject:t};Ws.bridgeRequests.push(o),window.nestedAppAuthBridge.postMessage(JSON.stringify(r))}))}static validateBridgeResultOrThrow(e){if(void 0===e){throw{status:Gs}}return e}constructor(e,t,r,o){this.sdkName=e,this.sdkVersion=t,this.accountContext=r,this.capabilities=o}static async create(){const e=await Ws.initializeNestedAppAuthBridge();return new Ws(e.sdkName,e.sdkVersion,e.accountContext,e.capabilities)}}Ws.bridgeRequests=[];class Vs extends Ds{constructor(){super(...arguments),this.bridgeProxy=void 0,this.accountContext=null}getModuleName(){return Vs.MODULE_NAME}getId(){return Vs.ID}getBridgeProxy(){return this.bridgeProxy}async initialize(){try{if("undefined"!=typeof window){"function"==typeof window.__initializeNestedAppAuth&&await window.__initializeNestedAppAuth();const e=await Ws.create();this.accountContext=e.getAccountContext(),this.bridgeProxy=e,this.available=void 0!==e}}catch(e){this.logger.infoPii(`Could not initialize Nested App Auth bridge (${e})`)}return this.logger.info(`Nested App Auth Bridge available: ${this.available}`),this.available}}Vs.MODULE_NAME="",Vs.ID="NestedAppOperatingContext";class Qs extends Ds{getModuleName(){return Qs.MODULE_NAME}getId(){return Qs.ID}async initialize(){return this.available="undefined"!=typeof window,this.available}}function Ys(e){return(new TextDecoder).decode(function(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 pi(ai)}const r=atob(t);return Uint8Array.from(r,(e=>e.codePointAt(0)||0))}(e))}Qs.MODULE_NAME="",Qs.ID="StandardOperatingContext";class Js{constructor(){this.dbName=Ki,this.version=1,this.tableName=ji,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(pi(ei))))}))}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(pi(Kn));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(pi(Kn));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(pi(Kn));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(pi(Kn));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(pi(Kn));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(Ki),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 Xs{constructor(){this.cache=new Map}getItem(e){return this.cache.get(e)||null}setItem(e,t){this.cache.set(e,t)}removeItem(e){this.cache.delete(e)}getKeys(){const e=[];return this.cache.forEach(((t,r)=>{e.push(r)})),e}containsKey(e){return this.cache.has(e)}clear(){this.cache.clear()}}class Zs{constructor(e){this.inMemoryCache=new Xs,this.indexedDBCache=new Js,this.logger=e}handleDatabaseAccessError(e){if(!(e instanceof gi&&e.errorCode===ei))throw e;this.logger.error("Could not access persistent storage. This may be caused by browser privacy features which block persistent storage in third-party contexts.")}async getItem(e){const t=this.inMemoryCache.getItem(e);if(!t)try{return this.logger.verbose("Queried item not found in in-memory cache, now querying persistent storage."),await this.indexedDBCache.getItem(e)}catch(e){this.handleDatabaseAccessError(e)}return t}async setItem(e,t){this.inMemoryCache.setItem(e,t);try{await this.indexedDBCache.setItem(e,t)}catch(e){this.handleDatabaseAccessError(e)}}async removeItem(e){this.inMemoryCache.removeItem(e);try{await this.indexedDBCache.removeItem(e)}catch(e){this.handleDatabaseAccessError(e)}}async getKeys(){const e=this.inMemoryCache.getKeys();if(0===e.length)try{return this.logger.verbose("In-memory cache is empty, now querying persistent storage."),await this.indexedDBCache.getKeys()}catch(e){this.handleDatabaseAccessError(e)}return e}async containsKey(e){const t=this.inMemoryCache.containsKey(e);if(!t)try{return this.logger.verbose("Key not found in in-memory cache, now querying persistent storage."),await this.indexedDBCache.containsKey(e)}catch(e){this.handleDatabaseAccessError(e)}return t}clearInMemory(){this.logger.verbose("Deleting in-memory keystore"),this.inMemoryCache.clear(),this.logger.verbose("In-memory keystore deleted")}async clearPersistent(){try{this.logger.verbose("Deleting persistent keystore");const e=await this.indexedDBCache.deleteDatabase();return e&&this.logger.verbose("Persistent keystore deleted"),e}catch(e){return this.handleDatabaseAccessError(e),!1}}}class ea{constructor(e,t){this.logger=e,function(e){if(!("crypto"in window))throw e.error("BrowserCrypto: crypto interface is unavailable"),pi(vn);e.verbose("BrowserCrypto: modern crypto interface available")}(e),this.cache=new Zs(this.logger),this.performanceClient=t}createNewGuid(){return ss()}base64Encode(e){return Yi(e)}base64Decode(e){return Ys(e)}base64UrlEncode(e){return Vi(e)}encodeKid(e){return this.base64UrlEncode(JSON.stringify({kid:e}))}async getPublicKeyThumbprint(e){const t=this.performanceClient?.startMeasurement(yo.CryptoOptsGetPublicKeyThumbprint,e.correlationId),r=await async function(e,t){return window.crypto.subtle.generateKey(rs,e,t)}(ea.EXTRACTABLE,ea.POP_KEY_USAGES),o=await as(r.publicKey),n=ta({e:o.e,kty:o.kty,n:o.n}),i=await this.hashString(n),s=await as(r.privateKey),a=await async function(e,t,r){return window.crypto.subtle.importKey("jwk",e,rs,t,r)}(s,!1,["sign"]);return await this.cache.setItem(i,{privateKey:a,publicKey:r.publicKey,requestMethod:e.resourceRequestMethod,requestUri:e.resourceRequestUri}),t&&t.end({success:!0}),i}async removeTokenBindingKey(e){await this.cache.removeItem(e);return!await this.cache.containsKey(e)}async clearKeystore(){this.cache.clearInMemory();try{return await this.cache.clearPersistent(),!0}catch(e){return e instanceof Error?this.logger.error(`Clearing keystore failed with error: ${e.message}`):this.logger.error("Clearing keystore failed with unknown error"),!1}}async signJwt(e,t,r,o){const n=this.performanceClient?.startMeasurement(yo.CryptoOptsSignJwt,o),i=await this.cache.getItem(t);if(!i)throw pi(Yn);const s=await as(i.publicKey),a=ta(s),c=Vi(JSON.stringify({kid:t})),l=Vi(un.getShrHeaderString({...r?.header,alg:s.alg,kid:c}));e.cnf={jwk:JSON.parse(a)};const d=`${l}.${Vi(JSON.stringify(e))}`,u=(new TextEncoder).encode(d),h=await async function(e,t){return window.crypto.subtle.sign(rs,e,t)}(i.privateKey,u),g=`${d}.${Qi(new Uint8Array(h))}`;return n&&n.end({success:!0}),g}async hashString(e){return cs(e)}}function ta(e){return JSON.stringify(e,Object.keys(e).sort())}ea.POP_KEY_USAGES=["sign","verify"],ea.EXTRACTABLE=!0;class ra{constructor(e){this.validateWindowStorage(e),this.windowStorage=window[e]}validateWindowStorage(e){if(e!==Ii.LocalStorage&&e!==Ii.SessionStorage||!window[e])throw fs(ls)}getItem(e){return this.windowStorage.getItem(e)}setItem(e,t){this.windowStorage.setItem(e,t)}removeItem(e){this.windowStorage.removeItem(e)}getKeys(){return Object.keys(this.windowStorage)}containsKey(e){return this.windowStorage.hasOwnProperty(e)}}function oa(e,t){if(!t)return null;try{return jo.parseRequestState(e,t).libraryState.meta}catch(e){throw vt(Oe)}}class na extends Gr{constructor(e,t,r,o,n,i){super(e,r,o,n),this.COOKIE_LIFE_MULTIPLIER=864e5,this.cacheConfig=t,this.logger=o,this.internalStorage=new Xs,this.browserStorage=this.setupBrowserStorage(this.cacheConfig.cacheLocation),this.temporaryCacheStorage=this.setupTemporaryCacheStorage(this.cacheConfig.temporaryCacheLocation,this.cacheConfig.cacheLocation),t.cacheMigrationEnabled&&(this.migrateCacheEntries(),this.createKeyMaps()),this.performanceClient=i}setupBrowserStorage(e){switch(e){case Ii.LocalStorage:case Ii.SessionStorage:try{return new ra(e)}catch(e){this.logger.verbose(e);break}}return this.cacheConfig.cacheLocation=Ii.MemoryStorage,new Xs}setupTemporaryCacheStorage(e,t){switch(t){case Ii.LocalStorage:case Ii.SessionStorage:try{return new ra(e||Ii.SessionStorage)}catch(e){return this.logger.verbose(e),this.internalStorage}default:return this.internalStorage}}migrateCacheEntries(){const e=`${r.CACHE_PREFIX}.${f}`,t=`${r.CACHE_PREFIX}.${y}`,o=`${r.CACHE_PREFIX}.${C}`,n=`${r.CACHE_PREFIX}.${w}`,i=[this.browserStorage.getItem(e),this.browserStorage.getItem(t),this.browserStorage.getItem(o),this.browserStorage.getItem(n)];[f,y,C,w].forEach(((e,t)=>{const r=i[t];r&&this.setTemporaryCache(e,r,!0)}))}createKeyMaps(){this.logger.trace("BrowserCacheManager - createKeyMaps called.");const e=this.getItem(xi),t=this.getItem(`${Li}.${this.clientId}`);if(e&&t)return void this.logger.verbose("BrowserCacheManager:createKeyMaps - account and token key maps already exist, skipping migration.");this.browserStorage.getKeys().forEach((e=>{if(this.isCredentialKey(e)){const t=this.getItem(e);if(t){const r=this.validateAndParseJson(t);if(r&&r.hasOwnProperty("credentialType"))switch(r.credentialType){case D.ID_TOKEN:if(xt(r)){this.logger.trace("BrowserCacheManager:createKeyMaps - idToken found, saving key to token key map"),this.logger.tracePii(`BrowserCacheManager:createKeyMaps - idToken with key: ${e} found, saving key to token key map`);const t=r,o=this.updateCredentialCacheKey(e,t);return void this.addTokenKey(o,D.ID_TOKEN)}this.logger.trace("BrowserCacheManager:createKeyMaps - key found matching idToken schema with value containing idToken credentialType field but value failed IdTokenEntity validation, skipping."),this.logger.tracePii(`BrowserCacheManager:createKeyMaps - failed idToken validation on key: ${e}`);break;case D.ACCESS_TOKEN:case D.ACCESS_TOKEN_WITH_AUTH_SCHEME:if(Ut(r)){this.logger.trace("BrowserCacheManager:createKeyMaps - accessToken found, saving key to token key map"),this.logger.tracePii(`BrowserCacheManager:createKeyMaps - accessToken with key: ${e} found, saving key to token key map`);const t=r,o=this.updateCredentialCacheKey(e,t);return void this.addTokenKey(o,D.ACCESS_TOKEN)}this.logger.trace("BrowserCacheManager:createKeyMaps - key found matching accessToken schema with value containing accessToken credentialType field but value failed AccessTokenEntity validation, skipping."),this.logger.tracePii(`BrowserCacheManager:createKeyMaps - failed accessToken validation on key: ${e}`);break;case D.REFRESH_TOKEN:if(Lt(r)){this.logger.trace("BrowserCacheManager:createKeyMaps - refreshToken found, saving key to token key map"),this.logger.tracePii(`BrowserCacheManager:createKeyMaps - refreshToken with key: ${e} found, saving key to token key map`);const t=r,o=this.updateCredentialCacheKey(e,t);return void this.addTokenKey(o,D.REFRESH_TOKEN)}this.logger.trace("BrowserCacheManager:createKeyMaps - key found matching refreshToken schema with value containing refreshToken credentialType field but value failed RefreshTokenEntity validation, skipping."),this.logger.tracePii(`BrowserCacheManager:createKeyMaps - failed refreshToken validation on key: ${e}`)}}}if(this.isAccountKey(e)){const t=this.getItem(e);if(t){const r=this.validateAndParseJson(t);r&&Nr.isAccountEntity(r)&&(this.logger.trace("BrowserCacheManager:createKeyMaps - account found, saving key to account key map"),this.logger.tracePii(`BrowserCacheManager:createKeyMaps - account with key: ${e} found, saving key to account key map`),this.addAccountKeyToMap(e))}}}))}validateAndParseJson(e){try{const t=JSON.parse(e);return t&&"object"==typeof t?t:null}catch(e){return null}}getItem(e){return this.browserStorage.getItem(e)}setItem(e,t){this.browserStorage.setItem(e,t)}getAccount(e,t){this.logger.trace("BrowserCacheManager.getAccount called");const r=this.getCachedAccountEntity(e);return this.updateOutdatedCachedAccount(e,r,t)}getCachedAccountEntity(e){const t=this.getItem(e);if(!t)return this.removeAccountKeyFromMap(e),null;const r=this.validateAndParseJson(t);return r&&Nr.isAccountEntity(r)?Gr.toObject(new Nr,r):(this.removeAccountKeyFromMap(e),null)}setAccount(e){this.logger.trace("BrowserCacheManager.setAccount called");const t=e.generateAccountKey();this.setItem(t,JSON.stringify(e)),this.addAccountKeyToMap(t)}getAccountKeys(){this.logger.trace("BrowserCacheManager.getAccountKeys called");const e=this.getItem(xi);return e?JSON.parse(e):(this.logger.verbose("BrowserCacheManager.getAccountKeys - No account keys found"),[])}addAccountKeyToMap(e){this.logger.trace("BrowserCacheManager.addAccountKeyToMap called"),this.logger.tracePii(`BrowserCacheManager.addAccountKeyToMap called with key: ${e}`);const t=this.getAccountKeys();-1===t.indexOf(e)?(t.push(e),this.setItem(xi,JSON.stringify(t)),this.logger.verbose("BrowserCacheManager.addAccountKeyToMap account key added")):this.logger.verbose("BrowserCacheManager.addAccountKeyToMap account key already exists in map")}removeAccountKeyFromMap(e){this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap called"),this.logger.tracePii(`BrowserCacheManager.removeAccountKeyFromMap called with key: ${e}`);const t=this.getAccountKeys(),r=t.indexOf(e);r>-1?(t.splice(r,1),this.setItem(xi,JSON.stringify(t)),this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap account key removed")):this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap key not found in existing map")}async removeAccount(e){super.removeAccount(e),this.removeAccountKeyFromMap(e)}removeOutdatedAccount(e){this.removeItem(e),this.removeAccountKeyFromMap(e)}removeIdToken(e){super.removeIdToken(e),this.removeTokenKey(e,D.ID_TOKEN)}async removeAccessToken(e){super.removeAccessToken(e),this.removeTokenKey(e,D.ACCESS_TOKEN)}removeRefreshToken(e){super.removeRefreshToken(e),this.removeTokenKey(e,D.REFRESH_TOKEN)}getTokenKeys(){this.logger.trace("BrowserCacheManager.getTokenKeys called");const e=this.getItem(`${Li}.${this.clientId}`);if(e){const t=this.validateAndParseJson(e);if(t&&t.hasOwnProperty("idToken")&&t.hasOwnProperty("accessToken")&&t.hasOwnProperty("refreshToken"))return t;this.logger.error("BrowserCacheManager.getTokenKeys - Token keys found but in an unknown format. Returning empty key map.")}else this.logger.verbose("BrowserCacheManager.getTokenKeys - No token keys found");return{idToken:[],accessToken:[],refreshToken:[]}}addTokenKey(e,t){this.logger.trace("BrowserCacheManager addTokenKey called");const r=this.getTokenKeys();switch(t){case D.ID_TOKEN:-1===r.idToken.indexOf(e)&&(this.logger.info("BrowserCacheManager: addTokenKey - idToken added to map"),r.idToken.push(e));break;case D.ACCESS_TOKEN:-1===r.accessToken.indexOf(e)&&(this.logger.info("BrowserCacheManager: addTokenKey - accessToken added to map"),r.accessToken.push(e));break;case D.REFRESH_TOKEN:-1===r.refreshToken.indexOf(e)&&(this.logger.info("BrowserCacheManager: addTokenKey - refreshToken added to map"),r.refreshToken.push(e));break;default:throw this.logger.error(`BrowserCacheManager:addTokenKey - CredentialType provided invalid. CredentialType: ${t}`),vt(Ze)}this.setItem(`${Li}.${this.clientId}`,JSON.stringify(r))}removeTokenKey(e,t){this.logger.trace("BrowserCacheManager removeTokenKey called");const r=this.getTokenKeys();switch(t){case D.ID_TOKEN:this.logger.infoPii(`BrowserCacheManager: removeTokenKey - attempting to remove idToken with key: ${e} from map`);const o=r.idToken.indexOf(e);o>-1?(this.logger.info("BrowserCacheManager: removeTokenKey - idToken removed from map"),r.idToken.splice(o,1)):this.logger.info("BrowserCacheManager: removeTokenKey - idToken does not exist in map. Either it was previously removed or it was never added.");break;case D.ACCESS_TOKEN:this.logger.infoPii(`BrowserCacheManager: removeTokenKey - attempting to remove accessToken with key: ${e} from map`);const n=r.accessToken.indexOf(e);n>-1?(this.logger.info("BrowserCacheManager: removeTokenKey - accessToken removed from map"),r.accessToken.splice(n,1)):this.logger.info("BrowserCacheManager: removeTokenKey - accessToken does not exist in map. Either it was previously removed or it was never added.");break;case D.REFRESH_TOKEN:this.logger.infoPii(`BrowserCacheManager: removeTokenKey - attempting to remove refreshToken with key: ${e} from map`);const i=r.refreshToken.indexOf(e);i>-1?(this.logger.info("BrowserCacheManager: removeTokenKey - refreshToken removed from map"),r.refreshToken.splice(i,1)):this.logger.info("BrowserCacheManager: removeTokenKey - refreshToken does not exist in map. Either it was previously removed or it was never added.");break;default:throw this.logger.error(`BrowserCacheManager:removeTokenKey - CredentialType provided invalid. CredentialType: ${t}`),vt(Ze)}this.setItem(`${Li}.${this.clientId}`,JSON.stringify(r))}getIdTokenCredential(e){const t=this.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit"),this.removeTokenKey(e,D.ID_TOKEN),null;const r=this.validateAndParseJson(t);return r&&xt(r)?(this.logger.trace("BrowserCacheManager.getIdTokenCredential: cache hit"),r):(this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit"),this.removeTokenKey(e,D.ID_TOKEN),null)}setIdTokenCredential(e){this.logger.trace("BrowserCacheManager.setIdTokenCredential called");const t=Pt(e);this.setItem(t,JSON.stringify(e)),this.addTokenKey(t,D.ID_TOKEN)}getAccessTokenCredential(e){const t=this.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit"),this.removeTokenKey(e,D.ACCESS_TOKEN),null;const r=this.validateAndParseJson(t);return r&&Ut(r)?(this.logger.trace("BrowserCacheManager.getAccessTokenCredential: cache hit"),r):(this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit"),this.removeTokenKey(e,D.ACCESS_TOKEN),null)}setAccessTokenCredential(e){this.logger.trace("BrowserCacheManager.setAccessTokenCredential called");const t=Pt(e);this.setItem(t,JSON.stringify(e)),this.addTokenKey(t,D.ACCESS_TOKEN)}getRefreshTokenCredential(e){const t=this.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit"),this.removeTokenKey(e,D.REFRESH_TOKEN),null;const r=this.validateAndParseJson(t);return r&&Lt(r)?(this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: cache hit"),r):(this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit"),this.removeTokenKey(e,D.REFRESH_TOKEN),null)}setRefreshTokenCredential(e){this.logger.trace("BrowserCacheManager.setRefreshTokenCredential called");const t=Pt(e);this.setItem(t,JSON.stringify(e)),this.addTokenKey(t,D.REFRESH_TOKEN)}getAppMetadata(e){const t=this.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit"),null;const r=this.validateAndParseJson(t);return r&&(o=e,(n=r)&&0===o.indexOf(H)&&n.hasOwnProperty("clientId")&&n.hasOwnProperty("environment"))?(this.logger.trace("BrowserCacheManager.getAppMetadata: cache hit"),r):(this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit"),null);var o,n}setAppMetadata(e){this.logger.trace("BrowserCacheManager.setAppMetadata called");const t=function({environment:e,clientId:t}){return[H,e,t].join(L.CACHE_KEY_SEPARATOR).toLowerCase()}(e);this.setItem(t,JSON.stringify(e))}getServerTelemetry(e){const t=this.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit"),null;const r=this.validateAndParseJson(t);return r&&function(e,t){const r=0===e.indexOf(W.CACHE_KEY);let o=!0;return t&&(o=t.hasOwnProperty("failedRequests")&&t.hasOwnProperty("errors")&&t.hasOwnProperty("cacheHits")),r&&o}(e,r)?(this.logger.trace("BrowserCacheManager.getServerTelemetry: cache hit"),r):(this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit"),null)}setServerTelemetry(e,t){this.logger.trace("BrowserCacheManager.setServerTelemetry called"),this.setItem(e,JSON.stringify(t))}getAuthorityMetadata(e){const t=this.internalStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getAuthorityMetadata: called, no cache hit"),null;const r=this.validateAndParseJson(t);return r&&function(e,t){return!!t&&0===e.indexOf($)&&t.hasOwnProperty("aliases")&&t.hasOwnProperty("preferred_cache")&&t.hasOwnProperty("preferred_network")&&t.hasOwnProperty("canonical_authority")&&t.hasOwnProperty("authorization_endpoint")&&t.hasOwnProperty("token_endpoint")&&t.hasOwnProperty("issuer")&&t.hasOwnProperty("aliasesFromNetwork")&&t.hasOwnProperty("endpointsFromNetwork")&&t.hasOwnProperty("expiresAt")&&t.hasOwnProperty("jwks_uri")}(e,r)?(this.logger.trace("BrowserCacheManager.getAuthorityMetadata: cache hit"),r):null}getAuthorityMetadataKeys(){return this.internalStorage.getKeys().filter((e=>this.isAuthorityMetadata(e)))}setWrapperMetadata(e,t){this.internalStorage.setItem(Di,e),this.internalStorage.setItem(Hi,t)}getWrapperMetadata(){return[this.internalStorage.getItem(Di)||r.EMPTY_STRING,this.internalStorage.getItem(Hi)||r.EMPTY_STRING]}setAuthorityMetadata(e,t){this.logger.trace("BrowserCacheManager.setAuthorityMetadata called"),this.internalStorage.setItem(e,JSON.stringify(t))}getActiveAccount(){const e=this.generateCacheKey(k),t=this.getItem(e);if(!t){this.logger.trace("BrowserCacheManager.getActiveAccount: No active account filters cache schema found, looking for legacy schema");const e=this.generateCacheKey(T),t=this.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getActiveAccount: No active account found"),null;const r=this.getAccountInfoFilteredBy({localAccountId:t});return r?(this.logger.trace("BrowserCacheManager.getActiveAccount: Legacy active account cache schema found"),this.logger.trace("BrowserCacheManager.getActiveAccount: Adding active account filters cache schema"),this.setActiveAccount(r),r):null}const r=this.validateAndParseJson(t);return r?(this.logger.trace("BrowserCacheManager.getActiveAccount: Active account filters schema found"),this.getAccountInfoFilteredBy({homeAccountId:r.homeAccountId,localAccountId:r.localAccountId,tenantId:r.tenantId})):(this.logger.trace("BrowserCacheManager.getActiveAccount: No active account found"),null)}setActiveAccount(e){const t=this.generateCacheKey(k),r=this.generateCacheKey(T);if(e){this.logger.verbose("setActiveAccount: Active account set");const o={homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,tenantId:e.tenantId};this.browserStorage.setItem(t,JSON.stringify(o)),this.browserStorage.setItem(r,e.localAccountId)}else this.logger.verbose("setActiveAccount: No account passed, active account not set"),this.browserStorage.removeItem(t),this.browserStorage.removeItem(r)}getThrottlingCache(e){const t=this.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit"),null;const r=this.validateAndParseJson(t);return r&&function(e,t){let r=!1;e&&(r=0===e.indexOf(J));let o=!0;return t&&(o=t.hasOwnProperty("throttleTime")),r&&o}(e,r)?(this.logger.trace("BrowserCacheManager.getThrottlingCache: cache hit"),r):(this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit"),null)}setThrottlingCache(e,t){this.logger.trace("BrowserCacheManager.setThrottlingCache called"),this.setItem(e,JSON.stringify(t))}getTemporaryCache(e,t){const r=t?this.generateCacheKey(e):e;if(this.cacheConfig.storeAuthStateInCookie){const e=this.getItemCookie(r);if(e)return this.logger.trace("BrowserCacheManager.getTemporaryCache: storeAuthStateInCookies set to true, retrieving from cookies"),e}const o=this.temporaryCacheStorage.getItem(r);if(!o){if(this.cacheConfig.cacheLocation===Ii.LocalStorage){const e=this.browserStorage.getItem(r);if(e)return this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item found in local storage"),e}return this.logger.trace("BrowserCacheManager.getTemporaryCache: No cache item found in local storage"),null}return this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item returned"),o}setTemporaryCache(e,t,r){const o=r?this.generateCacheKey(e):e;this.temporaryCacheStorage.setItem(o,t),this.cacheConfig.storeAuthStateInCookie&&(this.logger.trace("BrowserCacheManager.setTemporaryCache: storeAuthStateInCookie set to true, setting item cookie"),this.setItemCookie(o,t))}removeItem(e){this.browserStorage.removeItem(e)}removeTemporaryItem(e){this.temporaryCacheStorage.removeItem(e),this.cacheConfig.storeAuthStateInCookie&&(this.logger.trace("BrowserCacheManager.removeItem: storeAuthStateInCookie is true, clearing item cookie"),this.clearItemCookie(e))}getKeys(){return this.browserStorage.getKeys()}async clear(){await this.removeAllAccounts(),this.removeAppMetadata(),this.temporaryCacheStorage.getKeys().forEach((e=>{-1===e.indexOf(r.CACHE_PREFIX)&&-1===e.indexOf(this.clientId)||this.removeTemporaryItem(e)})),this.browserStorage.getKeys().forEach((e=>{-1===e.indexOf(r.CACHE_PREFIX)&&-1===e.indexOf(this.clientId)||this.browserStorage.removeItem(e)})),this.internalStorage.clear()}async clearTokensAndKeysWithClaims(e,t){e.addQueueMeasurement(yo.ClearTokensAndKeysWithClaims,t);const r=this.getTokenKeys(),o=[];r.accessToken.forEach((e=>{const t=this.getAccessTokenCredential(e);t?.requestedClaimsHash&&e.includes(t.requestedClaimsHash.toLowerCase())&&o.push(this.removeAccessToken(e))})),await Promise.all(o),o.length>0&&this.logger.warning(`${o.length} access tokens with claims in the cache keys have been removed from the cache.`)}setItemCookie(e,t,r){let o=`${encodeURIComponent(e)}=${encodeURIComponent(t)};path=/;SameSite=Lax;`;if(r){o+=`expires=${this.getCookieExpirationTime(r)};`}this.cacheConfig.secureCookies&&(o+="Secure;"),document.cookie=o}getItemCookie(e){const t=`${encodeURIComponent(e)}=`,o=document.cookie.split(";");for(let e=0;e<o.length;e++){let r=o[e];for(;" "===r.charAt(0);)r=r.substring(1);if(0===r.indexOf(t))return decodeURIComponent(r.substring(t.length,r.length))}return r.EMPTY_STRING}clearMsalCookies(){const e=`${r.CACHE_PREFIX}.${this.clientId}`;document.cookie.split(";").forEach((t=>{for(;" "===t.charAt(0);)t=t.substring(1);if(0===t.indexOf(e)){const e=t.split("=")[0];this.clearItemCookie(e)}}))}clearItemCookie(e){this.setItemCookie(e,r.EMPTY_STRING,-1)}getCookieExpirationTime(e){const t=new Date;return new Date(t.getTime()+e*this.COOKIE_LIFE_MULTIPLIER).toUTCString()}generateCacheKey(e){return this.validateAndParseJson(e)?JSON.stringify(e):wr.startsWith(e,r.CACHE_PREFIX)||wr.startsWith(e,v)?e:`${r.CACHE_PREFIX}.${this.clientId}.${e}`}generateAuthorityKey(e){const{libraryState:{id:t}}=jo.parseRequestState(this.cryptoImpl,e);return this.generateCacheKey(`${Si}.${t}`)}generateNonceKey(e){const{libraryState:{id:t}}=jo.parseRequestState(this.cryptoImpl,e);return this.generateCacheKey(`${Ri}.${t}`)}generateStateKey(e){const{libraryState:{id:t}}=jo.parseRequestState(this.cryptoImpl,e);return this.generateCacheKey(`${Ei}.${t}`)}getCachedAuthority(e){const t=this.generateStateKey(e),r=this.getTemporaryCache(t);if(!r)return null;const o=this.generateAuthorityKey(r);return this.getTemporaryCache(o)}updateCacheEntries(e,t,r,o,n){this.logger.trace("BrowserCacheManager.updateCacheEntries called");const i=this.generateStateKey(e);this.setTemporaryCache(i,e,!1);const s=this.generateNonceKey(e);this.setTemporaryCache(s,t,!1);const a=this.generateAuthorityKey(e);if(this.setTemporaryCache(a,r,!1),n){const e={credential:n.homeAccountId,type:so};this.setTemporaryCache(Ni,JSON.stringify(e),!0)}else if(o){const e={credential:o,type:ao};this.setTemporaryCache(Ni,JSON.stringify(e),!0)}}resetRequestCache(e){this.logger.trace("BrowserCacheManager.resetRequestCache called"),e&&(this.temporaryCacheStorage.getKeys().forEach((t=>{-1!==t.indexOf(e)&&this.removeTemporaryItem(t)})),this.removeTemporaryItem(this.generateStateKey(e)),this.removeTemporaryItem(this.generateNonceKey(e)),this.removeTemporaryItem(this.generateAuthorityKey(e))),this.removeTemporaryItem(this.generateCacheKey(Mi)),this.removeTemporaryItem(this.generateCacheKey(_i)),this.removeTemporaryItem(this.generateCacheKey(Pi)),this.removeTemporaryItem(this.generateCacheKey(qi)),this.removeTemporaryItem(this.generateCacheKey(Ni)),this.removeTemporaryItem(this.generateCacheKey(Ui)),this.setInteractionInProgress(!1)}cleanRequestByState(e){if(this.logger.trace("BrowserCacheManager.cleanRequestByState called"),e){const t=this.generateStateKey(e),o=this.temporaryCacheStorage.getItem(t);this.logger.infoPii(`BrowserCacheManager.cleanRequestByState: Removing temporary cache items for state: ${o}`),this.resetRequestCache(o||r.EMPTY_STRING)}this.clearMsalCookies()}cleanRequestByInteractionType(e){this.logger.trace("BrowserCacheManager.cleanRequestByInteractionType called"),this.temporaryCacheStorage.getKeys().forEach((t=>{if(-1===t.indexOf(Ei))return;const r=this.temporaryCacheStorage.getItem(t);if(!r)return;const o=oa(this.cryptoImpl,r);o&&o.interactionType===e&&(this.logger.infoPii(`BrowserCacheManager.cleanRequestByInteractionType: Removing temporary cache items for state: ${r}`),this.resetRequestCache(r))})),this.clearMsalCookies(),this.setInteractionInProgress(!1)}cacheCodeRequest(e){this.logger.trace("BrowserCacheManager.cacheCodeRequest called");const t=Yi(JSON.stringify(e));this.setTemporaryCache(Mi,t,!0)}getCachedRequest(e){this.logger.trace("BrowserCacheManager.getCachedRequest called");const t=this.getTemporaryCache(Mi,!0);if(!t)throw pi(Dn);let r;try{r=JSON.parse(Ys(t))}catch(e){throw this.logger.errorPii(`Attempted to parse: ${t}`),this.logger.error(`Parsing cached token request threw with error: ${e}`),pi(Hn)}if(this.removeTemporaryItem(this.generateCacheKey(Mi)),!r.authority){const t=this.generateAuthorityKey(e),o=this.getTemporaryCache(t);if(!o)throw pi(Bn);r.authority=o}return r}getCachedNativeRequest(){this.logger.trace("BrowserCacheManager.getCachedNativeRequest called");const e=this.getTemporaryCache(Ui,!0);if(!e)return this.logger.trace("BrowserCacheManager.getCachedNativeRequest: No cached native request found"),null;const t=this.validateAndParseJson(e);return t||(this.logger.error("BrowserCacheManager.getCachedNativeRequest: Unable to parse native request"),null)}isInteractionInProgress(e){const t=this.getInteractionInProgress();return e?t===this.clientId:!!t}getInteractionInProgress(){const e=`${r.CACHE_PREFIX}.${Oi}`;return this.getTemporaryCache(e,!1)}setInteractionInProgress(e){const t=`${r.CACHE_PREFIX}.${Oi}`;if(e){if(this.getInteractionInProgress())throw pi(bn);this.setTemporaryCache(t,this.clientId,!1)}else e||this.getInteractionInProgress()!==this.clientId||this.removeTemporaryItem(t)}getLegacyLoginHint(){const e=this.getTemporaryCache(v);e&&(this.browserStorage.removeItem(v),this.logger.verbose("Cached ADAL id token retrieved."));const t=this.getTemporaryCache(f,!0);t&&(this.browserStorage.removeItem(this.generateCacheKey(f)),this.logger.verbose("Cached MSAL.js v1 id token retrieved"));const r=t||e;if(r){const e=bt(r,Ys);if(e.preferred_username)return this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, setting ADAL/MSAL v1 preferred_username as loginHint"),e.preferred_username;if(e.upn)return this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, setting ADAL/MSAL v1 upn as loginHint"),e.upn;this.logger.verbose("No SSO params used and ADAL/MSAL v1 token retrieved, however, no account hint claim found. Enable preferred_username or upn id token claim to get SSO.")}return null}updateCredentialCacheKey(e,t){const r=Pt(t);if(e!==r){const o=this.getItem(e);if(o)return this.browserStorage.removeItem(e),this.setItem(r,o),this.logger.verbose(`Updated an outdated ${t.credentialType} cache key`),r;this.logger.error(`Attempted to update an outdated ${t.credentialType} cache key but no item matching the outdated key was found in storage`)}return e}async hydrateCache(e,t){const r=Mt(e.account?.homeAccountId,e.account?.environment,e.idToken,this.clientId,e.tenantId);let o;t.claims&&(o=await this.cryptoImpl.hashString(t.claims));const n={idToken:r,accessToken:Ot(e.account?.homeAccountId,e.account.environment,e.accessToken,this.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?e.expiresOn.getTime()/1e3:0,e.extExpiresOn?e.extExpiresOn.getTime()/1e3:0,Ys,void 0,e.tokenType,void 0,t.sshKid,t.claims,o)};return this.saveCacheRecord(n)}async saveCacheRecord(e,t,r){try{await super.saveCacheRecord(e,t,r)}catch(e){if(e instanceof jr&&this.performanceClient&&r)try{const e=this.getTokenKeys();this.performanceClient.addFields({cacheRtCount:e.refreshToken.length,cacheIdCount:e.idToken.length,cacheAtCount:e.accessToken.length},r)}catch(e){}throw e}}}const ia=(e,t)=>new na(e,{cacheLocation:Ii.MemoryStorage,temporaryCacheLocation:Ii.MemoryStorage,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!1,claimsBasedCachingEnabled:!1},Ct,t);function sa(e,t,r,o){return e.verbose("getAllAccounts called"),r?t.getAllAccounts(o):[]}function aa(e,t,r){if(t.trace("getAccount called"),0===Object.keys(e).length)return t.warning("getAccount: No accountFilter provided"),null;const o=r.getAccountInfoFilteredBy(e);return o?(t.verbose("getAccount: Account matching provided filter found, returning"),o):(t.verbose("getAccount: No matching account found, returning null"),null)}function ca(e,t,r){if(t.trace("getAccountByUsername called"),!e)return t.warning("getAccountByUsername: No username provided"),null;const o=r.getAccountInfoFilteredBy({username:e});return o?(t.verbose("getAccountByUsername: Account matching username found, returning"),t.verbosePii(`getAccountByUsername: Returning signed-in accounts matching username: ${e}`),o):(t.verbose("getAccountByUsername: No matching account found, returning null"),null)}function la(e,t,r){if(t.trace("getAccountByHomeId called"),!e)return t.warning("getAccountByHomeId: No homeAccountId provided"),null;const o=r.getAccountInfoFilteredBy({homeAccountId:e});return o?(t.verbose("getAccountByHomeId: Account matching homeAccountId found, returning"),t.verbosePii(`getAccountByHomeId: Returning signed-in accounts matching homeAccountId: ${e}`),o):(t.verbose("getAccountByHomeId: No matching account found, returning null"),null)}function da(e,t,r){if(t.trace("getAccountByLocalId called"),!e)return t.warning("getAccountByLocalId: No localAccountId provided"),null;const o=r.getAccountInfoFilteredBy({localAccountId:e});return o?(t.verbose("getAccountByLocalId: Account matching localAccountId found, returning"),t.verbosePii(`getAccountByLocalId: Returning signed-in accounts matching localAccountId: ${e}`),o):(t.verbose("getAccountByLocalId: No matching account found, returning null"),null)}function ua(e,t){t.setActiveAccount(e)}function ha(e){return e.getActiveAccount()}const ga={INITIALIZE_START:"msal:initializeStart",INITIALIZE_END:"msal:initializeEnd",ACCOUNT_ADDED:"msal:accountAdded",ACCOUNT_REMOVED:"msal:accountRemoved",ACTIVE_ACCOUNT_CHANGED:"msal:activeAccountChanged",LOGIN_START:"msal:loginStart",LOGIN_SUCCESS:"msal:loginSuccess",LOGIN_FAILURE:"msal:loginFailure",ACQUIRE_TOKEN_START:"msal:acquireTokenStart",ACQUIRE_TOKEN_SUCCESS:"msal:acquireTokenSuccess",ACQUIRE_TOKEN_FAILURE:"msal:acquireTokenFailure",ACQUIRE_TOKEN_NETWORK_START:"msal:acquireTokenFromNetworkStart",SSO_SILENT_START:"msal:ssoSilentStart",SSO_SILENT_SUCCESS:"msal:ssoSilentSuccess",SSO_SILENT_FAILURE:"msal:ssoSilentFailure",ACQUIRE_TOKEN_BY_CODE_START:"msal:acquireTokenByCodeStart",ACQUIRE_TOKEN_BY_CODE_SUCCESS:"msal:acquireTokenByCodeSuccess",ACQUIRE_TOKEN_BY_CODE_FAILURE:"msal:acquireTokenByCodeFailure",HANDLE_REDIRECT_START:"msal:handleRedirectStart",HANDLE_REDIRECT_END:"msal:handleRedirectEnd",POPUP_OPENED:"msal:popupOpened",LOGOUT_START:"msal:logoutStart",LOGOUT_SUCCESS:"msal:logoutSuccess",LOGOUT_FAILURE:"msal:logoutFailure",LOGOUT_END:"msal:logoutEnd",RESTORE_FROM_BFCACHE:"msal:restoreFromBFCache"};class pa{constructor(e){this.eventCallbacks=new Map,this.logger=e||new Tt({})}addEventCallback(e,t,r){if("undefined"!=typeof window){const o=r||Ms();return this.eventCallbacks.has(o)?(this.logger.error(`Event callback with id: ${o} is already registered. Please provide a unique id or remove the existing callback and try again.`),null):(this.eventCallbacks.set(o,[e,t||[]]),this.logger.verbose(`Event callback registered with id: ${o}`),o)}return null}removeEventCallback(e){this.eventCallbacks.delete(e),this.logger.verbose(`Event callback ${e} removed.`)}emitEvent(e,t,r,o){if("undefined"!=typeof window){const n={eventType:e,interactionType:t||null,payload:r||null,error:o||null,timestamp:Date.now()};this.eventCallbacks.forEach((([t,r],o)=>{(0===r.length||r.includes(e))&&(this.logger.verbose(`Emitting event to callback ${o}: ${e}`),t.apply(null,[n]))}))}}}class ma{constructor(e,t,r,o,n,i,s,a,c){this.config=e,this.browserStorage=t,this.browserCrypto=r,this.networkClient=this.config.system.networkClient,this.eventHandler=n,this.navigationClient=i,this.nativeMessageHandler=a,this.correlationId=c||ss(),this.logger=o.clone(mi.MSAL_SKU,Ls,this.correlationId),this.performanceClient=s}async clearCacheOnLogout(e){if(e){Nr.accountInfoIsEqual(e,this.browserStorage.getActiveAccount(),!1)&&(this.logger.verbose("Setting active account to null"),this.browserStorage.setActiveAccount(null));try{await this.browserStorage.removeAccount(Nr.generateAccountCacheKey(e)),this.logger.verbose("Cleared cache items belonging to the account provided in the logout request.")}catch(e){this.logger.error("Account provided in logout request was not found. Local cache unchanged.")}}else try{this.logger.verbose("No account provided in logout request, clearing all cache items.",this.correlationId),await this.browserStorage.clear(),await this.browserCrypto.clearKeystore()}catch(e){this.logger.error("Attempted to clear all MSAL cache items and failed. Local cache unchanged.")}}getRedirectUri(e){this.logger.verbose("getRedirectUri called");const t=e||this.config.auth.redirectUri||Ts();return xr.getAbsoluteUrl(t,Ts())}initializeServerTelemetryManager(e,t){this.logger.verbose("initializeServerTelemetryManager called");const r={clientId:this.config.auth.clientId,correlationId:this.correlationId,apiId:e,forceRefresh:t||!1,wrapperSKU:this.browserStorage.getWrapperMetadata()[0],wrapperVer:this.browserStorage.getWrapperMetadata()[1]};return new nn(r,this.browserStorage)}async getDiscoveredAuthority(e){const{account:t}=e,r=e.requestExtraQueryParameters&&e.requestExtraQueryParameters.hasOwnProperty("instance_aware")?e.requestExtraQueryParameters.instance_aware:void 0;this.performanceClient.addQueueMeasurement(yo.StandardInteractionClientGetDiscoveredAuthority,this.correlationId);const o={protocolMode:this.config.auth.protocolMode,OIDCOptions:this.config.auth.OIDCOptions,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache},n=e.requestAuthority||this.config.auth.authority,i=r?.length?"true"===r:this.config.auth.instanceAware,s=t&&i?this.config.auth.authority.replace(xr.getDomainFromUrl(n),t.environment):n,a=bo.generateAuthority(s,e.requestAzureCloudOptions||this.config.auth.azureCloudOptions),c=await Io(Ro,yo.AuthorityFactoryCreateDiscoveredInstance,this.logger,this.performanceClient,this.correlationId)(a,this.config.system.networkClient,this.browserStorage,o,this.logger,this.correlationId,this.performanceClient);if(t&&!c.isAlias(t.environment))throw Cr(pr);return c}}const fa=32;async function ya(e,t,r){e.addQueueMeasurement(yo.GeneratePkceCodes,r);const o=ko(va,yo.GenerateCodeVerifier,t,e,r)(e,t,r);return{verifier:o,challenge:await Io(Ca,yo.GenerateCodeChallengeFromVerifier,t,e,r)(o,e,t,r)}}function va(e,t,r){try{const o=new Uint8Array(fa);ko(ns,yo.GetRandomValues,t,e,r)(o);return Qi(o)}catch(e){throw pi(yn)}}async function Ca(e,t,r,o){t.addQueueMeasurement(yo.GenerateCodeChallengeFromVerifier,o);try{const n=await Io(os,yo.Sha256Digest,r,t,o)(e,t,o);return Qi(new Uint8Array(n))}catch(e){throw pi(yn)}}async function wa(e,t,r,o){r.addQueueMeasurement(yo.InitializeBaseRequest,e.correlationId);const n=e.authority||t.auth.authority,i=[...e&&e.scopes||[]],s={...e,correlationId:e.correlationId,authority:n,scopes:i};if(s.authenticationScheme){if(s.authenticationScheme===V.SSH){if(!e.sshJwk)throw Cr(cr);if(!e.sshKid)throw Cr(lr)}o.verbose(`Authentication Scheme set to "${s.authenticationScheme}" as configured in Auth request`)}else s.authenticationScheme=V.BEARER,o.verbose('Authentication Scheme wasn\'t explicitly set in request, defaulting to "Bearer" request');return t.cache.claimsBasedCachingEnabled&&e.claims&&!wr.isEmptyObj(e.claims)&&(s.requestedClaimsHash=await cs(e.claims)),s}async function Ta(e,t,r,o,n){o.addQueueMeasurement(yo.InitializeSilentRequest,e.correlationId);const i=await Io(wa,yo.InitializeBaseRequest,n,o,e.correlationId)(e,r,o,n);return{...e,...i,account:t,forceRefresh:e.forceRefresh||!1}}class ka extends ma{async initializeAuthorizationCodeRequest(e){this.performanceClient.addQueueMeasurement(yo.StandardInteractionClientInitializeAuthorizationCodeRequest,this.correlationId);const t=await Io(ya,yo.GeneratePkceCodes,this.logger,this.performanceClient,this.correlationId)(this.performanceClient,this.logger,this.correlationId),o={...e,redirectUri:e.redirectUri,code:r.EMPTY_STRING,codeVerifier:t.verifier};return e.codeChallenge=t.challenge,e.codeChallengeMethod=r.S256_CODE_CHALLENGE_METHOD,o}initializeLogoutRequest(e){this.logger.verbose("initializeLogoutRequest called",e?.correlationId);const t={correlationId:this.correlationId||ss(),...e};if(e)if(e.logoutHint)this.logger.verbose("logoutHint has already been set in logoutRequest");else if(e.account){const r=this.getLogoutHintFromIdTokenClaims(e.account);r&&(this.logger.verbose("Setting logoutHint to login_hint ID Token Claim value for the account provided"),t.logoutHint=r)}else this.logger.verbose("logoutHint was not set and account was not passed into logout request, logoutHint will not be set");else this.logger.verbose("logoutHint will not be set since no logout request was configured");return e&&null===e.postLogoutRedirectUri?this.logger.verbose("postLogoutRedirectUri passed as null, not setting post logout redirect uri",t.correlationId):e&&e.postLogoutRedirectUri?(this.logger.verbose("Setting postLogoutRedirectUri to uri set on logout request",t.correlationId),t.postLogoutRedirectUri=xr.getAbsoluteUrl(e.postLogoutRedirectUri,Ts())):null===this.config.auth.postLogoutRedirectUri?this.logger.verbose("postLogoutRedirectUri configured as null and no uri set on request, not passing post logout redirect",t.correlationId):this.config.auth.postLogoutRedirectUri?(this.logger.verbose("Setting postLogoutRedirectUri to configured uri",t.correlationId),t.postLogoutRedirectUri=xr.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri,Ts())):(this.logger.verbose("Setting postLogoutRedirectUri to current page",t.correlationId),t.postLogoutRedirectUri=xr.getAbsoluteUrl(Ts(),Ts())),t}getLogoutHintFromIdTokenClaims(e){const t=e.idTokenClaims;if(t){if(t.login_hint)return t.login_hint;this.logger.verbose("The ID Token Claims tied to the provided account do not contain a login_hint claim, logoutHint will not be added to logout request")}else this.logger.verbose("The provided account does not contain ID Token Claims, logoutHint will not be added to logout request");return null}async createAuthCodeClient(e){this.performanceClient.addQueueMeasurement(yo.StandardInteractionClientCreateAuthCodeClient,this.correlationId);const t=await Io(this.getClientConfiguration.bind(this),yo.StandardInteractionClientGetClientConfiguration,this.logger,this.performanceClient,this.correlationId)(e);return new Xo(t,this.performanceClient)}async getClientConfiguration(e){const{serverTelemetryManager:t,requestAuthority:o,requestAzureCloudOptions:n,requestExtraQueryParameters:i,account:s}=e;this.performanceClient.addQueueMeasurement(yo.StandardInteractionClientGetClientConfiguration,this.correlationId);const a=await Io(this.getDiscoveredAuthority.bind(this),yo.StandardInteractionClientGetDiscoveredAuthority,this.logger,this.performanceClient,this.correlationId)({requestAuthority:o,requestAzureCloudOptions:n,requestExtraQueryParameters:i,account:s}),c=this.config.system.loggerOptions;return{authOptions:{clientId:this.config.auth.clientId,authority:a,clientCapabilities:this.config.auth.clientCapabilities},systemOptions:{tokenRenewalOffsetSeconds:this.config.system.tokenRenewalOffsetSeconds,preventCorsPreflight:!0},loggerOptions:{loggerCallback:c.loggerCallback,piiLoggingEnabled:c.piiLoggingEnabled,logLevel:c.logLevel,correlationId:this.correlationId},cacheOptions:{claimsBasedCachingEnabled:this.config.cache.claimsBasedCachingEnabled},cryptoInterface:this.browserCrypto,networkInterface:this.networkClient,storageInterface:this.browserStorage,serverTelemetryManager:t,libraryInfo:{sku:mi.MSAL_SKU,version:Ls,cpu:r.EMPTY_STRING,os:r.EMPTY_STRING},telemetry:this.config.telemetry}}async initializeAuthorizationRequest(e,t){this.performanceClient.addQueueMeasurement(yo.StandardInteractionClientInitializeAuthorizationRequest,this.correlationId);const o=this.getRedirectUri(e.redirectUri),n={interactionType:t},i=jo.setRequestState(this.browserCrypto,e&&e.state||r.EMPTY_STRING,n),s={...await Io(wa,yo.InitializeBaseRequest,this.logger,this.performanceClient,this.correlationId)({...e,correlationId:this.correlationId},this.config,this.performanceClient,this.logger),redirectUri:o,state:i,nonce:e.nonce||ss(),responseMode:this.config.auth.OIDCOptions.serverResponseType},a=e.account||this.browserStorage.getActiveAccount();if(a&&(this.logger.verbose("Setting validated request account",this.correlationId),this.logger.verbosePii(`Setting validated request account: ${a.homeAccountId}`,this.correlationId),s.account=a),!s.loginHint&&!a){const e=this.browserStorage.getLegacyLoginHint();e&&(s.loginHint=e)}return s}}const Ia="user_switch",Aa={[Ia]:"User attempted to switch accounts in the native broker, which is not allowed. All new accounts must sign-in through the standard web flow first, please try again."};class ba extends ke{constructor(e,t,r){super(e,t),Object.setPrototypeOf(this,ba.prototype),this.name="NativeAuthError",this.ext=r}}function Sa(e){return!(!e.ext||!e.ext.status||"PERSISTENT_ERROR"!==e.ext.status&&"DISABLED"!==e.ext.status)||(!(!e.ext||!e.ext.error||-2147186943!==e.ext.error)||"ContentError"===e.errorCode)}function Ea(e,t,r){if(r&&r.status)switch(r.status){case"ACCOUNT_UNAVAILABLE":return Ko(Mo);case"USER_INTERACTION_REQUIRED":return new Fo(e,t);case"USER_CANCEL":return pi(Rn);case"NO_NETWORK":return pi(jn)}return new ba(e,Aa[e]||t,r)}class Ra extends ka{async acquireToken(e){this.performanceClient.addQueueMeasurement(yo.SilentCacheClientAcquireToken,e.correlationId);const t=this.initializeServerTelemetryManager(Bi.acquireTokenSilent_silentFlow),r=await Io(this.getClientConfiguration.bind(this),yo.StandardInteractionClientGetClientConfiguration,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,account:e.account}),o=new en(r,this.performanceClient);this.logger.verbose("Silent auth client created");try{const t=(await Io(o.acquireCachedToken.bind(o),yo.SilentFlowClientAcquireCachedToken,this.logger,this.performanceClient,e.correlationId)(e))[0];return this.performanceClient.addFields({fromCache:!0},e.correlationId),t}catch(e){throw e instanceof gi&&e.errorCode===Yn&&this.logger.verbose("Signing keypair for bound access token not found. Refreshing bound access token and generating a new crypto keypair."),e}}logout(e){this.logger.verbose("logoutRedirect called");const t=this.initializeLogoutRequest(e);return this.clearCacheOnLogout(t?.account)}}const _a="brk_client_id",Pa="brk_redirect_uri";class Ma extends ma{constructor(e,t,r,o,n,i,s,a,c,l,d,u){super(e,t,r,o,n,i,a,c,u),this.apiId=s,this.accountId=l,this.nativeMessageHandler=c,this.nativeStorageManager=d,this.silentCacheClient=new Ra(e,this.nativeStorageManager,r,o,n,i,a,c,u),this.serverTelemetryManager=this.initializeServerTelemetryManager(this.apiId);const h=this.nativeMessageHandler.getExtensionId()===yi?"chrome":this.nativeMessageHandler.getExtensionId()?.length?"unknown":void 0;this.skus=nn.makeExtraSkuString({libraryName:mi.MSAL_SKU,libraryVersion:Ls,extensionName:h,extensionVersion:this.nativeMessageHandler.getExtensionVersion()})}addRequestSKUs(e){e.extraParameters={...e.extraParameters,[po]:this.skus}}async acquireToken(e){this.performanceClient.addQueueMeasurement(yo.NativeInteractionClientAcquireToken,e.correlationId),this.logger.trace("NativeInteractionClient - acquireToken called.");const t=this.performanceClient.startMeasurement(yo.NativeInteractionClientAcquireToken,e.correlationId),r=Et();try{const o=await this.initializeNativeRequest(e);try{const e=await this.acquireTokensFromCache(this.accountId,o);return t.end({success:!0,isNativeBroker:!1,fromCache:!0}),e}catch(e){this.logger.info("MSAL internal Cache does not contain tokens, proceed to make a native call")}const{...n}=o,i={method:Ti,request:n},s=await this.nativeMessageHandler.sendMessage(i),a=this.validateNativeResponse(s);return await this.handleNativeResponse(a,o,r).then((e=>(t.end({success:!0,isNativeBroker:!0,requestId:e.requestId}),this.serverTelemetryManager.clearNativeBrokerErrorCode(),e))).catch((e=>{throw t.end({success:!1,errorCode:e.errorCode,subErrorCode:e.subError,isNativeBroker:!0}),e}))}catch(e){throw e instanceof ba&&this.serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode),e}}createSilentCacheRequest(e,t){return{authority:e.authority,correlationId:this.correlationId,scopes:Tr.fromString(e.scope).asArray(),account:t,forceRefresh:!1}}async acquireTokensFromCache(e,t){if(!e)throw this.logger.warning("NativeInteractionClient:acquireTokensFromCache - No nativeAccountId provided"),vt(Je);const r=this.browserStorage.getBaseAccountInfo({nativeAccountId:e});if(!r)throw vt(Je);try{const e=this.createSilentCacheRequest(t,r),o=await this.silentCacheClient.acquireToken(e),n={...r,idTokenClaims:o?.idTokenClaims,idToken:o?.idToken};return{...o,account:n}}catch(e){throw e}}async acquireTokenRedirect(e,t){this.logger.trace("NativeInteractionClient - acquireTokenRedirect called.");const{...r}=e;delete r.onRedirectNavigate;const o=await this.initializeNativeRequest(r),n={method:Ti,request:o};try{const e=await this.nativeMessageHandler.sendMessage(n);this.validateNativeResponse(e)}catch(e){if(e instanceof ba&&(this.serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode),Sa(e)))throw e}this.browserStorage.setTemporaryCache(Ui,JSON.stringify(o),!0);const i={apiId:Bi.acquireTokenRedirect,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},s=this.config.auth.navigateToLoginRequestUrl?window.location.href:this.getRedirectUri(e.redirectUri);t.end({success:!0}),await this.navigationClient.navigateExternal(s,i)}async handleRedirectPromise(e,t){if(this.logger.trace("NativeInteractionClient - handleRedirectPromise called."),!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null."),null;const r=this.browserStorage.getCachedNativeRequest();if(!r)return this.logger.verbose("NativeInteractionClient - handleRedirectPromise called but there is no cached request, returning null."),e&&t&&e?.addFields({errorCode:"no_cached_request"},t),null;const{prompt:o,...n}=r;o&&this.logger.verbose("NativeInteractionClient - handleRedirectPromise called and prompt was included in the original request, removing prompt from cached request to prevent second interaction with native broker window."),this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Ui));const i={method:Ti,request:n},s=Et();try{this.logger.verbose("NativeInteractionClient - handleRedirectPromise sending message to native broker.");const e=await this.nativeMessageHandler.sendMessage(i);this.validateNativeResponse(e);const t=this.handleNativeResponse(e,n,s);this.browserStorage.setInteractionInProgress(!1);const r=await t;return this.serverTelemetryManager.clearNativeBrokerErrorCode(),r}catch(e){throw this.browserStorage.setInteractionInProgress(!1),e}}logout(){return this.logger.trace("NativeInteractionClient - logout called."),Promise.reject("Logout not implemented yet")}async handleNativeResponse(e,t,r){this.logger.trace("NativeInteractionClient - handleNativeResponse called.");const o=bt(e.id_token,Ys),n=this.createHomeAccountIdentifier(e,o),i=this.browserStorage.getAccountInfoFilteredBy({nativeAccountId:t.accountId})?.homeAccountId;if(n!==i&&e.account.id!==t.accountId)throw Ea(Ia);const s=await this.getDiscoveredAuthority({requestAuthority:t.authority}),a=Yo(this.browserStorage,s,n,Ys,o,e.client_info,void 0,o.tid,void 0,e.account.id,this.logger),c=await this.generateAuthenticationResult(e,t,o,a,s.canonicalAuthority,r);return this.cacheAccount(a),this.cacheNativeTokens(e,t,n,o,e.access_token,c.tenantId,r),c}createHomeAccountIdentifier(e,t){return Nr.generateHomeAccountId(e.client_info||r.EMPTY_STRING,Er,this.logger,this.browserCrypto,t)}generateScopes(e,t){return e.scope?Tr.fromString(e.scope):Tr.fromString(t.scope)}async generatePopAccessToken(e,t){if(t.tokenType===V.POP&&t.signPopToken){if(e.shr)return this.logger.trace("handleNativeServerResponse: SHR is enabled in native layer"),e.shr;const r=new Wo(this.browserCrypto),o={resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,shrNonce:t.shrNonce};if(!t.keyId)throw vt(ct);return r.signPopToken(e.access_token,t.keyId,o)}return e.access_token}async generateAuthenticationResult(e,t,o,n,i,s){const a=this.addTelemetryFromNativeResponse(e),c=e.scope?Tr.fromString(e.scope):Tr.fromString(t.scope),l=e.account.properties||{},d=l.UID||o.oid||o.sub||r.EMPTY_STRING,u=l.TenantId||o.tid||r.EMPTY_STRING,h=Sr(n.getAccountInfo(),void 0,o,e.id_token);h.nativeAccountId!==e.account.id&&(h.nativeAccountId=e.account.id);const g=await this.generatePopAccessToken(e,t),p=t.tokenType===V.POP?V.POP:V.BEARER;return{authority:i,uniqueId:d,tenantId:u,scopes:c.asArray(),account:h,idToken:e.id_token,idTokenClaims:o,accessToken:g,fromCache:!!a&&this.isResponseFromCache(a),expiresOn:new Date(1e3*Number(s+e.expires_in)),tokenType:p,correlationId:this.correlationId,state:e.state,fromNativeBroker:!0}}cacheAccount(e){this.browserStorage.setAccount(e),this.browserStorage.removeAccountContext(e).catch((e=>{this.logger.error(`Error occurred while removing account context from browser storage. ${e}`)}))}cacheNativeTokens(e,t,o,n,i,s,a){const c=Mt(o,t.authority,e.id_token||"",t.clientId,n.tid||""),l=a+(t.tokenType===V.POP?r.SHR_NONCE_VALIDITY:("string"==typeof e.expires_in?parseInt(e.expires_in,10):e.expires_in)||0),d=this.generateScopes(e,t),u={idToken:c,accessToken:Ot(o,t.authority,i,t.clientId,n.tid||s,d.printScopes(),l,0,Ys,void 0,t.tokenType,void 0,t.keyId)};this.nativeStorageManager.saveCacheRecord(u,t.storeInCache)}addTelemetryFromNativeResponse(e){const t=this.getMATSFromResponse(e);return t?(this.performanceClient.addFields({extensionId:this.nativeMessageHandler.getExtensionId(),extensionVersion:this.nativeMessageHandler.getExtensionVersion(),matsBrokerVersion:t.broker_version,matsAccountJoinOnStart:t.account_join_on_start,matsAccountJoinOnEnd:t.account_join_on_end,matsDeviceJoin:t.device_join,matsPromptBehavior:t.prompt_behavior,matsApiErrorCode:t.api_error_code,matsUiVisible:t.ui_visible,matsSilentCode:t.silent_code,matsSilentBiSubCode:t.silent_bi_sub_code,matsSilentMessage:t.silent_message,matsSilentStatus:t.silent_status,matsHttpStatus:t.http_status,matsHttpEventCount:t.http_event_count},this.correlationId),t):null}validateNativeResponse(e){if(e.hasOwnProperty("access_token")&&e.hasOwnProperty("id_token")&&e.hasOwnProperty("client_info")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scope")&&e.hasOwnProperty("expires_in"))return e;throw Ie(ye,"Response missing expected properties.")}getMATSFromResponse(e){if(e.properties.MATS)try{return JSON.parse(e.properties.MATS)}catch(e){this.logger.error("NativeInteractionClient - Error parsing MATS telemetry, returning null instead")}return null}isResponseFromCache(e){return void 0===e.is_cached?(this.logger.verbose("NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false."),!1):!!e.is_cached}async initializeNativeRequest(e){this.logger.trace("NativeInteractionClient - initializeNativeRequest called");const t=e.authority||this.config.auth.authority;e.account&&await this.getDiscoveredAuthority({requestAuthority:t,requestAzureCloudOptions:e.azureCloudOptions,account:e.account});const r=new xr(t);r.validateAsUri();const{scopes:o,...n}=e,i=new Tr(o||[]);i.appendScopes(a);const s={...n,accountId:this.accountId,clientId:this.config.auth.clientId,authority:r.urlString,scope:i.printScopes(),redirectUri:this.getRedirectUri(e.redirectUri),prompt:(()=>{switch(this.apiId){case Bi.ssoSilent:case Bi.acquireTokenSilent_silentFlow:return this.logger.trace("initializeNativeRequest: silent request sets prompt to none"),R.NONE}if(e.prompt)switch(e.prompt){case R.NONE:case R.CONSENT:case R.LOGIN:return this.logger.trace("initializeNativeRequest: prompt is compatible with native flow"),e.prompt;default:throw this.logger.trace(`initializeNativeRequest: prompt = ${e.prompt} is not compatible with native flow`),pi(si)}else this.logger.trace("initializeNativeRequest: prompt was not provided")})(),correlationId:this.correlationId,tokenType:e.authenticationScheme,windowTitleSubstring:document.title,extraParameters:{...e.extraQueryParameters,...e.tokenQueryParameters},extendedExpiryToken:!1,keyId:e.popKid};if(s.signPopToken&&e.popKid)throw pi(ci);if(this.handleExtraBrokerParams(s),s.extraParameters=s.extraParameters||{},s.extraParameters.telemetry=vi,e.authenticationScheme===V.POP){const t={resourceRequestUri:e.resourceRequestUri,resourceRequestMethod:e.resourceRequestMethod,shrClaims:e.shrClaims,shrNonce:e.shrNonce},r=new Wo(this.browserCrypto);let o;if(s.keyId)o=this.browserCrypto.base64UrlEncode(JSON.stringify({kid:s.keyId})),s.signPopToken=!1;else{const n=await Io(r.generateCnf.bind(r),yo.PopTokenGenerateCnf,this.logger,this.performanceClient,e.correlationId)(t,this.logger);o=n.reqCnfString,s.keyId=n.kid,s.signPopToken=!0}s.reqCnf=o}return this.addRequestSKUs(s),s}handleExtraBrokerParams(e){if(e.extraParameters&&e.extraParameters.hasOwnProperty(_a)&&e.extraParameters.hasOwnProperty(Pa)&&e.extraParameters.hasOwnProperty(co)){const t=e.extraParameters[co],r=e.redirectUri,o=e.extraParameters[Pa];e.extraParameters={child_client_id:t,child_redirect_uri:r},e.redirectUri=o}}}class Oa{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=r.startMeasurement(yo.NativeMessageHandlerHandshake)}async sendMessage(e){this.logger.trace("NativeMessageHandler - sendMessage called.");const t={channel:fi,extensionId:this.extensionId,responseId:ss(),body:e};return this.logger.trace("NativeMessageHandler - Sending request to browser extension"),this.logger.tracePii(`NativeMessageHandler - Sending request to browser extension: ${JSON.stringify(t)}`),this.messageChannel.port1.postMessage(t),new Promise(((e,r)=>{this.resolvers.set(t.responseId,{resolve:e,reject:r})}))}static async createProvider(e,t,r){e.trace("NativeMessageHandler - createProvider called.");try{const o=new Oa(e,t,r,yi);return await o.sendHandshakeRequest(),o}catch(o){const n=new Oa(e,t,r);return await n.sendHandshakeRequest(),n}}async sendHandshakeRequest(){this.logger.trace("NativeMessageHandler - sendHandshakeRequest called."),window.addEventListener("message",this.windowListener,!1);const e={channel:fi,extensionId:this.extensionId,responseId:ss(),body:{method:Ci}};return this.handshakeEvent.add({extensionId:this.extensionId,extensionHandshakeTimeoutMs:this.handshakeTimeoutMs}),this.messageChannel.port1.onmessage=e=>{this.onChannelMessage(e)},window.postMessage(e,window.origin,[this.messageChannel.port2]),new Promise(((t,r)=>{this.handshakeResolvers.set(e.responseId,{resolve:t,reject:r}),this.timeoutId=window.setTimeout((()=>{window.removeEventListener("message",this.windowListener,!1),this.messageChannel.port1.close(),this.messageChannel.port2.close(),this.handshakeEvent.end({extensionHandshakeTimedOut:!0,success:!1}),r(pi(ri)),this.handshakeResolvers.delete(e.responseId)}),this.handshakeTimeoutMs)}))}onWindowMessage(e){if(this.logger.trace("NativeMessageHandler - onWindowMessage called"),e.source!==window)return;const t=e.data;if(t.channel&&t.channel===fi&&(!t.extensionId||t.extensionId===this.extensionId)&&t.body.method===Ci){const e=this.handshakeResolvers.get(t.responseId);if(!e)return void this.logger.trace(`NativeMessageHandler.onWindowMessage - resolver can't be found for request ${t.responseId}`);this.logger.verbose(t.extensionId?`Extension with id: ${t.extensionId} not installed`:"No extension installed"),clearTimeout(this.timeoutId),this.messageChannel.port1.close(),this.messageChannel.port2.close(),window.removeEventListener("message",this.windowListener,!1),this.handshakeEvent.end({success:!1,extensionInstalled:!1}),e.reject(pi(oi))}}onChannelMessage(e){this.logger.trace("NativeMessageHandler - onChannelMessage called.");const t=e.data,r=this.resolvers.get(t.responseId),o=this.handshakeResolvers.get(t.responseId);try{const e=t.body.method;if(e===ki){if(!r)return;const e=t.body.response;if(this.logger.trace("NativeMessageHandler - Received response from browser extension"),this.logger.tracePii(`NativeMessageHandler - Received response from browser extension: ${JSON.stringify(e)}`),"Success"!==e.status)r.reject(Ea(e.code,e.description,e.ext));else{if(!e.result)throw Ie(ye,"Event does not contain result.");e.result.code&&e.result.description?r.reject(Ea(e.result.code,e.result.description,e.result.ext)):r.resolve(e.result)}this.resolvers.delete(t.responseId)}else if(e===wi){if(!o)return void this.logger.trace(`NativeMessageHandler.onChannelMessage - resolver can't be found for request ${t.responseId}`);clearTimeout(this.timeoutId),window.removeEventListener("message",this.windowListener,!1),this.extensionId=t.extensionId,this.extensionVersion=t.body.version,this.logger.verbose(`NativeMessageHandler - Received HandshakeResponse from extension: ${this.extensionId}`),this.handshakeEvent.end({extensionInstalled:!0,success:!0}),o.resolve(),this.handshakeResolvers.delete(t.responseId)}}catch(t){this.logger.error("Error parsing response from WAM Extension"),this.logger.errorPii(`Error parsing response from WAM Extension: ${t}`),this.logger.errorPii(`Unable to parse ${e}`),r?r.reject(t):o&&o.reject(t)}}getExtensionId(){return this.extensionId}getExtensionVersion(){return this.extensionVersion}static isNativeAvailable(e,t,r,o){if(t.trace("isNativeAvailable called"),!e.system.allowNativeBroker)return t.trace("isNativeAvailable: allowNativeBroker is not enabled, returning false"),!1;if(!r)return t.trace("isNativeAvailable: WAM extension provider is not initialized, returning false"),!1;if(o)switch(o){case V.BEARER:case V.POP:return t.trace("isNativeAvailable: authenticationScheme is supported, returning true"),!0;default:return t.trace("isNativeAvailable: authenticationScheme is not supported, returning false"),!1}return!0}}class Na{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){let r;this.performanceClient.addQueueMeasurement(yo.HandleCodeResponse,t.correlationId);try{r=this.authModule.handleFragmentResponse(e,t.state)}catch(e){throw e instanceof oo&&e.subError===Rn?pi(Rn):e}return Io(this.handleCodeResponseFromServer.bind(this),yo.HandleCodeResponseFromServer,this.logger,this.performanceClient,t.correlationId)(r,t)}async handleCodeResponseFromServer(e,t,r=!0){if(this.performanceClient.addQueueMeasurement(yo.HandleCodeResponseFromServer,t.correlationId),this.logger.trace("InteractionHandler.handleCodeResponseFromServer called"),this.authCodeRequest.code=e.code,e.cloud_instance_host_name&&await Io(this.authModule.updateAuthority.bind(this.authModule),yo.UpdateTokenEndpointAuthority,this.logger,this.performanceClient,t.correlationId)(e.cloud_instance_host_name,t.correlationId),r&&(e.nonce=t.nonce||void 0),e.state=t.state,e.client_info)this.authCodeRequest.clientInfo=e.client_info;else{const e=this.createCcsCredentials(t);e&&(this.authCodeRequest.ccsCredential=e)}return await Io(this.authModule.acquireToken.bind(this.authModule),yo.AuthClientAcquireToken,this.logger,this.performanceClient,t.correlationId)(this.authCodeRequest,e)}createCcsCredentials(e){return e.account?{credential:e.account.homeAccountId,type:so}:e.loginHint?{credential:e.loginHint,type:ao}:null}}function qa(e,t,r){const o=Ur(e);if(!o)throw qr(e)?(r.error(`A ${t} is present in the iframe but it does not contain known properties. It's likely that the ${t} has been replaced by code running on the redirectUri page.`),r.errorPii(`The ${t} detected is: ${e}`),pi(kn)):(r.error(`The request has returned to the redirectUri but a ${t} is not present. It's likely that the ${t} has been removed or the page has been redirected by code running on the redirectUri page.`),pi(wn));return o}class Ua extends ka{constructor(e,t,r,o,n,i,s,a,c,l){super(e,t,r,o,n,i,s,c,l),this.unloadWindow=this.unloadWindow.bind(this),this.nativeStorage=a}acquireToken(e){try{const t={popupName:this.generatePopupName(e.scopes||a,e.authority||this.config.auth.authority),popupWindowAttributes:e.popupWindowAttributes||{},popupWindowParent:e.popupWindowParent??window};return this.config.system.asyncPopups?(this.logger.verbose("asyncPopups set to true, acquiring token"),this.acquireTokenPopupAsync(e,t)):(this.logger.verbose("asyncPopup set to false, opening popup before acquiring token"),t.popup=this.openSizedPopup("about:blank",t),this.acquireTokenPopupAsync(e,t))}catch(e){return Promise.reject(e)}}logout(e){try{this.logger.verbose("logoutPopup called");const t=this.initializeLogoutRequest(e),r={popupName:this.generateLogoutPopupName(t),popupWindowAttributes:e?.popupWindowAttributes||{},popupWindowParent:e?.popupWindowParent??window},o=e&&e.authority,n=e&&e.mainWindowRedirectUri;return this.config.system.asyncPopups?(this.logger.verbose("asyncPopups set to true"),this.logoutPopupAsync(t,r,o,n)):(this.logger.verbose("asyncPopup set to false, opening popup"),r.popup=this.openSizedPopup("about:blank",r),this.logoutPopupAsync(t,r,o,n))}catch(e){return Promise.reject(e)}}async acquireTokenPopupAsync(e,r){this.logger.verbose("acquireTokenPopupAsync called");const o=this.initializeServerTelemetryManager(Bi.acquireTokenPopup),n=await Io(this.initializeAuthorizationRequest.bind(this),yo.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,this.correlationId)(e,t.InteractionType.Popup);Ps(n.authority);try{const i=await Io(this.initializeAuthorizationCodeRequest.bind(this),yo.StandardInteractionClientInitializeAuthorizationCodeRequest,this.logger,this.performanceClient,this.correlationId)(n),s=await Io(this.createAuthCodeClient.bind(this),yo.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:o,requestAuthority:n.authority,requestAzureCloudOptions:n.azureCloudOptions,requestExtraQueryParameters:n.extraQueryParameters,account:n.account}),a=Oa.isNativeAvailable(this.config,this.logger,this.nativeMessageHandler,e.authenticationScheme);let c;a&&(c=this.performanceClient.startMeasurement(yo.FetchAccountIdWithNativeBroker,e.correlationId));const l=await s.getAuthCodeUrl({...n,nativeBroker:a}),d=new Na(s,this.browserStorage,i,this.logger,this.performanceClient),u=this.initiateAuthRequest(l,r);this.eventHandler.emitEvent(ga.POPUP_OPENED,t.InteractionType.Popup,{popupWindow:u},null);const h=await this.monitorPopupForHash(u,r.popupWindowParent),g=ko(qa,yo.DeserializeResponse,this.logger,this.performanceClient,this.correlationId)(h,this.config.auth.OIDCOptions.serverResponseType,this.logger);if(no.removeThrottle(this.browserStorage,this.config.auth.clientId,i),g.accountId){if(this.logger.verbose("Account id found in hash, calling WAM for token"),c&&c.end({success:!0,isNativeBroker:!0}),!this.nativeMessageHandler)throw pi(ni);const e=new Ma(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Bi.acquireTokenPopup,this.performanceClient,this.nativeMessageHandler,g.accountId,this.nativeStorage,n.correlationId),{userRequestState:t}=jo.parseRequestState(this.browserCrypto,n.state);return await e.acquireToken({...n,state:t,prompt:void 0})}return await d.handleCodeResponse(g,n)}catch(e){throw r.popup?.close(),e instanceof ke&&(e.setCorrelationId(this.correlationId),o.cacheFailedRequest(e)),e}}async logoutPopupAsync(e,r,o,n){this.logger.verbose("logoutPopupAsync called"),this.eventHandler.emitEvent(ga.LOGOUT_START,t.InteractionType.Popup,e);const i=this.initializeServerTelemetryManager(Bi.logoutPopup);try{await this.clearCacheOnLogout(e.account);const s=await Io(this.createAuthCodeClient.bind(this),yo.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:i,requestAuthority:o,account:e.account||void 0});try{s.authority.endSessionEndpoint}catch{if(e.account?.homeAccountId&&e.postLogoutRedirectUri&&s.authority.protocolMode===Or.OIDC){if(this.browserStorage.removeAccount(e.account?.homeAccountId),this.eventHandler.emitEvent(ga.LOGOUT_SUCCESS,t.InteractionType.Popup,e),n){const e={apiId:Bi.logoutPopup,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=xr.getAbsoluteUrl(n,Ts());await this.navigationClient.navigateInternal(t,e)}return void r.popup?.close()}}const a=s.getLogoutUri(e);this.eventHandler.emitEvent(ga.LOGOUT_SUCCESS,t.InteractionType.Popup,e);const c=this.openPopup(a,r);if(this.eventHandler.emitEvent(ga.POPUP_OPENED,t.InteractionType.Popup,{popupWindow:c},null),await this.monitorPopupForHash(c,r.popupWindowParent).catch((()=>{})),n){const e={apiId:Bi.logoutPopup,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},t=xr.getAbsoluteUrl(n,Ts());this.logger.verbose("Redirecting main window to url specified in the request"),this.logger.verbosePii(`Redirecting main window to: ${t}`),await this.navigationClient.navigateInternal(t,e)}else this.logger.verbose("No main window navigation requested")}catch(e){throw r.popup?.close(),e instanceof ke&&(e.setCorrelationId(this.correlationId),i.cacheFailedRequest(e)),this.browserStorage.setInteractionInProgress(!1),this.eventHandler.emitEvent(ga.LOGOUT_FAILURE,t.InteractionType.Popup,null,e),this.eventHandler.emitEvent(ga.LOGOUT_END,t.InteractionType.Popup),e}this.eventHandler.emitEvent(ga.LOGOUT_END,t.InteractionType.Popup)}initiateAuthRequest(e,t){if(e)return this.logger.infoPii(`Navigate to: ${e}`),this.openPopup(e,t);throw this.logger.error("Navigate url is empty"),pi(Cn)}monitorPopupForHash(e,t){return new Promise(((t,r)=>{this.logger.verbose("PopupHandler.monitorPopupForHash - polling started");const o=setInterval((()=>{if(e.closed)return this.logger.error("PopupHandler.monitorPopupForHash - window closed"),clearInterval(o),void r(pi(Rn));let n="";try{n=e.location.href}catch(e){}if(!n||"about:blank"===n)return;clearInterval(o);let i="";const s=this.config.auth.OIDCOptions.serverResponseType;e&&(i=s===P.QUERY?e.location.search:e.location.hash),this.logger.verbose("PopupHandler.monitorPopupForHash - popup window is on same origin as caller"),t(i)}),this.config.system.pollIntervalMilliseconds)})).finally((()=>{this.cleanPopup(e,t)}))}openPopup(e,t){try{let r;if(t.popup?(r=t.popup,this.logger.verbosePii(`Navigating popup window to: ${e}`),r.location.assign(e)):void 0===t.popup&&(this.logger.verbosePii(`Opening popup window to: ${e}`),r=this.openSizedPopup(e,t)),!r)throw pi(En);return r.focus&&r.focus(),this.currentWindow=r,t.popupWindowParent.addEventListener("beforeunload",this.unloadWindow),r}catch(e){throw this.logger.error("error opening popup "+e.message),this.browserStorage.setInteractionInProgress(!1),pi(Sn)}}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,d=r.popupPosition?.top,u=r.popupPosition?.left;return(!c||c<0||c>s)&&(this.logger.verbose("Default popup window width used. Window width not configured or invalid."),c=mi.POPUP_WIDTH),(!l||l<0||l>a)&&(this.logger.verbose("Default popup window height used. Window height not configured or invalid."),l=mi.POPUP_HEIGHT),(!d||d<0||d>a)&&(this.logger.verbose("Default popup window top position used. Window top not configured or invalid."),d=Math.max(0,a/2-mi.POPUP_HEIGHT/2+i)),(!u||u<0||u>s)&&(this.logger.verbose("Default popup window left position used. Window left not configured or invalid."),u=Math.max(0,s/2-mi.POPUP_WIDTH/2+n)),o.open(e,t,`width=${c}, height=${l}, top=${d}, left=${u}, scrollbars=yes`)}unloadWindow(e){this.browserStorage.cleanRequestByInteractionType(t.InteractionType.Popup),this.currentWindow&&this.currentWindow.close(),e.preventDefault()}cleanPopup(e,t){e.close(),t.removeEventListener("beforeunload",this.unloadWindow),this.browserStorage.setInteractionInProgress(!1)}generatePopupName(e,t){return`${mi.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${e.join("-")}.${t}.${this.correlationId}`}generateLogoutPopupName(e){const t=e.account&&e.account.homeAccountId;return`${mi.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${t}.${this.correlationId}`}}class xa{constructor(e,t,r,o,n){this.authModule=e,this.browserStorage=t,this.authCodeRequest=r,this.logger=o,this.performanceClient=n}async initiateAuthRequest(e,t){if(this.logger.verbose("RedirectHandler.initiateAuthRequest called"),e){t.redirectStartPage&&(this.logger.verbose("RedirectHandler.initiateAuthRequest: redirectStartPage set, caching start page"),this.browserStorage.setTemporaryCache(_i,t.redirectStartPage,!0)),this.browserStorage.setTemporaryCache(qi,this.authCodeRequest.correlationId,!0),this.browserStorage.cacheCodeRequest(this.authCodeRequest),this.logger.infoPii(`RedirectHandler.initiateAuthRequest: Navigate to: ${e}`);const r={apiId:Bi.acquireTokenRedirect,timeout:t.redirectTimeout,noHistory:!1};if("function"==typeof t.onRedirectNavigate){this.logger.verbose("RedirectHandler.initiateAuthRequest: Invoking onRedirectNavigate callback");return!1!==t.onRedirectNavigate(e)?(this.logger.verbose("RedirectHandler.initiateAuthRequest: onRedirectNavigate did not return false, navigating"),void await t.navigationClient.navigateExternal(e,r)):void this.logger.verbose("RedirectHandler.initiateAuthRequest: onRedirectNavigate returned false, stopping navigation")}return this.logger.verbose("RedirectHandler.initiateAuthRequest: Navigating window to navigate url"),void await t.navigationClient.navigateExternal(e,r)}throw this.logger.info("RedirectHandler.initiateAuthRequest: Navigate url is empty"),pi(Cn)}async handleCodeResponse(e,t){this.logger.verbose("RedirectHandler.handleCodeResponse called"),this.browserStorage.setInteractionInProgress(!1);const r=this.browserStorage.generateStateKey(t),o=this.browserStorage.getTemporaryCache(r);if(!o)throw vt(qe,"Cached State");let n;try{n=this.authModule.handleFragmentResponse(e,o)}catch(e){throw e instanceof oo&&e.subError===Rn?pi(Rn):e}const i=this.browserStorage.generateNonceKey(o),s=this.browserStorage.getTemporaryCache(i);if(this.authCodeRequest.code=n.code,n.cloud_instance_host_name&&await Io(this.authModule.updateAuthority.bind(this.authModule),yo.UpdateTokenEndpointAuthority,this.logger,this.performanceClient,this.authCodeRequest.correlationId)(n.cloud_instance_host_name,this.authCodeRequest.correlationId),n.nonce=s||void 0,n.state=o,n.client_info)this.authCodeRequest.clientInfo=n.client_info;else{const e=this.checkCcsCredentials();e&&(this.authCodeRequest.ccsCredential=e)}const a=await this.authModule.acquireToken(this.authCodeRequest,n);return this.browserStorage.cleanRequestByState(t),a}checkCcsCredentials(){const e=this.browserStorage.getTemporaryCache(Ni,!0);if(e)try{return JSON.parse(e)}catch(t){this.authModule.logger.error("Cache credential could not be parsed"),this.authModule.logger.errorPii(`Cache credential could not be parsed: ${e}`)}return null}}class La extends ka{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 r=await Io(this.initializeAuthorizationRequest.bind(this),yo.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,this.correlationId)(e,t.InteractionType.Redirect);this.browserStorage.updateCacheEntries(r.state,r.nonce,r.authority,r.loginHint||"",r.account||null);const o=this.initializeServerTelemetryManager(Bi.acquireTokenRedirect),n=e=>{e.persisted&&(this.logger.verbose("Page was restored from back/forward cache. Clearing temporary cache."),this.browserStorage.cleanRequestByState(r.state),this.eventHandler.emitEvent(ga.RESTORE_FROM_BFCACHE,t.InteractionType.Redirect))};try{const t=await Io(this.initializeAuthorizationCodeRequest.bind(this),yo.StandardInteractionClientInitializeAuthorizationCodeRequest,this.logger,this.performanceClient,this.correlationId)(r),i=await Io(this.createAuthCodeClient.bind(this),yo.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:o,requestAuthority:r.authority,requestAzureCloudOptions:r.azureCloudOptions,requestExtraQueryParameters:r.extraQueryParameters,account:r.account}),s=new xa(i,this.browserStorage,t,this.logger,this.performanceClient),a=await i.getAuthCodeUrl({...r,nativeBroker:Oa.isNativeAvailable(this.config,this.logger,this.nativeMessageHandler,e.authenticationScheme)}),c=this.getRedirectStartPage(e.redirectStartPage);return this.logger.verbosePii(`Redirect start page: ${c}`),window.addEventListener("pageshow",n),await s.initiateAuthRequest(a,{navigationClient:this.navigationClient,redirectTimeout:this.config.system.redirectNavigationTimeout,redirectStartPage:c,onRedirectNavigate:e.onRedirectNavigate||this.config.auth.onRedirectNavigate})}catch(e){throw e instanceof ke&&(e.setCorrelationId(this.correlationId),o.cacheFailedRequest(e)),window.removeEventListener("pageshow",n),this.browserStorage.cleanRequestByState(r.state),e}}async handleRedirectPromise(e="",o){const n=this.initializeServerTelemetryManager(Bi.handleRedirectPromise);try{if(!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null."),null;const[i,s]=this.getRedirectResponse(e||"");if(!i)return this.logger.info("handleRedirectPromise did not detect a response as a result of a redirect. Cleaning temporary cache."),this.browserStorage.cleanRequestByInteractionType(t.InteractionType.Redirect),"back_forward"!==function(){if("undefined"==typeof window||void 0===window.performance||"function"!=typeof window.performance.getEntriesByType)return;const e=window.performance.getEntriesByType("navigation"),t=e.length?e[0]:void 0;return t?.type}()?o.event.errorCode="no_server_response":this.logger.verbose("Back navigation event detected. Muting no_server_response error"),null;const a=this.browserStorage.getTemporaryCache(_i,!0)||r.EMPTY_STRING,c=xr.removeHashFromUrl(a);if(c===xr.removeHashFromUrl(window.location.href)&&this.config.auth.navigateToLoginRequestUrl){this.logger.verbose("Current page is loginRequestUrl, handling response"),a.indexOf("#")>-1&&vs(a);return await this.handleResponse(i,n)}if(!this.config.auth.navigateToLoginRequestUrl)return this.logger.verbose("NavigateToLoginRequestUrl set to false, handling response"),await this.handleResponse(i,n);if(!Cs()||this.config.system.allowRedirectInIframe){this.browserStorage.setTemporaryCache(Pi,s,!0);const e={apiId:Bi.handleRedirectPromise,timeout:this.config.system.redirectNavigationTimeout,noHistory:!0};let t=!0;if(a&&"null"!==a)this.logger.verbose(`Navigating to loginRequestUrl: ${a}`),t=await this.navigationClient.navigateInternal(a,e);else{const r=ks();this.browserStorage.setTemporaryCache(_i,r,!0),this.logger.warning("Unable to get valid login request url from cache, redirecting to home page"),t=await this.navigationClient.navigateInternal(r,e)}if(!t)return await this.handleResponse(i,n)}return null}catch(e){throw e instanceof ke&&(e.setCorrelationId(this.correlationId),n.cacheFailedRequest(e)),this.browserStorage.cleanRequestByInteractionType(t.InteractionType.Redirect),e}}getRedirectResponse(e){this.logger.verbose("getRedirectResponseHash called");let r=e;r||(r=this.config.auth.OIDCOptions.serverResponseType===P.QUERY?window.location.search:window.location.hash);let o=Ur(r);if(o){try{!function(e,t,r){if(!e.state)throw pi(Tn);const o=oa(t,e.state);if(!o)throw pi(In);if(o.interactionType!==r)throw pi(An)}(o,this.browserCrypto,t.InteractionType.Redirect)}catch(e){return e instanceof ke&&this.logger.error(`Interaction type validation failed due to ${e.errorCode}: ${e.errorMessage}`),[null,""]}return ys(window),this.logger.verbose("Hash contains known properties, returning response hash"),[o,r]}const n=this.browserStorage.getTemporaryCache(Pi,!0);return this.browserStorage.removeItem(this.browserStorage.generateCacheKey(Pi)),n&&(o=Ur(n),o)?(this.logger.verbose("Hash does not contain known properties, returning cached hash"),[o,n]):[null,""]}async handleResponse(e,t){const r=e.state;if(!r)throw pi(Tn);const o=this.browserStorage.getCachedRequest(r);if(this.logger.verbose("handleResponse called, retrieved cached request"),e.accountId){if(this.logger.verbose("Account id found in hash, calling WAM for token"),!this.nativeMessageHandler)throw pi(ni);const t=new Ma(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Bi.acquireTokenPopup,this.performanceClient,this.nativeMessageHandler,e.accountId,this.nativeStorage,o.correlationId),{userRequestState:n}=jo.parseRequestState(this.browserCrypto,r);return t.acquireToken({...o,state:n,prompt:void 0}).finally((()=>{this.browserStorage.cleanRequestByState(r)}))}const n=this.browserStorage.getCachedAuthority(r);if(!n)throw pi(Bn);const i=await Io(this.createAuthCodeClient.bind(this),yo.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:n});no.removeThrottle(this.browserStorage,this.config.auth.clientId,o);return new xa(i,this.browserStorage,o,this.logger,this.performanceClient).handleCodeResponse(e,r)}async logout(e){this.logger.verbose("logoutRedirect called");const r=this.initializeLogoutRequest(e),o=this.initializeServerTelemetryManager(Bi.logout);try{this.eventHandler.emitEvent(ga.LOGOUT_START,t.InteractionType.Redirect,e),await this.clearCacheOnLogout(r.account);const n={apiId:Bi.logout,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},i=await Io(this.createAuthCodeClient.bind(this),yo.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:o,requestAuthority:e&&e.authority,requestExtraQueryParameters:e?.extraQueryParameters,account:e&&e.account||void 0});if(i.authority.protocolMode===Or.OIDC)try{i.authority.endSessionEndpoint}catch{if(r.account?.homeAccountId)return this.browserStorage.removeAccount(r.account?.homeAccountId),void this.eventHandler.emitEvent(ga.LOGOUT_SUCCESS,t.InteractionType.Redirect,r)}const s=i.getLogoutUri(r);if(this.eventHandler.emitEvent(ga.LOGOUT_SUCCESS,t.InteractionType.Redirect,r),!e||"function"!=typeof e.onRedirectNavigate)return this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0),void await this.navigationClient.navigateExternal(s,n);if(!1!==e.onRedirectNavigate(s))return this.logger.verbose("Logout onRedirectNavigate did not return false, navigating"),this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0),void await this.navigationClient.navigateExternal(s,n);this.browserStorage.setInteractionInProgress(!1),this.logger.verbose("Logout onRedirectNavigate returned false, stopping navigation")}catch(e){throw e instanceof ke&&(e.setCorrelationId(this.correlationId),o.cacheFailedRequest(e)),this.eventHandler.emitEvent(ga.LOGOUT_FAILURE,t.InteractionType.Redirect,null,e),this.eventHandler.emitEvent(ga.LOGOUT_END,t.InteractionType.Redirect),e}this.eventHandler.emitEvent(ga.LOGOUT_END,t.InteractionType.Redirect)}getRedirectStartPage(e){const t=e||window.location.href;return xr.getAbsoluteUrl(t,Ts())}}async function Da(e,t,r,o,n){if(t.addQueueMeasurement(yo.SilentHandlerInitiateAuthRequest,o),!e)throw r.info("Navigate url is empty"),pi(Cn);return n?Io(Ba,yo.SilentHandlerLoadFrame,r,t,o)(e,n,t,o):ko($a,yo.SilentHandlerLoadFrameSync,r,t,o)(e)}async function Ha(e,t,r,o,n,i,s){return o.addQueueMeasurement(yo.SilentHandlerMonitorIframeForHash,i),new Promise(((o,i)=>{t<Us&&n.warning(`system.loadFrameTimeout or system.iframeHashTimeout set to lower (${t}ms) than the default (10000ms). This may result in timeouts.`);const a=window.setTimeout((()=>{window.clearInterval(c),i(pi(Pn))}),t),c=window.setInterval((()=>{let t="";const r=e.contentWindow;try{t=r?r.location.href:""}catch(e){}if(!t||"about:blank"===t)return;let n="";r&&(n=s===P.QUERY?r.location.search:r.location.hash),window.clearTimeout(a),window.clearInterval(c),o(n)}),r)})).finally((()=>{ko(za,yo.RemoveHiddenIframe,n,o,i)(e)}))}function Ba(e,t,r,o){return r.addQueueMeasurement(yo.SilentHandlerLoadFrame,o),new Promise(((r,o)=>{const n=Fa();window.setTimeout((()=>{n?(n.src=e,r(n)):o("Unable to load iframe")}),t)}))}function $a(e){const t=Fa();return t.src=e,t}function Fa(){const e=document.createElement("iframe");return e.className="msalSilentIframe",e.style.visibility="hidden",e.style.position="absolute",e.style.width=e.style.height="0",e.style.border="0",e.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),document.body.appendChild(e),e}function za(e){document.body===e.parentNode&&document.body.removeChild(e)}class Ka extends ka{constructor(e,t,r,o,n,i,s,a,c,l,d){super(e,t,r,o,n,i,a,l,d),this.apiId=s,this.nativeStorage=c}async acquireToken(e){this.performanceClient.addQueueMeasurement(yo.SilentIframeClientAcquireToken,e.correlationId),e.loginHint||e.sid||e.account&&e.account.username||this.logger.warning("No user hint provided. The authorization server may need more information to complete this request.");const r={...e};r.prompt?r.prompt!==R.NONE&&r.prompt!==R.NO_SESSION&&(this.logger.warning(`SilentIframeClient. Replacing invalid prompt ${r.prompt} with ${R.NONE}`),r.prompt=R.NONE):r.prompt=R.NONE;const o=await Io(this.initializeAuthorizationRequest.bind(this),yo.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,e.correlationId)(r,t.InteractionType.Silent);Ps(o.authority);const n=this.initializeServerTelemetryManager(this.apiId);let i;try{return i=await Io(this.createAuthCodeClient.bind(this),yo.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:n,requestAuthority:o.authority,requestAzureCloudOptions:o.azureCloudOptions,requestExtraQueryParameters:o.extraQueryParameters,account:o.account}),await Io(this.silentTokenHelper.bind(this),yo.SilentIframeClientTokenHelper,this.logger,this.performanceClient,e.correlationId)(i,o)}catch(o){if(o instanceof ke&&(o.setCorrelationId(this.correlationId),n.cacheFailedRequest(o)),!(i&&o instanceof ke&&o.errorCode===mi.INVALID_GRANT_ERROR))throw o;this.performanceClient.addFields({retryError:o.errorCode},this.correlationId);const s=await Io(this.initializeAuthorizationRequest.bind(this),yo.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,e.correlationId)(r,t.InteractionType.Silent);return await Io(this.silentTokenHelper.bind(this),yo.SilentIframeClientTokenHelper,this.logger,this.performanceClient,this.correlationId)(i,s)}}logout(){return Promise.reject(pi(Un))}async silentTokenHelper(e,t){const r=t.correlationId;this.performanceClient.addQueueMeasurement(yo.SilentIframeClientTokenHelper,r);const o=await Io(this.initializeAuthorizationCodeRequest.bind(this),yo.StandardInteractionClientInitializeAuthorizationCodeRequest,this.logger,this.performanceClient,r)(t),n=await Io(e.getAuthCodeUrl.bind(e),yo.GetAuthCodeUrl,this.logger,this.performanceClient,r)({...t,nativeBroker:Oa.isNativeAvailable(this.config,this.logger,this.nativeMessageHandler,t.authenticationScheme)}),i=new Na(e,this.browserStorage,o,this.logger,this.performanceClient),s=await Io(Da,yo.SilentHandlerInitiateAuthRequest,this.logger,this.performanceClient,r)(n,this.performanceClient,this.logger,r,this.config.system.navigateFrameWait),a=this.config.auth.OIDCOptions.serverResponseType,c=await Io(Ha,yo.SilentHandlerMonitorIframeForHash,this.logger,this.performanceClient,r)(s,this.config.system.iframeHashTimeout,this.config.system.pollIntervalMilliseconds,this.performanceClient,this.logger,r,a),l=ko(qa,yo.DeserializeResponse,this.logger,this.performanceClient,this.correlationId)(c,a,this.logger);if(l.accountId){if(this.logger.verbose("Account id found in hash, calling WAM for token"),!this.nativeMessageHandler)throw pi(ni);const e=new Ma(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.apiId,this.performanceClient,this.nativeMessageHandler,l.accountId,this.browserStorage,r),{userRequestState:o}=jo.parseRequestState(this.browserCrypto,t.state);return Io(e.acquireToken.bind(e),yo.NativeInteractionClientAcquireToken,this.logger,this.performanceClient,r)({...t,state:o,prompt:t.prompt||R.NONE})}return Io(i.handleCodeResponse.bind(i),yo.HandleCodeResponse,this.logger,this.performanceClient,r)(l,t)}}class ja extends ka{async acquireToken(e){this.performanceClient.addQueueMeasurement(yo.SilentRefreshClientAcquireToken,e.correlationId);const t=await Io(wa,yo.InitializeBaseRequest,this.logger,this.performanceClient,e.correlationId)(e,this.config,this.performanceClient,this.logger),r={...e,...t};e.redirectUri&&(r.redirectUri=this.getRedirectUri(e.redirectUri));const o=this.initializeServerTelemetryManager(Bi.acquireTokenSilent_silentFlow),n=await this.createRefreshTokenClient({serverTelemetryManager:o,authorityUrl:r.authority,azureCloudOptions:r.azureCloudOptions,account:r.account});return Io(n.acquireTokenByRefreshToken.bind(n),yo.RefreshTokenClientAcquireTokenByRefreshToken,this.logger,this.performanceClient,e.correlationId)(r).catch((e=>{throw e.setCorrelationId(this.correlationId),o.cacheFailedRequest(e),e}))}logout(){return Promise.reject(pi(Un))}async createRefreshTokenClient(e){const t=await Io(this.getClientConfiguration.bind(this),yo.StandardInteractionClientGetClientConfiguration,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:e.serverTelemetryManager,requestAuthority:e.authorityUrl,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return new Zo(t,this.performanceClient)}}class Ga{constructor(e,t,r,o){this.isBrowserEnvironment="undefined"!=typeof window,this.config=e,this.storage=t,this.logger=r,this.cryptoObj=o}loadExternalTokens(e,t,r){if(!this.isBrowserEnvironment)throw pi(zn);const o=t.id_token?bt(t.id_token,Ys):void 0,n={protocolMode:this.config.auth.protocolMode,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache},i=e.authority?new bo(bo.generateAuthority(e.authority,e.azureCloudOptions),this.config.system.networkClient,this.storage,n,this.logger,e.correlationId||ss()):void 0,s=this.loadAccount(e,r.clientInfo||t.client_info||"",o,i),a=this.loadIdToken(t,s.homeAccountId,s.environment,s.realm),c=this.loadAccessToken(e,t,s.homeAccountId,s.environment,s.realm,r),l=this.loadRefreshToken(t,s.homeAccountId,s.environment);return this.generateAuthenticationResult(e,{account:s,idToken:a,accessToken:c,refreshToken:l},o,i)}loadAccount(e,t,r,o){if(this.logger.verbose("TokenCache - loading account"),e.account){const t=Nr.createFromAccountInfo(e.account);return this.storage.setAccount(t),t}if(!o||!t&&!r)throw this.logger.error("TokenCache - if an account is not provided on the request, authority and either clientInfo or idToken must be provided instead."),pi(Qn);const n=Nr.generateHomeAccountId(t,o.authorityType,this.logger,this.cryptoObj,r),i=r?.tid,s=Yo(this.storage,o,n,Ys,r,t,o.hostnameAndPort,i,void 0,void 0,this.logger);return this.storage.setAccount(s),s}loadIdToken(e,t,r,o){if(!e.id_token)return this.logger.verbose("TokenCache - no id token found in response"),null;this.logger.verbose("TokenCache - loading id token");const n=Mt(t,r,e.id_token,this.config.auth.clientId,o);return this.storage.setIdTokenCredential(n),n}loadAccessToken(e,t,r,o,n,i){if(!t.access_token)return this.logger.verbose("TokenCache - no access token found in response"),null;if(!t.expires_in)return this.logger.error("TokenCache - no expiration set on the access token. Cannot add it to the cache."),null;if(!(t.scope||e.scopes&&e.scopes.length))return this.logger.error("TokenCache - scopes not specified in the request or response. Cannot add token to the cache."),null;this.logger.verbose("TokenCache - loading access token");const s=t.scope?Tr.fromString(t.scope):new Tr(e.scopes),a=i.expiresOn||t.expires_in+(new Date).getTime()/1e3,c=i.extendedExpiresOn||(t.ext_expires_in||t.expires_in)+(new Date).getTime()/1e3,l=Ot(r,o,t.access_token,this.config.auth.clientId,n,s.printScopes(),a,c,Ys);return this.storage.setAccessTokenCredential(l),l}loadRefreshToken(e,t,r){if(!e.refresh_token)return this.logger.verbose("TokenCache - no refresh token found in response"),null;this.logger.verbose("TokenCache - loading refresh token");const o=Nt(t,r,e.refresh_token,this.config.auth.clientId,e.foci,void 0,e.refresh_token_expires_in);return this.storage.setRefreshTokenCredential(o),o}generateAuthenticationResult(e,t,r,o){let n,i="",s=[],a=null;t?.accessToken&&(i=t.accessToken.secret,s=Tr.fromString(t.accessToken.target).asArray(),a=new Date(1e3*Number(t.accessToken.expiresOn)),n=new Date(1e3*Number(t.accessToken.extendedExpiresOn)));const c=t.account;return{authority:o?o.canonicalAuthority:"",uniqueId:t.account.localAccountId,tenantId:t.account.realm,scopes:s,account:c.getAccountInfo(),idToken:t.idToken?.secret||"",idTokenClaims:r||{},accessToken:i,fromCache:!0,expiresOn:a,correlationId:e.correlationId||"",requestId:"",extExpiresOn:n,familyId:t.refreshToken?.familyId||"",tokenType:t?.accessToken?.tokenType||"",state:e.state||"",cloudGraphHostName:c.cloudGraphHostName||"",msGraphHost:c.msGraphHost||"",fromNativeBroker:!1}}}class Wa extends Xo{constructor(e){super(e),this.includeRedirectUri=!1}}class Va extends ka{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 pi(Jn);const r=await Io(this.initializeAuthorizationRequest.bind(this),yo.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,e.correlationId)(e,t.InteractionType.Silent),o=this.initializeServerTelemetryManager(this.apiId);try{const t={...r,code:e.code},n=await Io(this.getClientConfiguration.bind(this),yo.StandardInteractionClientGetClientConfiguration,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:o,requestAuthority:r.authority,requestAzureCloudOptions:r.azureCloudOptions,requestExtraQueryParameters:r.extraQueryParameters,account:r.account}),i=new Wa(n);this.logger.verbose("Auth code client created");const s=new Na(i,this.browserStorage,t,this.logger,this.performanceClient);return await Io(s.handleCodeResponseFromServer.bind(s),yo.HandleCodeResponseFromServer,this.logger,this.performanceClient,e.correlationId)({code:e.code,msgraph_host:e.msGraphHost,cloud_graph_host_name:e.cloudGraphHostName,cloud_instance_host_name:e.cloudInstanceHostName},r,!1)}catch(e){throw e instanceof ke&&(e.setCorrelationId(this.correlationId),o.cacheFailedRequest(e)),e}}logout(){return Promise.reject(pi(Un))}}function Qa(e){const t=e?.idTokenClaims;return t?.tfp||t?.acr?"B2C":t?.tid?"9188040d-6c67-4c5b-b112-36a304b66dad"===t?.tid?"MSA":"AAD":void 0}function Ya(e,t){try{Rs(e)}catch(e){throw t.end({success:!1},e),e}}class Ja{constructor(e){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 ea(this.logger,this.performanceClient):Ct,this.eventHandler=new pa(this.logger),this.browserStorage=this.isBrowserEnvironment?new na(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,Eo(this.config.auth),this.performanceClient):ia(this.config.auth.clientId,this.logger);const t={cacheLocation:Ii.MemoryStorage,temporaryCacheLocation:Ii.MemoryStorage,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!1,claimsBasedCachingEnabled:!1};this.nativeInternalStorage=new na(this.config.auth.clientId,t,this.browserCrypto,this.logger,void 0,this.performanceClient),this.tokenCache=new Ga(this.config,this.browserStorage,this.logger,this.browserCrypto),this.activeSilentTokenRequests=new Map,this.trackPageVisibility=this.trackPageVisibility.bind(this),this.trackPageVisibilityWithMeasurement=this.trackPageVisibilityWithMeasurement.bind(this),this.listeningToStorageEvents=!1,this.handleAccountCacheChange=this.handleAccountCacheChange.bind(this)}static async createController(e,t){const r=new Ja(e);return await r.initialize(t),r}trackPageVisibility(e){e&&(this.logger.info("Perf: Visibility change detected"),this.performanceClient.incrementFields({visibilityChangeCount:1},e))}async initialize(e){if(this.logger.trace("initialize called"),this.initialized)return void this.logger.info("initialize has already been called, exiting early.");if(!this.isBrowserEnvironment)return this.logger.info("in non-browser environment, exiting early."),this.initialized=!0,void this.eventHandler.emitEvent(ga.INITIALIZE_END);const t=e?.correlationId||this.getRequestCorrelationId(),r=this.config.system.allowNativeBroker,o=this.performanceClient.startMeasurement(yo.InitializeClientApplication,t);if(this.eventHandler.emitEvent(ga.INITIALIZE_START),r)try{this.nativeExtensionProvider=await Oa.createProvider(this.logger,this.config.system.nativeBrokerHandshakeTimeout,this.performanceClient)}catch(e){this.logger.verbose(e)}this.config.cache.claimsBasedCachingEnabled||(this.logger.verbose("Claims-based caching is disabled. Clearing the previous cache with claims"),await Io(this.browserStorage.clearTokensAndKeysWithClaims.bind(this.browserStorage),yo.ClearTokensAndKeysWithClaims,this.logger,this.performanceClient,t)(this.performanceClient,t)),this.initialized=!0,this.eventHandler.emitEvent(ga.INITIALIZE_END),o.end({allowNativeBroker:r,success:!0})}async handleRedirectPromise(e){if(this.logger.verbose("handleRedirectPromise called"),Es(this.initialized),this.isBrowserEnvironment){const t=e||"";let r=this.redirectResponse.get(t);return void 0===r?(r=this.handleRedirectPromiseInternal(e),this.redirectResponse.set(t,r),this.logger.verbose("handleRedirectPromise has been called for the first time, storing the promise")):this.logger.verbose("handleRedirectPromise has been called previously, returning the result from the first call"),r}return this.logger.verbose("handleRedirectPromise returns null, not browser environment"),null}async handleRedirectPromiseInternal(e){const r=this.getAllAccounts(),o=this.browserStorage.getCachedNativeRequest(),n=o&&Oa.isNativeAvailable(this.config,this.logger,this.nativeExtensionProvider)&&this.nativeExtensionProvider&&!e,i=n?o?.correlationId:this.browserStorage.getTemporaryCache(qi,!0)||"",s=this.performanceClient.startMeasurement(yo.AcquireTokenRedirect,i);let a;if(this.eventHandler.emitEvent(ga.HANDLE_REDIRECT_START,t.InteractionType.Redirect),n&&this.nativeExtensionProvider){this.logger.trace("handleRedirectPromise - acquiring token from native platform");const e=new Ma(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Bi.handleRedirectPromise,this.performanceClient,this.nativeExtensionProvider,o.accountId,this.nativeInternalStorage,o.correlationId);a=Io(e.handleRedirectPromise.bind(e),yo.HandleNativeRedirectPromiseMeasurement,this.logger,this.performanceClient,s.event.correlationId)(this.performanceClient,s.event.correlationId)}else{this.logger.trace("handleRedirectPromise - acquiring token from web flow");const t=this.createRedirectClient(i);a=Io(t.handleRedirectPromise.bind(t),yo.HandleRedirectPromiseMeasurement,this.logger,this.performanceClient,s.event.correlationId)(e,s)}return a.then((e=>{if(e){r.length<this.getAllAccounts().length?(this.eventHandler.emitEvent(ga.LOGIN_SUCCESS,t.InteractionType.Redirect,e),this.logger.verbose("handleRedirectResponse returned result, login success")):(this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_SUCCESS,t.InteractionType.Redirect,e),this.logger.verbose("handleRedirectResponse returned result, acquire token success")),s.end({success:!0,accountType:Qa(e.account)})}else s.event.errorCode?s.end({success:!1}):s.discard();return this.eventHandler.emitEvent(ga.HANDLE_REDIRECT_END,t.InteractionType.Redirect),e})).catch((e=>{const o=e;throw r.length>0?this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_FAILURE,t.InteractionType.Redirect,null,o):this.eventHandler.emitEvent(ga.LOGIN_FAILURE,t.InteractionType.Redirect,null,o),this.eventHandler.emitEvent(ga.HANDLE_REDIRECT_END,t.InteractionType.Redirect),s.end({success:!1},o),e}))}async acquireTokenRedirect(e){const r=this.getRequestCorrelationId(e);this.logger.verbose("acquireTokenRedirect called",r);const o=this.performanceClient.startMeasurement(yo.AcquireTokenPreRedirect,r);o.add({accountType:Qa(e.account),scenarioId:e.scenarioId});const n=e.onRedirectNavigate;if(n)e.onRedirectNavigate=e=>{const t="function"==typeof n?n(e):void 0;return!1!==t?o.end({success:!0}):o.discard(),t};else{const e=this.config.auth.onRedirectNavigate;this.config.auth.onRedirectNavigate=t=>{const r="function"==typeof e?e(t):void 0;return!1!==r?o.end({success:!0}):o.discard(),r}}const i=this.getAllAccounts().length>0;try{let n;if(_s(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0),i?this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_START,t.InteractionType.Redirect,e):this.eventHandler.emitEvent(ga.LOGIN_START,t.InteractionType.Redirect,e),this.nativeExtensionProvider&&this.canUseNative(e)){n=new Ma(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Bi.acquireTokenRedirect,this.performanceClient,this.nativeExtensionProvider,this.getNativeAccountId(e),this.nativeInternalStorage,r).acquireTokenRedirect(e,o).catch((t=>{if(t instanceof ba&&Sa(t)){this.nativeExtensionProvider=void 0;return this.createRedirectClient(r).acquireToken(e)}if(t instanceof Fo){this.logger.verbose("acquireTokenRedirect - Resolving interaction required error thrown by native broker by falling back to web flow");return this.createRedirectClient(r).acquireToken(e)}throw this.browserStorage.setInteractionInProgress(!1),t}))}else{n=this.createRedirectClient(r).acquireToken(e)}return await n}catch(e){throw o.end({success:!1},e),i?this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_FAILURE,t.InteractionType.Redirect,null,e):this.eventHandler.emitEvent(ga.LOGIN_FAILURE,t.InteractionType.Redirect,null,e),e}}acquireTokenPopup(e){const r=this.getRequestCorrelationId(e),o=this.performanceClient.startMeasurement(yo.AcquireTokenPopup,r);o.add({scenarioId:e.scenarioId,accountType:Qa(e.account)});try{this.logger.verbose("acquireTokenPopup called",r),Ya(this.initialized,o),this.browserStorage.setInteractionInProgress(!0)}catch(e){return Promise.reject(e)}const n=this.getAllAccounts();let i;if(n.length>0?this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_START,t.InteractionType.Popup,e):this.eventHandler.emitEvent(ga.LOGIN_START,t.InteractionType.Popup,e),this.canUseNative(e))i=this.acquireTokenNative({...e,correlationId:r},Bi.acquireTokenPopup).then((e=>(this.browserStorage.setInteractionInProgress(!1),o.end({success:!0,isNativeBroker:!0,requestId:e.requestId,accountType:Qa(e.account)}),e))).catch((t=>{if(t instanceof ba&&Sa(t)){this.nativeExtensionProvider=void 0;return this.createPopupClient(r).acquireToken(e)}if(t instanceof Fo){this.logger.verbose("acquireTokenPopup - Resolving interaction required error thrown by native broker by falling back to web flow");return this.createPopupClient(r).acquireToken(e)}throw this.browserStorage.setInteractionInProgress(!1),t}));else{i=this.createPopupClient(r).acquireToken(e)}return i.then((e=>(n.length<this.getAllAccounts().length?this.eventHandler.emitEvent(ga.LOGIN_SUCCESS,t.InteractionType.Popup,e):this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_SUCCESS,t.InteractionType.Popup,e),o.end({success:!0,requestId:e.requestId,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length,accountType:Qa(e.account)}),e))).catch((e=>(n.length>0?this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_FAILURE,t.InteractionType.Popup,null,e):this.eventHandler.emitEvent(ga.LOGIN_FAILURE,t.InteractionType.Popup,null,e),o.end({success:!1},e),Promise.reject(e))))}trackPageVisibilityWithMeasurement(){const e=this.ssoSilentMeasurement||this.acquireTokenByCodeAsyncMeasurement;e&&(this.logger.info("Perf: Visibility change detected in ",e.event.name),e.increment({visibilityChangeCount:1}))}async ssoSilent(e){const r=this.getRequestCorrelationId(e),o={...e,prompt:e.prompt,correlationId:r};let n;if(this.ssoSilentMeasurement=this.performanceClient.startMeasurement(yo.SsoSilent,r),this.ssoSilentMeasurement?.add({scenarioId:e.scenarioId,accountType:Qa(e.account)}),Ya(this.initialized,this.ssoSilentMeasurement),this.ssoSilentMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement),this.logger.verbose("ssoSilent called",r),this.eventHandler.emitEvent(ga.SSO_SILENT_START,t.InteractionType.Silent,o),this.canUseNative(o))n=this.acquireTokenNative(o,Bi.ssoSilent).catch((e=>{if(e instanceof ba&&Sa(e)){this.nativeExtensionProvider=void 0;return this.createSilentIframeClient(o.correlationId).acquireToken(o)}throw e}));else{n=this.createSilentIframeClient(o.correlationId).acquireToken(o)}return n.then((e=>(this.eventHandler.emitEvent(ga.SSO_SILENT_SUCCESS,t.InteractionType.Silent,e),this.ssoSilentMeasurement?.end({success:!0,isNativeBroker:e.fromNativeBroker,requestId:e.requestId,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length,accountType:Qa(e.account)}),e))).catch((e=>{throw this.eventHandler.emitEvent(ga.SSO_SILENT_FAILURE,t.InteractionType.Silent,null,e),this.ssoSilentMeasurement?.end({success:!1},e),e})).finally((()=>{document.removeEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement)}))}async acquireTokenByCode(e){const r=this.getRequestCorrelationId(e);this.logger.trace("acquireTokenByCode called",r);const o=this.performanceClient.startMeasurement(yo.AcquireTokenByCode,r);Ya(this.initialized,o),this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_BY_CODE_START,t.InteractionType.Silent,e),o.add({scenarioId:e.scenarioId});try{if(e.code&&e.nativeAccountId)throw pi(Zn);if(e.code){const n=e.code;let i=this.hybridAuthCodeResponses.get(n);return i?(this.logger.verbose("Existing acquireTokenByCode request found",r),o.discard()):(this.logger.verbose("Initiating new acquireTokenByCode request",r),i=this.acquireTokenByCodeAsync({...e,correlationId:r}).then((e=>(this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_BY_CODE_SUCCESS,t.InteractionType.Silent,e),this.hybridAuthCodeResponses.delete(n),o.end({success:!0,isNativeBroker:e.fromNativeBroker,requestId:e.requestId,accessTokenSize:e.accessToken.length,idTokenSize:e.idToken.length,accountType:Qa(e.account)}),e))).catch((e=>{throw this.hybridAuthCodeResponses.delete(n),this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_BY_CODE_FAILURE,t.InteractionType.Silent,null,e),o.end({success:!1},e),e})),this.hybridAuthCodeResponses.set(n,i)),await i}if(e.nativeAccountId){if(this.canUseNative(e,e.nativeAccountId)){const t=await this.acquireTokenNative({...e,correlationId:r},Bi.acquireTokenByCode,e.nativeAccountId).catch((e=>{throw e instanceof ba&&Sa(e)&&(this.nativeExtensionProvider=void 0),e}));return o.end({accountType:Qa(t.account),success:!0}),t}throw pi(ti)}throw pi(Xn)}catch(e){throw this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_BY_CODE_FAILURE,t.InteractionType.Silent,null,e),o.end({success:!1},e),e}}async acquireTokenByCodeAsync(e){this.logger.trace("acquireTokenByCodeAsync called",e.correlationId),this.acquireTokenByCodeAsyncMeasurement=this.performanceClient.startMeasurement(yo.AcquireTokenByCodeAsync,e.correlationId),this.acquireTokenByCodeAsyncMeasurement?.increment({visibilityChangeCount:0}),document.addEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement);const t=this.createSilentAuthCodeClient(e.correlationId);return await t.acquireToken(e).then((e=>(this.acquireTokenByCodeAsyncMeasurement?.end({success:!0,fromCache:e.fromCache,isNativeBroker:e.fromNativeBroker,requestId:e.requestId}),e))).catch((e=>{throw this.acquireTokenByCodeAsyncMeasurement?.end({success:!1},e),e})).finally((()=>{document.removeEventListener("visibilitychange",this.trackPageVisibilityWithMeasurement)}))}async acquireTokenFromCache(e,t){switch(this.performanceClient.addQueueMeasurement(yo.AcquireTokenFromCache,e.correlationId),t){case Gi.Default:case Gi.AccessToken:case Gi.AccessTokenAndRefreshToken:const t=this.createSilentCacheClient(e.correlationId);return Io(t.acquireToken.bind(t),yo.SilentCacheClientAcquireToken,this.logger,this.performanceClient,e.correlationId)(e);default:throw vt(rt)}}async acquireTokenByRefreshToken(e,t){switch(this.performanceClient.addQueueMeasurement(yo.AcquireTokenByRefreshToken,e.correlationId),t){case Gi.Default:case Gi.AccessTokenAndRefreshToken:case Gi.RefreshToken:case Gi.RefreshTokenAndNetwork:const t=this.createSilentRefreshClient(e.correlationId);return Io(t.acquireToken.bind(t),yo.SilentRefreshClientAcquireToken,this.logger,this.performanceClient,e.correlationId)(e);default:throw vt(rt)}}async acquireTokenBySilentIframe(e){this.performanceClient.addQueueMeasurement(yo.AcquireTokenBySilentIframe,e.correlationId);const t=this.createSilentIframeClient(e.correlationId);return Io(t.acquireToken.bind(t),yo.SilentIframeClientAcquireToken,this.logger,this.performanceClient,e.correlationId)(e)}async logout(e){const t=this.getRequestCorrelationId(e);return this.logger.warning("logout API is deprecated and will be removed in msal-browser v3.0.0. Use logoutRedirect instead.",t),this.logoutRedirect({correlationId:t,...e})}async logoutRedirect(e){const t=this.getRequestCorrelationId(e);_s(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0);return this.createRedirectClient(t).logout(e)}logoutPopup(e){try{const t=this.getRequestCorrelationId(e);Rs(this.initialized),this.browserStorage.setInteractionInProgress(!0);return this.createPopupClient(t).logout(e)}catch(e){return Promise.reject(e)}}async clearCache(e){if(!this.isBrowserEnvironment)return void this.logger.info("in non-browser environment, returning early.");const t=this.getRequestCorrelationId(e);return this.createSilentCacheClient(t).logout(e)}getAllAccounts(e){return sa(this.logger,this.browserStorage,this.isBrowserEnvironment,e)}getAccount(e){return aa(e,this.logger,this.browserStorage)}getAccountByUsername(e){return ca(e,this.logger,this.browserStorage)}getAccountByHomeId(e){return la(e,this.logger,this.browserStorage)}getAccountByLocalId(e){return da(e,this.logger,this.browserStorage)}setActiveAccount(e){ua(e,this.browserStorage)}getActiveAccount(){return ha(this.browserStorage)}async hydrateCache(e,t){this.logger.verbose("hydrateCache called");const r=Nr.createFromAccountInfo(e.account,e.cloudGraphHostName,e.msGraphHost);return this.browserStorage.setAccount(r),e.fromNativeBroker?(this.logger.verbose("Response was from native broker, storing in-memory"),this.nativeInternalStorage.hydrateCache(e,t)):this.browserStorage.hydrateCache(e,t)}async acquireTokenNative(e,t,r){if(this.logger.trace("acquireTokenNative called"),!this.nativeExtensionProvider)throw pi(ni);return new Ma(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,t,this.performanceClient,this.nativeExtensionProvider,r||this.getNativeAccountId(e),this.nativeInternalStorage,e.correlationId).acquireToken(e)}canUseNative(e,t){if(this.logger.trace("canUseNative called"),!Oa.isNativeAvailable(this.config,this.logger,this.nativeExtensionProvider,e.authenticationScheme))return this.logger.trace("canUseNative: isNativeAvailable returned false, returning false"),!1;if(e.prompt)switch(e.prompt){case R.NONE:case R.CONSENT:case R.LOGIN:this.logger.trace("canUseNative: prompt is compatible with native flow");break;default:return this.logger.trace(`canUseNative: prompt = ${e.prompt} is not compatible with native flow, returning false`),!1}return!(!t&&!this.getNativeAccountId(e))||(this.logger.trace("canUseNative: nativeAccountId is not available, returning false"),!1)}getNativeAccountId(e){const t=e.account||this.getAccount({loginHint:e.loginHint,sid:e.sid})||this.getActiveAccount();return t&&t.nativeAccountId||""}createPopupClient(e){return new Ua(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,this.nativeExtensionProvider,e)}createRedirectClient(e){return new La(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,this.nativeExtensionProvider,e)}createSilentIframeClient(e){return new Ka(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Bi.ssoSilent,this.performanceClient,this.nativeInternalStorage,this.nativeExtensionProvider,e)}createSilentCacheClient(e){return new Ra(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeExtensionProvider,e)}createSilentRefreshClient(e){return new ja(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeExtensionProvider,e)}createSilentAuthCodeClient(e){return new Va(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,Bi.acquireTokenByCode,this.performanceClient,this.nativeExtensionProvider,e)}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){return Ss(),this.performanceClient.addPerformanceCallback(e)}removePerformanceCallback(e){return this.performanceClient.removePerformanceCallback(e)}enableAccountStorageEvents(){"undefined"!=typeof window&&(this.listeningToStorageEvents?this.logger.verbose("Account storage listener already registered."):(this.logger.verbose("Adding account storage listener."),this.listeningToStorageEvents=!0,window.addEventListener("storage",this.handleAccountCacheChange)))}disableAccountStorageEvents(){"undefined"!=typeof window&&(this.listeningToStorageEvents?(this.logger.verbose("Removing account storage listener."),window.removeEventListener("storage",this.handleAccountCacheChange),this.listeningToStorageEvents=!1):this.logger.verbose("No account storage listener registered."))}handleAccountCacheChange(e){try{e.key?.includes(k)&&this.eventHandler.emitEvent(ga.ACTIVE_ACCOUNT_CHANGED);const t=e.newValue||e.oldValue;if(!t)return;const r=JSON.parse(t);if("object"!=typeof r||!Nr.isAccountEntity(r))return;const o=Gr.toObject(new Nr,r).getAccountInfo();!e.oldValue&&e.newValue?(this.logger.info("Account was added to cache in a different window"),this.eventHandler.emitEvent(ga.ACCOUNT_ADDED,void 0,o)):!e.newValue&&e.oldValue&&(this.logger.info("Account was removed from cache in a different window"),this.eventHandler.emitEvent(ga.ACCOUNT_REMOVED,void 0,o))}catch(e){return}}getTokenCache(){return this.tokenCache}getLogger(){return this.logger}setLogger(e){this.logger=e}initializeWrapperLibrary(e,t){this.browserStorage.setWrapperMetadata(e,t)}setNavigationClient(e){this.navigationClient=e}getConfiguration(){return this.config}getPerformanceClient(){return this.performanceClient}isBrowserEnv(){return this.isBrowserEnvironment}getRequestCorrelationId(e){return e?.correlationId?e.correlationId:this.isBrowserEnvironment?ss():r.EMPTY_STRING}async loginRedirect(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("loginRedirect called",t),this.acquireTokenRedirect({correlationId:t,...e||zi})}loginPopup(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("loginPopup called",t),this.acquireTokenPopup({correlationId:t,...e||zi})}async acquireTokenSilent(e){const t=this.getRequestCorrelationId(e),o=this.performanceClient.startMeasurement(yo.AcquireTokenSilent,t);o.add({cacheLookupPolicy:e.cacheLookupPolicy,scenarioId:e.scenarioId}),Ya(this.initialized,o),this.logger.verbose("acquireTokenSilent called",t);const n=e.account||this.getActiveAccount();if(!n)throw pi(xn);o.add({accountType:Qa(n)});const i={clientId:this.config.auth.clientId,authority:e.authority||r.EMPTY_STRING,scopes:e.scopes,homeAccountIdentifier:n.homeAccountId,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid,shrOptions:e.shrOptions},s=JSON.stringify(i),a=this.activeSilentTokenRequests.get(s);if(void 0===a){this.logger.verbose("acquireTokenSilent called for the first time, storing active request",t);const r=Io(this.acquireTokenSilentAsync.bind(this),yo.AcquireTokenSilentAsync,this.logger,this.performanceClient,t)({...e,correlationId:t},n).then((t=>(this.activeSilentTokenRequests.delete(s),o.end({success:!0,fromCache:t.fromCache,isNativeBroker:t.fromNativeBroker,cacheLookupPolicy:e.cacheLookupPolicy,requestId:t.requestId,accessTokenSize:t.accessToken.length,idTokenSize:t.idToken.length}),t))).catch((e=>{throw this.activeSilentTokenRequests.delete(s),o.end({success:!1},e),e}));return this.activeSilentTokenRequests.set(s,r),{...await r,state:e.state}}return this.logger.verbose("acquireTokenSilent has been called previously, returning the result from the first call",t),o.discard(),{...await a,state:e.state}}async acquireTokenSilentAsync(e,r){const o=()=>this.trackPageVisibility(e.correlationId);this.performanceClient.addQueueMeasurement(yo.AcquireTokenSilentAsync,e.correlationId),this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_START,t.InteractionType.Silent,e),e.correlationId&&this.performanceClient.incrementFields({visibilityChangeCount:0},e.correlationId),document.addEventListener("visibilitychange",o);const n=await Io(Ta,yo.InitializeSilentRequest,this.logger,this.performanceClient,e.correlationId)(e,r,this.config,this.performanceClient,this.logger),i=e.cacheLookupPolicy||Gi.Default;return this.acquireTokenSilentNoIframe(n,i).catch((async e=>{const t=function(e,t){const r=!(e instanceof Fo&&e.subError!==xo),o=e.errorCode===mi.INVALID_GRANT_ERROR||e.errorCode===rt,n=r&&o||e.errorCode===Po||e.errorCode===Oo,i=Wi.includes(t);return n&&i}(e,i);if(t){if(this.activeIframeRequest){if(i!==Gi.Skip){const[t,r]=this.activeIframeRequest;this.logger.verbose(`Iframe request is already in progress, awaiting resolution for request with correlationId: ${r}`,n.correlationId);const o=this.performanceClient.startMeasurement(yo.AwaitConcurrentIframe,n.correlationId);o.add({awaitIframeCorrelationId:r});const s=await t;if(o.end({success:s}),s)return this.logger.verbose(`Parallel iframe request with correlationId: ${r} succeeded. Retrying cache and/or RT redemption`,n.correlationId),this.acquireTokenSilentNoIframe(n,i);throw this.logger.info(`Iframe request with correlationId: ${r} failed. Interaction is required.`),e}return this.logger.warning("Another iframe request is currently in progress and CacheLookupPolicy is set to Skip. This may result in degraded performance and/or reliability for both calls. Please consider changing the CacheLookupPolicy to take advantage of request queuing and token cache.",n.correlationId),Io(this.acquireTokenBySilentIframe.bind(this),yo.AcquireTokenBySilentIframe,this.logger,this.performanceClient,n.correlationId)(n)}{let e;return this.activeIframeRequest=[new Promise((t=>{e=t})),n.correlationId],this.logger.verbose("Refresh token expired/invalid or CacheLookupPolicy is set to Skip, attempting acquire token by iframe.",n.correlationId),Io(this.acquireTokenBySilentIframe.bind(this),yo.AcquireTokenBySilentIframe,this.logger,this.performanceClient,n.correlationId)(n).then((t=>(e(!0),t))).catch((t=>{throw e(!1),t})).finally((()=>{this.activeIframeRequest=void 0}))}}throw e})).then((r=>(this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_SUCCESS,t.InteractionType.Silent,r),e.correlationId&&this.performanceClient.addFields({fromCache:r.fromCache,isNativeBroker:r.fromNativeBroker,requestId:r.requestId},e.correlationId),r))).catch((e=>{throw this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_FAILURE,t.InteractionType.Silent,null,e),e})).finally((()=>{document.removeEventListener("visibilitychange",o)}))}async acquireTokenSilentNoIframe(e,r){return Oa.isNativeAvailable(this.config,this.logger,this.nativeExtensionProvider,e.authenticationScheme)&&e.account.nativeAccountId?(this.logger.verbose("acquireTokenSilent - attempting to acquire token from native platform"),this.acquireTokenNative(e,Bi.acquireTokenSilent_silentFlow).catch((async e=>{if(e instanceof ba&&Sa(e))throw this.logger.verbose("acquireTokenSilent - native platform unavailable, falling back to web flow"),this.nativeExtensionProvider=void 0,vt(rt);throw e}))):(this.logger.verbose("acquireTokenSilent - attempting to acquire token from web flow"),Io(this.acquireTokenFromCache.bind(this),yo.AcquireTokenFromCache,this.logger,this.performanceClient,e.correlationId)(e,r).catch((o=>{if(r===Gi.AccessToken)throw o;return this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_NETWORK_START,t.InteractionType.Silent,e),Io(this.acquireTokenByRefreshToken.bind(this),yo.AcquireTokenByRefreshToken,this.logger,this.performanceClient,e.correlationId)(e,r)})))}}class Xa{constructor(e,t,r,o){this.clientId=e,this.clientCapabilities=t,this.crypto=r,this.logger=o}toNaaTokenRequest(e){let t;t=void 0===e.extraQueryParameters?new Map:new Map(Object.entries(e.extraQueryParameters));const r=(new fo).addClientCapabilitiesToClaims(e.claims,this.clientCapabilities),o=e.scopes||a;return{platformBrokerId:e.account?.homeAccountId,clientId:this.clientId,authority:e.authority,scope:o.join(" "),correlationId:void 0!==e.correlationId?e.correlationId:this.crypto.createNewGuid(),claims:wr.isEmptyObj(r)?void 0:r,state:e.state,authenticationScheme:e.authenticationScheme||V.BEARER,extraParameters:t}}fromNaaTokenResponse(e,t,r){if(!t.token.id_token||!t.token.access_token)throw vt(Ee);const o=new Date(1e3*(r+(t.token.expires_in||0))),n=bt(t.token.id_token,this.crypto.base64Decode),i=this.fromNaaAccountInfo(t.account,t.token.id_token,n),s=t.token.scope||e.scope;return{authority:t.token.authority||i.environment,uniqueId:i.localAccountId,tenantId:i.tenantId,scopes:s.split(" "),account:i,idToken:t.token.id_token,idTokenClaims:n,accessToken:t.token.access_token,fromCache:!1,expiresOn:o,tokenType:e.authenticationScheme||V.BEARER,correlationId:e.correlationId,extExpiresOn:o,state:e.state}}fromNaaAccountInfo(e,t,r){const o=r||e.idTokenClaims,n=e.localAccountId||o?.oid||o?.sub||"",i=e.tenantId||o?.tid||"",s=e.homeAccountId||`${n}.${i}`,a=e.username||o?.preferred_username||"",c=e.name||o?.name,l=new Map,d=br(s,n,i,o);l.set(i,d);return{homeAccountId:s,environment:e.environment,tenantId:i,username:a,localAccountId:n,name:c,idToken:t,idTokenClaims:o,tenantProfiles:l}}fromBridgeError(e){if(!function(e){return void 0!==e.status}(e))return new ke("unknown_error","An unknown error occurred");switch(e.status){case Bs:return new yt(dt);case $s:return new yt(lt);case js:return new yt(Je);case Ks:return new yt(gt);case Gs:return new yt(e.code||gt,e.description);case Fs:case zs:return new oo(e.code,e.description);case Hs:return new Fo(e.code,e.description);default:return new ke(e.code,e.description)}}toAuthenticationResultFromCache(e,t,r,o,n){if(!t||!r)throw vt(Ee);const i=bt(t.secret,this.crypto.base64Decode),s=r.target||o.scopes.join(" ");return{authority:r.environment||e.environment,uniqueId:e.localAccountId,tenantId:e.tenantId,scopes:s.split(" "),account:e,idToken:t.secret,idTokenClaims:i||{},accessToken:r.secret,fromCache:!0,expiresOn:new Date(1e3*Number(r.expiresOn)),tokenType:o.authenticationScheme||V.BEARER,correlationId:n,extExpiresOn:new Date(1e3*Number(r.extendedExpiresOn)),state:o.state}}}const Za={code:"unsupported_method",desc:"This method is not supported in nested app environment."};class ec extends ke{constructor(e,t){super(e,t),Object.setPrototypeOf(this,ec.prototype),this.name="NestedAppAuthError"}static createUnsupportedError(){return new ec(Za.code,Za.desc)}}class tc{constructor(e){this.operatingContext=e;const t=this.operatingContext.getBridgeProxy();if(void 0===t)throw new Error("unexpected: bridgeProxy is undefined");this.bridgeProxy=t,this.config=e.getConfig(),this.logger=this.operatingContext.getLogger(),this.performanceClient=this.config.telemetry.client,this.browserCrypto=e.isBrowserEnvironment()?new ea(this.logger,this.performanceClient):Ct,this.browserStorage=this.operatingContext.isBrowserEnvironment()?new na(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,Eo(this.config.auth)):ia(this.config.auth.clientId,this.logger),this.eventHandler=new pa(this.logger),this.nestedAppAuthAdapter=new Xa(this.config.auth.clientId,this.config.auth.clientCapabilities,this.browserCrypto,this.logger);const r=this.bridgeProxy.getAccountContext();if(r){ua(aa(r,this.logger,this.browserStorage),this.browserStorage)}}static async createController(e){const t=new tc(e);return Promise.resolve(t)}initialize(){return Promise.resolve()}ensureValidRequest(e){return e?.correlationId?e:{...e,correlationId:this.browserCrypto.createNewGuid()}}async acquireTokenInteractive(e){const r=this.ensureValidRequest(e);this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_START,t.InteractionType.Popup,r);const o=this.performanceClient.startMeasurement(yo.AcquireTokenPopup,r.correlationId);o?.add({nestedAppAuthRequest:!0});try{const n=this.nestedAppAuthAdapter.toNaaTokenRequest(r),i=Et(),s=await this.bridgeProxy.getTokenInteractive(n),a={...this.nestedAppAuthAdapter.fromNaaTokenResponse(n,s,i)};return await this.hydrateCache(a,e),this.browserStorage.setActiveAccount(a.account),this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_SUCCESS,t.InteractionType.Popup,a),o.add({accessTokenSize:a.accessToken.length,idTokenSize:a.idToken.length}),o.end({success:!0,requestId:a.requestId}),a}catch(e){const r=this.nestedAppAuthAdapter.fromBridgeError(e);throw this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_FAILURE,t.InteractionType.Popup,null,e),o.end({success:!1},e),r}}async acquireTokenSilentInternal(e){const r=this.ensureValidRequest(e);this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_START,t.InteractionType.Silent,r);const o=await this.acquireTokenFromCache(r);if(o)return this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_SUCCESS,t.InteractionType.Silent,o),o;const n=this.performanceClient.startMeasurement(yo.SsoSilent,r.correlationId);n?.increment({visibilityChangeCount:0}),n?.add({nestedAppAuthRequest:!0});try{const o=this.nestedAppAuthAdapter.toNaaTokenRequest(r),i=Et(),s=await this.bridgeProxy.getTokenSilent(o),a=this.nestedAppAuthAdapter.fromNaaTokenResponse(o,s,i);return await this.hydrateCache(a,e),this.browserStorage.setActiveAccount(a.account),this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_SUCCESS,t.InteractionType.Silent,a),n?.add({accessTokenSize:a.accessToken.length,idTokenSize:a.idToken.length}),n?.end({success:!0,requestId:a.requestId}),a}catch(e){const r=this.nestedAppAuthAdapter.fromBridgeError(e);throw this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_FAILURE,t.InteractionType.Silent,null,e),n?.end({success:!1},e),r}}async acquireTokenFromCache(e){const r=this.performanceClient.startMeasurement(yo.AcquireTokenSilent,e.correlationId);if(r?.add({nestedAppAuthRequest:!0}),e.claims)return this.logger.verbose("Claims are present in the request, skipping cache lookup"),null;let o=null;switch(e.cacheLookupPolicy){case Gi.Default:case Gi.AccessToken:case Gi.AccessTokenAndRefreshToken:o=await this.acquireTokenFromCacheInternal(e);break;default:return null}return o?(this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_SUCCESS,t.InteractionType.Silent,o),r?.add({accessTokenSize:o?.accessToken.length,idTokenSize:o?.idToken.length}),r?.end({success:!0}),o):(this.logger.error("Cached tokens are not found for the account, proceeding with silent token request."),this.eventHandler.emitEvent(ga.ACQUIRE_TOKEN_FAILURE,t.InteractionType.Silent,null),r?.end({success:!1}),null)}async acquireTokenFromCacheInternal(e){const t=this.bridgeProxy.getAccountContext();let r=null;if(t){r=aa(t,this.logger,this.browserStorage)||e.account}if(!r)return this.logger.verbose("No active account found, falling back to the host"),Promise.resolve(null);this.logger.verbose("active account found, attempting to acquire token silently");const o={...e,correlationId:e.correlationId||this.browserCrypto.createNewGuid(),authority:e.authority||r.environment,scopes:e.scopes?.length?e.scopes:[...a]},n=this.browserStorage.getTokenKeys(),i=this.browserStorage.getAccessToken(r,o,n,r.tenantId,this.performanceClient,o.correlationId);if(!i)return this.logger.verbose("No cached access token found"),Promise.resolve(null);if(_t(i.cachedAt)||Rt(i.expiresOn,this.config.system.tokenRenewalOffsetSeconds))return this.logger.verbose("Cached access token has expired"),Promise.resolve(null);const s=this.browserStorage.getIdToken(r,n,r.tenantId,this.performanceClient,o.correlationId);return s?this.nestedAppAuthAdapter.toAuthenticationResultFromCache(r,s,i,o,o.correlationId):(this.logger.verbose("No cached id token found"),Promise.resolve(null))}async acquireTokenPopup(e){return this.acquireTokenInteractive(e)}acquireTokenRedirect(e){throw ec.createUnsupportedError()}async acquireTokenSilent(e){return this.acquireTokenSilentInternal(e)}acquireTokenByCode(e){throw ec.createUnsupportedError()}acquireTokenNative(e,t,r){throw ec.createUnsupportedError()}acquireTokenByRefreshToken(e,t){throw ec.createUnsupportedError()}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){throw ec.createUnsupportedError()}removePerformanceCallback(e){throw ec.createUnsupportedError()}enableAccountStorageEvents(){throw ec.createUnsupportedError()}disableAccountStorageEvents(){throw ec.createUnsupportedError()}getAllAccounts(e){return sa(this.logger,this.browserStorage,this.isBrowserEnv(),e)}getAccount(e){return aa(e,this.logger,this.browserStorage)}getAccountByUsername(e){return ca(e,this.logger,this.browserStorage)}getAccountByHomeId(e){return la(e,this.logger,this.browserStorage)}getAccountByLocalId(e){return da(e,this.logger,this.browserStorage)}setActiveAccount(e){return ua(e,this.browserStorage)}getActiveAccount(){return ha(this.browserStorage)}handleRedirectPromise(e){return Promise.resolve(null)}loginPopup(e){return this.acquireTokenInteractive(e||zi)}loginRedirect(e){throw ec.createUnsupportedError()}logout(e){throw ec.createUnsupportedError()}logoutRedirect(e){throw ec.createUnsupportedError()}logoutPopup(e){throw ec.createUnsupportedError()}ssoSilent(e){return this.acquireTokenSilentInternal(e)}getTokenCache(){throw ec.createUnsupportedError()}getLogger(){return this.logger}setLogger(e){this.logger=e}initializeWrapperLibrary(e,t){}setNavigationClient(e){this.logger.warning("setNavigationClient is not supported in nested app auth")}getConfiguration(){return this.config}isBrowserEnv(){return this.operatingContext.isBrowserEnvironment()}getBrowserCrypto(){return this.browserCrypto}getPerformanceClient(){throw ec.createUnsupportedError()}getRedirectResponse(){throw ec.createUnsupportedError()}async clearCache(e){throw ec.createUnsupportedError()}async hydrateCache(e,t){this.logger.verbose("hydrateCache called");const r=Nr.createFromAccountInfo(e.account,e.cloudGraphHostName,e.msGraphHost);return this.browserStorage.setAccount(r),this.browserStorage.hydrateCache(e,t)}}async function rc(e){const t=new Qs(e),r=new Vs(e),o=[t.initialize(),r.initialize()];return await Promise.all(o),r.isAvailable()&&e.auth.supportsNestedAppAuth?tc.createController(r):t.isAvailable()?Ja.createController(t):null}class oc{static async createPublicClientApplication(e){const t=await async function(e,t){const r=new Qs(e);return await r.initialize(),Ja.createController(r,t)}(e);return new oc(e,t)}constructor(e,t){this.controller=t||new Ja(new Qs(e))}async initialize(e){return this.controller.initialize(e)}async acquireTokenPopup(e){return this.controller.acquireTokenPopup(e)}acquireTokenRedirect(e){return this.controller.acquireTokenRedirect(e)}acquireTokenSilent(e){return this.controller.acquireTokenSilent(e)}acquireTokenByCode(e){return this.controller.acquireTokenByCode(e)}addEventCallback(e,t){return this.controller.addEventCallback(e,t)}removeEventCallback(e){return this.controller.removeEventCallback(e)}addPerformanceCallback(e){return this.controller.addPerformanceCallback(e)}removePerformanceCallback(e){return this.controller.removePerformanceCallback(e)}enableAccountStorageEvents(){this.controller.enableAccountStorageEvents()}disableAccountStorageEvents(){this.controller.disableAccountStorageEvents()}getAccount(e){return this.controller.getAccount(e)}getAccountByHomeId(e){return this.controller.getAccountByHomeId(e)}getAccountByLocalId(e){return this.controller.getAccountByLocalId(e)}getAccountByUsername(e){return this.controller.getAccountByUsername(e)}getAllAccounts(e){return this.controller.getAllAccounts(e)}handleRedirectPromise(e){return this.controller.handleRedirectPromise(e)}loginPopup(e){return this.controller.loginPopup(e)}loginRedirect(e){return this.controller.loginRedirect(e)}logout(e){return this.controller.logout(e)}logoutRedirect(e){return this.controller.logoutRedirect(e)}logoutPopup(e){return this.controller.logoutPopup(e)}ssoSilent(e){return this.controller.ssoSilent(e)}getTokenCache(){return this.controller.getTokenCache()}getLogger(){return this.controller.getLogger()}setLogger(e){this.controller.setLogger(e)}setActiveAccount(e){this.controller.setActiveAccount(e)}getActiveAccount(){return this.controller.getActiveAccount()}initializeWrapperLibrary(e,t){return this.controller.initializeWrapperLibrary(e,t)}setNavigationClient(e){this.controller.setNavigationClient(e)}getConfiguration(){return this.controller.getConfiguration()}async hydrateCache(e,t){return this.controller.hydrateCache(e,t)}clearCache(e){return this.controller.clearCache(e)}}async function nc(e){const t=new oc(e);return await t.initialize(),t}class ic{constructor(e){this.initialized=!1,this.operatingContext=e,this.isBrowserEnvironment=this.operatingContext.isBrowserEnvironment(),this.config=e.getConfig(),this.logger=e.getLogger(),this.performanceClient=this.config.telemetry.client,this.browserCrypto=this.isBrowserEnvironment?new ea(this.logger,this.performanceClient):Ct,this.browserStorage=this.isBrowserEnvironment?new na(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,void 0,this.performanceClient):ia(this.config.auth.clientId,this.logger)}getBrowserStorage(){return this.browserStorage}getAccount(e){return null}getAccountByHomeId(e){return null}getAccountByLocalId(e){return null}getAccountByUsername(e){return null}getAllAccounts(){return[]}initialize(){return this.initialized=!0,Promise.resolve()}acquireTokenPopup(e){return Es(this.initialized),Ss(),{}}acquireTokenRedirect(e){return Es(this.initialized),Ss(),Promise.resolve()}acquireTokenSilent(e){return Es(this.initialized),Ss(),{}}acquireTokenByCode(e){return Es(this.initialized),Ss(),{}}acquireTokenNative(e,t,r){return Es(this.initialized),Ss(),{}}acquireTokenByRefreshToken(e,t){return Es(this.initialized),Ss(),{}}addEventCallback(e,t){return null}removeEventCallback(e){}addPerformanceCallback(e){return Es(this.initialized),Ss(),""}removePerformanceCallback(e){return Es(this.initialized),Ss(),!0}enableAccountStorageEvents(){Es(this.initialized),Ss()}disableAccountStorageEvents(){Es(this.initialized),Ss()}handleRedirectPromise(e){return Es(this.initialized),Promise.resolve(null)}loginPopup(e){return Es(this.initialized),Ss(),{}}loginRedirect(e){return Es(this.initialized),Ss(),{}}logout(e){return Es(this.initialized),Ss(),{}}logoutRedirect(e){return Es(this.initialized),Ss(),{}}logoutPopup(e){return Es(this.initialized),Ss(),{}}ssoSilent(e){return Es(this.initialized),Ss(),{}}getTokenCache(){return Es(this.initialized),Ss(),{}}getLogger(){return this.logger}setLogger(e){Es(this.initialized),Ss()}setActiveAccount(e){Es(this.initialized),Ss()}getActiveAccount(){return Es(this.initialized),Ss(),null}initializeWrapperLibrary(e,t){this.browserStorage.setWrapperMetadata(e,t)}setNavigationClient(e){Es(this.initialized),Ss()}getConfiguration(){return this.config}isBrowserEnv(){return Es(this.initialized),Ss(),!0}getBrowserCrypto(){return Es(this.initialized),Ss(),{}}getPerformanceClient(){return Es(this.initialized),Ss(),{}}getRedirectResponse(){return Es(this.initialized),Ss(),{}}async clearCache(e){Es(this.initialized),Ss()}async hydrateCache(e,t){Es(this.initialized),Ss()}}class sc extends Ds{getId(){return sc.ID}getModuleName(){return sc.MODULE_NAME}async initialize(){return!0}}sc.MODULE_NAME="",sc.ID="UnknownOperatingContext";class ac{static async createPublicClientApplication(e){const t=await rc(e);let r;return r=null!==t?new ac(e,t):new ac(e),r}constructor(e,t){if(this.configuration=e,t)this.controller=t;else{const t=new sc(e);this.controller=new ic(t)}}async initialize(){if(this.controller instanceof ic){const e=await rc(this.configuration);return null!==e&&(this.controller=e),this.controller.initialize()}return Promise.resolve()}async acquireTokenPopup(e){return this.controller.acquireTokenPopup(e)}acquireTokenRedirect(e){return this.controller.acquireTokenRedirect(e)}acquireTokenSilent(e){return this.controller.acquireTokenSilent(e)}acquireTokenByCode(e){return this.controller.acquireTokenByCode(e)}addEventCallback(e,t){return this.controller.addEventCallback(e,t)}removeEventCallback(e){return this.controller.removeEventCallback(e)}addPerformanceCallback(e){return this.controller.addPerformanceCallback(e)}removePerformanceCallback(e){return this.controller.removePerformanceCallback(e)}enableAccountStorageEvents(){this.controller.enableAccountStorageEvents()}disableAccountStorageEvents(){this.controller.disableAccountStorageEvents()}getAccount(e){return this.controller.getAccount(e)}getAccountByHomeId(e){return this.controller.getAccountByHomeId(e)}getAccountByLocalId(e){return this.controller.getAccountByLocalId(e)}getAccountByUsername(e){return this.controller.getAccountByUsername(e)}getAllAccounts(e){return this.controller.getAllAccounts(e)}handleRedirectPromise(e){return this.controller.handleRedirectPromise(e)}loginPopup(e){return this.controller.loginPopup(e)}loginRedirect(e){return this.controller.loginRedirect(e)}logout(e){return this.controller.logout(e)}logoutRedirect(e){return this.controller.logoutRedirect(e)}logoutPopup(e){return this.controller.logoutPopup(e)}ssoSilent(e){return this.controller.ssoSilent(e)}getTokenCache(){return this.controller.getTokenCache()}getLogger(){return this.controller.getLogger()}setLogger(e){this.controller.setLogger(e)}setActiveAccount(e){this.controller.setActiveAccount(e)}getActiveAccount(){return this.controller.getActiveAccount()}initializeWrapperLibrary(e,t){return this.controller.initializeWrapperLibrary(e,t)}setNavigationClient(e){this.controller.setNavigationClient(e)}getConfiguration(){return this.controller.getConfiguration()}async hydrateCache(e,t){return this.controller.hydrateCache(e,t)}clearCache(e){return this.controller.clearCache(e)}}const cc={initialize:()=>Promise.reject(fs(ds)),acquireTokenPopup:()=>Promise.reject(fs(ds)),acquireTokenRedirect:()=>Promise.reject(fs(ds)),acquireTokenSilent:()=>Promise.reject(fs(ds)),acquireTokenByCode:()=>Promise.reject(fs(ds)),getAllAccounts:()=>[],getAccount:()=>null,getAccountByHomeId:()=>null,getAccountByUsername:()=>null,getAccountByLocalId:()=>null,handleRedirectPromise:()=>Promise.reject(fs(ds)),loginPopup:()=>Promise.reject(fs(ds)),loginRedirect:()=>Promise.reject(fs(ds)),logout:()=>Promise.reject(fs(ds)),logoutRedirect:()=>Promise.reject(fs(ds)),logoutPopup:()=>Promise.reject(fs(ds)),ssoSilent:()=>Promise.reject(fs(ds)),addEventCallback:()=>null,removeEventCallback:()=>{},addPerformanceCallback:()=>"",removePerformanceCallback:()=>!1,enableAccountStorageEvents:()=>{},disableAccountStorageEvents:()=>{},getTokenCache:()=>{throw fs(ds)},getLogger:()=>{throw fs(ds)},setLogger:()=>{},setActiveAccount:()=>{},getActiveAccount:()=>null,initializeWrapperLibrary:()=>{},setNavigationClient:()=>{},getConfiguration:()=>{throw fs(ds)},hydrateCache:()=>Promise.reject(fs(ds)),clearCache:()=>Promise.reject(fs(ds))};function lc(){let e;try{e=window[Ii.SessionStorage];const t=e?.getItem("msal.browser.performance.enabled");if(1===Number(t))return Promise.resolve().then((function(){return gc}))}catch(e){}}function dc(){return"undefined"!=typeof window&&void 0!==window.performance&&"function"==typeof window.performance.now}function uc(e){if(e&&dc())return Math.round(window.performance.now()-e)}class hc{constructor(e,t){this.correlationId=t,this.measureName=hc.makeMeasureName(e,t),this.startMark=hc.makeStartMark(e,t),this.endMark=hc.makeEndMark(e,t)}static makeMeasureName(e,t){return`msal.measure.${e}.${t}`}static makeStartMark(e,t){return`msal.start.${e}.${t}`}static makeEndMark(e,t){return`msal.end.${e}.${t}`}static supportsBrowserPerformance(){return"undefined"!=typeof window&&void 0!==window.performance&&"function"==typeof window.performance.mark&&"function"==typeof window.performance.measure&&"function"==typeof window.performance.clearMarks&&"function"==typeof window.performance.clearMeasures&&"function"==typeof window.performance.getEntriesByName}static flushMeasurements(e,t){if(hc.supportsBrowserPerformance())try{t.forEach((t=>{const r=hc.makeMeasureName(t.name,e);window.performance.getEntriesByName(r,"measure").length>0&&(window.performance.clearMeasures(r),window.performance.clearMarks(hc.makeStartMark(r,e)),window.performance.clearMarks(hc.makeEndMark(r,e)))}))}catch(e){}}startMeasurement(){if(hc.supportsBrowserPerformance())try{window.performance.mark(this.startMark)}catch(e){}}endMeasurement(){if(hc.supportsBrowserPerformance())try{window.performance.mark(this.endMark),window.performance.measure(this.measureName,this.startMark,this.endMark)}catch(e){}}flushMeasurement(){if(hc.supportsBrowserPerformance())try{const e=window.performance.getEntriesByName(this.measureName,"measure");if(e.length>0){const t=e[0].duration;return window.performance.clearMeasures(this.measureName),window.performance.clearMarks(this.startMark),window.performance.clearMarks(this.endMark),t}}catch(e){}return null}}var gc=Object.freeze({__proto__:null,BrowserPerformanceMeasurement:hc});t.AccountEntity=Nr,t.ApiId=Bi,t.AuthError=ke,t.AuthErrorCodes=Ce,t.AuthErrorMessage=Te,t.AuthenticationHeaderParser=class{constructor(e){this.headers=e}getShrNonce(){const e=this.headers[g];if(e){const t=this.parseChallenges(e);if(t.nextnonce)return t.nextnonce;throw Cr(ur)}const t=this.headers[h];if(t){const e=this.parseChallenges(t);if(e.nonce)return e.nonce;throw Cr(ur)}throw Cr(dr)}parseChallenges(e){const t=e.indexOf(" "),o=e.substr(t+1).split(","),n={};return o.forEach((e=>{const[t,o]=e.split("=");n[t]=unescape(o.replace(/['"]+/g,r.EMPTY_STRING))})),n}},t.AuthenticationScheme=V,t.AzureCloudInstance=At,t.BrowserAuthError=gi,t.BrowserAuthErrorCodes=li,t.BrowserAuthErrorMessage=hi,t.BrowserCacheLocation=Ii,t.BrowserConfigurationAuthError=ms,t.BrowserConfigurationAuthErrorCodes=hs,t.BrowserConfigurationAuthErrorMessage=ps,t.BrowserPerformanceClient=class extends fn{constructor(e,t,o){super(e.auth.clientId,e.auth.authority||`${r.DEFAULT_AUTHORITY}`,new Tt(e.system?.loggerOptions||{},xs,Ls),xs,Ls,e.telemetry?.application||{appName:"",appVersion:""},t,o)}generateId(){return ss()}getPageVisibility(){return document.visibilityState?.toString()||null}deleteIncompleteSubMeasurements(e){lc()?.then((t=>{const r=this.eventsByCorrelationId.get(e.event.correlationId),o=r&&r.eventId===e.event.eventId,n=[];o&&r?.incompleteSubMeasurements&&r.incompleteSubMeasurements.forEach((e=>{n.push({...e})})),t.BrowserPerformanceMeasurement.flushMeasurements(e.event.correlationId,n)}))}startMeasurement(e,t){const r=this.getPageVisibility(),o=super.startMeasurement(e,t),n=dc()?window.performance.now():void 0,i=lc()?.then((t=>new t.BrowserPerformanceMeasurement(e,o.event.correlationId)));return i?.then((e=>e.startMeasurement())),{...o,end:(e,t)=>{const s=o.end({...e,startPageVisibility:r,endPageVisibility:this.getPageVisibility(),durationMs:uc(n)},t);return i?.then((e=>e.endMeasurement())),this.deleteIncompleteSubMeasurements(o),s},discard:()=>{o.discard(),i?.then((e=>e.flushMeasurement())),this.deleteIncompleteSubMeasurements(o)}}}setPreQueueTime(e,t){if(!dc())return void this.logger.trace(`BrowserPerformanceClient: window performance API not available, unable to set telemetry queue time for ${e}`);if(!t)return void this.logger.trace(`BrowserPerformanceClient: correlationId for ${e} not provided, unable to set telemetry queue time`);const r=this.preQueueTimeByCorrelationId.get(t);r&&(this.logger.trace(`BrowserPerformanceClient: Incomplete pre-queue ${r.name} found`,t),this.addQueueMeasurement(r.name,t,void 0,!0)),this.preQueueTimeByCorrelationId.set(t,{name:e,time:window.performance.now()})}addQueueMeasurement(e,t,r,o){if(!dc())return void this.logger.trace(`BrowserPerformanceClient: window performance API not available, unable to add queue measurement for ${e}`);if(!t)return void this.logger.trace(`BrowserPerformanceClient: correlationId for ${e} not provided, unable to add queue measurement`);const n=super.getPreQueueTime(e,t);if(!n)return;const i=window.performance.now(),s=r||super.calculateQueuedTime(n,i);return super.addQueueMeasurement(e,t,s,o)}},t.BrowserPerformanceMeasurement=hc,t.BrowserStorage=ra,t.BrowserUtils=Os,t.CacheLookupPolicy=Gi,t.ClientAuthError=yt,t.ClientAuthErrorCodes=pt,t.ClientAuthErrorMessage=ft,t.ClientConfigurationError=vr,t.ClientConfigurationErrorCodes=mr,t.ClientConfigurationErrorMessage=yr,t.DEFAULT_IFRAME_TIMEOUT_MS=Us,t.EventHandler=pa,t.EventMessageUtils=class{static getInteractionStatusFromEvent(e,r){switch(e.eventType){case ga.LOGIN_START:return Fi.Login;case ga.SSO_SILENT_START:return Fi.SsoSilent;case ga.ACQUIRE_TOKEN_START:if(e.interactionType===t.InteractionType.Redirect||e.interactionType===t.InteractionType.Popup)return Fi.AcquireToken;break;case ga.HANDLE_REDIRECT_START:return Fi.HandleRedirect;case ga.LOGOUT_START:return Fi.Logout;case ga.SSO_SILENT_SUCCESS:case ga.SSO_SILENT_FAILURE:if(r&&r!==Fi.SsoSilent)break;return Fi.None;case ga.LOGOUT_END:if(r&&r!==Fi.Logout)break;return Fi.None;case ga.HANDLE_REDIRECT_END:if(r&&r!==Fi.HandleRedirect)break;return Fi.None;case ga.LOGIN_SUCCESS:case ga.LOGIN_FAILURE:case ga.ACQUIRE_TOKEN_SUCCESS:case ga.ACQUIRE_TOKEN_FAILURE:case ga.RESTORE_FROM_BFCACHE:if(e.interactionType===t.InteractionType.Redirect||e.interactionType===t.InteractionType.Popup){if(r&&r!==Fi.Login&&r!==Fi.AcquireToken)break;return Fi.None}}return null}},t.EventType=ga,t.InteractionRequiredAuthError=Fo,t.InteractionRequiredAuthErrorCodes=Lo,t.InteractionRequiredAuthErrorMessage=$o,t.InteractionStatus=Fi,t.JsonWebTokenTypes=fe,t.Logger=Tt,t.MemoryStorage=Xs,t.NavigationClient=Ns,t.OIDC_DEFAULT_SCOPES=a,t.PerformanceEvents=yo,t.PromptValue=R,t.ProtocolMode=Or,t.PublicClientApplication=oc,t.PublicClientNext=ac,t.ServerError=oo,t.ServerResponseType=P,t.SignedHttpRequest=class{constructor(e,t){const r=t&&t.loggerOptions||{};this.logger=new Tt(r,xs,Ls),this.cryptoOps=new ea(this.logger),this.popTokenGenerator=new Wo(this.cryptoOps),this.shrParameters=e}async generatePublicKeyThumbprint(){const{kid:e}=await this.popTokenGenerator.generateKid(this.shrParameters);return e}async signRequest(e,t,r){return this.popTokenGenerator.signPayload(e,t,this.shrParameters,r)}async removeKeys(e){return this.cryptoOps.removeTokenBindingKey(e)}},t.StringUtils=wr,t.StubPerformanceClient=gn,t.UrlString=xr,t.WrapperSKU={React:"@azure/msal-react",Angular:"@azure/msal-angular"},t.createNestablePublicClientApplication=async function(e){const t=new Vs(e);if(await t.initialize(),t.isAvailable()){const r=new tc(t);return new oc(e,r)}return nc(e)},t.createStandardPublicClientApplication=nc,t.stubbedPublicClientApplication=cc,t.version=Ls},9804:e=>{e.exports=JSON.parse('["ms-vscode","ms-toolsai","ms-azuretools","quantum","SynapseVSCode"]')}},r={};function o(e){var n=r[e];if(void 0!==n)return n.exports;var i=r[e]={exports:{}};return t[e].call(i.exports,i,i.exports,o),i.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};o(6268);</script></html>