bc-telemetry-buddy-mcp 3.4.1 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.5.1] - 2026-06-02
11
+
12
+ _Highest blast-radius rating across all plans landed in this release: `low-risk`._
13
+
14
+ ### Fixed
15
+ - **`npx -y bc-telemetry-buddy-mcp start` failed to launch the server (`could not determine executable to run`), breaking Claude Desktop and other clients with "Server disconnected".** v3.5.0 added the `bctb-setup*` bins, so the package exposed multiple binaries with none matching the package name — `npx <pkg>` can only auto-select when there is a single bin or one named after the package. Added a `bc-telemetry-buddy-mcp` → `dist/cli.js` bin alias so the documented `npx bc-telemetry-buddy-mcp` invocation resolves again. A regression test (`package-bin.test.ts`) locks the package-name bin in place. See [docs/plans/done/mcp-bin-package-name-alias.md](../../docs/plans/done/mcp-bin-package-name-alias.md).
16
+
17
+ ## [3.5.0] - 2026-06-01
18
+
19
+ _Highest blast-radius rating across all plans landed in this release: `low-risk`._
20
+
21
+ ### Added
22
+ - **`bctb-setup` — interactive guided connection setup.** A single command that walks you from start to finish (Azure CLI): checks/triggers `az login`, lists your Application Insights resources, you pick one by number, then it writes `.bctb-config.json` into the chosen folder (manual App-ID fallback when `az` is unavailable). Runs in any terminal (`npx -p bc-telemetry-buddy-mcp bctb-setup`) and is what the extension's Setup Wizard "Guided setup" button launches. Built on the existing tested `setup/` logic plus a `createPrompter` helper that works reliably with both TTY and piped input (unit-tested), and a `parseSelection` helper (unit-tested).
23
+
10
24
  ## [3.4.1] - 2026-06-01
11
25
 
12
26
  _Highest blast-radius rating across all plans landed in this release: `low-risk`._
package/dist/cli.js CHANGED
@@ -56,7 +56,7 @@ Connection: close\r
56
56
  `),ne=parseInt(te[0].split(" ")[1]),Ue=te[0].split(" ").slice(2).join(" "),Ce=te[te.length-1],Ee=te.slice(1,te.length-2),F=new Map;Ee.forEach(ee=>{let Je=ee.split(new RegExp(/:\s(.*)/s)),qe=Je[0],rt=Je[1];try{let mt=JSON.parse(rt);mt&&typeof mt=="object"&&(rt=mt)}catch{}F.set(qe,rt)});let X=Object.fromEntries(F),U=rI.getNetworkResponse(X,this.parseBody(ne,Ue,X,Ce),ne);this.shouldDestroyRequest(ne,U)&&g.destroy(),m(U)}),_.on("error",B=>{g.destroy(),_.destroy(),y(new Error(B.toString()))})}),g.on("error",v=>{this.logger.error(`HttpClient - Proxy request error: ${v.toString()}`,""),this.logUrlWithPiiAwareness("Destination URL",c),this.logUrlWithPiiAwareness("Proxy URL",this.proxyUrl),this.logger.error(`HttpClient - Method: ${o}`,""),this.logger.errorPii(`HttpClient - Headers: ${JSON.stringify(l)}`,""),g.destroy(),y(new Error(v.toString()))})})},this.networkRequestViaHttps=(o,c,r,t)=>{let a=o===Ba.POST,u=r?.body||"",l=new URL(c),p=r?.headers||{},d={method:o,headers:p,...rI.urlToHttpOptions(l)};return this.customAgentOptions&&Object.keys(this.customAgentOptions).length&&(d.agent=new b4e.Agent(this.customAgentOptions)),a?d.headers={...d.headers,"Content-Length":u.length}:t&&(d.timeout=t),new Promise((h,m)=>{let y;d.protocol==="http:"?y=DB.request(d):y=b4e.request(d),a&&y.write(u),t&&y.on("timeout",()=>{this.logUrlWithPiiAwareness(`HTTPS request timeout after ${t}ms for URL`,c),y.destroy(),m(new Error(`Request time out after ${t}ms`))}),y.end(),y.on("response",g=>{let v=g.headers,_=g.statusCode,k=g.statusMessage,D=[];g.on("data",B=>{D.push(B)}),g.on("end",()=>{let B=Buffer.concat([...D]).toString(),te=v,ne=rI.getNetworkResponse(te,this.parseBody(_,k,te,B),_);this.shouldDestroyRequest(_,ne)&&y.destroy(),h(ne)})}),y.on("error",g=>{this.logger.error(`HttpClient - HTTPS request error: ${g.toString()}`,""),this.logUrlWithPiiAwareness("URL",c),this.logger.error(`HttpClient - Method: ${o}`,""),this.logger.errorPii(`HttpClient - Headers: ${JSON.stringify(p)}`,""),y.destroy(),m(new Error(g.toString()))})})},this.parseBody=(o,c,r,t)=>{let a;try{a=JSON.parse(t)}catch{let l,p;o>=Eo.CLIENT_ERROR_RANGE_START&&o<=Eo.CLIENT_ERROR_RANGE_END?(l="client_error",p="A client"):o>=Eo.SERVER_ERROR_RANGE_START&&o<=Eo.SERVER_ERROR_RANGE_END?(l="server_error",p="A server"):(l="unknown_error",p="An unknown"),a={error:l,error_description:`${p} error occured.
57
57
  Http status code: ${o}
58
58
  Http status message: ${c||"Unknown"}
59
- Headers: ${JSON.stringify(r)}`}}return a},this.logUrlWithPiiAwareness=(o,c)=>{if(this.isPiiEnabled)this.logger.errorPii(`HttpClient - ${o}: ${c}`,"");else{let r;try{let t=new URL(c);r=`${t.protocol}//${t.host}${t.pathname}`}catch{r=c.split("?")[0]||"unknown"}this.logger.error(`HttpClient - ${o}: ${r} [Enable PII logging to see additional details]`,"")}},this.shouldDestroyRequest=(o,c)=>(o<Eo.SUCCESS_RANGE_START||o>Eo.SUCCESS_RANGE_END)&&!(c.body&&typeof c.body=="object"&&"error"in c.body&&c.body.error===xy.AUTHORIZATION_PENDING),this.proxyUrl=e||"",this.customAgentOptions=i||{},this.logger=new _y(s||{},Yue,y_),this.isPiiEnabled=this.logger.isPiiLoggingEnabled()}async sendGetRequestAsync(e,i,s){return this.proxyUrl?this.networkRequestViaProxy(Ba.GET,e,i,s):this.networkRequestViaHttps(Ba.GET,e,i,s)}async sendPostRequestAsync(e,i){return this.proxyUrl?this.networkRequestViaProxy(Ba.POST,e,i):this.networkRequestViaHttps(Ba.POST,e,i)}},gze="invalid_file_extension",vze="invalid_file_path",nI="invalid_managed_identity_id_type",_ze="invalid_secret",Cir="missing_client_id",Mir="network_unavailable",bze="platform_not_supported",Tze="unable_to_create_azure_arc",Sze="unable_to_create_cloud_shell",Eze="unable_to_create_source",Sue="unable_to_read_secret_file",Lir="user_assigned_not_available_at_runtime",Oze="www_authenticate_header_missing",xze="www_authenticate_header_unsupported_format",Zw={[ir.AZURE_POD_IDENTITY_AUTHORITY_HOST]:"azure_pod_identity_authority_host_url_malformed",[ir.IDENTITY_ENDPOINT]:"identity_endpoint_url_malformed",[ir.IMDS_ENDPOINT]:"imds_endpoint_url_malformed",[ir.MSI_ENDPOINT]:"msi_endpoint_url_malformed"},kir={[gze]:"The file path in the WWW-Authenticate header does not contain a .key file.",[vze]:"The file path in the WWW-Authenticate header is not in a valid Windows or Linux Format.",[nI]:"More than one ManagedIdentityIdType was provided.",[_ze]:"The secret in the file on the file path in the WWW-Authenticate header is greater than 4096 bytes.",[bze]:"The platform is not supported by Azure Arc. Azure Arc only supports Windows and Linux.",[Cir]:"A ManagedIdentityId id was not provided.",[Zw.AZURE_POD_IDENTITY_AUTHORITY_HOST]:`The Managed Identity's '${ir.AZURE_POD_IDENTITY_AUTHORITY_HOST}' environment variable is malformed.`,[Zw.IDENTITY_ENDPOINT]:`The Managed Identity's '${ir.IDENTITY_ENDPOINT}' environment variable is malformed.`,[Zw.IMDS_ENDPOINT]:`The Managed Identity's '${ir.IMDS_ENDPOINT}' environment variable is malformed.`,[Zw.MSI_ENDPOINT]:`The Managed Identity's '${ir.MSI_ENDPOINT}' environment variable is malformed.`,[Mir]:"Authentication unavailable. The request to the managed identity endpoint timed out.",[Tze]:"Azure Arc Managed Identities can only be system assigned.",[Sze]:"Cloud Shell Managed Identities can only be system assigned.",[Eze]:"Unable to create a Managed Identity source based on environment variables.",[Sue]:"Unable to read the secret file.",[Lir]:"Service Fabric user assigned managed identity ClientId or ResourceId is not configurable at runtime.",[Oze]:"A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is missing.",[xze]:"A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is in an unsupported format."},Eue=class n extends Bn{constructor(e){super(e,kir[e]),this.name="ManagedIdentityError",Object.setPrototypeOf(this,n.prototype)}};function ja(n){return new Eue(n)}var Oue=class{get id(){return this._id}set id(e){this._id=e}get idType(){return this._idType}set idType(e){this._idType=e}constructor(e){let i=e?.userAssignedClientId,s=e?.userAssignedResourceId,o=e?.userAssignedObjectId;if(i){if(s||o)throw ja(nI);this.id=i,this.idType=xs.USER_ASSIGNED_CLIENT_ID}else if(s){if(i||o)throw ja(nI);this.id=s,this.idType=xs.USER_ASSIGNED_RESOURCE_ID}else if(o){if(i||s)throw ja(nI);this.id=o,this.idType=xs.USER_ASSIGNED_OBJECT_ID}else this.id=xir,this.idType=xs.SYSTEM_ASSIGNED}},To={invalidLoopbackAddressType:{code:"invalid_loopback_server_address_type",desc:"Loopback server address is not type string. This is unexpected."},unableToLoadRedirectUri:{code:"unable_to_load_redirectUrl",desc:"Loopback server callback was invoked without a url. This is unexpected."},noAuthCodeInResponse:{code:"no_auth_code_in_response",desc:"No auth code found in the server response. Please check your network trace to determine what happened."},noLoopbackServerExists:{code:"no_loopback_server_exists",desc:"No loopback server exists yet."},loopbackServerAlreadyExists:{code:"loopback_server_already_exists",desc:"Loopback server already exists. Cannot create another."},loopbackServerTimeout:{code:"loopback_server_timeout",desc:"Timed out waiting for auth code listener to be registered."},stateNotFoundError:{code:"state_not_found",desc:"State not found. Please verify that the request originated from msal."},thumbprintMissing:{code:"thumbprint_missing_from_client_certificate",desc:"Client certificate does not contain a SHA-1 or SHA-256 thumbprint."},redirectUriNotSupported:{code:"redirect_uri_not_supported",desc:"RedirectUri is not supported in this scenario. Please remove redirectUri from the request."}},Cu=class n extends Bn{constructor(e,i){super(e,i),this.name="NodeAuthError"}static createInvalidLoopbackAddressTypeError(){return new n(To.invalidLoopbackAddressType.code,`${To.invalidLoopbackAddressType.desc}`)}static createUnableToLoadRedirectUrlError(){return new n(To.unableToLoadRedirectUri.code,`${To.unableToLoadRedirectUri.desc}`)}static createNoAuthCodeInResponseError(){return new n(To.noAuthCodeInResponse.code,`${To.noAuthCodeInResponse.desc}`)}static createNoLoopbackServerExistsError(){return new n(To.noLoopbackServerExists.code,`${To.noLoopbackServerExists.desc}`)}static createLoopbackServerAlreadyExistsError(){return new n(To.loopbackServerAlreadyExists.code,`${To.loopbackServerAlreadyExists.desc}`)}static createLoopbackServerTimeoutError(){return new n(To.loopbackServerTimeout.code,`${To.loopbackServerTimeout.desc}`)}static createStateNotFoundError(){return new n(To.stateNotFoundError.code,To.stateNotFoundError.desc)}static createThumbprintMissingError(){return new n(To.thumbprintMissing.code,To.thumbprintMissing.desc)}static createRedirectUriNotSupportedError(){return new n(To.redirectUriNotSupported.code,To.redirectUriNotSupported.desc)}},Dir={clientId:ue.EMPTY_STRING,authority:ue.DEFAULT_AUTHORITY,clientSecret:ue.EMPTY_STRING,clientAssertion:ue.EMPTY_STRING,clientCertificate:{thumbprint:ue.EMPTY_STRING,thumbprintSha256:ue.EMPTY_STRING,privateKey:ue.EMPTY_STRING,x5c:ue.EMPTY_STRING},knownAuthorities:[],cloudDiscoveryMetadata:ue.EMPTY_STRING,authorityMetadata:ue.EMPTY_STRING,clientCapabilities:[],protocolMode:by.AAD,azureCloudOptions:{azureCloudInstance:RV.None,tenant:ue.EMPTY_STRING},skipAuthorityMetadataCache:!1,encodeExtraQueryParams:!1},Uir={claimsBasedCachingEnabled:!1},Wue={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:bt.LogLevel.Info},qir={loggerOptions:Wue,networkClient:new BI,proxyUrl:ue.EMPTY_STRING,customAgentOptions:{},disableInternalRetries:!1},jir={application:{appName:ue.EMPTY_STRING,appVersion:ue.EMPTY_STRING}};function Bir({auth:n,broker:e,cache:i,system:s,telemetry:o}){let c={...qir,networkClient:new BI(s?.proxyUrl,s?.customAgentOptions),loggerOptions:s?.loggerOptions||Wue,disableInternalRetries:s?.disableInternalRetries||!1};if(n.clientCertificate&&!n.clientCertificate.thumbprint&&!n.clientCertificate.thumbprintSha256)throw Cu.createStateNotFoundError();return{auth:{...Dir,...n},broker:{...e},cache:{...Uir,...i},system:{...c,...s},telemetry:{...jir,...o}}}function Vir({clientCapabilities:n,managedIdentityIdParams:e,system:i}){let s=new Oue(e),o=i?.loggerOptions||Wue,c;return i?.networkClient?c=i.networkClient:c=new BI(i?.proxyUrl,i?.customAgentOptions),{clientCapabilities:n||[],managedIdentityId:s,system:{loggerOptions:o,networkClient:c},disableInternalRetries:i?.disableInternalRetries||!1}}var yV=class{generateGuid(){return Srr.v4()}isGuid(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}},Jh=class n{static base64Encode(e,i){return Buffer.from(e,i).toString(Zh.BASE64)}static base64EncodeUrl(e,i){return n.base64Encode(e,i).replace(/=/g,ue.EMPTY_STRING).replace(/\+/g,"-").replace(/\//g,"_")}static base64Decode(e){return Buffer.from(e,Zh.BASE64).toString("utf8")}static base64DecodeUrl(e){let i=e.replace(/-/g,"+").replace(/_/g,"/");for(;i.length%4;)i+="=";return n.base64Decode(i)}},VI=class{sha256(e){return F4e.createHash(wir.SHA256).update(e).digest()}},xue=class{constructor(){this.hashUtils=new VI}async generatePkceCodes(){let e=this.generateCodeVerifier(),i=this.generateCodeChallengeFromVerifier(e);return{verifier:e,challenge:i}}generateCodeVerifier(){let e=[],i=256-256%pue.CV_CHARSET.length;for(;e.length<=Nir;){let o=F4e.randomBytes(1)[0];if(o>=i)continue;let c=o%pue.CV_CHARSET.length;e.push(pue.CV_CHARSET[c])}let s=e.join(ue.EMPTY_STRING);return Jh.base64EncodeUrl(s)}generateCodeChallengeFromVerifier(e){return Jh.base64EncodeUrl(this.hashUtils.sha256(e).toString(Zh.BASE64),Zh.BASE64)}},HE=class{constructor(){this.pkceGenerator=new xue,this.guidGenerator=new yV,this.hashUtils=new VI}base64UrlEncode(){throw new Error("Method not implemented.")}encodeKid(){throw new Error("Method not implemented.")}createNewGuid(){return this.guidGenerator.generateGuid()}base64Encode(e){return Jh.base64Encode(e)}base64Decode(e){return Jh.base64Decode(e)}generatePkceCodes(){return this.pkceGenerator.generatePkceCodes()}getPublicKeyThumbprint(){throw new Error("Method not implemented.")}removeTokenBindingKey(){throw new Error("Method not implemented.")}clearKeystore(){throw new Error("Method not implemented.")}signJwt(){throw new Error("Method not implemented.")}async hashString(e){return Jh.base64EncodeUrl(this.hashUtils.sha256(e).toString(Zh.BASE64),Zh.BASE64)}};function $ir(n){let e=n.credentialType===Gi.REFRESH_TOKEN&&n.familyId||n.clientId,i=n.tokenType&&n.tokenType.toLowerCase()!==ii.BEARER.toLowerCase()?n.tokenType.toLowerCase():"";return[n.homeAccountId,n.environment,n.credentialType,e,n.realm||"",n.target||"",n.requestedClaimsHash||"",i].join(yze.KEY_SEPARATOR).toLowerCase()}function Fir(n){let e=n.homeAccountId.split(".")[1];return[n.homeAccountId,n.environment,e||n.tenantId||""].join(yze.KEY_SEPARATOR).toLowerCase()}var $I=class extends UI{constructor(e,i,s,o){super(i,s,e,new Os.StubPerformanceClient,o),this.cache={},this.changeEmitters=[],this.logger=e}registerChangeEmitter(e){this.changeEmitters.push(e)}emitChange(){this.changeEmitters.forEach(e=>e.call(null))}cacheToInMemoryCache(e){let i={accounts:{},idTokens:{},accessTokens:{},refreshTokens:{},appMetadata:{}};for(let s in e){let o=e[s];if(typeof o=="object")if(o instanceof Xc)i.accounts[s]=o;else if(I4e(o))i.idTokens[s]=o;else if(w4e(o))i.accessTokens[s]=o;else if(C4e(o))i.refreshTokens[s]=o;else if(M4e(s,o))i.appMetadata[s]=o;else continue}return i}inMemoryCacheToCache(e){let i=this.getCache();return i={...i,...e.accounts,...e.idTokens,...e.accessTokens,...e.refreshTokens,...e.appMetadata},i}getInMemoryCache(){return this.logger.trace("Getting in-memory cache"),this.cacheToInMemoryCache(this.getCache())}setInMemoryCache(e){this.logger.trace("Setting in-memory cache");let i=this.inMemoryCacheToCache(e);this.setCache(i),this.emitChange()}getCache(){return this.logger.trace("Getting cache key-value store"),this.cache}setCache(e){this.logger.trace("Setting cache key value store"),this.cache=e,this.emitChange()}getItem(e){return this.logger.tracePii(`Item key: ${e}`),this.getCache()[e]}setItem(e,i){this.logger.tracePii(`Item key: ${e}`);let s=this.getCache();s[e]=i,this.setCache(s)}generateCredentialKey(e){return $ir(e)}generateAccountKey(e){return Fir(e)}getAccountKeys(){let e=this.getInMemoryCache();return Object.keys(e.accounts)}getTokenKeys(){let e=this.getInMemoryCache();return{idToken:Object.keys(e.idTokens),accessToken:Object.keys(e.accessTokens),refreshToken:Object.keys(e.refreshTokens)}}getAccount(e){return this.getItem(e)?Object.assign(new Xc,this.getItem(e)):null}async setAccount(e){let i=this.generateAccountKey(Xc.getAccountInfo(e));this.setItem(i,e)}getIdTokenCredential(e){let i=this.getItem(e);return I4e(i)?i:null}async setIdTokenCredential(e){let i=this.generateCredentialKey(e);this.setItem(i,e)}getAccessTokenCredential(e){let i=this.getItem(e);return w4e(i)?i:null}async setAccessTokenCredential(e){let i=this.generateCredentialKey(e);this.setItem(i,e)}getRefreshTokenCredential(e){let i=this.getItem(e);return C4e(i)?i:null}async setRefreshTokenCredential(e){let i=this.generateCredentialKey(e);this.setItem(i,e)}getAppMetadata(e){let i=this.getItem(e);return M4e(e,i)?i:null}setAppMetadata(e){let i=sir(e);this.setItem(i,e)}getServerTelemetry(e){let i=this.getItem(e);return i&&oir(e,i)?i:null}setServerTelemetry(e,i){this.setItem(e,i)}getAuthorityMetadata(e){let i=this.getItem(e);return i&&cir(e,i)?i:null}getAuthorityMetadataKeys(){return this.getKeys().filter(e=>this.isAuthorityMetadata(e))}setAuthorityMetadata(e,i){this.setItem(e,i)}getThrottlingCache(e){let i=this.getItem(e);return i&&air(e,i)?i:null}setThrottlingCache(e,i){this.setItem(e,i)}removeItem(e){this.logger.tracePii(`Item key: ${e}`);let i=!1,s=this.getCache();return s[e]&&(delete s[e],i=!0),i&&(this.setCache(s),this.emitChange()),i}removeOutdatedAccount(e){this.removeItem(e)}containsKey(e){return this.getKeys().includes(e)}getKeys(){this.logger.trace("Retrieving all cache keys");let e=this.getCache();return[...Object.keys(e)]}clear(){this.logger.trace("Clearing cache entries created by MSAL"),this.getKeys().forEach(i=>{this.removeItem(i)}),this.emitChange()}static generateInMemoryCache(e){return zE.deserializeAllCache(zE.deserializeJSONBlob(e))}static generateJsonCache(e){return iI.serializeAllCache(e)}updateCredentialCacheKey(e,i){let s=this.generateCredentialKey(i);if(e!==s){let o=this.getItem(e);if(o)return this.removeItem(e),this.setItem(s,o),this.logger.verbose(`Updated an outdated ${i.credentialType} cache key`),s;this.logger.error(`Attempted to update an outdated ${i.credentialType} cache key but no item matching the outdated key was found in storage`)}return e}},Jw={Account:{},IdToken:{},AccessToken:{},RefreshToken:{},AppMetadata:{}},gV=class{constructor(e,i,s){this.cacheHasChanged=!1,this.storage=e,this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this)),s&&(this.persistence=s),this.logger=i}hasChanged(){return this.cacheHasChanged}serialize(){this.logger.trace("Serializing in-memory cache");let e=iI.serializeAllCache(this.storage.getInMemoryCache());return this.cacheSnapshot?(this.logger.trace("Reading cache snapshot from disk"),e=this.mergeState(JSON.parse(this.cacheSnapshot),e)):this.logger.trace("No cache snapshot to merge"),this.cacheHasChanged=!1,JSON.stringify(e)}deserialize(e){if(this.logger.trace("Deserializing JSON to in-memory cache"),this.cacheSnapshot=e,this.cacheSnapshot){this.logger.trace("Reading cache snapshot from disk");let i=zE.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));this.storage.setInMemoryCache(i)}else this.logger.trace("No cache snapshot to deserialize")}getKVStore(){return this.storage.getCache()}getCacheSnapshot(){let e=$I.generateInMemoryCache(this.cacheSnapshot);return this.storage.inMemoryCacheToCache(e)}async getAllAccounts(e=new HE().createNewGuid()){this.logger.trace("getAllAccounts called");let i;try{return this.persistence&&(i=new vy(this,!1),await this.persistence.beforeCacheAccess(i)),this.storage.getAllAccounts({},e)}finally{this.persistence&&i&&await this.persistence.afterCacheAccess(i)}}async getAccountByHomeId(e){let i=await this.getAllAccounts();return e&&i&&i.length&&i.filter(s=>s.homeAccountId===e)[0]||null}async getAccountByLocalId(e){let i=await this.getAllAccounts();return e&&i&&i.length&&i.filter(s=>s.localAccountId===e)[0]||null}async removeAccount(e,i){this.logger.trace("removeAccount called");let s;try{this.persistence&&(s=new vy(this,!0),await this.persistence.beforeCacheAccess(s)),this.storage.removeAccount(e,i||new yV().generateGuid())}finally{this.persistence&&s&&await this.persistence.afterCacheAccess(s)}}async overwriteCache(){if(!this.persistence){this.logger.info("No persistence layer specified, cache cannot be overwritten");return}this.logger.info("Overwriting in-memory cache with persistent cache"),this.storage.clear();let e=new vy(this,!1);await this.persistence.beforeCacheAccess(e);let i=this.getCacheSnapshot();this.storage.setCache(i),await this.persistence.afterCacheAccess(e)}handleChangeEvent(){this.cacheHasChanged=!0}mergeState(e,i){this.logger.trace("Merging in-memory cache with cache snapshot");let s=this.mergeRemovals(e,i);return this.mergeUpdates(s,i)}mergeUpdates(e,i){return Object.keys(i).forEach(s=>{let o=i[s];if(!e.hasOwnProperty(s))o!==null&&(e[s]=o);else{let c=o!==null,r=typeof o=="object",t=!Array.isArray(o),a=typeof e[s]<"u"&&e[s]!==null;c&&r&&t&&a?this.mergeUpdates(e[s],o):e[s]=o}}),e}mergeRemovals(e,i){this.logger.trace("Remove updated entries in cache");let s=e.Account?this.mergeRemovalsDict(e.Account,i.Account):e.Account,o=e.AccessToken?this.mergeRemovalsDict(e.AccessToken,i.AccessToken):e.AccessToken,c=e.RefreshToken?this.mergeRemovalsDict(e.RefreshToken,i.RefreshToken):e.RefreshToken,r=e.IdToken?this.mergeRemovalsDict(e.IdToken,i.IdToken):e.IdToken,t=e.AppMetadata?this.mergeRemovalsDict(e.AppMetadata,i.AppMetadata):e.AppMetadata;return{...e,Account:s,AccessToken:o,RefreshToken:c,IdToken:r,AppMetadata:t}}mergeRemovalsDict(e,i){let s={...e};return Object.keys(e).forEach(o=>{(!i||!i.hasOwnProperty(o))&&delete s[o]}),s}overlayDefaults(e){return this.logger.trace("Overlaying input cache with the default cache"),{Account:{...Jw.Account,...e.Account},IdToken:{...Jw.IdToken,...e.IdToken},AccessToken:{...Jw.AccessToken,...e.AccessToken},RefreshToken:{...Jw.RefreshToken,...e.RefreshToken},AppMetadata:{...Jw.AppMetadata,...e.AppMetadata}}}},GE=class n{static fromAssertion(e){let i=new n;return i.jwt=e,i}static fromCertificate(e,i,s){let o=new n;return o.privateKey=i,o.thumbprint=e,o.useSha256=!1,s&&(o.publicCertificate=this.parseCertificate(s)),o}static fromCertificateWithSha256Thumbprint(e,i,s){let o=new n;return o.privateKey=i,o.thumbprint=e,o.useSha256=!0,s&&(o.publicCertificate=this.parseCertificate(s)),o}getJwt(e,i,s){if(this.privateKey&&this.thumbprint)return this.jwt&&!this.isExpired()&&i===this.issuer&&s===this.jwtAudience?this.jwt:this.createJwt(e,i,s);if(this.jwt)return this.jwt;throw we(SI)}createJwt(e,i,s){this.issuer=i,this.jwtAudience=s;let o=Ki();this.expirationTime=o+600;let r={alg:this.useSha256?Sp.PSS_256:Sp.RSA_256},t=this.useSha256?Sp.X5T_256:Sp.X5T;Object.assign(r,{[t]:Jh.base64EncodeUrl(this.thumbprint,Zh.HEX)}),this.publicCertificate&&Object.assign(r,{[Sp.X5C]:this.publicCertificate});let a={[Sp.AUDIENCE]:this.jwtAudience,[Sp.EXPIRATION_TIME]:this.expirationTime,[Sp.ISSUER]:this.issuer,[Sp.SUBJECT]:this.issuer,[Sp.NOT_BEFORE]:o,[Sp.JWT_ID]:e.createNewGuid()};return this.jwt=Err.sign(a,this.privateKey,{header:r}),this.jwt}isExpired(){return this.expirationTime<Ki()}static parseCertificate(e){let i=/-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs,s=[],o;for(;(o=i.exec(e))!==null;)s.push(o[1].replace(/\r*\n/g,ue.EMPTY_STRING));return s}},vV=class extends Xh{constructor(e){super(e)}async acquireToken(e){this.logger.info("in acquireToken call in username-password client");let i=Ki(),s=await this.executeTokenRequest(this.authority,e),o=new Mu(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return o.validateTokenResponse(s.body),o.handleServerTokenResponse(s.body,this.authority,i,e)}async executeTokenRequest(e,i){let s=this.createTokenQueryParameters(i),o=ni.appendQueryString(e.tokenEndpoint,s),c=await this.createTokenRequestBody(i),r=this.createTokenRequestHeaders({credential:i.username,type:Ld.UPN}),t={clientId:this.config.authOptions.clientId,authority:e.canonicalAuthority,scopes:i.scopes,claims:i.claims,authenticationScheme:i.authenticationScheme,resourceRequestMethod:i.resourceRequestMethod,resourceRequestUri:i.resourceRequestUri,shrClaims:i.shrClaims,sshKid:i.sshKid};return this.executePostToTokenEndpoint(o,c,r,t,i.correlationId)}async createTokenRequestBody(e){let i=new Map;Sy(i,this.config.authOptions.clientId),Knr(i,e.username),Ynr(i,e.password),Ty(i,e.scopes),oze(i,z4e.IDTOKEN_TOKEN),YE(i,KE.RESOURCE_OWNER_PASSWORD_GRANT),WE(i),v_(i,this.config.libraryInfo),__(i,this.config.telemetry.application),ZE(i),this.serverTelemetryManager&&JE(i,this.serverTelemetryManager);let s=e.correlationId||this.config.cryptoInterface.createNewGuid();g_(i,s),this.config.clientCredentials.clientSecret&&KI(i,this.config.clientCredentials.clientSecret);let o=this.config.clientCredentials.clientAssertion;return o&&(YI(i,await b_(o.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),WI(i,o.assertionType)),(!Xs.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(i,e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.username&&qI(i,e.username),Qc(i)}};function zir(n,e,i,s){let o=vir({...n.auth,authority:e,redirectUri:i.redirectUri||""},i,s);return v_(o,{sku:xy.MSAL_SKU,version:y_,cpu:process.arch||"",os:process.platform||""}),n.auth.protocolMode!==by.OIDC&&__(o,n.telemetry.application),oze(o,z4e.CODE),i.codeChallenge&&i.codeChallengeMethod&&jnr(o,i.codeChallenge,i.codeChallengeMethod),Dd(o,i.extraQueryParameters||{}),_ir(e,o,n.auth.encodeExtraQueryParams,i.extraQueryParameters)}var FI=class{constructor(e){this.config=Bir(e),this.cryptoProvider=new HE,this.logger=new _y(this.config.system.loggerOptions,Yue,y_),this.storage=new $I(this.logger,this.config.auth.clientId,this.cryptoProvider,lir(this.config.auth)),this.tokenCache=new gV(this.storage,this.logger,this.config.cache.cachePlugin)}async getAuthCodeUrl(e){this.logger.info("getAuthCodeUrl called",e.correlationId);let i={...e,...await this.initializeBaseRequest(e),responseMode:e.responseMode||PV.QUERY,authenticationScheme:ii.BEARER,state:e.state||"",nonce:e.nonce||""},s=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions);return zir(this.config,s,i,this.logger)}async acquireTokenByCode(e,i){this.logger.info("acquireTokenByCode called"),e.state&&i&&(this.logger.info("acquireTokenByCode - validating state"),this.validateState(e.state,i.state||""),i={...i,state:""});let s={...e,...await this.initializeBaseRequest(e),authenticationScheme:ii.BEARER},o=this.initializeServerTelemetryManager(xE.acquireTokenByCode,s.correlationId);try{let c=await this.createAuthority(s.authority,s.correlationId,void 0,e.azureCloudOptions),r=await this.buildOauthClientConfiguration(c,s.correlationId,s.redirectUri,o),t=new bue(r);return this.logger.verbose("Auth code client created",s.correlationId),await t.acquireToken(s,i)}catch(c){throw c instanceof Bn&&c.setCorrelationId(s.correlationId),o.cacheFailedRequest(c),c}}async acquireTokenByRefreshToken(e){this.logger.info("acquireTokenByRefreshToken called",e.correlationId);let i={...e,...await this.initializeBaseRequest(e),authenticationScheme:ii.BEARER},s=this.initializeServerTelemetryManager(xE.acquireTokenByRefreshToken,i.correlationId);try{let o=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),c=await this.buildOauthClientConfiguration(o,i.correlationId,i.redirectUri||"",s),r=new tI(c);return this.logger.verbose("Refresh token client created",i.correlationId),await r.acquireToken(i)}catch(o){throw o instanceof Bn&&o.setCorrelationId(i.correlationId),s.cacheFailedRequest(o),o}}async acquireTokenSilent(e){let i={...e,...await this.initializeBaseRequest(e),forceRefresh:e.forceRefresh||!1},s=this.initializeServerTelemetryManager(xE.acquireTokenSilent,i.correlationId,i.forceRefresh);try{let o=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),c=await this.buildOauthClientConfiguration(o,i.correlationId,i.redirectUri||"",s),r=new Tue(c);this.logger.verbose("Silent flow client created",i.correlationId);try{return await this.tokenCache.overwriteCache(),await this.acquireCachedTokenSilent(i,r,c)}catch(t){if(t instanceof RI&&t.errorCode===kd)return new tI(c).acquireTokenByRefreshToken(i);throw t}}catch(o){throw o instanceof Bn&&o.setCorrelationId(i.correlationId),s.cacheFailedRequest(o),o}}async acquireCachedTokenSilent(e,i,s){let[o,c]=await i.acquireCachedToken({...e,scopes:e.scopes?.length?e.scopes:[...Yh]});if(c===So.PROACTIVELY_REFRESHED){this.logger.info("ClientApplication:acquireCachedTokenSilent - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.");let r=new tI(s);try{await r.acquireTokenByRefreshToken(e)}catch{}}return o}async acquireTokenByUsernamePassword(e){this.logger.info("acquireTokenByUsernamePassword called",e.correlationId);let i={...e,...await this.initializeBaseRequest(e)},s=this.initializeServerTelemetryManager(xE.acquireTokenByUsernamePassword,i.correlationId);try{let o=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),c=await this.buildOauthClientConfiguration(o,i.correlationId,"",s),r=new vV(c);return this.logger.verbose("Username password client created",i.correlationId),await r.acquireToken(i)}catch(o){throw o instanceof Bn&&o.setCorrelationId(i.correlationId),s.cacheFailedRequest(o),o}}getTokenCache(){return this.logger.info("getTokenCache called"),this.tokenCache}validateState(e,i){if(!e)throw Cu.createStateNotFoundError();if(e!==i)throw we(pI)}getLogger(){return this.logger}setLogger(e){this.logger=e}async buildOauthClientConfiguration(e,i,s,o){return this.logger.verbose("buildOauthClientConfiguration called",i),this.logger.info(`Building oauth client configuration with the following authority: ${e.tokenEndpoint}.`,i),o?.updateRegionDiscoveryMetadata(e.regionDiscoveryMetadata),{authOptions:{clientId:this.config.auth.clientId,authority:e,clientCapabilities:this.config.auth.clientCapabilities,redirectUri:s},loggerOptions:{logLevel:this.config.system.loggerOptions.logLevel,loggerCallback:this.config.system.loggerOptions.loggerCallback,piiLoggingEnabled:this.config.system.loggerOptions.piiLoggingEnabled,correlationId:i},cacheOptions:{claimsBasedCachingEnabled:this.config.cache.claimsBasedCachingEnabled},cryptoInterface:this.cryptoProvider,networkInterface:this.config.system.networkClient,storageInterface:this.storage,serverTelemetryManager:o,clientCredentials:{clientSecret:this.clientSecret,clientAssertion:await this.getClientAssertion(e)},libraryInfo:{sku:xy.MSAL_SKU,version:y_,cpu:process.arch||ue.EMPTY_STRING,os:process.platform||ue.EMPTY_STRING},telemetry:this.config.telemetry,persistencePlugin:this.config.cache.cachePlugin,serializableCache:this.tokenCache}}async getClientAssertion(e){return this.developerProvidedClientAssertion&&(this.clientAssertion=GE.fromAssertion(await b_(this.developerProvidedClientAssertion,this.config.auth.clientId,e.tokenEndpoint))),this.clientAssertion&&{assertion:this.clientAssertion.getJwt(this.cryptoProvider,this.config.auth.clientId,e.tokenEndpoint),assertionType:xy.JWT_BEARER_ASSERTION_TYPE}}async initializeBaseRequest(e){return this.logger.verbose("initializeRequestScopes called",e.correlationId),e.authenticationScheme&&e.authenticationScheme===ii.POP&&this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",e.correlationId),e.authenticationScheme=ii.BEARER,this.config.cache.claimsBasedCachingEnabled&&e.claims&&!Xs.isEmptyObj(e.claims)&&(e.requestedClaimsHash=await this.cryptoProvider.hashString(e.claims)),{...e,scopes:[...e&&e.scopes||[],...Yh],correlationId:e&&e.correlationId||this.cryptoProvider.createNewGuid(),authority:e.authority||this.config.auth.authority}}initializeServerTelemetryManager(e,i,s){let o={clientId:this.config.auth.clientId,correlationId:i,apiId:e,forceRefresh:s||!1};return new mV(o,this.storage)}async createAuthority(e,i,s,o){this.logger.verbose("createAuthority called",i);let c=f_.generateAuthority(e,o||this.config.auth.azureCloudOptions),r={protocolMode:this.config.auth.protocolMode,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,azureRegionConfiguration:s,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache};return pze(c,this.config.system.networkClient,this.storage,r,this.logger,i)}clearCache(){this.storage.clear()}},Aue=class{async listenForAuthCode(e,i){if(this.server)throw Cu.createLoopbackServerAlreadyExistsError();return new Promise((s,o)=>{this.server=DB.createServer((c,r)=>{let t=c.url;if(t){if(t===ue.FORWARD_SLASH){r.end(e||"Auth code was successfully acquired. You can close this window now.");return}}else{r.end(i||"Error occurred loading redirectUrl"),o(Cu.createUnableToLoadRedirectUrlError());return}let a=this.getRedirectUri(),u=new URL(t,a),l=Z4e(u.search)||{};l.code&&(r.writeHead(Eo.REDIRECT,{location:a}),r.end()),l.error&&r.end(i||`Error occurred: ${l.error}`),s(l)}),this.server.listen(0,"127.0.0.1")})}getRedirectUri(){if(!this.server||!this.server.listening)throw Cu.createNoLoopbackServerExistsError();let e=this.server.address();if(!e||typeof e=="string"||!e.port)throw this.closeServer(),Cu.createInvalidLoopbackAddressTypeError();let i=e&&e.port;return`${xy.HTTP_PROTOCOL}${xy.LOCALHOST}:${i}`}closeServer(){this.server&&(this.server.close(),typeof this.server.closeAllConnections=="function"&&this.server.closeAllConnections(),this.server.unref(),this.server=void 0)}},_V=class extends Xh{constructor(e){super(e)}async acquireToken(e){let i=await this.getDeviceCode(e);e.deviceCodeCallback(i);let s=Ki(),o=await this.acquireTokenWithDeviceCode(e,i),c=new Mu(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return c.validateTokenResponse(o),c.handleServerTokenResponse(o,this.authority,s,e)}async getDeviceCode(e){let i=this.createExtraQueryParameters(e),s=ni.appendQueryString(this.authority.deviceCodeEndpoint,i),o=this.createQueryString(e),c=this.createTokenRequestHeaders(),r={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid};return this.executePostRequestToDeviceCodeEndpoint(s,o,c,r,e.correlationId)}createExtraQueryParameters(e){let i=new Map;return e.extraQueryParameters&&Dd(i,e.extraQueryParameters),Qc(i)}async executePostRequestToDeviceCodeEndpoint(e,i,s,o,c){let{body:{user_code:r,device_code:t,verification_uri:a,expires_in:u,interval:l,message:p}}=await this.sendPostRequest(o,e,{body:i,headers:s},c);return{userCode:r,deviceCode:t,verificationUri:a,expiresIn:u,interval:l,message:p}}createQueryString(e){let i=new Map;return Ty(i,e.scopes),Sy(i,this.config.authOptions.clientId),e.extraQueryParameters&&Dd(i,e.extraQueryParameters),(e.claims||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(i,e.claims,this.config.authOptions.clientCapabilities),Qc(i)}continuePolling(e,i,s){if(s)throw this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true"),we(vI);if(i&&i<e&&Ki()>i)throw this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${i}`),we(EI);if(Ki()>e)throw i&&this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${i}`),this.logger.error(`Device code expired. Expiration time of device code was ${e}`),we(_I);return!0}async acquireTokenWithDeviceCode(e,i){let s=this.createTokenQueryParameters(e),o=ni.appendQueryString(this.authority.tokenEndpoint,s),c=this.createTokenRequestBody(e,i),r=this.createTokenRequestHeaders(),t=e.timeout?Ki()+e.timeout:void 0,a=Ki()+i.expiresIn,u=i.interval*1e3;for(;this.continuePolling(a,t,e.cancel);){let l={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid},p=await this.executePostToTokenEndpoint(o,c,r,l,e.correlationId);if(p.body&&p.body.error)if(p.body.error===ue.AUTHORIZATION_PENDING)this.logger.info("Authorization pending. Continue polling."),await tir(u);else throw this.logger.info("Unexpected error in polling from the server"),Nrr(aI,p.body.error);else return this.logger.verbose("Authorization completed successfully. Polling stopped."),p.body}throw this.logger.error("Polling stopped for unknown reasons."),we(bI)}createTokenRequestBody(e,i){let s=new Map;Ty(s,e.scopes),Sy(s,this.config.authOptions.clientId),YE(s,KE.DEVICE_CODE_GRANT),Vnr(s,i.deviceCode);let o=e.correlationId||this.config.cryptoInterface.createNewGuid();return g_(s,o),WE(s),v_(s,this.config.libraryInfo),__(s,this.config.telemetry.application),ZE(s),this.serverTelemetryManager&&JE(s,this.serverTelemetryManager),(!Xs.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(s,e.claims,this.config.authOptions.clientCapabilities),Qc(s)}},Pue=class extends FI{constructor(e){super(e),this.config.broker.nativeBrokerPlugin&&(this.config.broker.nativeBrokerPlugin.isBrokerAvailable?(this.nativeBrokerPlugin=this.config.broker.nativeBrokerPlugin,this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions)):this.logger.warning("NativeBroker implementation was provided but the broker is unavailable.")),this.skus=mV.makeExtraSkuString({libraryName:xy.MSAL_SKU,libraryVersion:y_})}async acquireTokenByDeviceCode(e){this.logger.info("acquireTokenByDeviceCode called",e.correlationId);let i=Object.assign(e,await this.initializeBaseRequest(e)),s=this.initializeServerTelemetryManager(xE.acquireTokenByDeviceCode,i.correlationId);try{let o=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),c=await this.buildOauthClientConfiguration(o,i.correlationId,"",s),r=new _V(c);return this.logger.verbose("Device code client created",i.correlationId),await r.acquireToken(i)}catch(o){throw o instanceof Bn&&o.setCorrelationId(i.correlationId),s.cacheFailedRequest(o),o}}async acquireTokenInteractive(e){let i=e.correlationId||this.cryptoProvider.createNewGuid();this.logger.trace("acquireTokenInteractive called",i);let{openBrowser:s,successTemplate:o,errorTemplate:c,windowHandle:r,loopbackClient:t,...a}=e;if(this.nativeBrokerPlugin){let m={...a,clientId:this.config.auth.clientId,scopes:e.scopes||Yh,redirectUri:e.redirectUri||"",authority:e.authority||this.config.auth.authority,correlationId:i,extraParameters:{...a.extraQueryParameters,...a.tokenQueryParameters,[P4e]:this.skus},accountId:a.account?.nativeAccountId};return this.nativeBrokerPlugin.acquireTokenInteractive(m,r)}if(e.redirectUri){if(!this.config.broker.nativeBrokerPlugin)throw Cu.createRedirectUriNotSupportedError();e.redirectUri=""}let{verifier:u,challenge:l}=await this.cryptoProvider.generatePkceCodes(),p=t||new Aue,d={},h=null;try{let m=p.listenForAuthCode(o,c).then(D=>{d=D}).catch(D=>{h=D}),y=await this.waitForRedirectUri(p),g={...a,correlationId:i,scopes:e.scopes||Yh,redirectUri:y,responseMode:PV.QUERY,codeChallenge:l,codeChallengeMethod:xrr.S256},v=await this.getAuthCodeUrl(g);if(await s(v),await m,h)throw h;if(d.error)throw new h_(d.error,d.error_description,d.suberror);if(!d.code)throw Cu.createNoAuthCodeInResponseError();let _=d.client_info,k={code:d.code,codeVerifier:u,clientInfo:_||ue.EMPTY_STRING,...g};return await this.acquireTokenByCode(k)}finally{p.closeServer()}}async acquireTokenSilent(e){let i=e.correlationId||this.cryptoProvider.createNewGuid();if(this.logger.trace("acquireTokenSilent called",i),this.nativeBrokerPlugin){let s={...e,clientId:this.config.auth.clientId,scopes:e.scopes||Yh,redirectUri:e.redirectUri||"",authority:e.authority||this.config.auth.authority,correlationId:i,extraParameters:{...e.tokenQueryParameters,[P4e]:this.skus},accountId:e.account.nativeAccountId,forceRefresh:e.forceRefresh||!1};return this.nativeBrokerPlugin.acquireTokenSilent(s)}if(e.redirectUri){if(!this.config.broker.nativeBrokerPlugin)throw Cu.createRedirectUriNotSupportedError();e.redirectUri=""}return super.acquireTokenSilent(e)}async signOut(e){if(this.nativeBrokerPlugin&&e.account.nativeAccountId){let i={clientId:this.config.auth.clientId,accountId:e.account.nativeAccountId,correlationId:e.correlationId||this.cryptoProvider.createNewGuid()};await this.nativeBrokerPlugin.signOut(i)}await this.getTokenCache().removeAccount(e.account,e.correlationId)}async getAllAccounts(){if(this.nativeBrokerPlugin){let e=this.cryptoProvider.createNewGuid();return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId,e)}return this.getTokenCache().getAllAccounts()}async waitForRedirectUri(e){return new Promise((i,s)=>{let o=0,c=setInterval(()=>{if(due.TIMEOUT_MS/due.INTERVAL_MS<o){clearInterval(c),s(Cu.createLoopbackServerTimeoutError());return}try{let r=e.getRedirectUri();clearInterval(c),i(r);return}catch(r){if(r instanceof Bn&&r.errorCode===To.noLoopbackServerExists.code){o++;return}clearInterval(c),s(r);return}},due.INTERVAL_MS)})}},zI=class extends Xh{constructor(e,i){super(e),this.appTokenProvider=i}async acquireToken(e){if(e.skipCache||e.claims)return this.executeTokenRequest(e,this.authority);let[i,s]=await this.getCachedAuthenticationResult(e,this.config,this.cryptoUtils,this.authority,this.cacheManager,this.serverTelemetryManager);return i?(s===So.PROACTIVELY_REFRESHED&&(this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."),await this.executeTokenRequest(e,this.authority,!0)),i):this.executeTokenRequest(e,this.authority)}async getCachedAuthenticationResult(e,i,s,o,c,r){let t=i,a=i,u=So.NOT_APPLICABLE,l;t.serializableCache&&t.persistencePlugin&&(l=new vy(t.serializableCache,!1),await t.persistencePlugin.beforeCacheAccess(l));let p=this.readAccessTokenFromCache(o,a.managedIdentityId?.id||t.authOptions.clientId,new Zs(e.scopes||[]),c,e.correlationId);return t.serializableCache&&t.persistencePlugin&&l&&await t.persistencePlugin.afterCacheAccess(l),p?VE(p.expiresOn,t.systemOptions?.tokenRenewalOffsetSeconds||G4e)?(r?.setCacheOutcome(So.CACHED_ACCESS_TOKEN_EXPIRED),[null,So.CACHED_ACCESS_TOKEN_EXPIRED]):(p.refreshOn&&VE(p.refreshOn.toString(),0)&&(u=So.PROACTIVELY_REFRESHED,r?.setCacheOutcome(So.PROACTIVELY_REFRESHED)),[await Mu.generateAuthenticationResult(s,o,{account:null,idToken:null,accessToken:p,refreshToken:null,appMetadata:null},!0,e),u]):(r?.setCacheOutcome(So.NO_CACHED_ACCESS_TOKEN),[null,So.NO_CACHED_ACCESS_TOKEN])}readAccessTokenFromCache(e,i,s,o,c){let r={homeAccountId:ue.EMPTY_STRING,environment:e.canonicalAuthorityUrlComponents.HostNameAndPort,credentialType:Gi.ACCESS_TOKEN,clientId:i,realm:e.tenant,target:Zs.createSearchScopes(s.asArray())},t=o.getAccessTokensByFilter(r,c);if(t.length<1)return null;if(t.length>1)throw we(IE);return t[0]}async executeTokenRequest(e,i,s){let o,c;if(this.appTokenProvider){this.logger.info("Using appTokenProvider extensibility.");let a={correlationId:e.correlationId,tenantId:this.config.authOptions.authority.tenant,scopes:e.scopes,claims:e.claims};c=Ki();let u=await this.appTokenProvider(a);o={access_token:u.accessToken,expires_in:u.expiresInSeconds,refresh_in:u.refreshInSeconds,token_type:ii.BEARER}}else{let a=this.createTokenQueryParameters(e),u=ni.appendQueryString(i.tokenEndpoint,a),l=await this.createTokenRequestBody(e),p=this.createTokenRequestHeaders(),d={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid};this.logger.info("Sending token request to endpoint: "+i.tokenEndpoint),c=Ki();let h=await this.executePostToTokenEndpoint(u,l,p,d,e.correlationId);o=h.body,o.status=h.status}let r=new Mu(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return r.validateTokenResponse(o,s),await r.handleServerTokenResponse(o,this.authority,c,e)}async createTokenRequestBody(e){let i=new Map;Sy(i,this.config.authOptions.clientId),Ty(i,e.scopes,!1),YE(i,KE.CLIENT_CREDENTIALS_GRANT),v_(i,this.config.libraryInfo),__(i,this.config.telemetry.application),ZE(i),this.serverTelemetryManager&&JE(i,this.serverTelemetryManager);let s=e.correlationId||this.config.cryptoInterface.createNewGuid();g_(i,s),this.config.clientCredentials.clientSecret&&KI(i,this.config.clientCredentials.clientSecret);let o=e.clientAssertion||this.config.clientCredentials.clientAssertion;return o&&(YI(i,await b_(o.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),WI(i,o.assertionType)),(!Xs.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(i,e.claims,this.config.authOptions.clientCapabilities),Qc(i)}},bV=class extends Xh{constructor(e){super(e)}async acquireToken(e){if(this.scopeSet=new Zs(e.scopes||[]),this.userAssertionHash=await this.cryptoUtils.hashString(e.oboAssertion),e.skipCache||e.claims)return this.executeTokenRequest(e,this.authority,this.userAssertionHash);try{return await this.getCachedAuthenticationResult(e)}catch{return await this.executeTokenRequest(e,this.authority,this.userAssertionHash)}}async getCachedAuthenticationResult(e){let i=this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId,e);if(i){if(VE(i.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.serverTelemetryManager?.setCacheOutcome(So.CACHED_ACCESS_TOKEN_EXPIRED),this.logger.info(`OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`),we(kd)}else throw this.serverTelemetryManager?.setCacheOutcome(So.NO_CACHED_ACCESS_TOKEN),this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties."),we(kd);let s=this.readIdTokenFromCacheForOBO(i.homeAccountId,e.correlationId),o,c=null;if(s){o=HI(s.secret,Jh.base64Decode);let r=o.oid||o.sub,t={homeAccountId:s.homeAccountId,environment:s.environment,tenantId:s.realm,username:ue.EMPTY_STRING,localAccountId:r||ue.EMPTY_STRING};c=this.cacheManager.getAccount(this.cacheManager.generateAccountKey(t),e.correlationId)}return this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),Mu.generateAuthenticationResult(this.cryptoUtils,this.authority,{account:c,accessToken:i,idToken:s,refreshToken:null,appMetadata:null},!0,e,o)}readIdTokenFromCacheForOBO(e,i){let s={homeAccountId:e,environment:this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,credentialType:Gi.ID_TOKEN,clientId:this.config.authOptions.clientId,realm:this.authority.tenant},o=this.cacheManager.getIdTokensByFilter(s,i);return Object.values(o).length<1?null:Object.values(o)[0]}readAccessTokenFromCacheForOBO(e,i){let s=i.authenticationScheme||ii.BEARER,c={credentialType:s.toLowerCase()!==ii.BEARER.toLowerCase()?Gi.ACCESS_TOKEN_WITH_AUTH_SCHEME:Gi.ACCESS_TOKEN,clientId:e,target:Zs.createSearchScopes(this.scopeSet.asArray()),tokenType:s,keyId:i.sshKid,requestedClaimsHash:i.requestedClaimsHash,userAssertionHash:this.userAssertionHash},r=this.cacheManager.getAccessTokensByFilter(c,i.correlationId),t=r.length;if(t<1)return null;if(t>1)throw we(IE);return r[0]}async executeTokenRequest(e,i,s){let o=this.createTokenQueryParameters(e),c=ni.appendQueryString(i.tokenEndpoint,o),r=await this.createTokenRequestBody(e),t=this.createTokenRequestHeaders(),a={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid},u=Ki(),l=await this.executePostToTokenEndpoint(c,r,t,a,e.correlationId),p=new Mu(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return p.validateTokenResponse(l.body),await p.handleServerTokenResponse(l.body,this.authority,u,e,void 0,s)}async createTokenRequestBody(e){let i=new Map;Sy(i,this.config.authOptions.clientId),Ty(i,e.scopes),YE(i,KE.JWT_BEARER),WE(i),v_(i,this.config.libraryInfo),__(i,this.config.telemetry.application),ZE(i),this.serverTelemetryManager&&JE(i,this.serverTelemetryManager);let s=e.correlationId||this.config.cryptoInterface.createNewGuid();g_(i,s),Hnr(i,Rnr),znr(i,e.oboAssertion),this.config.clientCredentials.clientSecret&&KI(i,this.config.clientCredentials.clientSecret);let o=this.config.clientCredentials.clientAssertion;return o&&(YI(i,await b_(o.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),WI(i,o.assertionType)),(e.claims||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(i,e.claims,this.config.authOptions.clientCapabilities),Qc(i)}},Rue=class extends FI{constructor(e){super(e);let i=!!this.config.auth.clientSecret,s=!!this.config.auth.clientAssertion,o=(!!this.config.auth.clientCertificate?.thumbprint||!!this.config.auth.clientCertificate?.thumbprintSha256)&&!!this.config.auth.clientCertificate?.privateKey;if(!this.appTokenProvider){if(i&&s||s&&o||i&&o)throw we(DE);if(this.config.auth.clientSecret){this.clientSecret=this.config.auth.clientSecret;return}if(this.config.auth.clientAssertion){this.developerProvidedClientAssertion=this.config.auth.clientAssertion;return}if(o)this.clientAssertion=this.config.auth.clientCertificate.thumbprintSha256?GE.fromCertificateWithSha256Thumbprint(this.config.auth.clientCertificate.thumbprintSha256,this.config.auth.clientCertificate.privateKey,this.config.auth.clientCertificate.x5c):GE.fromCertificate(this.config.auth.clientCertificate.thumbprint,this.config.auth.clientCertificate.privateKey,this.config.auth.clientCertificate.x5c);else throw we(DE);this.appTokenProvider=void 0}}SetAppTokenProvider(e){this.appTokenProvider=e}async acquireTokenByClientCredential(e){this.logger.info("acquireTokenByClientCredential called",e.correlationId);let i;e.clientAssertion&&(i={assertion:await b_(e.clientAssertion,this.config.auth.clientId),assertionType:xy.JWT_BEARER_ASSERTION_TYPE});let s=await this.initializeBaseRequest(e),o={...s,scopes:s.scopes.filter(d=>!Yh.includes(d))},c={...e,...o,clientAssertion:i},t=new ni(c.authority).getUrlComponents().PathSegments[0];if(Object.values(Wh).includes(t))throw we(PI);let a=process.env[Rir],u;c.azureRegion!=="DisableMsalForceRegion"&&(!c.azureRegion&&a?u=a:u=c.azureRegion);let l={azureRegion:u,environmentRegion:process.env[Pir]},p=this.initializeServerTelemetryManager(xE.acquireTokenByClientCredential,c.correlationId,c.skipCache);try{let d=await this.createAuthority(c.authority,c.correlationId,l,e.azureCloudOptions),h=await this.buildOauthClientConfiguration(d,c.correlationId,"",p),m=new zI(h,this.appTokenProvider);return this.logger.verbose("Client credential client created",c.correlationId),await m.acquireToken(c)}catch(d){throw d instanceof Bn&&d.setCorrelationId(c.correlationId),p.cacheFailedRequest(d),d}}async acquireTokenOnBehalfOf(e){this.logger.info("acquireTokenOnBehalfOf called",e.correlationId);let i={...e,...await this.initializeBaseRequest(e)};try{let s=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),o=await this.buildOauthClientConfiguration(s,i.correlationId,"",void 0),c=new bV(o);return this.logger.verbose("On behalf of client created",i.correlationId),await c.acquireToken(i)}catch(s){throw s instanceof Bn&&s.setCorrelationId(i.correlationId),s}}};function Hir(n){if(typeof n!="string")return!1;let e=new Date(n);return!isNaN(e.getTime())&&e.toISOString()===n}var Nue=class{constructor(e,i,s){this.httpClientNoRetries=e,this.retryPolicy=i,this.logger=s}async sendNetworkRequestAsyncHelper(e,i,s){return e===Ba.GET?this.httpClientNoRetries.sendGetRequestAsync(i,s):this.httpClientNoRetries.sendPostRequestAsync(i,s)}async sendNetworkRequestAsync(e,i,s){let o=await this.sendNetworkRequestAsyncHelper(e,i,s);"isNewRequest"in this.retryPolicy&&(this.retryPolicy.isNewRequest=!0);let c=0;for(;await this.retryPolicy.pauseForRetry(o.status,c,this.logger,o.headers[ga.RETRY_AFTER]);)o=await this.sendNetworkRequestAsyncHelper(e,i,s),c++;return o}async sendGetRequestAsync(e,i){return this.sendNetworkRequestAsync(Ba.GET,e,i)}async sendPostRequestAsync(e,i){return this.sendNetworkRequestAsync(Ba.POST,e,i)}},OE={MANAGED_IDENTITY_CLIENT_ID_2017:"clientid",MANAGED_IDENTITY_CLIENT_ID:"client_id",MANAGED_IDENTITY_OBJECT_ID:"object_id",MANAGED_IDENTITY_RESOURCE_ID_IMDS:"msi_res_id",MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS:"mi_res_id"},Qh=class{constructor(e,i,s,o,c){this.logger=e,this.nodeStorage=i,this.networkClient=s,this.cryptoProvider=o,this.disableInternalRetries=c}async getServerTokenResponseAsync(e,i,s,o){return this.getServerTokenResponse(e)}getServerTokenResponse(e){let i,s;return e.body.expires_on&&(Hir(e.body.expires_on)&&(e.body.expires_on=new Date(e.body.expires_on).getTime()/1e3),s=e.body.expires_on-Ki(),s>2*3600&&(i=s/2)),{status:e.status,access_token:e.body.access_token,expires_in:s,scope:e.body.resource,token_type:e.body.token_type,refresh_in:i,correlation_id:e.body.correlation_id||e.body.correlationId,error:typeof e.body.error=="string"?e.body.error:e.body.error?.code,error_description:e.body.message||(typeof e.body.error=="string"?e.body.error_description:e.body.error?.message),error_codes:e.body.error_codes,timestamp:e.body.timestamp,trace_id:e.body.trace_id}}async acquireTokenWithManagedIdentity(e,i,s,o){let c=this.createRequest(e.resource,i);if(e.revokedTokenSha256Hash&&(this.logger.info(`[Managed Identity] The following claims are present in the request: ${e.claims}`),c.queryParameters[eu.SHA256_TOKEN_TO_REFRESH]=e.revokedTokenSha256Hash),e.clientCapabilities?.length){let h=e.clientCapabilities.toString();this.logger.info(`[Managed Identity] The following client capabilities are present in the request: ${h}`),c.queryParameters[eu.XMS_CC]=h}let r=c.headers;r[ga.CONTENT_TYPE]=ue.URL_FORM_CONTENT_TYPE;let t={headers:r};Object.keys(c.bodyParameters).length&&(t.body=c.computeParametersBodyString());let a=this.disableInternalRetries?this.networkClient:new Nue(this.networkClient,c.retryPolicy,this.logger),u=Ki(),l;try{c.httpMethod===Ba.POST?l=await a.sendPostRequestAsync(c.computeUri(),t):l=await a.sendGetRequestAsync(c.computeUri(),t)}catch(h){throw h instanceof Bn?h:we(d_)}let p=new Mu(i.id,this.nodeStorage,this.cryptoProvider,this.logger,null,null),d=await this.getServerTokenResponseAsync(l,a,c,t);return p.validateTokenResponse(d,o),p.handleServerTokenResponse(d,s,u,e)}getManagedIdentityUserAssignedIdQueryParameterKey(e,i,s){switch(e){case xs.USER_ASSIGNED_CLIENT_ID:return this.logger.info(`[Managed Identity] [API version ${s?"2017+":"2019+"}] Adding user assigned client id to the request.`),s?OE.MANAGED_IDENTITY_CLIENT_ID_2017:OE.MANAGED_IDENTITY_CLIENT_ID;case xs.USER_ASSIGNED_RESOURCE_ID:return this.logger.info("[Managed Identity] Adding user assigned resource id to the request."),i?OE.MANAGED_IDENTITY_RESOURCE_ID_IMDS:OE.MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS;case xs.USER_ASSIGNED_OBJECT_ID:return this.logger.info("[Managed Identity] Adding user assigned object id to the request."),OE.MANAGED_IDENTITY_OBJECT_ID;default:throw ja(nI)}}};Qh.getValidatedEnvVariableUrlString=(n,e,i,s)=>{try{return new ni(e).urlString}catch{throw s.info(`[Managed Identity] ${i} managed identity is unavailable because the '${n}' environment variable is malformed.`),ja(Zw[n])}};var wue=class{calculateDelay(e,i){if(!e)return i;let s=Math.round(parseFloat(e)*1e3);return isNaN(s)&&(s=new Date(e).valueOf()-new Date().valueOf()),Math.max(i,s)}},Gir=3,Kir=1e3,Yir=[Os.HttpStatus.NOT_FOUND,Os.HttpStatus.REQUEST_TIMEOUT,Os.HttpStatus.TOO_MANY_REQUESTS,Os.HttpStatus.SERVER_ERROR,Os.HttpStatus.SERVICE_UNAVAILABLE,Os.HttpStatus.GATEWAY_TIMEOUT],Iue=class n{constructor(){this.linearRetryStrategy=new wue}static get DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS(){return Kir}async pauseForRetry(e,i,s,o){if(Yir.includes(e)&&i<Gir){let c=this.linearRetryStrategy.calculateDelay(o,n.DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS);return s.verbose(`Retrying request in ${c}ms (retry attempt: ${i+1})`),await new Promise(r=>setTimeout(r,c)),!0}return!1}},Ay=class{constructor(e,i,s){this.httpMethod=e,this._baseEndpoint=i,this.headers={},this.bodyParameters={},this.queryParameters={},this.retryPolicy=s||new Iue}computeUri(){let e=new Map;this.queryParameters&&Dd(e,this.queryParameters);let i=Qc(e);return ni.appendQueryString(this._baseEndpoint,i)}computeParametersBodyString(){let e=new Map;return this.bodyParameters&&Dd(e,this.bodyParameters),Qc(e)}},Wir="2019-08-01",TV=class n extends Qh{constructor(e,i,s,o,c,r,t){super(e,i,s,o,c),this.identityEndpoint=r,this.identityHeader=t}static getEnvironmentVariables(){let e=process.env[ir.IDENTITY_ENDPOINT],i=process.env[ir.IDENTITY_HEADER];return[e,i]}static tryCreate(e,i,s,o,c){let[r,t]=n.getEnvironmentVariables();if(!r||!t)return e.info(`[Managed Identity] ${_r.APP_SERVICE} managed identity is unavailable because one or both of the '${ir.IDENTITY_HEADER}' and '${ir.IDENTITY_ENDPOINT}' environment variables are not defined.`),null;let a=n.getValidatedEnvVariableUrlString(ir.IDENTITY_ENDPOINT,r,_r.APP_SERVICE,e);return e.info(`[Managed Identity] Environment variables validation passed for ${_r.APP_SERVICE} managed identity. Endpoint URI: ${a}. Creating ${_r.APP_SERVICE} managed identity.`),new n(e,i,s,o,c,r,t)}createRequest(e,i){let s=new Ay(Ba.GET,this.identityEndpoint);return s.headers[Oy.APP_SERVICE_SECRET_HEADER_NAME]=this.identityHeader,s.queryParameters[eu.API_VERSION]=Wir,s.queryParameters[eu.RESOURCE]=e,i.idType!==xs.SYSTEM_ASSIGNED&&(s.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(i.idType)]=i.id),s}},Jir="2019-11-01",B4e="http://127.0.0.1:40342/metadata/identity/oauth2/token",V4e="N/A: himds executable exists",$4e={win32:`${process.env.ProgramData}\\AzureConnectedMachineAgent\\Tokens\\`,linux:"/var/opt/azcmagent/tokens/"},Zir={win32:`${process.env.ProgramFiles}\\AzureConnectedMachineAgent\\himds.exe`,linux:"/opt/azcmagent/bin/himds"},SV=class n extends Qh{constructor(e,i,s,o,c,r){super(e,i,s,o,c),this.identityEndpoint=r}static getEnvironmentVariables(){let e=process.env[ir.IDENTITY_ENDPOINT],i=process.env[ir.IMDS_ENDPOINT];if(!e||!i){let s=Zir[process.platform];try{Ww.accessSync(s,Ww.constants.F_OK|Ww.constants.R_OK),e=B4e,i=V4e}catch{}}return[e,i]}static tryCreate(e,i,s,o,c,r){let[t,a]=n.getEnvironmentVariables();if(!t||!a)return e.info(`[Managed Identity] ${_r.AZURE_ARC} managed identity is unavailable through environment variables because one or both of '${ir.IDENTITY_ENDPOINT}' and '${ir.IMDS_ENDPOINT}' are not defined. ${_r.AZURE_ARC} managed identity is also unavailable through file detection.`),null;if(a===V4e)e.info(`[Managed Identity] ${_r.AZURE_ARC} managed identity is available through file detection. Defaulting to known ${_r.AZURE_ARC} endpoint: ${B4e}. Creating ${_r.AZURE_ARC} managed identity.`);else{let u=n.getValidatedEnvVariableUrlString(ir.IDENTITY_ENDPOINT,t,_r.AZURE_ARC,e);u.endsWith("/")&&u.slice(0,-1),n.getValidatedEnvVariableUrlString(ir.IMDS_ENDPOINT,a,_r.AZURE_ARC,e),e.info(`[Managed Identity] Environment variables validation passed for ${_r.AZURE_ARC} managed identity. Endpoint URI: ${u}. Creating ${_r.AZURE_ARC} managed identity.`)}if(r.idType!==xs.SYSTEM_ASSIGNED)throw ja(Tze);return new n(e,i,s,o,c,t)}createRequest(e){let i=new Ay(Ba.GET,this.identityEndpoint.replace("localhost","127.0.0.1"));return i.headers[Oy.METADATA_HEADER_NAME]="true",i.queryParameters[eu.API_VERSION]=Jir,i.queryParameters[eu.RESOURCE]=e,i}async getServerTokenResponseAsync(e,i,s,o){let c;if(e.status===Eo.UNAUTHORIZED){let r=e.headers["www-authenticate"];if(!r)throw ja(Oze);if(!r.includes("Basic realm="))throw ja(xze);let t=r.split("Basic realm=")[1];if(!$4e.hasOwnProperty(process.platform))throw ja(bze);let a=$4e[process.platform],u=Orr.basename(t);if(!u.endsWith(".key"))throw ja(gze);if(a+u!==t)throw ja(vze);let l;try{l=await Ww.statSync(t).size}catch{throw ja(Sue)}if(l>Iir)throw ja(_ze);let p;try{p=Ww.readFileSync(t,Zh.UTF8)}catch{throw ja(Sue)}let d=`Basic ${p}`;this.logger.info("[Managed Identity] Adding authorization header to the request."),s.headers[Oy.AUTHORIZATION_HEADER_NAME]=d;try{c=await i.sendGetRequestAsync(s.computeUri(),o)}catch(h){throw h instanceof Bn?h:we(d_)}}return this.getServerTokenResponse(c||e)}},EV=class n extends Qh{constructor(e,i,s,o,c,r){super(e,i,s,o,c),this.msiEndpoint=r}static getEnvironmentVariables(){return[process.env[ir.MSI_ENDPOINT]]}static tryCreate(e,i,s,o,c,r){let[t]=n.getEnvironmentVariables();if(!t)return e.info(`[Managed Identity] ${_r.CLOUD_SHELL} managed identity is unavailable because the '${ir.MSI_ENDPOINT} environment variable is not defined.`),null;let a=n.getValidatedEnvVariableUrlString(ir.MSI_ENDPOINT,t,_r.CLOUD_SHELL,e);if(e.info(`[Managed Identity] Environment variable validation passed for ${_r.CLOUD_SHELL} managed identity. Endpoint URI: ${a}. Creating ${_r.CLOUD_SHELL} managed identity.`),r.idType!==xs.SYSTEM_ASSIGNED)throw ja(Sze);return new n(e,i,s,o,c,t)}createRequest(e){let i=new Ay(Ba.POST,this.msiEndpoint);return i.headers[Oy.METADATA_HEADER_NAME]="true",i.bodyParameters[eu.RESOURCE]=e,i}},Cue=class{constructor(e,i,s){this.minExponentialBackoff=e,this.maxExponentialBackoff=i,this.exponentialDeltaBackoff=s}calculateDelay(e){return e===0?this.minExponentialBackoff:Math.min(Math.pow(2,e-1)*this.exponentialDeltaBackoff,this.maxExponentialBackoff)}},Xir=[Os.HttpStatus.NOT_FOUND,Os.HttpStatus.REQUEST_TIMEOUT,Os.HttpStatus.GONE,Os.HttpStatus.TOO_MANY_REQUESTS],Qir=3,eor=7,tor=1e3,ror=4e3,nor=2e3,ior=10*1e3,Mue=class n{constructor(){this.exponentialRetryStrategy=new Cue(n.MIN_EXPONENTIAL_BACKOFF_MS,n.MAX_EXPONENTIAL_BACKOFF_MS,n.EXPONENTIAL_DELTA_BACKOFF_MS)}static get MIN_EXPONENTIAL_BACKOFF_MS(){return tor}static get MAX_EXPONENTIAL_BACKOFF_MS(){return ror}static get EXPONENTIAL_DELTA_BACKOFF_MS(){return nor}static get HTTP_STATUS_GONE_RETRY_AFTER_MS(){return ior}set isNewRequest(e){this._isNewRequest=e}async pauseForRetry(e,i,s){if(this._isNewRequest&&(this._isNewRequest=!1,this.maxRetries=e===Os.HttpStatus.GONE?eor:Qir),(Xir.includes(e)||e>=Os.HttpStatus.SERVER_ERROR_RANGE_START&&e<=Os.HttpStatus.SERVER_ERROR_RANGE_END&&i<this.maxRetries)&&i<this.maxRetries){let o=e===Os.HttpStatus.GONE?n.HTTP_STATUS_GONE_RETRY_AFTER_MS:this.exponentialRetryStrategy.calculateDelay(i);return s.verbose(`Retrying request in ${o}ms (retry attempt: ${i+1})`),await new Promise(c=>setTimeout(c,o)),!0}return!1}},Aze="/metadata/identity/oauth2/token",oor=`http://169.254.169.254${Aze}`,aor="2018-02-01",Lue=class n extends Qh{constructor(e,i,s,o,c,r){super(e,i,s,o,c),this.identityEndpoint=r}static tryCreate(e,i,s,o,c){let r;return process.env[ir.AZURE_POD_IDENTITY_AUTHORITY_HOST]?(e.info(`[Managed Identity] Environment variable ${ir.AZURE_POD_IDENTITY_AUTHORITY_HOST} for ${_r.IMDS} returned endpoint: ${process.env[ir.AZURE_POD_IDENTITY_AUTHORITY_HOST]}`),r=n.getValidatedEnvVariableUrlString(ir.AZURE_POD_IDENTITY_AUTHORITY_HOST,`${process.env[ir.AZURE_POD_IDENTITY_AUTHORITY_HOST]}${Aze}`,_r.IMDS,e)):(e.info(`[Managed Identity] Unable to find ${ir.AZURE_POD_IDENTITY_AUTHORITY_HOST} environment variable for ${_r.IMDS}, using the default endpoint.`),r=oor),new n(e,i,s,o,c,r)}createRequest(e,i){let s=new Ay(Ba.GET,this.identityEndpoint);return s.headers[Oy.METADATA_HEADER_NAME]="true",s.queryParameters[eu.API_VERSION]=aor,s.queryParameters[eu.RESOURCE]=e,i.idType!==xs.SYSTEM_ASSIGNED&&(s.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(i.idType,!0)]=i.id),s.retryPolicy=new Mue,s}},sor="2019-07-01-preview",OV=class n extends Qh{constructor(e,i,s,o,c,r,t){super(e,i,s,o,c),this.identityEndpoint=r,this.identityHeader=t}static getEnvironmentVariables(){let e=process.env[ir.IDENTITY_ENDPOINT],i=process.env[ir.IDENTITY_HEADER],s=process.env[ir.IDENTITY_SERVER_THUMBPRINT];return[e,i,s]}static tryCreate(e,i,s,o,c,r){let[t,a,u]=n.getEnvironmentVariables();if(!t||!a||!u)return e.info(`[Managed Identity] ${_r.SERVICE_FABRIC} managed identity is unavailable because one or all of the '${ir.IDENTITY_HEADER}', '${ir.IDENTITY_ENDPOINT}' or '${ir.IDENTITY_SERVER_THUMBPRINT}' environment variables are not defined.`),null;let l=n.getValidatedEnvVariableUrlString(ir.IDENTITY_ENDPOINT,t,_r.SERVICE_FABRIC,e);return e.info(`[Managed Identity] Environment variables validation passed for ${_r.SERVICE_FABRIC} managed identity. Endpoint URI: ${l}. Creating ${_r.SERVICE_FABRIC} managed identity.`),r.idType!==xs.SYSTEM_ASSIGNED&&e.warning(`[Managed Identity] ${_r.SERVICE_FABRIC} user assigned managed identity is configured in the cluster, not during runtime. See also: https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service.`),new n(e,i,s,o,c,t,a)}createRequest(e,i){let s=new Ay(Ba.GET,this.identityEndpoint);return s.headers[Oy.ML_AND_SF_SECRET_HEADER_NAME]=this.identityHeader,s.queryParameters[eu.API_VERSION]=sor,s.queryParameters[eu.RESOURCE]=e,i.idType!==xs.SYSTEM_ASSIGNED&&(s.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(i.idType)]=i.id),s}},cor="2017-09-01",uor=`Only client id is supported for user-assigned managed identity in ${_r.MACHINE_LEARNING}.`,xV=class n extends Qh{constructor(e,i,s,o,c,r,t){super(e,i,s,o,c),this.msiEndpoint=r,this.secret=t}static getEnvironmentVariables(){let e=process.env[ir.MSI_ENDPOINT],i=process.env[ir.MSI_SECRET];return[e,i]}static tryCreate(e,i,s,o,c){let[r,t]=n.getEnvironmentVariables();if(!r||!t)return e.info(`[Managed Identity] ${_r.MACHINE_LEARNING} managed identity is unavailable because one or both of the '${ir.MSI_ENDPOINT}' and '${ir.MSI_SECRET}' environment variables are not defined.`),null;let a=n.getValidatedEnvVariableUrlString(ir.MSI_ENDPOINT,r,_r.MACHINE_LEARNING,e);return e.info(`[Managed Identity] Environment variables validation passed for ${_r.MACHINE_LEARNING} managed identity. Endpoint URI: ${a}. Creating ${_r.MACHINE_LEARNING} managed identity.`),new n(e,i,s,o,c,r,t)}createRequest(e,i){let s=new Ay(Ba.GET,this.msiEndpoint);if(s.headers[Oy.METADATA_HEADER_NAME]="true",s.headers[Oy.ML_AND_SF_SECRET_HEADER_NAME]=this.secret,s.queryParameters[eu.API_VERSION]=cor,s.queryParameters[eu.RESOURCE]=e,i.idType===xs.SYSTEM_ASSIGNED)s.queryParameters[OE.MANAGED_IDENTITY_CLIENT_ID_2017]=process.env[ir.DEFAULT_IDENTITY_CLIENT_ID];else if(i.idType===xs.USER_ASSIGNED_CLIENT_ID)s.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(i.idType,!1,!0)]=i.id;else throw new Error(uor);return s}},AV=class n{constructor(e,i,s,o,c){this.logger=e,this.nodeStorage=i,this.networkClient=s,this.cryptoProvider=o,this.disableInternalRetries=c}async sendManagedIdentityTokenRequest(e,i,s,o){return n.identitySource||(n.identitySource=this.selectManagedIdentitySource(this.logger,this.nodeStorage,this.networkClient,this.cryptoProvider,this.disableInternalRetries,i)),n.identitySource.acquireTokenWithManagedIdentity(e,i,s,o)}allEnvironmentVariablesAreDefined(e){return Object.values(e).every(i=>i!==void 0)}getManagedIdentitySource(){return n.sourceName=this.allEnvironmentVariablesAreDefined(OV.getEnvironmentVariables())?_r.SERVICE_FABRIC:this.allEnvironmentVariablesAreDefined(TV.getEnvironmentVariables())?_r.APP_SERVICE:this.allEnvironmentVariablesAreDefined(xV.getEnvironmentVariables())?_r.MACHINE_LEARNING:this.allEnvironmentVariablesAreDefined(EV.getEnvironmentVariables())?_r.CLOUD_SHELL:this.allEnvironmentVariablesAreDefined(SV.getEnvironmentVariables())?_r.AZURE_ARC:_r.DEFAULT_TO_IMDS,n.sourceName}selectManagedIdentitySource(e,i,s,o,c,r){let t=OV.tryCreate(e,i,s,o,c,r)||TV.tryCreate(e,i,s,o,c)||xV.tryCreate(e,i,s,o,c)||EV.tryCreate(e,i,s,o,c,r)||SV.tryCreate(e,i,s,o,c,r)||Lue.tryCreate(e,i,s,o,c);if(!t)throw ja(Eze);return t}},lor=[_r.SERVICE_FABRIC],kue=class n{constructor(e){this.config=Vir(e||{}),this.logger=new _y(this.config.system.loggerOptions,Yue,y_);let i={canonicalAuthority:ue.DEFAULT_AUTHORITY};n.nodeStorage||(n.nodeStorage=new $I(this.logger,this.config.managedIdentityId.id,fue,i)),this.networkClient=this.config.system.networkClient,this.cryptoProvider=new HE;let s={protocolMode:by.AAD,knownAuthorities:[j4e],cloudDiscoveryMetadata:"",authorityMetadata:""};this.fakeAuthority=new f_(j4e,this.networkClient,n.nodeStorage,s,this.logger,this.cryptoProvider.createNewGuid(),void 0,!0),this.fakeClientCredentialClient=new zI({authOptions:{clientId:this.config.managedIdentityId.id,authority:this.fakeAuthority}}),this.managedIdentityClient=new AV(this.logger,n.nodeStorage,this.networkClient,this.cryptoProvider,this.config.disableInternalRetries),this.hashUtils=new VI}async acquireToken(e){if(!e.resource)throw oo(UE);let i={forceRefresh:e.forceRefresh,resource:e.resource.replace("/.default",""),scopes:[e.resource.replace("/.default","")],authority:this.fakeAuthority.canonicalAuthority,correlationId:this.cryptoProvider.createNewGuid(),claims:e.claims,clientCapabilities:this.config.clientCapabilities};if(i.forceRefresh)return this.acquireTokenFromManagedIdentity(i,this.config.managedIdentityId,this.fakeAuthority);let[s,o]=await this.fakeClientCredentialClient.getCachedAuthenticationResult(i,this.config,this.cryptoProvider,this.fakeAuthority,n.nodeStorage);if(i.claims){let c=this.managedIdentityClient.getManagedIdentitySource();if(s&&lor.includes(c)){let r=this.hashUtils.sha256(s.accessToken).toString(Zh.HEX);i.revokedTokenSha256Hash=r}return this.acquireTokenFromManagedIdentity(i,this.config.managedIdentityId,this.fakeAuthority)}return s?(o===So.PROACTIVELY_REFRESHED&&(this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."),await this.acquireTokenFromManagedIdentity(i,this.config.managedIdentityId,this.fakeAuthority,!0)),s):this.acquireTokenFromManagedIdentity(i,this.config.managedIdentityId,this.fakeAuthority)}async acquireTokenFromManagedIdentity(e,i,s,o){return this.managedIdentityClient.sendManagedIdentityTokenRequest(e,i,s,o)}getManagedIdentitySource(){return AV.sourceName||this.managedIdentityClient.getManagedIdentitySource()}},Due=class{constructor(e,i){this.client=e,this.partitionManager=i}async beforeCacheAccess(e){let i=await this.partitionManager.getKey(),s=await this.client.get(i);e.tokenCache.deserialize(s)}async afterCacheAccess(e){if(e.cacheHasChanged){let i=e.tokenCache.getKVStore(),s=Object.values(i).filter(c=>Xc.isAccountEntity(c)),o;if(s.length>0){let c=s[0];o=await this.partitionManager.extractKey(c)}else o=await this.partitionManager.getKey();await this.client.set(o,e.tokenCache.serialize())}}};bt.AuthError=Bn;bt.AuthErrorCodes=Prr;bt.AuthErrorMessage=Rrr;bt.AzureCloudInstance=RV;bt.ClientApplication=FI;bt.ClientAssertion=GE;bt.ClientAuthError=RI;bt.ClientAuthErrorCodes=wrr;bt.ClientAuthErrorMessage=Irr;bt.ClientConfigurationError=cV;bt.ClientConfigurationErrorCodes=Crr;bt.ClientConfigurationErrorMessage=Mrr;bt.ClientCredentialClient=zI;bt.ConfidentialClientApplication=Rue;bt.CryptoProvider=HE;bt.DeviceCodeClient=_V;bt.DistributedCachePlugin=Due;bt.InteractionRequiredAuthError=m_;bt.InteractionRequiredAuthErrorCodes=pir;bt.InteractionRequiredAuthErrorMessage=fir;bt.Logger=_y;bt.ManagedIdentityApplication=kue;bt.ManagedIdentitySourceNames=_r;bt.OnBehalfOfClient=bV;bt.PromptValue=UB;bt.ProtocolMode=by;bt.PublicClientApplication=Pue;bt.ResponseMode=PV;bt.ServerError=h_;bt.TokenCache=gV;bt.TokenCacheContext=vy;bt.UsernamePasswordClient=vV;bt.internals=Oir;bt.version=y_});var Jue=f(T_=>{"use strict";Object.defineProperty(T_,"__esModule",{value:!0});T_.TELEMETRY_EVENTS=void 0;T_.createTelemetryTimestamp=Rze;T_.createCommonProperties=por;T_.cleanTelemetryProperties=dor;T_.TELEMETRY_EVENTS={EXTENSION:{COMMAND_COMPLETED:"TB-EXT-002",COMMAND_FAILED:"TB-EXT-003",MCP_REQUEST_SENT:"TB-EXT-004",MCP_RESPONSE_RECEIVED:"TB-EXT-005",PROFILE_SWITCHED:"TB-EXT-006",CACHE_CLEARED:"TB-EXT-007",SETUP_WIZARD_OPENED:"TB-EXT-008",SETUP_WIZARD_COMPLETED:"TB-EXT-009",ERROR:"TB-EXT-010",ACTIVATED:"TB-EXT-011",TELEMETRY_ID_RESET:"TB-EXT-012",KB_PANEL_OPENED:"TB-EXT-013",KB_ARTICLE_OPENED:"TB-EXT-014",KB_ARTICLE_EXCLUDED:"TB-EXT-015",KB_COMMUNITY_TOGGLED:"TB-EXT-016",KB_REFRESH_COMPLETED:"TB-EXT-017",KB_REFRESH_FAILED:"TB-EXT-018",SETUP_POINTER_SHOWN:"TB-EXT-019"},MCP:{SERVER_STARTED:"TB-MCP-001",CONFIGURATION_LOADED:"TB-MCP-002",ERROR:"TB-MCP-005"},MCP_TOOLS:{QUERY_TELEMETRY:"TB-MCP-101",GET_SAVED_QUERIES:"TB-MCP-102",SEARCH_QUERIES:"TB-MCP-103",SAVE_QUERY:"TB-MCP-104",GENERATE_KQL:"TB-MCP-105",GET_RECOMMENDATIONS:"TB-MCP-106",LOOKUP_EVENT:"TB-MCP-107",GET_EVENT_CATALOG:"TB-MCP-108",GET_EVENT_SCHEMA:"TB-MCP-109",GET_EVENT_FIELD_SAMPLES:"TB-MCP-110",GET_KNOWLEDGE:"TB-MCP-111",SAVE_KNOWLEDGE:"TB-MCP-112",DEPRECATED_TOOL_CALLED:"TB-MCP-113",KB_HINT_EMITTED:"TB-MCP-114",SETUP_PROMPT_SERVED:"TB-MCP-115",GET_SETUP_GUIDE:"TB-MCP-116"},KUSTO:{QUERY_EXECUTED:"TB-KQL-001",QUERY_FAILED:"TB-KQL-002",QUERY_CACHED:"TB-KQL-003",CACHE_MISS:"TB-KQL-004"},AUTH:{AUTHENTICATION_ATTEMPT:"TB-AUTH-001",AUTHENTICATION_COMPLETED:"TB-AUTH-002",TOKEN_REFRESHED:"TB-AUTH-003",FAILED:"TB-AUTH-004"},CACHE:{HIT:"TB-CACHE-001",MISS:"TB-CACHE-002",SET:"TB-CACHE-003",CLEARED:"TB-CACHE-004",EXPIRED:"TB-CACHE-005"}};function Rze(){return new Date().toISOString()}function por(n,e,i,s,o,c){let r={eventId:n,timestamp:Rze(),component:e,sessionId:i,installationId:s,version:o};return c?.correlationId&&(r.correlationId=c.correlationId),c?.profileHash&&(r.profileHash=c.profileHash),c&&Object.keys(c).forEach(t=>{t!=="correlationId"&&t!=="profileHash"&&c[t]!==void 0&&(r[t]=c[t])}),r}function dor(n){let e={};return Object.keys(n).forEach(i=>{let s=n[i];s!==void 0&&(e[i]=s)}),e}});var wze=f(wV=>{"use strict";Object.defineProperty(wV,"__esModule",{value:!0});wV.AuthService=void 0;var Nze=Pze(),Ep=Jue(),hor=require("child_process"),mor=require("util"),yor=(0,mor.promisify)(hor.exec),Zue=class{config;usageTelemetry;authResult=null;constructor(e,i){this.config=e,this.usageTelemetry=i}getStatus(){return!this.authResult||!this.authResult.authenticated?{authenticated:!1}:this.authResult.expiresOn&&this.authResult.expiresOn<new Date?{authenticated:!1}:this.authResult}async authenticate(){return this.usageTelemetry?.trackEvent(Ep.TELEMETRY_EVENTS.AUTH.AUTHENTICATION_ATTEMPT,{authFlow:this.config.authFlow||"client_credentials"}),this.config.authFlow==="azure_cli"?this.authenticateAzureCLI():this.config.authFlow==="device_code"?this.authenticateDeviceCode():this.config.authFlow==="vscode_auth"?this.authenticateVSCode():this.authenticateClientCredentials()}async authenticateAzureCLI(){try{console.error("[MCP] Using Azure CLI authentication (az account get-access-token)...");let{stdout:e,stderr:i}=await yor("az account get-access-token --resource https://api.applicationinsights.io",{env:{...process.env,PYTHONWARNINGS:"ignore"}});i&&console.error("Azure CLI stderr:",i);let s=JSON.parse(e);if(!s.accessToken)throw new Error("No access token returned from Azure CLI");return this.authResult={authenticated:!0,accessToken:s.accessToken,user:s.subscription||"Azure CLI User",expiresOn:s.expiresOn?new Date(s.expiresOn):void 0},console.error("[MCP] \u2713 Authenticated via Azure CLI"),console.error(`[MCP] Subscription: ${s.subscription||"N/A"}`),console.error(`[MCP] Tenant: ${s.tenant||"N/A"}`),this.usageTelemetry?.trackEvent(Ep.TELEMETRY_EVENTS.AUTH.AUTHENTICATION_COMPLETED,{authFlow:"azure_cli"}),this.authResult}catch(e){throw console.error("Azure CLI authentication failed:",e.message),e.message.includes("az: command not found")||e.message.includes("not recognized")?(console.error(`
59
+ Headers: ${JSON.stringify(r)}`}}return a},this.logUrlWithPiiAwareness=(o,c)=>{if(this.isPiiEnabled)this.logger.errorPii(`HttpClient - ${o}: ${c}`,"");else{let r;try{let t=new URL(c);r=`${t.protocol}//${t.host}${t.pathname}`}catch{r=c.split("?")[0]||"unknown"}this.logger.error(`HttpClient - ${o}: ${r} [Enable PII logging to see additional details]`,"")}},this.shouldDestroyRequest=(o,c)=>(o<Eo.SUCCESS_RANGE_START||o>Eo.SUCCESS_RANGE_END)&&!(c.body&&typeof c.body=="object"&&"error"in c.body&&c.body.error===xy.AUTHORIZATION_PENDING),this.proxyUrl=e||"",this.customAgentOptions=i||{},this.logger=new _y(s||{},Yue,y_),this.isPiiEnabled=this.logger.isPiiLoggingEnabled()}async sendGetRequestAsync(e,i,s){return this.proxyUrl?this.networkRequestViaProxy(Ba.GET,e,i,s):this.networkRequestViaHttps(Ba.GET,e,i,s)}async sendPostRequestAsync(e,i){return this.proxyUrl?this.networkRequestViaProxy(Ba.POST,e,i):this.networkRequestViaHttps(Ba.POST,e,i)}},gze="invalid_file_extension",vze="invalid_file_path",nI="invalid_managed_identity_id_type",_ze="invalid_secret",Cir="missing_client_id",Mir="network_unavailable",bze="platform_not_supported",Tze="unable_to_create_azure_arc",Sze="unable_to_create_cloud_shell",Eze="unable_to_create_source",Sue="unable_to_read_secret_file",Lir="user_assigned_not_available_at_runtime",Oze="www_authenticate_header_missing",xze="www_authenticate_header_unsupported_format",Zw={[ir.AZURE_POD_IDENTITY_AUTHORITY_HOST]:"azure_pod_identity_authority_host_url_malformed",[ir.IDENTITY_ENDPOINT]:"identity_endpoint_url_malformed",[ir.IMDS_ENDPOINT]:"imds_endpoint_url_malformed",[ir.MSI_ENDPOINT]:"msi_endpoint_url_malformed"},kir={[gze]:"The file path in the WWW-Authenticate header does not contain a .key file.",[vze]:"The file path in the WWW-Authenticate header is not in a valid Windows or Linux Format.",[nI]:"More than one ManagedIdentityIdType was provided.",[_ze]:"The secret in the file on the file path in the WWW-Authenticate header is greater than 4096 bytes.",[bze]:"The platform is not supported by Azure Arc. Azure Arc only supports Windows and Linux.",[Cir]:"A ManagedIdentityId id was not provided.",[Zw.AZURE_POD_IDENTITY_AUTHORITY_HOST]:`The Managed Identity's '${ir.AZURE_POD_IDENTITY_AUTHORITY_HOST}' environment variable is malformed.`,[Zw.IDENTITY_ENDPOINT]:`The Managed Identity's '${ir.IDENTITY_ENDPOINT}' environment variable is malformed.`,[Zw.IMDS_ENDPOINT]:`The Managed Identity's '${ir.IMDS_ENDPOINT}' environment variable is malformed.`,[Zw.MSI_ENDPOINT]:`The Managed Identity's '${ir.MSI_ENDPOINT}' environment variable is malformed.`,[Mir]:"Authentication unavailable. The request to the managed identity endpoint timed out.",[Tze]:"Azure Arc Managed Identities can only be system assigned.",[Sze]:"Cloud Shell Managed Identities can only be system assigned.",[Eze]:"Unable to create a Managed Identity source based on environment variables.",[Sue]:"Unable to read the secret file.",[Lir]:"Service Fabric user assigned managed identity ClientId or ResourceId is not configurable at runtime.",[Oze]:"A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is missing.",[xze]:"A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is in an unsupported format."},Eue=class n extends Bn{constructor(e){super(e,kir[e]),this.name="ManagedIdentityError",Object.setPrototypeOf(this,n.prototype)}};function ja(n){return new Eue(n)}var Oue=class{get id(){return this._id}set id(e){this._id=e}get idType(){return this._idType}set idType(e){this._idType=e}constructor(e){let i=e?.userAssignedClientId,s=e?.userAssignedResourceId,o=e?.userAssignedObjectId;if(i){if(s||o)throw ja(nI);this.id=i,this.idType=xs.USER_ASSIGNED_CLIENT_ID}else if(s){if(i||o)throw ja(nI);this.id=s,this.idType=xs.USER_ASSIGNED_RESOURCE_ID}else if(o){if(i||s)throw ja(nI);this.id=o,this.idType=xs.USER_ASSIGNED_OBJECT_ID}else this.id=xir,this.idType=xs.SYSTEM_ASSIGNED}},To={invalidLoopbackAddressType:{code:"invalid_loopback_server_address_type",desc:"Loopback server address is not type string. This is unexpected."},unableToLoadRedirectUri:{code:"unable_to_load_redirectUrl",desc:"Loopback server callback was invoked without a url. This is unexpected."},noAuthCodeInResponse:{code:"no_auth_code_in_response",desc:"No auth code found in the server response. Please check your network trace to determine what happened."},noLoopbackServerExists:{code:"no_loopback_server_exists",desc:"No loopback server exists yet."},loopbackServerAlreadyExists:{code:"loopback_server_already_exists",desc:"Loopback server already exists. Cannot create another."},loopbackServerTimeout:{code:"loopback_server_timeout",desc:"Timed out waiting for auth code listener to be registered."},stateNotFoundError:{code:"state_not_found",desc:"State not found. Please verify that the request originated from msal."},thumbprintMissing:{code:"thumbprint_missing_from_client_certificate",desc:"Client certificate does not contain a SHA-1 or SHA-256 thumbprint."},redirectUriNotSupported:{code:"redirect_uri_not_supported",desc:"RedirectUri is not supported in this scenario. Please remove redirectUri from the request."}},Cu=class n extends Bn{constructor(e,i){super(e,i),this.name="NodeAuthError"}static createInvalidLoopbackAddressTypeError(){return new n(To.invalidLoopbackAddressType.code,`${To.invalidLoopbackAddressType.desc}`)}static createUnableToLoadRedirectUrlError(){return new n(To.unableToLoadRedirectUri.code,`${To.unableToLoadRedirectUri.desc}`)}static createNoAuthCodeInResponseError(){return new n(To.noAuthCodeInResponse.code,`${To.noAuthCodeInResponse.desc}`)}static createNoLoopbackServerExistsError(){return new n(To.noLoopbackServerExists.code,`${To.noLoopbackServerExists.desc}`)}static createLoopbackServerAlreadyExistsError(){return new n(To.loopbackServerAlreadyExists.code,`${To.loopbackServerAlreadyExists.desc}`)}static createLoopbackServerTimeoutError(){return new n(To.loopbackServerTimeout.code,`${To.loopbackServerTimeout.desc}`)}static createStateNotFoundError(){return new n(To.stateNotFoundError.code,To.stateNotFoundError.desc)}static createThumbprintMissingError(){return new n(To.thumbprintMissing.code,To.thumbprintMissing.desc)}static createRedirectUriNotSupportedError(){return new n(To.redirectUriNotSupported.code,To.redirectUriNotSupported.desc)}},Dir={clientId:ue.EMPTY_STRING,authority:ue.DEFAULT_AUTHORITY,clientSecret:ue.EMPTY_STRING,clientAssertion:ue.EMPTY_STRING,clientCertificate:{thumbprint:ue.EMPTY_STRING,thumbprintSha256:ue.EMPTY_STRING,privateKey:ue.EMPTY_STRING,x5c:ue.EMPTY_STRING},knownAuthorities:[],cloudDiscoveryMetadata:ue.EMPTY_STRING,authorityMetadata:ue.EMPTY_STRING,clientCapabilities:[],protocolMode:by.AAD,azureCloudOptions:{azureCloudInstance:RV.None,tenant:ue.EMPTY_STRING},skipAuthorityMetadataCache:!1,encodeExtraQueryParams:!1},Uir={claimsBasedCachingEnabled:!1},Wue={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:bt.LogLevel.Info},qir={loggerOptions:Wue,networkClient:new BI,proxyUrl:ue.EMPTY_STRING,customAgentOptions:{},disableInternalRetries:!1},jir={application:{appName:ue.EMPTY_STRING,appVersion:ue.EMPTY_STRING}};function Bir({auth:n,broker:e,cache:i,system:s,telemetry:o}){let c={...qir,networkClient:new BI(s?.proxyUrl,s?.customAgentOptions),loggerOptions:s?.loggerOptions||Wue,disableInternalRetries:s?.disableInternalRetries||!1};if(n.clientCertificate&&!n.clientCertificate.thumbprint&&!n.clientCertificate.thumbprintSha256)throw Cu.createStateNotFoundError();return{auth:{...Dir,...n},broker:{...e},cache:{...Uir,...i},system:{...c,...s},telemetry:{...jir,...o}}}function Vir({clientCapabilities:n,managedIdentityIdParams:e,system:i}){let s=new Oue(e),o=i?.loggerOptions||Wue,c;return i?.networkClient?c=i.networkClient:c=new BI(i?.proxyUrl,i?.customAgentOptions),{clientCapabilities:n||[],managedIdentityId:s,system:{loggerOptions:o,networkClient:c},disableInternalRetries:i?.disableInternalRetries||!1}}var yV=class{generateGuid(){return Srr.v4()}isGuid(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}},Jh=class n{static base64Encode(e,i){return Buffer.from(e,i).toString(Zh.BASE64)}static base64EncodeUrl(e,i){return n.base64Encode(e,i).replace(/=/g,ue.EMPTY_STRING).replace(/\+/g,"-").replace(/\//g,"_")}static base64Decode(e){return Buffer.from(e,Zh.BASE64).toString("utf8")}static base64DecodeUrl(e){let i=e.replace(/-/g,"+").replace(/_/g,"/");for(;i.length%4;)i+="=";return n.base64Decode(i)}},VI=class{sha256(e){return F4e.createHash(wir.SHA256).update(e).digest()}},xue=class{constructor(){this.hashUtils=new VI}async generatePkceCodes(){let e=this.generateCodeVerifier(),i=this.generateCodeChallengeFromVerifier(e);return{verifier:e,challenge:i}}generateCodeVerifier(){let e=[],i=256-256%pue.CV_CHARSET.length;for(;e.length<=Nir;){let o=F4e.randomBytes(1)[0];if(o>=i)continue;let c=o%pue.CV_CHARSET.length;e.push(pue.CV_CHARSET[c])}let s=e.join(ue.EMPTY_STRING);return Jh.base64EncodeUrl(s)}generateCodeChallengeFromVerifier(e){return Jh.base64EncodeUrl(this.hashUtils.sha256(e).toString(Zh.BASE64),Zh.BASE64)}},HE=class{constructor(){this.pkceGenerator=new xue,this.guidGenerator=new yV,this.hashUtils=new VI}base64UrlEncode(){throw new Error("Method not implemented.")}encodeKid(){throw new Error("Method not implemented.")}createNewGuid(){return this.guidGenerator.generateGuid()}base64Encode(e){return Jh.base64Encode(e)}base64Decode(e){return Jh.base64Decode(e)}generatePkceCodes(){return this.pkceGenerator.generatePkceCodes()}getPublicKeyThumbprint(){throw new Error("Method not implemented.")}removeTokenBindingKey(){throw new Error("Method not implemented.")}clearKeystore(){throw new Error("Method not implemented.")}signJwt(){throw new Error("Method not implemented.")}async hashString(e){return Jh.base64EncodeUrl(this.hashUtils.sha256(e).toString(Zh.BASE64),Zh.BASE64)}};function $ir(n){let e=n.credentialType===Gi.REFRESH_TOKEN&&n.familyId||n.clientId,i=n.tokenType&&n.tokenType.toLowerCase()!==ii.BEARER.toLowerCase()?n.tokenType.toLowerCase():"";return[n.homeAccountId,n.environment,n.credentialType,e,n.realm||"",n.target||"",n.requestedClaimsHash||"",i].join(yze.KEY_SEPARATOR).toLowerCase()}function Fir(n){let e=n.homeAccountId.split(".")[1];return[n.homeAccountId,n.environment,e||n.tenantId||""].join(yze.KEY_SEPARATOR).toLowerCase()}var $I=class extends UI{constructor(e,i,s,o){super(i,s,e,new Os.StubPerformanceClient,o),this.cache={},this.changeEmitters=[],this.logger=e}registerChangeEmitter(e){this.changeEmitters.push(e)}emitChange(){this.changeEmitters.forEach(e=>e.call(null))}cacheToInMemoryCache(e){let i={accounts:{},idTokens:{},accessTokens:{},refreshTokens:{},appMetadata:{}};for(let s in e){let o=e[s];if(typeof o=="object")if(o instanceof Xc)i.accounts[s]=o;else if(I4e(o))i.idTokens[s]=o;else if(w4e(o))i.accessTokens[s]=o;else if(C4e(o))i.refreshTokens[s]=o;else if(M4e(s,o))i.appMetadata[s]=o;else continue}return i}inMemoryCacheToCache(e){let i=this.getCache();return i={...i,...e.accounts,...e.idTokens,...e.accessTokens,...e.refreshTokens,...e.appMetadata},i}getInMemoryCache(){return this.logger.trace("Getting in-memory cache"),this.cacheToInMemoryCache(this.getCache())}setInMemoryCache(e){this.logger.trace("Setting in-memory cache");let i=this.inMemoryCacheToCache(e);this.setCache(i),this.emitChange()}getCache(){return this.logger.trace("Getting cache key-value store"),this.cache}setCache(e){this.logger.trace("Setting cache key value store"),this.cache=e,this.emitChange()}getItem(e){return this.logger.tracePii(`Item key: ${e}`),this.getCache()[e]}setItem(e,i){this.logger.tracePii(`Item key: ${e}`);let s=this.getCache();s[e]=i,this.setCache(s)}generateCredentialKey(e){return $ir(e)}generateAccountKey(e){return Fir(e)}getAccountKeys(){let e=this.getInMemoryCache();return Object.keys(e.accounts)}getTokenKeys(){let e=this.getInMemoryCache();return{idToken:Object.keys(e.idTokens),accessToken:Object.keys(e.accessTokens),refreshToken:Object.keys(e.refreshTokens)}}getAccount(e){return this.getItem(e)?Object.assign(new Xc,this.getItem(e)):null}async setAccount(e){let i=this.generateAccountKey(Xc.getAccountInfo(e));this.setItem(i,e)}getIdTokenCredential(e){let i=this.getItem(e);return I4e(i)?i:null}async setIdTokenCredential(e){let i=this.generateCredentialKey(e);this.setItem(i,e)}getAccessTokenCredential(e){let i=this.getItem(e);return w4e(i)?i:null}async setAccessTokenCredential(e){let i=this.generateCredentialKey(e);this.setItem(i,e)}getRefreshTokenCredential(e){let i=this.getItem(e);return C4e(i)?i:null}async setRefreshTokenCredential(e){let i=this.generateCredentialKey(e);this.setItem(i,e)}getAppMetadata(e){let i=this.getItem(e);return M4e(e,i)?i:null}setAppMetadata(e){let i=sir(e);this.setItem(i,e)}getServerTelemetry(e){let i=this.getItem(e);return i&&oir(e,i)?i:null}setServerTelemetry(e,i){this.setItem(e,i)}getAuthorityMetadata(e){let i=this.getItem(e);return i&&cir(e,i)?i:null}getAuthorityMetadataKeys(){return this.getKeys().filter(e=>this.isAuthorityMetadata(e))}setAuthorityMetadata(e,i){this.setItem(e,i)}getThrottlingCache(e){let i=this.getItem(e);return i&&air(e,i)?i:null}setThrottlingCache(e,i){this.setItem(e,i)}removeItem(e){this.logger.tracePii(`Item key: ${e}`);let i=!1,s=this.getCache();return s[e]&&(delete s[e],i=!0),i&&(this.setCache(s),this.emitChange()),i}removeOutdatedAccount(e){this.removeItem(e)}containsKey(e){return this.getKeys().includes(e)}getKeys(){this.logger.trace("Retrieving all cache keys");let e=this.getCache();return[...Object.keys(e)]}clear(){this.logger.trace("Clearing cache entries created by MSAL"),this.getKeys().forEach(i=>{this.removeItem(i)}),this.emitChange()}static generateInMemoryCache(e){return zE.deserializeAllCache(zE.deserializeJSONBlob(e))}static generateJsonCache(e){return iI.serializeAllCache(e)}updateCredentialCacheKey(e,i){let s=this.generateCredentialKey(i);if(e!==s){let o=this.getItem(e);if(o)return this.removeItem(e),this.setItem(s,o),this.logger.verbose(`Updated an outdated ${i.credentialType} cache key`),s;this.logger.error(`Attempted to update an outdated ${i.credentialType} cache key but no item matching the outdated key was found in storage`)}return e}},Jw={Account:{},IdToken:{},AccessToken:{},RefreshToken:{},AppMetadata:{}},gV=class{constructor(e,i,s){this.cacheHasChanged=!1,this.storage=e,this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this)),s&&(this.persistence=s),this.logger=i}hasChanged(){return this.cacheHasChanged}serialize(){this.logger.trace("Serializing in-memory cache");let e=iI.serializeAllCache(this.storage.getInMemoryCache());return this.cacheSnapshot?(this.logger.trace("Reading cache snapshot from disk"),e=this.mergeState(JSON.parse(this.cacheSnapshot),e)):this.logger.trace("No cache snapshot to merge"),this.cacheHasChanged=!1,JSON.stringify(e)}deserialize(e){if(this.logger.trace("Deserializing JSON to in-memory cache"),this.cacheSnapshot=e,this.cacheSnapshot){this.logger.trace("Reading cache snapshot from disk");let i=zE.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));this.storage.setInMemoryCache(i)}else this.logger.trace("No cache snapshot to deserialize")}getKVStore(){return this.storage.getCache()}getCacheSnapshot(){let e=$I.generateInMemoryCache(this.cacheSnapshot);return this.storage.inMemoryCacheToCache(e)}async getAllAccounts(e=new HE().createNewGuid()){this.logger.trace("getAllAccounts called");let i;try{return this.persistence&&(i=new vy(this,!1),await this.persistence.beforeCacheAccess(i)),this.storage.getAllAccounts({},e)}finally{this.persistence&&i&&await this.persistence.afterCacheAccess(i)}}async getAccountByHomeId(e){let i=await this.getAllAccounts();return e&&i&&i.length&&i.filter(s=>s.homeAccountId===e)[0]||null}async getAccountByLocalId(e){let i=await this.getAllAccounts();return e&&i&&i.length&&i.filter(s=>s.localAccountId===e)[0]||null}async removeAccount(e,i){this.logger.trace("removeAccount called");let s;try{this.persistence&&(s=new vy(this,!0),await this.persistence.beforeCacheAccess(s)),this.storage.removeAccount(e,i||new yV().generateGuid())}finally{this.persistence&&s&&await this.persistence.afterCacheAccess(s)}}async overwriteCache(){if(!this.persistence){this.logger.info("No persistence layer specified, cache cannot be overwritten");return}this.logger.info("Overwriting in-memory cache with persistent cache"),this.storage.clear();let e=new vy(this,!1);await this.persistence.beforeCacheAccess(e);let i=this.getCacheSnapshot();this.storage.setCache(i),await this.persistence.afterCacheAccess(e)}handleChangeEvent(){this.cacheHasChanged=!0}mergeState(e,i){this.logger.trace("Merging in-memory cache with cache snapshot");let s=this.mergeRemovals(e,i);return this.mergeUpdates(s,i)}mergeUpdates(e,i){return Object.keys(i).forEach(s=>{let o=i[s];if(!e.hasOwnProperty(s))o!==null&&(e[s]=o);else{let c=o!==null,r=typeof o=="object",t=!Array.isArray(o),a=typeof e[s]<"u"&&e[s]!==null;c&&r&&t&&a?this.mergeUpdates(e[s],o):e[s]=o}}),e}mergeRemovals(e,i){this.logger.trace("Remove updated entries in cache");let s=e.Account?this.mergeRemovalsDict(e.Account,i.Account):e.Account,o=e.AccessToken?this.mergeRemovalsDict(e.AccessToken,i.AccessToken):e.AccessToken,c=e.RefreshToken?this.mergeRemovalsDict(e.RefreshToken,i.RefreshToken):e.RefreshToken,r=e.IdToken?this.mergeRemovalsDict(e.IdToken,i.IdToken):e.IdToken,t=e.AppMetadata?this.mergeRemovalsDict(e.AppMetadata,i.AppMetadata):e.AppMetadata;return{...e,Account:s,AccessToken:o,RefreshToken:c,IdToken:r,AppMetadata:t}}mergeRemovalsDict(e,i){let s={...e};return Object.keys(e).forEach(o=>{(!i||!i.hasOwnProperty(o))&&delete s[o]}),s}overlayDefaults(e){return this.logger.trace("Overlaying input cache with the default cache"),{Account:{...Jw.Account,...e.Account},IdToken:{...Jw.IdToken,...e.IdToken},AccessToken:{...Jw.AccessToken,...e.AccessToken},RefreshToken:{...Jw.RefreshToken,...e.RefreshToken},AppMetadata:{...Jw.AppMetadata,...e.AppMetadata}}}},GE=class n{static fromAssertion(e){let i=new n;return i.jwt=e,i}static fromCertificate(e,i,s){let o=new n;return o.privateKey=i,o.thumbprint=e,o.useSha256=!1,s&&(o.publicCertificate=this.parseCertificate(s)),o}static fromCertificateWithSha256Thumbprint(e,i,s){let o=new n;return o.privateKey=i,o.thumbprint=e,o.useSha256=!0,s&&(o.publicCertificate=this.parseCertificate(s)),o}getJwt(e,i,s){if(this.privateKey&&this.thumbprint)return this.jwt&&!this.isExpired()&&i===this.issuer&&s===this.jwtAudience?this.jwt:this.createJwt(e,i,s);if(this.jwt)return this.jwt;throw we(SI)}createJwt(e,i,s){this.issuer=i,this.jwtAudience=s;let o=Ki();this.expirationTime=o+600;let r={alg:this.useSha256?Sp.PSS_256:Sp.RSA_256},t=this.useSha256?Sp.X5T_256:Sp.X5T;Object.assign(r,{[t]:Jh.base64EncodeUrl(this.thumbprint,Zh.HEX)}),this.publicCertificate&&Object.assign(r,{[Sp.X5C]:this.publicCertificate});let a={[Sp.AUDIENCE]:this.jwtAudience,[Sp.EXPIRATION_TIME]:this.expirationTime,[Sp.ISSUER]:this.issuer,[Sp.SUBJECT]:this.issuer,[Sp.NOT_BEFORE]:o,[Sp.JWT_ID]:e.createNewGuid()};return this.jwt=Err.sign(a,this.privateKey,{header:r}),this.jwt}isExpired(){return this.expirationTime<Ki()}static parseCertificate(e){let i=/-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs,s=[],o;for(;(o=i.exec(e))!==null;)s.push(o[1].replace(/\r*\n/g,ue.EMPTY_STRING));return s}},vV=class extends Xh{constructor(e){super(e)}async acquireToken(e){this.logger.info("in acquireToken call in username-password client");let i=Ki(),s=await this.executeTokenRequest(this.authority,e),o=new Mu(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return o.validateTokenResponse(s.body),o.handleServerTokenResponse(s.body,this.authority,i,e)}async executeTokenRequest(e,i){let s=this.createTokenQueryParameters(i),o=ni.appendQueryString(e.tokenEndpoint,s),c=await this.createTokenRequestBody(i),r=this.createTokenRequestHeaders({credential:i.username,type:Ld.UPN}),t={clientId:this.config.authOptions.clientId,authority:e.canonicalAuthority,scopes:i.scopes,claims:i.claims,authenticationScheme:i.authenticationScheme,resourceRequestMethod:i.resourceRequestMethod,resourceRequestUri:i.resourceRequestUri,shrClaims:i.shrClaims,sshKid:i.sshKid};return this.executePostToTokenEndpoint(o,c,r,t,i.correlationId)}async createTokenRequestBody(e){let i=new Map;Sy(i,this.config.authOptions.clientId),Knr(i,e.username),Ynr(i,e.password),Ty(i,e.scopes),oze(i,z4e.IDTOKEN_TOKEN),YE(i,KE.RESOURCE_OWNER_PASSWORD_GRANT),WE(i),v_(i,this.config.libraryInfo),__(i,this.config.telemetry.application),ZE(i),this.serverTelemetryManager&&JE(i,this.serverTelemetryManager);let s=e.correlationId||this.config.cryptoInterface.createNewGuid();g_(i,s),this.config.clientCredentials.clientSecret&&KI(i,this.config.clientCredentials.clientSecret);let o=this.config.clientCredentials.clientAssertion;return o&&(YI(i,await b_(o.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),WI(i,o.assertionType)),(!Xs.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(i,e.claims,this.config.authOptions.clientCapabilities),this.config.systemOptions.preventCorsPreflight&&e.username&&qI(i,e.username),Qc(i)}};function zir(n,e,i,s){let o=vir({...n.auth,authority:e,redirectUri:i.redirectUri||""},i,s);return v_(o,{sku:xy.MSAL_SKU,version:y_,cpu:process.arch||"",os:process.platform||""}),n.auth.protocolMode!==by.OIDC&&__(o,n.telemetry.application),oze(o,z4e.CODE),i.codeChallenge&&i.codeChallengeMethod&&jnr(o,i.codeChallenge,i.codeChallengeMethod),Dd(o,i.extraQueryParameters||{}),_ir(e,o,n.auth.encodeExtraQueryParams,i.extraQueryParameters)}var FI=class{constructor(e){this.config=Bir(e),this.cryptoProvider=new HE,this.logger=new _y(this.config.system.loggerOptions,Yue,y_),this.storage=new $I(this.logger,this.config.auth.clientId,this.cryptoProvider,lir(this.config.auth)),this.tokenCache=new gV(this.storage,this.logger,this.config.cache.cachePlugin)}async getAuthCodeUrl(e){this.logger.info("getAuthCodeUrl called",e.correlationId);let i={...e,...await this.initializeBaseRequest(e),responseMode:e.responseMode||PV.QUERY,authenticationScheme:ii.BEARER,state:e.state||"",nonce:e.nonce||""},s=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions);return zir(this.config,s,i,this.logger)}async acquireTokenByCode(e,i){this.logger.info("acquireTokenByCode called"),e.state&&i&&(this.logger.info("acquireTokenByCode - validating state"),this.validateState(e.state,i.state||""),i={...i,state:""});let s={...e,...await this.initializeBaseRequest(e),authenticationScheme:ii.BEARER},o=this.initializeServerTelemetryManager(xE.acquireTokenByCode,s.correlationId);try{let c=await this.createAuthority(s.authority,s.correlationId,void 0,e.azureCloudOptions),r=await this.buildOauthClientConfiguration(c,s.correlationId,s.redirectUri,o),t=new bue(r);return this.logger.verbose("Auth code client created",s.correlationId),await t.acquireToken(s,i)}catch(c){throw c instanceof Bn&&c.setCorrelationId(s.correlationId),o.cacheFailedRequest(c),c}}async acquireTokenByRefreshToken(e){this.logger.info("acquireTokenByRefreshToken called",e.correlationId);let i={...e,...await this.initializeBaseRequest(e),authenticationScheme:ii.BEARER},s=this.initializeServerTelemetryManager(xE.acquireTokenByRefreshToken,i.correlationId);try{let o=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),c=await this.buildOauthClientConfiguration(o,i.correlationId,i.redirectUri||"",s),r=new tI(c);return this.logger.verbose("Refresh token client created",i.correlationId),await r.acquireToken(i)}catch(o){throw o instanceof Bn&&o.setCorrelationId(i.correlationId),s.cacheFailedRequest(o),o}}async acquireTokenSilent(e){let i={...e,...await this.initializeBaseRequest(e),forceRefresh:e.forceRefresh||!1},s=this.initializeServerTelemetryManager(xE.acquireTokenSilent,i.correlationId,i.forceRefresh);try{let o=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),c=await this.buildOauthClientConfiguration(o,i.correlationId,i.redirectUri||"",s),r=new Tue(c);this.logger.verbose("Silent flow client created",i.correlationId);try{return await this.tokenCache.overwriteCache(),await this.acquireCachedTokenSilent(i,r,c)}catch(t){if(t instanceof RI&&t.errorCode===kd)return new tI(c).acquireTokenByRefreshToken(i);throw t}}catch(o){throw o instanceof Bn&&o.setCorrelationId(i.correlationId),s.cacheFailedRequest(o),o}}async acquireCachedTokenSilent(e,i,s){let[o,c]=await i.acquireCachedToken({...e,scopes:e.scopes?.length?e.scopes:[...Yh]});if(c===So.PROACTIVELY_REFRESHED){this.logger.info("ClientApplication:acquireCachedTokenSilent - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.");let r=new tI(s);try{await r.acquireTokenByRefreshToken(e)}catch{}}return o}async acquireTokenByUsernamePassword(e){this.logger.info("acquireTokenByUsernamePassword called",e.correlationId);let i={...e,...await this.initializeBaseRequest(e)},s=this.initializeServerTelemetryManager(xE.acquireTokenByUsernamePassword,i.correlationId);try{let o=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),c=await this.buildOauthClientConfiguration(o,i.correlationId,"",s),r=new vV(c);return this.logger.verbose("Username password client created",i.correlationId),await r.acquireToken(i)}catch(o){throw o instanceof Bn&&o.setCorrelationId(i.correlationId),s.cacheFailedRequest(o),o}}getTokenCache(){return this.logger.info("getTokenCache called"),this.tokenCache}validateState(e,i){if(!e)throw Cu.createStateNotFoundError();if(e!==i)throw we(pI)}getLogger(){return this.logger}setLogger(e){this.logger=e}async buildOauthClientConfiguration(e,i,s,o){return this.logger.verbose("buildOauthClientConfiguration called",i),this.logger.info(`Building oauth client configuration with the following authority: ${e.tokenEndpoint}.`,i),o?.updateRegionDiscoveryMetadata(e.regionDiscoveryMetadata),{authOptions:{clientId:this.config.auth.clientId,authority:e,clientCapabilities:this.config.auth.clientCapabilities,redirectUri:s},loggerOptions:{logLevel:this.config.system.loggerOptions.logLevel,loggerCallback:this.config.system.loggerOptions.loggerCallback,piiLoggingEnabled:this.config.system.loggerOptions.piiLoggingEnabled,correlationId:i},cacheOptions:{claimsBasedCachingEnabled:this.config.cache.claimsBasedCachingEnabled},cryptoInterface:this.cryptoProvider,networkInterface:this.config.system.networkClient,storageInterface:this.storage,serverTelemetryManager:o,clientCredentials:{clientSecret:this.clientSecret,clientAssertion:await this.getClientAssertion(e)},libraryInfo:{sku:xy.MSAL_SKU,version:y_,cpu:process.arch||ue.EMPTY_STRING,os:process.platform||ue.EMPTY_STRING},telemetry:this.config.telemetry,persistencePlugin:this.config.cache.cachePlugin,serializableCache:this.tokenCache}}async getClientAssertion(e){return this.developerProvidedClientAssertion&&(this.clientAssertion=GE.fromAssertion(await b_(this.developerProvidedClientAssertion,this.config.auth.clientId,e.tokenEndpoint))),this.clientAssertion&&{assertion:this.clientAssertion.getJwt(this.cryptoProvider,this.config.auth.clientId,e.tokenEndpoint),assertionType:xy.JWT_BEARER_ASSERTION_TYPE}}async initializeBaseRequest(e){return this.logger.verbose("initializeRequestScopes called",e.correlationId),e.authenticationScheme&&e.authenticationScheme===ii.POP&&this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request",e.correlationId),e.authenticationScheme=ii.BEARER,this.config.cache.claimsBasedCachingEnabled&&e.claims&&!Xs.isEmptyObj(e.claims)&&(e.requestedClaimsHash=await this.cryptoProvider.hashString(e.claims)),{...e,scopes:[...e&&e.scopes||[],...Yh],correlationId:e&&e.correlationId||this.cryptoProvider.createNewGuid(),authority:e.authority||this.config.auth.authority}}initializeServerTelemetryManager(e,i,s){let o={clientId:this.config.auth.clientId,correlationId:i,apiId:e,forceRefresh:s||!1};return new mV(o,this.storage)}async createAuthority(e,i,s,o){this.logger.verbose("createAuthority called",i);let c=f_.generateAuthority(e,o||this.config.auth.azureCloudOptions),r={protocolMode:this.config.auth.protocolMode,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,azureRegionConfiguration:s,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache};return pze(c,this.config.system.networkClient,this.storage,r,this.logger,i)}clearCache(){this.storage.clear()}},Aue=class{async listenForAuthCode(e,i){if(this.server)throw Cu.createLoopbackServerAlreadyExistsError();return new Promise((s,o)=>{this.server=DB.createServer((c,r)=>{let t=c.url;if(t){if(t===ue.FORWARD_SLASH){r.end(e||"Auth code was successfully acquired. You can close this window now.");return}}else{r.end(i||"Error occurred loading redirectUrl"),o(Cu.createUnableToLoadRedirectUrlError());return}let a=this.getRedirectUri(),u=new URL(t,a),l=Z4e(u.search)||{};l.code&&(r.writeHead(Eo.REDIRECT,{location:a}),r.end()),l.error&&r.end(i||`Error occurred: ${l.error}`),s(l)}),this.server.listen(0,"127.0.0.1")})}getRedirectUri(){if(!this.server||!this.server.listening)throw Cu.createNoLoopbackServerExistsError();let e=this.server.address();if(!e||typeof e=="string"||!e.port)throw this.closeServer(),Cu.createInvalidLoopbackAddressTypeError();let i=e&&e.port;return`${xy.HTTP_PROTOCOL}${xy.LOCALHOST}:${i}`}closeServer(){this.server&&(this.server.close(),typeof this.server.closeAllConnections=="function"&&this.server.closeAllConnections(),this.server.unref(),this.server=void 0)}},_V=class extends Xh{constructor(e){super(e)}async acquireToken(e){let i=await this.getDeviceCode(e);e.deviceCodeCallback(i);let s=Ki(),o=await this.acquireTokenWithDeviceCode(e,i),c=new Mu(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return c.validateTokenResponse(o),c.handleServerTokenResponse(o,this.authority,s,e)}async getDeviceCode(e){let i=this.createExtraQueryParameters(e),s=ni.appendQueryString(this.authority.deviceCodeEndpoint,i),o=this.createQueryString(e),c=this.createTokenRequestHeaders(),r={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid};return this.executePostRequestToDeviceCodeEndpoint(s,o,c,r,e.correlationId)}createExtraQueryParameters(e){let i=new Map;return e.extraQueryParameters&&Dd(i,e.extraQueryParameters),Qc(i)}async executePostRequestToDeviceCodeEndpoint(e,i,s,o,c){let{body:{user_code:r,device_code:t,verification_uri:a,expires_in:u,interval:l,message:p}}=await this.sendPostRequest(o,e,{body:i,headers:s},c);return{userCode:r,deviceCode:t,verificationUri:a,expiresIn:u,interval:l,message:p}}createQueryString(e){let i=new Map;return Ty(i,e.scopes),Sy(i,this.config.authOptions.clientId),e.extraQueryParameters&&Dd(i,e.extraQueryParameters),(e.claims||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(i,e.claims,this.config.authOptions.clientCapabilities),Qc(i)}continuePolling(e,i,s){if(s)throw this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true"),we(vI);if(i&&i<e&&Ki()>i)throw this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${i}`),we(EI);if(Ki()>e)throw i&&this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${i}`),this.logger.error(`Device code expired. Expiration time of device code was ${e}`),we(_I);return!0}async acquireTokenWithDeviceCode(e,i){let s=this.createTokenQueryParameters(e),o=ni.appendQueryString(this.authority.tokenEndpoint,s),c=this.createTokenRequestBody(e,i),r=this.createTokenRequestHeaders(),t=e.timeout?Ki()+e.timeout:void 0,a=Ki()+i.expiresIn,u=i.interval*1e3;for(;this.continuePolling(a,t,e.cancel);){let l={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid},p=await this.executePostToTokenEndpoint(o,c,r,l,e.correlationId);if(p.body&&p.body.error)if(p.body.error===ue.AUTHORIZATION_PENDING)this.logger.info("Authorization pending. Continue polling."),await tir(u);else throw this.logger.info("Unexpected error in polling from the server"),Nrr(aI,p.body.error);else return this.logger.verbose("Authorization completed successfully. Polling stopped."),p.body}throw this.logger.error("Polling stopped for unknown reasons."),we(bI)}createTokenRequestBody(e,i){let s=new Map;Ty(s,e.scopes),Sy(s,this.config.authOptions.clientId),YE(s,KE.DEVICE_CODE_GRANT),Vnr(s,i.deviceCode);let o=e.correlationId||this.config.cryptoInterface.createNewGuid();return g_(s,o),WE(s),v_(s,this.config.libraryInfo),__(s,this.config.telemetry.application),ZE(s),this.serverTelemetryManager&&JE(s,this.serverTelemetryManager),(!Xs.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(s,e.claims,this.config.authOptions.clientCapabilities),Qc(s)}},Pue=class extends FI{constructor(e){super(e),this.config.broker.nativeBrokerPlugin&&(this.config.broker.nativeBrokerPlugin.isBrokerAvailable?(this.nativeBrokerPlugin=this.config.broker.nativeBrokerPlugin,this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions)):this.logger.warning("NativeBroker implementation was provided but the broker is unavailable.")),this.skus=mV.makeExtraSkuString({libraryName:xy.MSAL_SKU,libraryVersion:y_})}async acquireTokenByDeviceCode(e){this.logger.info("acquireTokenByDeviceCode called",e.correlationId);let i=Object.assign(e,await this.initializeBaseRequest(e)),s=this.initializeServerTelemetryManager(xE.acquireTokenByDeviceCode,i.correlationId);try{let o=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),c=await this.buildOauthClientConfiguration(o,i.correlationId,"",s),r=new _V(c);return this.logger.verbose("Device code client created",i.correlationId),await r.acquireToken(i)}catch(o){throw o instanceof Bn&&o.setCorrelationId(i.correlationId),s.cacheFailedRequest(o),o}}async acquireTokenInteractive(e){let i=e.correlationId||this.cryptoProvider.createNewGuid();this.logger.trace("acquireTokenInteractive called",i);let{openBrowser:s,successTemplate:o,errorTemplate:c,windowHandle:r,loopbackClient:t,...a}=e;if(this.nativeBrokerPlugin){let m={...a,clientId:this.config.auth.clientId,scopes:e.scopes||Yh,redirectUri:e.redirectUri||"",authority:e.authority||this.config.auth.authority,correlationId:i,extraParameters:{...a.extraQueryParameters,...a.tokenQueryParameters,[P4e]:this.skus},accountId:a.account?.nativeAccountId};return this.nativeBrokerPlugin.acquireTokenInteractive(m,r)}if(e.redirectUri){if(!this.config.broker.nativeBrokerPlugin)throw Cu.createRedirectUriNotSupportedError();e.redirectUri=""}let{verifier:u,challenge:l}=await this.cryptoProvider.generatePkceCodes(),p=t||new Aue,d={},h=null;try{let m=p.listenForAuthCode(o,c).then(D=>{d=D}).catch(D=>{h=D}),y=await this.waitForRedirectUri(p),g={...a,correlationId:i,scopes:e.scopes||Yh,redirectUri:y,responseMode:PV.QUERY,codeChallenge:l,codeChallengeMethod:xrr.S256},v=await this.getAuthCodeUrl(g);if(await s(v),await m,h)throw h;if(d.error)throw new h_(d.error,d.error_description,d.suberror);if(!d.code)throw Cu.createNoAuthCodeInResponseError();let _=d.client_info,k={code:d.code,codeVerifier:u,clientInfo:_||ue.EMPTY_STRING,...g};return await this.acquireTokenByCode(k)}finally{p.closeServer()}}async acquireTokenSilent(e){let i=e.correlationId||this.cryptoProvider.createNewGuid();if(this.logger.trace("acquireTokenSilent called",i),this.nativeBrokerPlugin){let s={...e,clientId:this.config.auth.clientId,scopes:e.scopes||Yh,redirectUri:e.redirectUri||"",authority:e.authority||this.config.auth.authority,correlationId:i,extraParameters:{...e.tokenQueryParameters,[P4e]:this.skus},accountId:e.account.nativeAccountId,forceRefresh:e.forceRefresh||!1};return this.nativeBrokerPlugin.acquireTokenSilent(s)}if(e.redirectUri){if(!this.config.broker.nativeBrokerPlugin)throw Cu.createRedirectUriNotSupportedError();e.redirectUri=""}return super.acquireTokenSilent(e)}async signOut(e){if(this.nativeBrokerPlugin&&e.account.nativeAccountId){let i={clientId:this.config.auth.clientId,accountId:e.account.nativeAccountId,correlationId:e.correlationId||this.cryptoProvider.createNewGuid()};await this.nativeBrokerPlugin.signOut(i)}await this.getTokenCache().removeAccount(e.account,e.correlationId)}async getAllAccounts(){if(this.nativeBrokerPlugin){let e=this.cryptoProvider.createNewGuid();return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId,e)}return this.getTokenCache().getAllAccounts()}async waitForRedirectUri(e){return new Promise((i,s)=>{let o=0,c=setInterval(()=>{if(due.TIMEOUT_MS/due.INTERVAL_MS<o){clearInterval(c),s(Cu.createLoopbackServerTimeoutError());return}try{let r=e.getRedirectUri();clearInterval(c),i(r);return}catch(r){if(r instanceof Bn&&r.errorCode===To.noLoopbackServerExists.code){o++;return}clearInterval(c),s(r);return}},due.INTERVAL_MS)})}},zI=class extends Xh{constructor(e,i){super(e),this.appTokenProvider=i}async acquireToken(e){if(e.skipCache||e.claims)return this.executeTokenRequest(e,this.authority);let[i,s]=await this.getCachedAuthenticationResult(e,this.config,this.cryptoUtils,this.authority,this.cacheManager,this.serverTelemetryManager);return i?(s===So.PROACTIVELY_REFRESHED&&(this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."),await this.executeTokenRequest(e,this.authority,!0)),i):this.executeTokenRequest(e,this.authority)}async getCachedAuthenticationResult(e,i,s,o,c,r){let t=i,a=i,u=So.NOT_APPLICABLE,l;t.serializableCache&&t.persistencePlugin&&(l=new vy(t.serializableCache,!1),await t.persistencePlugin.beforeCacheAccess(l));let p=this.readAccessTokenFromCache(o,a.managedIdentityId?.id||t.authOptions.clientId,new Zs(e.scopes||[]),c,e.correlationId);return t.serializableCache&&t.persistencePlugin&&l&&await t.persistencePlugin.afterCacheAccess(l),p?VE(p.expiresOn,t.systemOptions?.tokenRenewalOffsetSeconds||G4e)?(r?.setCacheOutcome(So.CACHED_ACCESS_TOKEN_EXPIRED),[null,So.CACHED_ACCESS_TOKEN_EXPIRED]):(p.refreshOn&&VE(p.refreshOn.toString(),0)&&(u=So.PROACTIVELY_REFRESHED,r?.setCacheOutcome(So.PROACTIVELY_REFRESHED)),[await Mu.generateAuthenticationResult(s,o,{account:null,idToken:null,accessToken:p,refreshToken:null,appMetadata:null},!0,e),u]):(r?.setCacheOutcome(So.NO_CACHED_ACCESS_TOKEN),[null,So.NO_CACHED_ACCESS_TOKEN])}readAccessTokenFromCache(e,i,s,o,c){let r={homeAccountId:ue.EMPTY_STRING,environment:e.canonicalAuthorityUrlComponents.HostNameAndPort,credentialType:Gi.ACCESS_TOKEN,clientId:i,realm:e.tenant,target:Zs.createSearchScopes(s.asArray())},t=o.getAccessTokensByFilter(r,c);if(t.length<1)return null;if(t.length>1)throw we(IE);return t[0]}async executeTokenRequest(e,i,s){let o,c;if(this.appTokenProvider){this.logger.info("Using appTokenProvider extensibility.");let a={correlationId:e.correlationId,tenantId:this.config.authOptions.authority.tenant,scopes:e.scopes,claims:e.claims};c=Ki();let u=await this.appTokenProvider(a);o={access_token:u.accessToken,expires_in:u.expiresInSeconds,refresh_in:u.refreshInSeconds,token_type:ii.BEARER}}else{let a=this.createTokenQueryParameters(e),u=ni.appendQueryString(i.tokenEndpoint,a),l=await this.createTokenRequestBody(e),p=this.createTokenRequestHeaders(),d={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid};this.logger.info("Sending token request to endpoint: "+i.tokenEndpoint),c=Ki();let h=await this.executePostToTokenEndpoint(u,l,p,d,e.correlationId);o=h.body,o.status=h.status}let r=new Mu(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return r.validateTokenResponse(o,s),await r.handleServerTokenResponse(o,this.authority,c,e)}async createTokenRequestBody(e){let i=new Map;Sy(i,this.config.authOptions.clientId),Ty(i,e.scopes,!1),YE(i,KE.CLIENT_CREDENTIALS_GRANT),v_(i,this.config.libraryInfo),__(i,this.config.telemetry.application),ZE(i),this.serverTelemetryManager&&JE(i,this.serverTelemetryManager);let s=e.correlationId||this.config.cryptoInterface.createNewGuid();g_(i,s),this.config.clientCredentials.clientSecret&&KI(i,this.config.clientCredentials.clientSecret);let o=e.clientAssertion||this.config.clientCredentials.clientAssertion;return o&&(YI(i,await b_(o.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),WI(i,o.assertionType)),(!Xs.isEmptyObj(e.claims)||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(i,e.claims,this.config.authOptions.clientCapabilities),Qc(i)}},bV=class extends Xh{constructor(e){super(e)}async acquireToken(e){if(this.scopeSet=new Zs(e.scopes||[]),this.userAssertionHash=await this.cryptoUtils.hashString(e.oboAssertion),e.skipCache||e.claims)return this.executeTokenRequest(e,this.authority,this.userAssertionHash);try{return await this.getCachedAuthenticationResult(e)}catch{return await this.executeTokenRequest(e,this.authority,this.userAssertionHash)}}async getCachedAuthenticationResult(e){let i=this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId,e);if(i){if(VE(i.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.serverTelemetryManager?.setCacheOutcome(So.CACHED_ACCESS_TOKEN_EXPIRED),this.logger.info(`OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`),we(kd)}else throw this.serverTelemetryManager?.setCacheOutcome(So.NO_CACHED_ACCESS_TOKEN),this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties."),we(kd);let s=this.readIdTokenFromCacheForOBO(i.homeAccountId,e.correlationId),o,c=null;if(s){o=HI(s.secret,Jh.base64Decode);let r=o.oid||o.sub,t={homeAccountId:s.homeAccountId,environment:s.environment,tenantId:s.realm,username:ue.EMPTY_STRING,localAccountId:r||ue.EMPTY_STRING};c=this.cacheManager.getAccount(this.cacheManager.generateAccountKey(t),e.correlationId)}return this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),Mu.generateAuthenticationResult(this.cryptoUtils,this.authority,{account:c,accessToken:i,idToken:s,refreshToken:null,appMetadata:null},!0,e,o)}readIdTokenFromCacheForOBO(e,i){let s={homeAccountId:e,environment:this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,credentialType:Gi.ID_TOKEN,clientId:this.config.authOptions.clientId,realm:this.authority.tenant},o=this.cacheManager.getIdTokensByFilter(s,i);return Object.values(o).length<1?null:Object.values(o)[0]}readAccessTokenFromCacheForOBO(e,i){let s=i.authenticationScheme||ii.BEARER,c={credentialType:s.toLowerCase()!==ii.BEARER.toLowerCase()?Gi.ACCESS_TOKEN_WITH_AUTH_SCHEME:Gi.ACCESS_TOKEN,clientId:e,target:Zs.createSearchScopes(this.scopeSet.asArray()),tokenType:s,keyId:i.sshKid,requestedClaimsHash:i.requestedClaimsHash,userAssertionHash:this.userAssertionHash},r=this.cacheManager.getAccessTokensByFilter(c,i.correlationId),t=r.length;if(t<1)return null;if(t>1)throw we(IE);return r[0]}async executeTokenRequest(e,i,s){let o=this.createTokenQueryParameters(e),c=ni.appendQueryString(i.tokenEndpoint,o),r=await this.createTokenRequestBody(e),t=this.createTokenRequestHeaders(),a={clientId:this.config.authOptions.clientId,authority:e.authority,scopes:e.scopes,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid},u=Ki(),l=await this.executePostToTokenEndpoint(c,r,t,a,e.correlationId),p=new Mu(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return p.validateTokenResponse(l.body),await p.handleServerTokenResponse(l.body,this.authority,u,e,void 0,s)}async createTokenRequestBody(e){let i=new Map;Sy(i,this.config.authOptions.clientId),Ty(i,e.scopes),YE(i,KE.JWT_BEARER),WE(i),v_(i,this.config.libraryInfo),__(i,this.config.telemetry.application),ZE(i),this.serverTelemetryManager&&JE(i,this.serverTelemetryManager);let s=e.correlationId||this.config.cryptoInterface.createNewGuid();g_(i,s),Hnr(i,Rnr),znr(i,e.oboAssertion),this.config.clientCredentials.clientSecret&&KI(i,this.config.clientCredentials.clientSecret);let o=this.config.clientCredentials.clientAssertion;return o&&(YI(i,await b_(o.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),WI(i,o.assertionType)),(e.claims||this.config.authOptions.clientCapabilities&&this.config.authOptions.clientCapabilities.length>0)&&Ey(i,e.claims,this.config.authOptions.clientCapabilities),Qc(i)}},Rue=class extends FI{constructor(e){super(e);let i=!!this.config.auth.clientSecret,s=!!this.config.auth.clientAssertion,o=(!!this.config.auth.clientCertificate?.thumbprint||!!this.config.auth.clientCertificate?.thumbprintSha256)&&!!this.config.auth.clientCertificate?.privateKey;if(!this.appTokenProvider){if(i&&s||s&&o||i&&o)throw we(DE);if(this.config.auth.clientSecret){this.clientSecret=this.config.auth.clientSecret;return}if(this.config.auth.clientAssertion){this.developerProvidedClientAssertion=this.config.auth.clientAssertion;return}if(o)this.clientAssertion=this.config.auth.clientCertificate.thumbprintSha256?GE.fromCertificateWithSha256Thumbprint(this.config.auth.clientCertificate.thumbprintSha256,this.config.auth.clientCertificate.privateKey,this.config.auth.clientCertificate.x5c):GE.fromCertificate(this.config.auth.clientCertificate.thumbprint,this.config.auth.clientCertificate.privateKey,this.config.auth.clientCertificate.x5c);else throw we(DE);this.appTokenProvider=void 0}}SetAppTokenProvider(e){this.appTokenProvider=e}async acquireTokenByClientCredential(e){this.logger.info("acquireTokenByClientCredential called",e.correlationId);let i;e.clientAssertion&&(i={assertion:await b_(e.clientAssertion,this.config.auth.clientId),assertionType:xy.JWT_BEARER_ASSERTION_TYPE});let s=await this.initializeBaseRequest(e),o={...s,scopes:s.scopes.filter(d=>!Yh.includes(d))},c={...e,...o,clientAssertion:i},t=new ni(c.authority).getUrlComponents().PathSegments[0];if(Object.values(Wh).includes(t))throw we(PI);let a=process.env[Rir],u;c.azureRegion!=="DisableMsalForceRegion"&&(!c.azureRegion&&a?u=a:u=c.azureRegion);let l={azureRegion:u,environmentRegion:process.env[Pir]},p=this.initializeServerTelemetryManager(xE.acquireTokenByClientCredential,c.correlationId,c.skipCache);try{let d=await this.createAuthority(c.authority,c.correlationId,l,e.azureCloudOptions),h=await this.buildOauthClientConfiguration(d,c.correlationId,"",p),m=new zI(h,this.appTokenProvider);return this.logger.verbose("Client credential client created",c.correlationId),await m.acquireToken(c)}catch(d){throw d instanceof Bn&&d.setCorrelationId(c.correlationId),p.cacheFailedRequest(d),d}}async acquireTokenOnBehalfOf(e){this.logger.info("acquireTokenOnBehalfOf called",e.correlationId);let i={...e,...await this.initializeBaseRequest(e)};try{let s=await this.createAuthority(i.authority,i.correlationId,void 0,e.azureCloudOptions),o=await this.buildOauthClientConfiguration(s,i.correlationId,"",void 0),c=new bV(o);return this.logger.verbose("On behalf of client created",i.correlationId),await c.acquireToken(i)}catch(s){throw s instanceof Bn&&s.setCorrelationId(i.correlationId),s}}};function Hir(n){if(typeof n!="string")return!1;let e=new Date(n);return!isNaN(e.getTime())&&e.toISOString()===n}var Nue=class{constructor(e,i,s){this.httpClientNoRetries=e,this.retryPolicy=i,this.logger=s}async sendNetworkRequestAsyncHelper(e,i,s){return e===Ba.GET?this.httpClientNoRetries.sendGetRequestAsync(i,s):this.httpClientNoRetries.sendPostRequestAsync(i,s)}async sendNetworkRequestAsync(e,i,s){let o=await this.sendNetworkRequestAsyncHelper(e,i,s);"isNewRequest"in this.retryPolicy&&(this.retryPolicy.isNewRequest=!0);let c=0;for(;await this.retryPolicy.pauseForRetry(o.status,c,this.logger,o.headers[ga.RETRY_AFTER]);)o=await this.sendNetworkRequestAsyncHelper(e,i,s),c++;return o}async sendGetRequestAsync(e,i){return this.sendNetworkRequestAsync(Ba.GET,e,i)}async sendPostRequestAsync(e,i){return this.sendNetworkRequestAsync(Ba.POST,e,i)}},OE={MANAGED_IDENTITY_CLIENT_ID_2017:"clientid",MANAGED_IDENTITY_CLIENT_ID:"client_id",MANAGED_IDENTITY_OBJECT_ID:"object_id",MANAGED_IDENTITY_RESOURCE_ID_IMDS:"msi_res_id",MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS:"mi_res_id"},Qh=class{constructor(e,i,s,o,c){this.logger=e,this.nodeStorage=i,this.networkClient=s,this.cryptoProvider=o,this.disableInternalRetries=c}async getServerTokenResponseAsync(e,i,s,o){return this.getServerTokenResponse(e)}getServerTokenResponse(e){let i,s;return e.body.expires_on&&(Hir(e.body.expires_on)&&(e.body.expires_on=new Date(e.body.expires_on).getTime()/1e3),s=e.body.expires_on-Ki(),s>2*3600&&(i=s/2)),{status:e.status,access_token:e.body.access_token,expires_in:s,scope:e.body.resource,token_type:e.body.token_type,refresh_in:i,correlation_id:e.body.correlation_id||e.body.correlationId,error:typeof e.body.error=="string"?e.body.error:e.body.error?.code,error_description:e.body.message||(typeof e.body.error=="string"?e.body.error_description:e.body.error?.message),error_codes:e.body.error_codes,timestamp:e.body.timestamp,trace_id:e.body.trace_id}}async acquireTokenWithManagedIdentity(e,i,s,o){let c=this.createRequest(e.resource,i);if(e.revokedTokenSha256Hash&&(this.logger.info(`[Managed Identity] The following claims are present in the request: ${e.claims}`),c.queryParameters[eu.SHA256_TOKEN_TO_REFRESH]=e.revokedTokenSha256Hash),e.clientCapabilities?.length){let h=e.clientCapabilities.toString();this.logger.info(`[Managed Identity] The following client capabilities are present in the request: ${h}`),c.queryParameters[eu.XMS_CC]=h}let r=c.headers;r[ga.CONTENT_TYPE]=ue.URL_FORM_CONTENT_TYPE;let t={headers:r};Object.keys(c.bodyParameters).length&&(t.body=c.computeParametersBodyString());let a=this.disableInternalRetries?this.networkClient:new Nue(this.networkClient,c.retryPolicy,this.logger),u=Ki(),l;try{c.httpMethod===Ba.POST?l=await a.sendPostRequestAsync(c.computeUri(),t):l=await a.sendGetRequestAsync(c.computeUri(),t)}catch(h){throw h instanceof Bn?h:we(d_)}let p=new Mu(i.id,this.nodeStorage,this.cryptoProvider,this.logger,null,null),d=await this.getServerTokenResponseAsync(l,a,c,t);return p.validateTokenResponse(d,o),p.handleServerTokenResponse(d,s,u,e)}getManagedIdentityUserAssignedIdQueryParameterKey(e,i,s){switch(e){case xs.USER_ASSIGNED_CLIENT_ID:return this.logger.info(`[Managed Identity] [API version ${s?"2017+":"2019+"}] Adding user assigned client id to the request.`),s?OE.MANAGED_IDENTITY_CLIENT_ID_2017:OE.MANAGED_IDENTITY_CLIENT_ID;case xs.USER_ASSIGNED_RESOURCE_ID:return this.logger.info("[Managed Identity] Adding user assigned resource id to the request."),i?OE.MANAGED_IDENTITY_RESOURCE_ID_IMDS:OE.MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS;case xs.USER_ASSIGNED_OBJECT_ID:return this.logger.info("[Managed Identity] Adding user assigned object id to the request."),OE.MANAGED_IDENTITY_OBJECT_ID;default:throw ja(nI)}}};Qh.getValidatedEnvVariableUrlString=(n,e,i,s)=>{try{return new ni(e).urlString}catch{throw s.info(`[Managed Identity] ${i} managed identity is unavailable because the '${n}' environment variable is malformed.`),ja(Zw[n])}};var wue=class{calculateDelay(e,i){if(!e)return i;let s=Math.round(parseFloat(e)*1e3);return isNaN(s)&&(s=new Date(e).valueOf()-new Date().valueOf()),Math.max(i,s)}},Gir=3,Kir=1e3,Yir=[Os.HttpStatus.NOT_FOUND,Os.HttpStatus.REQUEST_TIMEOUT,Os.HttpStatus.TOO_MANY_REQUESTS,Os.HttpStatus.SERVER_ERROR,Os.HttpStatus.SERVICE_UNAVAILABLE,Os.HttpStatus.GATEWAY_TIMEOUT],Iue=class n{constructor(){this.linearRetryStrategy=new wue}static get DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS(){return Kir}async pauseForRetry(e,i,s,o){if(Yir.includes(e)&&i<Gir){let c=this.linearRetryStrategy.calculateDelay(o,n.DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS);return s.verbose(`Retrying request in ${c}ms (retry attempt: ${i+1})`),await new Promise(r=>setTimeout(r,c)),!0}return!1}},Ay=class{constructor(e,i,s){this.httpMethod=e,this._baseEndpoint=i,this.headers={},this.bodyParameters={},this.queryParameters={},this.retryPolicy=s||new Iue}computeUri(){let e=new Map;this.queryParameters&&Dd(e,this.queryParameters);let i=Qc(e);return ni.appendQueryString(this._baseEndpoint,i)}computeParametersBodyString(){let e=new Map;return this.bodyParameters&&Dd(e,this.bodyParameters),Qc(e)}},Wir="2019-08-01",TV=class n extends Qh{constructor(e,i,s,o,c,r,t){super(e,i,s,o,c),this.identityEndpoint=r,this.identityHeader=t}static getEnvironmentVariables(){let e=process.env[ir.IDENTITY_ENDPOINT],i=process.env[ir.IDENTITY_HEADER];return[e,i]}static tryCreate(e,i,s,o,c){let[r,t]=n.getEnvironmentVariables();if(!r||!t)return e.info(`[Managed Identity] ${_r.APP_SERVICE} managed identity is unavailable because one or both of the '${ir.IDENTITY_HEADER}' and '${ir.IDENTITY_ENDPOINT}' environment variables are not defined.`),null;let a=n.getValidatedEnvVariableUrlString(ir.IDENTITY_ENDPOINT,r,_r.APP_SERVICE,e);return e.info(`[Managed Identity] Environment variables validation passed for ${_r.APP_SERVICE} managed identity. Endpoint URI: ${a}. Creating ${_r.APP_SERVICE} managed identity.`),new n(e,i,s,o,c,r,t)}createRequest(e,i){let s=new Ay(Ba.GET,this.identityEndpoint);return s.headers[Oy.APP_SERVICE_SECRET_HEADER_NAME]=this.identityHeader,s.queryParameters[eu.API_VERSION]=Wir,s.queryParameters[eu.RESOURCE]=e,i.idType!==xs.SYSTEM_ASSIGNED&&(s.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(i.idType)]=i.id),s}},Jir="2019-11-01",B4e="http://127.0.0.1:40342/metadata/identity/oauth2/token",V4e="N/A: himds executable exists",$4e={win32:`${process.env.ProgramData}\\AzureConnectedMachineAgent\\Tokens\\`,linux:"/var/opt/azcmagent/tokens/"},Zir={win32:`${process.env.ProgramFiles}\\AzureConnectedMachineAgent\\himds.exe`,linux:"/opt/azcmagent/bin/himds"},SV=class n extends Qh{constructor(e,i,s,o,c,r){super(e,i,s,o,c),this.identityEndpoint=r}static getEnvironmentVariables(){let e=process.env[ir.IDENTITY_ENDPOINT],i=process.env[ir.IMDS_ENDPOINT];if(!e||!i){let s=Zir[process.platform];try{Ww.accessSync(s,Ww.constants.F_OK|Ww.constants.R_OK),e=B4e,i=V4e}catch{}}return[e,i]}static tryCreate(e,i,s,o,c,r){let[t,a]=n.getEnvironmentVariables();if(!t||!a)return e.info(`[Managed Identity] ${_r.AZURE_ARC} managed identity is unavailable through environment variables because one or both of '${ir.IDENTITY_ENDPOINT}' and '${ir.IMDS_ENDPOINT}' are not defined. ${_r.AZURE_ARC} managed identity is also unavailable through file detection.`),null;if(a===V4e)e.info(`[Managed Identity] ${_r.AZURE_ARC} managed identity is available through file detection. Defaulting to known ${_r.AZURE_ARC} endpoint: ${B4e}. Creating ${_r.AZURE_ARC} managed identity.`);else{let u=n.getValidatedEnvVariableUrlString(ir.IDENTITY_ENDPOINT,t,_r.AZURE_ARC,e);u.endsWith("/")&&u.slice(0,-1),n.getValidatedEnvVariableUrlString(ir.IMDS_ENDPOINT,a,_r.AZURE_ARC,e),e.info(`[Managed Identity] Environment variables validation passed for ${_r.AZURE_ARC} managed identity. Endpoint URI: ${u}. Creating ${_r.AZURE_ARC} managed identity.`)}if(r.idType!==xs.SYSTEM_ASSIGNED)throw ja(Tze);return new n(e,i,s,o,c,t)}createRequest(e){let i=new Ay(Ba.GET,this.identityEndpoint.replace("localhost","127.0.0.1"));return i.headers[Oy.METADATA_HEADER_NAME]="true",i.queryParameters[eu.API_VERSION]=Jir,i.queryParameters[eu.RESOURCE]=e,i}async getServerTokenResponseAsync(e,i,s,o){let c;if(e.status===Eo.UNAUTHORIZED){let r=e.headers["www-authenticate"];if(!r)throw ja(Oze);if(!r.includes("Basic realm="))throw ja(xze);let t=r.split("Basic realm=")[1];if(!$4e.hasOwnProperty(process.platform))throw ja(bze);let a=$4e[process.platform],u=Orr.basename(t);if(!u.endsWith(".key"))throw ja(gze);if(a+u!==t)throw ja(vze);let l;try{l=await Ww.statSync(t).size}catch{throw ja(Sue)}if(l>Iir)throw ja(_ze);let p;try{p=Ww.readFileSync(t,Zh.UTF8)}catch{throw ja(Sue)}let d=`Basic ${p}`;this.logger.info("[Managed Identity] Adding authorization header to the request."),s.headers[Oy.AUTHORIZATION_HEADER_NAME]=d;try{c=await i.sendGetRequestAsync(s.computeUri(),o)}catch(h){throw h instanceof Bn?h:we(d_)}}return this.getServerTokenResponse(c||e)}},EV=class n extends Qh{constructor(e,i,s,o,c,r){super(e,i,s,o,c),this.msiEndpoint=r}static getEnvironmentVariables(){return[process.env[ir.MSI_ENDPOINT]]}static tryCreate(e,i,s,o,c,r){let[t]=n.getEnvironmentVariables();if(!t)return e.info(`[Managed Identity] ${_r.CLOUD_SHELL} managed identity is unavailable because the '${ir.MSI_ENDPOINT} environment variable is not defined.`),null;let a=n.getValidatedEnvVariableUrlString(ir.MSI_ENDPOINT,t,_r.CLOUD_SHELL,e);if(e.info(`[Managed Identity] Environment variable validation passed for ${_r.CLOUD_SHELL} managed identity. Endpoint URI: ${a}. Creating ${_r.CLOUD_SHELL} managed identity.`),r.idType!==xs.SYSTEM_ASSIGNED)throw ja(Sze);return new n(e,i,s,o,c,t)}createRequest(e){let i=new Ay(Ba.POST,this.msiEndpoint);return i.headers[Oy.METADATA_HEADER_NAME]="true",i.bodyParameters[eu.RESOURCE]=e,i}},Cue=class{constructor(e,i,s){this.minExponentialBackoff=e,this.maxExponentialBackoff=i,this.exponentialDeltaBackoff=s}calculateDelay(e){return e===0?this.minExponentialBackoff:Math.min(Math.pow(2,e-1)*this.exponentialDeltaBackoff,this.maxExponentialBackoff)}},Xir=[Os.HttpStatus.NOT_FOUND,Os.HttpStatus.REQUEST_TIMEOUT,Os.HttpStatus.GONE,Os.HttpStatus.TOO_MANY_REQUESTS],Qir=3,eor=7,tor=1e3,ror=4e3,nor=2e3,ior=10*1e3,Mue=class n{constructor(){this.exponentialRetryStrategy=new Cue(n.MIN_EXPONENTIAL_BACKOFF_MS,n.MAX_EXPONENTIAL_BACKOFF_MS,n.EXPONENTIAL_DELTA_BACKOFF_MS)}static get MIN_EXPONENTIAL_BACKOFF_MS(){return tor}static get MAX_EXPONENTIAL_BACKOFF_MS(){return ror}static get EXPONENTIAL_DELTA_BACKOFF_MS(){return nor}static get HTTP_STATUS_GONE_RETRY_AFTER_MS(){return ior}set isNewRequest(e){this._isNewRequest=e}async pauseForRetry(e,i,s){if(this._isNewRequest&&(this._isNewRequest=!1,this.maxRetries=e===Os.HttpStatus.GONE?eor:Qir),(Xir.includes(e)||e>=Os.HttpStatus.SERVER_ERROR_RANGE_START&&e<=Os.HttpStatus.SERVER_ERROR_RANGE_END&&i<this.maxRetries)&&i<this.maxRetries){let o=e===Os.HttpStatus.GONE?n.HTTP_STATUS_GONE_RETRY_AFTER_MS:this.exponentialRetryStrategy.calculateDelay(i);return s.verbose(`Retrying request in ${o}ms (retry attempt: ${i+1})`),await new Promise(c=>setTimeout(c,o)),!0}return!1}},Aze="/metadata/identity/oauth2/token",oor=`http://169.254.169.254${Aze}`,aor="2018-02-01",Lue=class n extends Qh{constructor(e,i,s,o,c,r){super(e,i,s,o,c),this.identityEndpoint=r}static tryCreate(e,i,s,o,c){let r;return process.env[ir.AZURE_POD_IDENTITY_AUTHORITY_HOST]?(e.info(`[Managed Identity] Environment variable ${ir.AZURE_POD_IDENTITY_AUTHORITY_HOST} for ${_r.IMDS} returned endpoint: ${process.env[ir.AZURE_POD_IDENTITY_AUTHORITY_HOST]}`),r=n.getValidatedEnvVariableUrlString(ir.AZURE_POD_IDENTITY_AUTHORITY_HOST,`${process.env[ir.AZURE_POD_IDENTITY_AUTHORITY_HOST]}${Aze}`,_r.IMDS,e)):(e.info(`[Managed Identity] Unable to find ${ir.AZURE_POD_IDENTITY_AUTHORITY_HOST} environment variable for ${_r.IMDS}, using the default endpoint.`),r=oor),new n(e,i,s,o,c,r)}createRequest(e,i){let s=new Ay(Ba.GET,this.identityEndpoint);return s.headers[Oy.METADATA_HEADER_NAME]="true",s.queryParameters[eu.API_VERSION]=aor,s.queryParameters[eu.RESOURCE]=e,i.idType!==xs.SYSTEM_ASSIGNED&&(s.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(i.idType,!0)]=i.id),s.retryPolicy=new Mue,s}},sor="2019-07-01-preview",OV=class n extends Qh{constructor(e,i,s,o,c,r,t){super(e,i,s,o,c),this.identityEndpoint=r,this.identityHeader=t}static getEnvironmentVariables(){let e=process.env[ir.IDENTITY_ENDPOINT],i=process.env[ir.IDENTITY_HEADER],s=process.env[ir.IDENTITY_SERVER_THUMBPRINT];return[e,i,s]}static tryCreate(e,i,s,o,c,r){let[t,a,u]=n.getEnvironmentVariables();if(!t||!a||!u)return e.info(`[Managed Identity] ${_r.SERVICE_FABRIC} managed identity is unavailable because one or all of the '${ir.IDENTITY_HEADER}', '${ir.IDENTITY_ENDPOINT}' or '${ir.IDENTITY_SERVER_THUMBPRINT}' environment variables are not defined.`),null;let l=n.getValidatedEnvVariableUrlString(ir.IDENTITY_ENDPOINT,t,_r.SERVICE_FABRIC,e);return e.info(`[Managed Identity] Environment variables validation passed for ${_r.SERVICE_FABRIC} managed identity. Endpoint URI: ${l}. Creating ${_r.SERVICE_FABRIC} managed identity.`),r.idType!==xs.SYSTEM_ASSIGNED&&e.warning(`[Managed Identity] ${_r.SERVICE_FABRIC} user assigned managed identity is configured in the cluster, not during runtime. See also: https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service.`),new n(e,i,s,o,c,t,a)}createRequest(e,i){let s=new Ay(Ba.GET,this.identityEndpoint);return s.headers[Oy.ML_AND_SF_SECRET_HEADER_NAME]=this.identityHeader,s.queryParameters[eu.API_VERSION]=sor,s.queryParameters[eu.RESOURCE]=e,i.idType!==xs.SYSTEM_ASSIGNED&&(s.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(i.idType)]=i.id),s}},cor="2017-09-01",uor=`Only client id is supported for user-assigned managed identity in ${_r.MACHINE_LEARNING}.`,xV=class n extends Qh{constructor(e,i,s,o,c,r,t){super(e,i,s,o,c),this.msiEndpoint=r,this.secret=t}static getEnvironmentVariables(){let e=process.env[ir.MSI_ENDPOINT],i=process.env[ir.MSI_SECRET];return[e,i]}static tryCreate(e,i,s,o,c){let[r,t]=n.getEnvironmentVariables();if(!r||!t)return e.info(`[Managed Identity] ${_r.MACHINE_LEARNING} managed identity is unavailable because one or both of the '${ir.MSI_ENDPOINT}' and '${ir.MSI_SECRET}' environment variables are not defined.`),null;let a=n.getValidatedEnvVariableUrlString(ir.MSI_ENDPOINT,r,_r.MACHINE_LEARNING,e);return e.info(`[Managed Identity] Environment variables validation passed for ${_r.MACHINE_LEARNING} managed identity. Endpoint URI: ${a}. Creating ${_r.MACHINE_LEARNING} managed identity.`),new n(e,i,s,o,c,r,t)}createRequest(e,i){let s=new Ay(Ba.GET,this.msiEndpoint);if(s.headers[Oy.METADATA_HEADER_NAME]="true",s.headers[Oy.ML_AND_SF_SECRET_HEADER_NAME]=this.secret,s.queryParameters[eu.API_VERSION]=cor,s.queryParameters[eu.RESOURCE]=e,i.idType===xs.SYSTEM_ASSIGNED)s.queryParameters[OE.MANAGED_IDENTITY_CLIENT_ID_2017]=process.env[ir.DEFAULT_IDENTITY_CLIENT_ID];else if(i.idType===xs.USER_ASSIGNED_CLIENT_ID)s.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(i.idType,!1,!0)]=i.id;else throw new Error(uor);return s}},AV=class n{constructor(e,i,s,o,c){this.logger=e,this.nodeStorage=i,this.networkClient=s,this.cryptoProvider=o,this.disableInternalRetries=c}async sendManagedIdentityTokenRequest(e,i,s,o){return n.identitySource||(n.identitySource=this.selectManagedIdentitySource(this.logger,this.nodeStorage,this.networkClient,this.cryptoProvider,this.disableInternalRetries,i)),n.identitySource.acquireTokenWithManagedIdentity(e,i,s,o)}allEnvironmentVariablesAreDefined(e){return Object.values(e).every(i=>i!==void 0)}getManagedIdentitySource(){return n.sourceName=this.allEnvironmentVariablesAreDefined(OV.getEnvironmentVariables())?_r.SERVICE_FABRIC:this.allEnvironmentVariablesAreDefined(TV.getEnvironmentVariables())?_r.APP_SERVICE:this.allEnvironmentVariablesAreDefined(xV.getEnvironmentVariables())?_r.MACHINE_LEARNING:this.allEnvironmentVariablesAreDefined(EV.getEnvironmentVariables())?_r.CLOUD_SHELL:this.allEnvironmentVariablesAreDefined(SV.getEnvironmentVariables())?_r.AZURE_ARC:_r.DEFAULT_TO_IMDS,n.sourceName}selectManagedIdentitySource(e,i,s,o,c,r){let t=OV.tryCreate(e,i,s,o,c,r)||TV.tryCreate(e,i,s,o,c)||xV.tryCreate(e,i,s,o,c)||EV.tryCreate(e,i,s,o,c,r)||SV.tryCreate(e,i,s,o,c,r)||Lue.tryCreate(e,i,s,o,c);if(!t)throw ja(Eze);return t}},lor=[_r.SERVICE_FABRIC],kue=class n{constructor(e){this.config=Vir(e||{}),this.logger=new _y(this.config.system.loggerOptions,Yue,y_);let i={canonicalAuthority:ue.DEFAULT_AUTHORITY};n.nodeStorage||(n.nodeStorage=new $I(this.logger,this.config.managedIdentityId.id,fue,i)),this.networkClient=this.config.system.networkClient,this.cryptoProvider=new HE;let s={protocolMode:by.AAD,knownAuthorities:[j4e],cloudDiscoveryMetadata:"",authorityMetadata:""};this.fakeAuthority=new f_(j4e,this.networkClient,n.nodeStorage,s,this.logger,this.cryptoProvider.createNewGuid(),void 0,!0),this.fakeClientCredentialClient=new zI({authOptions:{clientId:this.config.managedIdentityId.id,authority:this.fakeAuthority}}),this.managedIdentityClient=new AV(this.logger,n.nodeStorage,this.networkClient,this.cryptoProvider,this.config.disableInternalRetries),this.hashUtils=new VI}async acquireToken(e){if(!e.resource)throw oo(UE);let i={forceRefresh:e.forceRefresh,resource:e.resource.replace("/.default",""),scopes:[e.resource.replace("/.default","")],authority:this.fakeAuthority.canonicalAuthority,correlationId:this.cryptoProvider.createNewGuid(),claims:e.claims,clientCapabilities:this.config.clientCapabilities};if(i.forceRefresh)return this.acquireTokenFromManagedIdentity(i,this.config.managedIdentityId,this.fakeAuthority);let[s,o]=await this.fakeClientCredentialClient.getCachedAuthenticationResult(i,this.config,this.cryptoProvider,this.fakeAuthority,n.nodeStorage);if(i.claims){let c=this.managedIdentityClient.getManagedIdentitySource();if(s&&lor.includes(c)){let r=this.hashUtils.sha256(s.accessToken).toString(Zh.HEX);i.revokedTokenSha256Hash=r}return this.acquireTokenFromManagedIdentity(i,this.config.managedIdentityId,this.fakeAuthority)}return s?(o===So.PROACTIVELY_REFRESHED&&(this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."),await this.acquireTokenFromManagedIdentity(i,this.config.managedIdentityId,this.fakeAuthority,!0)),s):this.acquireTokenFromManagedIdentity(i,this.config.managedIdentityId,this.fakeAuthority)}async acquireTokenFromManagedIdentity(e,i,s,o){return this.managedIdentityClient.sendManagedIdentityTokenRequest(e,i,s,o)}getManagedIdentitySource(){return AV.sourceName||this.managedIdentityClient.getManagedIdentitySource()}},Due=class{constructor(e,i){this.client=e,this.partitionManager=i}async beforeCacheAccess(e){let i=await this.partitionManager.getKey(),s=await this.client.get(i);e.tokenCache.deserialize(s)}async afterCacheAccess(e){if(e.cacheHasChanged){let i=e.tokenCache.getKVStore(),s=Object.values(i).filter(c=>Xc.isAccountEntity(c)),o;if(s.length>0){let c=s[0];o=await this.partitionManager.extractKey(c)}else o=await this.partitionManager.getKey();await this.client.set(o,e.tokenCache.serialize())}}};bt.AuthError=Bn;bt.AuthErrorCodes=Prr;bt.AuthErrorMessage=Rrr;bt.AzureCloudInstance=RV;bt.ClientApplication=FI;bt.ClientAssertion=GE;bt.ClientAuthError=RI;bt.ClientAuthErrorCodes=wrr;bt.ClientAuthErrorMessage=Irr;bt.ClientConfigurationError=cV;bt.ClientConfigurationErrorCodes=Crr;bt.ClientConfigurationErrorMessage=Mrr;bt.ClientCredentialClient=zI;bt.ConfidentialClientApplication=Rue;bt.CryptoProvider=HE;bt.DeviceCodeClient=_V;bt.DistributedCachePlugin=Due;bt.InteractionRequiredAuthError=m_;bt.InteractionRequiredAuthErrorCodes=pir;bt.InteractionRequiredAuthErrorMessage=fir;bt.Logger=_y;bt.ManagedIdentityApplication=kue;bt.ManagedIdentitySourceNames=_r;bt.OnBehalfOfClient=bV;bt.PromptValue=UB;bt.ProtocolMode=by;bt.PublicClientApplication=Pue;bt.ResponseMode=PV;bt.ServerError=h_;bt.TokenCache=gV;bt.TokenCacheContext=vy;bt.UsernamePasswordClient=vV;bt.internals=Oir;bt.version=y_});var Jue=f(T_=>{"use strict";Object.defineProperty(T_,"__esModule",{value:!0});T_.TELEMETRY_EVENTS=void 0;T_.createTelemetryTimestamp=Rze;T_.createCommonProperties=por;T_.cleanTelemetryProperties=dor;T_.TELEMETRY_EVENTS={EXTENSION:{COMMAND_COMPLETED:"TB-EXT-002",COMMAND_FAILED:"TB-EXT-003",MCP_REQUEST_SENT:"TB-EXT-004",MCP_RESPONSE_RECEIVED:"TB-EXT-005",PROFILE_SWITCHED:"TB-EXT-006",CACHE_CLEARED:"TB-EXT-007",SETUP_WIZARD_OPENED:"TB-EXT-008",SETUP_WIZARD_COMPLETED:"TB-EXT-009",ERROR:"TB-EXT-010",ACTIVATED:"TB-EXT-011",TELEMETRY_ID_RESET:"TB-EXT-012",KB_PANEL_OPENED:"TB-EXT-013",KB_ARTICLE_OPENED:"TB-EXT-014",KB_ARTICLE_EXCLUDED:"TB-EXT-015",KB_COMMUNITY_TOGGLED:"TB-EXT-016",KB_REFRESH_COMPLETED:"TB-EXT-017",KB_REFRESH_FAILED:"TB-EXT-018",SETUP_POINTER_SHOWN:"TB-EXT-019",GUIDED_SETUP_LAUNCHED:"TB-EXT-020"},MCP:{SERVER_STARTED:"TB-MCP-001",CONFIGURATION_LOADED:"TB-MCP-002",ERROR:"TB-MCP-005"},MCP_TOOLS:{QUERY_TELEMETRY:"TB-MCP-101",GET_SAVED_QUERIES:"TB-MCP-102",SEARCH_QUERIES:"TB-MCP-103",SAVE_QUERY:"TB-MCP-104",GENERATE_KQL:"TB-MCP-105",GET_RECOMMENDATIONS:"TB-MCP-106",LOOKUP_EVENT:"TB-MCP-107",GET_EVENT_CATALOG:"TB-MCP-108",GET_EVENT_SCHEMA:"TB-MCP-109",GET_EVENT_FIELD_SAMPLES:"TB-MCP-110",GET_KNOWLEDGE:"TB-MCP-111",SAVE_KNOWLEDGE:"TB-MCP-112",DEPRECATED_TOOL_CALLED:"TB-MCP-113",KB_HINT_EMITTED:"TB-MCP-114",SETUP_PROMPT_SERVED:"TB-MCP-115",GET_SETUP_GUIDE:"TB-MCP-116"},KUSTO:{QUERY_EXECUTED:"TB-KQL-001",QUERY_FAILED:"TB-KQL-002",QUERY_CACHED:"TB-KQL-003",CACHE_MISS:"TB-KQL-004"},AUTH:{AUTHENTICATION_ATTEMPT:"TB-AUTH-001",AUTHENTICATION_COMPLETED:"TB-AUTH-002",TOKEN_REFRESHED:"TB-AUTH-003",FAILED:"TB-AUTH-004"},CACHE:{HIT:"TB-CACHE-001",MISS:"TB-CACHE-002",SET:"TB-CACHE-003",CLEARED:"TB-CACHE-004",EXPIRED:"TB-CACHE-005"}};function Rze(){return new Date().toISOString()}function por(n,e,i,s,o,c){let r={eventId:n,timestamp:Rze(),component:e,sessionId:i,installationId:s,version:o};return c?.correlationId&&(r.correlationId=c.correlationId),c?.profileHash&&(r.profileHash=c.profileHash),c&&Object.keys(c).forEach(t=>{t!=="correlationId"&&t!=="profileHash"&&c[t]!==void 0&&(r[t]=c[t])}),r}function dor(n){let e={};return Object.keys(n).forEach(i=>{let s=n[i];s!==void 0&&(e[i]=s)}),e}});var wze=f(wV=>{"use strict";Object.defineProperty(wV,"__esModule",{value:!0});wV.AuthService=void 0;var Nze=Pze(),Ep=Jue(),hor=require("child_process"),mor=require("util"),yor=(0,mor.promisify)(hor.exec),Zue=class{config;usageTelemetry;authResult=null;constructor(e,i){this.config=e,this.usageTelemetry=i}getStatus(){return!this.authResult||!this.authResult.authenticated?{authenticated:!1}:this.authResult.expiresOn&&this.authResult.expiresOn<new Date?{authenticated:!1}:this.authResult}async authenticate(){return this.usageTelemetry?.trackEvent(Ep.TELEMETRY_EVENTS.AUTH.AUTHENTICATION_ATTEMPT,{authFlow:this.config.authFlow||"client_credentials"}),this.config.authFlow==="azure_cli"?this.authenticateAzureCLI():this.config.authFlow==="device_code"?this.authenticateDeviceCode():this.config.authFlow==="vscode_auth"?this.authenticateVSCode():this.authenticateClientCredentials()}async authenticateAzureCLI(){try{console.error("[MCP] Using Azure CLI authentication (az account get-access-token)...");let{stdout:e,stderr:i}=await yor("az account get-access-token --resource https://api.applicationinsights.io",{env:{...process.env,PYTHONWARNINGS:"ignore"}});i&&console.error("Azure CLI stderr:",i);let s=JSON.parse(e);if(!s.accessToken)throw new Error("No access token returned from Azure CLI");return this.authResult={authenticated:!0,accessToken:s.accessToken,user:s.subscription||"Azure CLI User",expiresOn:s.expiresOn?new Date(s.expiresOn):void 0},console.error("[MCP] \u2713 Authenticated via Azure CLI"),console.error(`[MCP] Subscription: ${s.subscription||"N/A"}`),console.error(`[MCP] Tenant: ${s.tenant||"N/A"}`),this.usageTelemetry?.trackEvent(Ep.TELEMETRY_EVENTS.AUTH.AUTHENTICATION_COMPLETED,{authFlow:"azure_cli"}),this.authResult}catch(e){throw console.error("Azure CLI authentication failed:",e.message),e.message.includes("az: command not found")||e.message.includes("not recognized")?(console.error(`
60
60
  \u26A0\uFE0F Azure CLI is not installed or not in PATH`),console.error(`Install from: https://docs.microsoft.com/cli/azure/install-azure-cli
61
61
  `)):e.message.includes("az login")&&(console.error(`
62
62
  \u26A0\uFE0F You need to login first using: az login`),console.error(`Run "az login" in your terminal and try again.
@@ -100,7 +100,7 @@ To skip this manual step in future, set \`BCTB_GITHUB_TOKEN\` in your environmen
100
100
  `),new Error("BCTB_WORKSPACE_PATH environment variable is required");return{connectionName:process.env.BCTB_CONNECTION_NAME||"Default",tenantId:process.env.BCTB_TENANT_ID||"",clientId:process.env.BCTB_CLIENT_ID,clientSecret:process.env.BCTB_CLIENT_SECRET,authFlow:process.env.BCTB_AUTH_FLOW||"azure_cli",applicationInsightsAppId:process.env.BCTB_APP_INSIGHTS_ID||"",kustoClusterUrl:process.env.BCTB_KUSTO_URL||"",cacheEnabled:process.env.BCTB_CACHE_ENABLED!=="false",cacheTTLSeconds:parseInt(process.env.BCTB_CACHE_TTL||"3600",10),removePII:process.env.BCTB_REMOVE_PII==="true",port:parseInt(process.env.BCTB_PORT||"52345",10),workspacePath:n,queriesFolder:process.env.BCTB_QUERIES_FOLDER||"queries",references:Rlr(process.env.BCTB_REFERENCES||"[]")}}function Rlr(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch(e){return console.error("Failed to parse references:",e),[]}}function y8e(n,e,i=new Set){if(i.has(e))throw new Error(`Circular profile inheritance detected: ${e}`);i.add(e);let s=n[e];if(!s)throw new Error(`Profile '${e}' not found`);if(!s.extends)return s3(s);let o=y8e(n,s.extends,i),c=g8e(o,s);return delete c.extends,s3(c)}function g8e(n,e){let i={...n};for(let s in e)s!=="extends"&&(typeof e[s]=="object"&&!Array.isArray(e[s])&&e[s]!==null?i[s]=g8e(n[s]||{},e[s]):i[s]=e[s]);return i}function s3(n){let e=Array.isArray(n)?[]:{};for(let i in n){let s=n[i];typeof s=="string"?e[i]=s.replace(/\$\{([^}]+)\}/g,(o,c)=>process.env[c]||""):typeof s=="object"&&s!==null?e[i]=s3(s):e[i]=s}return e}function Nlr(n){let e=[];return n.authFlow!=="azure_cli"&&n.authFlow!=="vscode_auth"&&!n.tenantId&&e.push("BCTB_TENANT_ID is required (unless using azure_cli or vscode_auth auth flow)"),n.applicationInsightsAppId||e.push("BCTB_APP_INSIGHTS_ID is required"),n.kustoClusterUrl||e.push("BCTB_KUSTO_URL is required"),n.authFlow==="client_credentials"&&!n.clientId&&e.push("BCTB_CLIENT_ID is required for client_credentials auth flow"),n.authFlow==="client_credentials"&&!n.clientSecret&&e.push("BCTB_CLIENT_SECRET is required for client_credentials auth flow"),e.length>0&&(console.error(`
101
101
  \u26A0\uFE0F Configuration Incomplete:`),e.forEach(i=>console.error(` - ${i}`)),console.error(`
102
102
  Server will start but queries will fail until configuration is complete.`),console.error(`Run "BC Telemetry Buddy: Setup Wizard" from Command Palette to configure.
103
- `)),e}});var mC=f(Mn=>{"use strict";var wlr=Mn&&Mn.__createBinding||(Object.create?(function(n,e,i,s){s===void 0&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(n,s,o)}):(function(n,e,i,s){s===void 0&&(s=i),n[s]=e[i]})),Rp=Mn&&Mn.__exportStar||function(n,e){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(e,i)&&wlr(e,n,i)};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.expandEnvironmentVariables=Mn.resolveProfileInheritance=Mn.validateConfig=Mn.loadConfig=Mn.TELEMETRY_CONNECTION_STRING=void 0;Rp(wze(),Mn);Rp(WGe(),Mn);Rp(JGe(),Mn);Rp(XGe(),Mn);Rp(o8e(),Mn);Rp(l8e(),Mn);Rp(d8e(),Mn);Rp(h8e(),Mn);Rp(ipe(),Mn);Rp(tpe(),Mn);Rp(Jue(),Mn);var Ilr=m8e();Object.defineProperty(Mn,"TELEMETRY_CONNECTION_STRING",{enumerable:!0,get:function(){return Ilr.TELEMETRY_CONNECTION_STRING}});var c3=v8e();Object.defineProperty(Mn,"loadConfig",{enumerable:!0,get:function(){return c3.loadConfig}});Object.defineProperty(Mn,"validateConfig",{enumerable:!0,get:function(){return c3.validateConfig}});Object.defineProperty(Mn,"resolveProfileInheritance",{enumerable:!0,get:function(){return c3.resolveProfileInheritance}});Object.defineProperty(Mn,"expandEnvironmentVariables",{enumerable:!0,get:function(){return c3.expandEnvironmentVariables}})});var oi,yC=L(()=>{"use strict";oi="3.4.1"});var u3,mpe=L(()=>{"use strict";u3=`# BC Telemetry Buddy \u2014 Connection Setup
103
+ `)),e}});var mC=f(Mn=>{"use strict";var wlr=Mn&&Mn.__createBinding||(Object.create?(function(n,e,i,s){s===void 0&&(s=i);var o=Object.getOwnPropertyDescriptor(e,i);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[i]}}),Object.defineProperty(n,s,o)}):(function(n,e,i,s){s===void 0&&(s=i),n[s]=e[i]})),Rp=Mn&&Mn.__exportStar||function(n,e){for(var i in n)i!=="default"&&!Object.prototype.hasOwnProperty.call(e,i)&&wlr(e,n,i)};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.expandEnvironmentVariables=Mn.resolveProfileInheritance=Mn.validateConfig=Mn.loadConfig=Mn.TELEMETRY_CONNECTION_STRING=void 0;Rp(wze(),Mn);Rp(WGe(),Mn);Rp(JGe(),Mn);Rp(XGe(),Mn);Rp(o8e(),Mn);Rp(l8e(),Mn);Rp(d8e(),Mn);Rp(h8e(),Mn);Rp(ipe(),Mn);Rp(tpe(),Mn);Rp(Jue(),Mn);var Ilr=m8e();Object.defineProperty(Mn,"TELEMETRY_CONNECTION_STRING",{enumerable:!0,get:function(){return Ilr.TELEMETRY_CONNECTION_STRING}});var c3=v8e();Object.defineProperty(Mn,"loadConfig",{enumerable:!0,get:function(){return c3.loadConfig}});Object.defineProperty(Mn,"validateConfig",{enumerable:!0,get:function(){return c3.validateConfig}});Object.defineProperty(Mn,"resolveProfileInheritance",{enumerable:!0,get:function(){return c3.resolveProfileInheritance}});Object.defineProperty(Mn,"expandEnvironmentVariables",{enumerable:!0,get:function(){return c3.expandEnvironmentVariables}})});var oi,yC=L(()=>{"use strict";oi="3.5.1"});var u3,mpe=L(()=>{"use strict";u3=`# BC Telemetry Buddy \u2014 Connection Setup
104
104
 
105
105
  You are helping the user set up a connection to their Microsoft Dynamics 365 Business Central telemetry (Azure Application Insights). Follow these steps **in order**. After each step, briefly tell the user what you did and what is next.
106
106
 
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ "use strict";var U=Object.create;var N=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var B=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty;var q=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of G(n))!J.call(e,r)&&r!==t&&N(e,r,{get:()=>n[r],enumerable:!(o=D(n,r))||o.enumerable});return e};var A=(e,n,t)=>(t=e!=null?U(B(e)):{},q(n||!e||!e.__esModule?N(t,"default",{value:e,enumerable:!0}):t,e));var u=A(require("fs")),h=A(require("path")),I=require("child_process"),z=require("util"),w=require("node:process");var f=class extends Error{constructor(n){super(n),this.name="AzUnavailableError"}},v="Azure CLI is unavailable or you are not signed in. Install Azure CLI and run `az login`, or set up the connection manually by pasting your Application Insights App ID from the Azure Portal.";function M(e){let n=e instanceof Error?e.message:String(e);return/command not found|not recognized|az login|please run 'az login'|no subscription/i.test(n)}function W(e){return JSON.parse(e).map(t=>({id:t.id,tenantId:t.tenantId}))}async function S(e){let n;try{n=W(await e("account list -o json"))}catch(o){throw M(o)?new f(v):new f(v)}let t=[];for(let o of n){let r;try{let i=await e(`resource list --resource-type microsoft.insights/components --subscription ${o.id} -o json`);r=JSON.parse(i)}catch{continue}for(let i of r)try{let a=await e(`monitor app-insights component show --ids ${i.id} -o json`),c=JSON.parse(a).appId;if(!c)continue;t.push({name:i.name,appId:c,resourceGroup:i.resourceGroup,subscriptionId:o.id,tenantId:o.tenantId,location:i.location})}catch{continue}}return t}var g="https://raw.githubusercontent.com/waldo1001/waldo.BCTelemetryBuddy/main/packages/mcp/config-schema.json",H="00000000-0000-0000-0000-000000000000",K="https://api.applicationinsights.io";function x(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function V(e){let n={connectionName:e.connectionName,authFlow:e.authFlow,tenantId:e.tenantId||H,applicationInsightsAppId:e.applicationInsightsAppId,kustoClusterUrl:e.kustoClusterUrl||K,cacheEnabled:!0,cacheTTLSeconds:3600,removePII:!1,workspacePath:"${workspaceFolder}",queriesFolder:"queries",references:[]};return e.clientId&&(n.clientId=e.clientId),n}var $=["connectionName","authFlow","tenantId","clientId","clientSecret","applicationInsightsAppId","kustoClusterUrl","cacheEnabled","cacheTTLSeconds","removePII","port","workspacePath","queriesFolder"];function Y(e){let n={};for(let t of $)e[t]!==void 0&&(n[t]=e[t]);return e.references!==void 0&&(n.references=e.references),n}function k(e,n){let t=V(n);if(!e||e.trim()===""){if(n.profileName){let d={$schema:g,defaultProfile:n.profileName,profiles:{[n.profileName]:t}};return{content:m(d),mode:"created",profileName:n.profileName}}let s={$schema:g,...t};return{content:m(s),mode:"created"}}let o=JSON.parse(e),r=n.profileName||x(n.connectionName),i=o.profiles&&typeof o.profiles=="object";if(!!n.profileName||i){let s={...o};if(s.$schema||(s.$schema=g),i)s.profiles={...o.profiles};else{let d=o.connectionName?x(o.connectionName):"default",y=Y(o);s.profiles={[d]:y},s.defaultProfile=s.defaultProfile||d;for(let p of[...$,"references"])delete s[p]}return s.profiles[r]=t,s.defaultProfile||(s.defaultProfile=r),{content:m(s),mode:"merged-profile",profileName:r}}let c={...o,$schema:o.$schema||g,...t};return{content:m(c),mode:"updated"}}function m(e){return JSON.stringify(e,null,2)+`
3
+ `}function E(e,n){if(!n.existsSync(e))throw new Error(`Target folder does not exist: ${e}
4
+ Pass --folder pointing at an existing workspace folder (create it first if needed).`);if(!n.statSync(e).isDirectory())throw new Error(`Target path is not a directory: ${e}`)}function F(e,n){let t=e.trim();if(!/^\d+$/.test(t))return null;let o=Number(t);return o<1||o>n?null:o-1}var C=A(require("node:readline"));function R(e,n){let t=C.createInterface({input:e,output:n}),o=[],r=[],i=!1;return t.on("line",a=>{let c=r.shift();c?c(a):o.push(a)}),t.on("close",()=>{for(i=!0;r.length;)r.shift()("")}),{question(a){return n.write(a),o.length>0?Promise.resolve(o.shift()):i?Promise.resolve(""):new Promise(c=>r.push(c))},close(){t.close()}}}var Z=(0,z.promisify)(I.exec),b=async e=>{let{stdout:n}=await Z(`az ${e}`,{env:{...process.env,PYTHONWARNINGS:"ignore"},maxBuffer:10485760});return n};function Q(e){let n=process.argv.indexOf(e);return n>=0&&process.argv[n+1]?process.argv[n+1]:void 0}async function X(){let e=R(w.stdin,w.stdout),n=async(t,o)=>(await e.question(o?`${t} [${o}]: `:`${t}: `)).trim()||o||"";try{console.log(`
5
+ BC Telemetry Buddy \u2014 guided setup
6
+ `);let t=Q("--folder")||await n("Folder to write .bctb-config.json into",process.cwd());t=h.resolve(t),E(t,u);let o=null;try{o=JSON.parse(await b("account show -o json"))}catch{let l=await n("Not signed in to Azure CLI. Run `az login` now? (y/n)","y");if(/^y/i.test(l)){(0,I.spawnSync)("az",["login"],{stdio:"inherit"});try{o=JSON.parse(await b("account show -o json"))}catch{}}}o?.user?.name&&console.log(`\u2713 Azure CLI: signed in as ${o.user.name}`),console.log(` Config target: ${t}
7
+ `);let r=[];try{console.log(`Finding your Application Insights resources\u2026
8
+ `),r=await S(b)}catch{r=[]}let i="",a=o?.tenantId||"",c="My BC Environment";if(r.length>0){r.forEach((P,j)=>console.log(` ${j+1}. ${P.name} (${P.resourceGroup}, ${P.location})`)),console.log("");let l=null;for(;l===null;)l=F(await n("Pick a number"),r.length),l===null&&console.log(" Invalid choice \u2014 enter the number next to the resource.");i=r[l].appId,a=r[l].tenantId,c=r[l].name}else{for(console.log("No resources found via Azure CLI (or it is unavailable). Enter values manually."),console.log(`Azure Portal \u2192 your Application Insights \u2192 Configure \u2192 API Access.
9
+ `);!i;)i=await n("Application Insights App ID");a=await n("Tenant ID",a||"00000000-0000-0000-0000-000000000000")}let s=await n("Connection name",c),d=await n("Profile name (leave blank for single-profile)",""),y={connectionName:s,authFlow:"azure_cli",applicationInsightsAppId:i,tenantId:a,profileName:d||void 0},p=h.join(t,".bctb-config.json"),L=u.existsSync(p)?u.readFileSync(p,"utf8"):null,{content:T,mode:_}=k(L,y),O=await n(`
10
+ Write ${p} (${_})? (y/n)`,"y");if(!/^y/i.test(O)){console.log("Aborted \u2014 nothing written."),e.close();return}u.writeFileSync(p,T,"utf8"),console.log(`
11
+ \u2713 Wrote ${p}`),console.log(` Reload VS Code (Developer: Reload Window) or restart the MCP server to start querying.
12
+ `),e.close()}catch(t){console.error(`
13
+ \u2717 ${t.message}`),e.close(),process.exit(1)}}X();
14
+ //# sourceMappingURL=setup.js.map