UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

28,063 lines • 1.15 MB
import { i as __require, t as __commonJSMin } from "./chunk-DORXReHP.js";
import { t as require_src$3 } from "./src-BoNU6eQs.js";
import "./follow-redirects-CVAaqIk4.js";
import { t as require_axios } from "./axios-CEyceml2.js";
import "./jws-DUvIsq9L.js";
import { t as require_jsonwebtoken } from "./jsonwebtoken-D7mxFmXm.js";
import "./semver-DgFx6ze4.js";
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/logger.js
var require_logger = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.Logger = void 0;
	exports.debug = debug;
	const debug_1 = __importDefault(require_src$3());
	const loggerLevels = [
		"info",
		"warn",
		"error",
		"debug"
	];
	/**
	* Logger class that provides colored logging functionality using the debug package.
	* Supports different log levels: info, warn, error, and debug.
	*/
	var Logger = class {
		/**
		* Creates a new Logger instance with the specified namespace.
		* @param namespace The namespace to use for the logger
		*/
		constructor(namespace = "") {
			this.loggers = {};
			this.initializeLoggers(namespace);
		}
		initializeLoggers(namespace) {
			for (const level of loggerLevels) {
				const logger = (0, debug_1.default)(`${namespace}:${level}`);
				logger.color = this.getPlatformColor(level);
				this.loggers[level] = logger;
			}
		}
		getPlatformColor(level) {
			return {
				node: {
					info: "2",
					warn: "3",
					error: "1",
					debug: "4"
				},
				browser: {
					info: "#33CC99",
					warn: "#CCCC33",
					error: "#CC3366",
					debug: "#0066FF"
				}
			}[typeof window !== "undefined" ? "browser" : "node"][level];
		}
		/**
		* Logs an informational message.
		* @param message The message to log
		* @param args Additional arguments to include in the log
		*/
		info(message, ...args) {
			this.loggers.info(message, ...args);
		}
		/**
		* Logs a warning message.
		* @param message The message to log
		* @param args Additional arguments to include in the log
		*/
		warn(message, ...args) {
			this.loggers.warn(message, ...args);
		}
		/**
		* Logs an error message.
		* @param message The message to log
		* @param args Additional arguments to include in the log
		*/
		error(message, ...args) {
			this.loggers.error(message, ...args);
		}
		/**
		* Logs a debug message.
		* @param message The message to log
		* @param args Additional arguments to include in the log
		*/
		debug(message, ...args) {
			this.loggers.debug(message, ...args);
		}
	};
	exports.Logger = Logger;
	/**
	* Creates a new Logger instance with the specified namespace.
	* @param namespace The namespace to use for the logger
	* @returns A new Logger instance
	*/
	function debug(namespace) {
		return new Logger(namespace);
	}
}));
//#endregion
//#region node_modules/.pnpm/object-path@0.11.8/node_modules/object-path/index.js
var require_object_path = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	(function(root, factory) {
		"use strict";
		/*istanbul ignore next:cant test*/
		if (typeof module === "object" && typeof module.exports === "object") module.exports = factory();
		else if (typeof define === "function" && define.amd) define([], factory);
		else root.objectPath = factory();
	})(exports, function() {
		"use strict";
		var toStr = Object.prototype.toString;
		function hasOwnProperty(obj, prop) {
			if (obj == null) return false;
			return Object.prototype.hasOwnProperty.call(obj, prop);
		}
		function isEmpty(value) {
			if (!value) return true;
			if (isArray(value) && value.length === 0) return true;
			else if (typeof value !== "string") {
				for (var i in value) if (hasOwnProperty(value, i)) return false;
				return true;
			}
			return false;
		}
		function toString(type) {
			return toStr.call(type);
		}
		function isObject(obj) {
			return typeof obj === "object" && toString(obj) === "[object Object]";
		}
		var isArray = Array.isArray || function(obj) {
			/*istanbul ignore next:cant test*/
			return toStr.call(obj) === "[object Array]";
		};
		function isBoolean(obj) {
			return typeof obj === "boolean" || toString(obj) === "[object Boolean]";
		}
		function getKey(key) {
			var intKey = parseInt(key);
			if (intKey.toString() === key) return intKey;
			return key;
		}
		function factory(options) {
			options = options || {};
			var objectPath = function(obj) {
				return Object.keys(objectPath).reduce(function(proxy, prop) {
					if (prop === "create") return proxy;
					/*istanbul ignore else*/
					if (typeof objectPath[prop] === "function") proxy[prop] = objectPath[prop].bind(objectPath, obj);
					return proxy;
				}, {});
			};
			var hasShallowProperty;
			if (options.includeInheritedProps) hasShallowProperty = function() {
				return true;
			};
			else hasShallowProperty = function(obj, prop) {
				return typeof prop === "number" && Array.isArray(obj) || hasOwnProperty(obj, prop);
			};
			function getShallowProperty(obj, prop) {
				if (hasShallowProperty(obj, prop)) return obj[prop];
			}
			var getShallowPropertySafely;
			if (options.includeInheritedProps) getShallowPropertySafely = function(obj, currentPath) {
				if (typeof currentPath !== "string" && typeof currentPath !== "number") currentPath = String(currentPath);
				var currentValue = getShallowProperty(obj, currentPath);
				if (currentPath === "__proto__" || currentPath === "prototype" || currentPath === "constructor" && typeof currentValue === "function") throw new Error("For security reasons, object's magic properties cannot be set");
				return currentValue;
			};
			else getShallowPropertySafely = function(obj, currentPath) {
				return getShallowProperty(obj, currentPath);
			};
			function set(obj, path, value, doNotReplace) {
				if (typeof path === "number") path = [path];
				if (!path || path.length === 0) return obj;
				if (typeof path === "string") return set(obj, path.split(".").map(getKey), value, doNotReplace);
				var currentPath = path[0];
				var currentValue = getShallowPropertySafely(obj, currentPath);
				if (path.length === 1) {
					if (currentValue === void 0 || !doNotReplace) obj[currentPath] = value;
					return currentValue;
				}
				if (currentValue === void 0) if (typeof path[1] === "number") obj[currentPath] = [];
				else obj[currentPath] = {};
				return set(obj[currentPath], path.slice(1), value, doNotReplace);
			}
			objectPath.has = function(obj, path) {
				if (typeof path === "number") path = [path];
				else if (typeof path === "string") path = path.split(".");
				if (!path || path.length === 0) return !!obj;
				for (var i = 0; i < path.length; i++) {
					var j = getKey(path[i]);
					if (typeof j === "number" && isArray(obj) && j < obj.length || (options.includeInheritedProps ? j in Object(obj) : hasOwnProperty(obj, j))) obj = obj[j];
					else return false;
				}
				return true;
			};
			objectPath.ensureExists = function(obj, path, value) {
				return set(obj, path, value, true);
			};
			objectPath.set = function(obj, path, value, doNotReplace) {
				return set(obj, path, value, doNotReplace);
			};
			objectPath.insert = function(obj, path, value, at) {
				var arr = objectPath.get(obj, path);
				at = ~~at;
				if (!isArray(arr)) {
					arr = [];
					objectPath.set(obj, path, arr);
				}
				arr.splice(at, 0, value);
			};
			objectPath.empty = function(obj, path) {
				if (isEmpty(path)) return;
				if (obj == null) return;
				var value, i;
				if (!(value = objectPath.get(obj, path))) return;
				if (typeof value === "string") return objectPath.set(obj, path, "");
				else if (isBoolean(value)) return objectPath.set(obj, path, false);
				else if (typeof value === "number") return objectPath.set(obj, path, 0);
				else if (isArray(value)) value.length = 0;
				else if (isObject(value)) {
					for (i in value) if (hasShallowProperty(value, i)) delete value[i];
				} else return objectPath.set(obj, path, null);
			};
			objectPath.push = function(obj, path) {
				var arr = objectPath.get(obj, path);
				if (!isArray(arr)) {
					arr = [];
					objectPath.set(obj, path, arr);
				}
				arr.push.apply(arr, Array.prototype.slice.call(arguments, 2));
			};
			objectPath.coalesce = function(obj, paths, defaultValue) {
				var value;
				for (var i = 0, len = paths.length; i < len; i++) if ((value = objectPath.get(obj, paths[i])) !== void 0) return value;
				return defaultValue;
			};
			objectPath.get = function(obj, path, defaultValue) {
				if (typeof path === "number") path = [path];
				if (!path || path.length === 0) return obj;
				if (obj == null) return defaultValue;
				if (typeof path === "string") return objectPath.get(obj, path.split("."), defaultValue);
				var currentPath = getKey(path[0]);
				var nextObj = getShallowPropertySafely(obj, currentPath);
				if (nextObj === void 0) return defaultValue;
				if (path.length === 1) return nextObj;
				return objectPath.get(obj[currentPath], path.slice(1), defaultValue);
			};
			objectPath.del = function del(obj, path) {
				if (typeof path === "number") path = [path];
				if (obj == null) return obj;
				if (isEmpty(path)) return obj;
				if (typeof path === "string") return objectPath.del(obj, path.split("."));
				var currentPath = getKey(path[0]);
				getShallowPropertySafely(obj, currentPath);
				if (!hasShallowProperty(obj, currentPath)) return obj;
				if (path.length === 1) if (isArray(obj)) obj.splice(currentPath, 1);
				else delete obj[currentPath];
				else return objectPath.del(obj[currentPath], path.slice(1));
				return obj;
			};
			return objectPath;
		}
		var mod = factory();
		mod.create = factory;
		mod.withInheritedProps = factory({ includeInheritedProps: true });
		return mod;
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/authConfiguration.js
var require_authConfiguration = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.loadPrevAuthConfigFromEnv = exports.loadAuthConfigFromEnv = void 0;
	exports.getAuthConfigWithDefaults = getAuthConfigWithDefaults;
	const logger_1 = require_logger();
	const object_path_1 = __importDefault(require_object_path());
	const logger = (0, logger_1.debug)("agents:authConfiguration");
	const DEFAULT_CONNECTION = "serviceConnection";
	/**
	* Loads the authentication configuration from environment variables.
	*
	* @returns The authentication configuration.
	* @throws Will throw an error if clientId is not provided in production.
	*
	* @remarks
	* - `clientId` is required
	*
	* @example
	* ```
	* tenantId=your-tenant-id
	* clientId=your-client-id
	* clientSecret=your-client-secret
	*
	* certPemFile=your-cert-pem-file
	* certKeyFile=your-cert-key-file
	* sendX5C=false
	*
	* FICClientId=your-FIC-client-id
	*
	* connectionName=your-connection-name
	* authority=your-authority-endpoint
	* ```
	*
	*/
	const loadAuthConfigFromEnv = (cnxName) => {
		var _a, _b, _c;
		const envConnections = loadConnectionsMapFromEnv();
		let authConfig;
		if (envConnections.connectionsMap.length === 0) {
			authConfig = buildLegacyAuthConfig(cnxName);
			envConnections.connections.set(DEFAULT_CONNECTION, authConfig);
			envConnections.connectionsMap.push({
				serviceUrl: "*",
				connection: DEFAULT_CONNECTION
			});
		} else {
			if (cnxName) {
				const entry = envConnections.connections.get(cnxName);
				if (entry) authConfig = entry;
				else throw new Error(`Connection "${cnxName}" not found in environment.`);
			} else {
				const defaultItem = envConnections.connectionsMap.find((item) => item.serviceUrl === "*");
				const defaultConn = defaultItem ? envConnections.connections.get(defaultItem.connection) : void 0;
				if (!defaultConn) throw new Error("No default connection found in environment connections.");
				authConfig = defaultConn;
			}
			(_a = authConfig.authority) !== null && _a !== void 0 || (authConfig.authority = "https://login.microsoftonline.com");
			(_b = authConfig.issuers) !== null && _b !== void 0 || (authConfig.issuers = getDefaultIssuers((_c = authConfig.tenantId) !== null && _c !== void 0 ? _c : "", authConfig.authority));
		}
		return {
			...authConfig,
			...envConnections
		};
	};
	exports.loadAuthConfigFromEnv = loadAuthConfigFromEnv;
	/**
	* Loads the agent authentication configuration from previous version environment variables.
	*
	* @returns The agent authentication configuration.
	* @throws Will throw an error if MicrosoftAppId is not provided in production.
	*
	* @example
	* ```
	* MicrosoftAppId=your-client-id
	* MicrosoftAppPassword=your-client-secret
	* MicrosoftAppTenantId=your-tenant-id
	* ```
	*
	*/
	const loadPrevAuthConfigFromEnv = () => {
		var _a, _b, _c, _d, _e;
		const envConnections = loadConnectionsMapFromEnv();
		let authConfig = {};
		if (envConnections.connectionsMap.length === 0) {
			if (process.env.MicrosoftAppId === void 0 && true) throw new Error("ClientId required in production");
			const authority = (_a = process.env.authorityEndpoint) !== null && _a !== void 0 ? _a : "https://login.microsoftonline.com";
			authConfig = {
				tenantId: process.env.MicrosoftAppTenantId,
				clientId: process.env.MicrosoftAppId,
				clientSecret: process.env.MicrosoftAppPassword,
				certPemFile: process.env.certPemFile,
				certKeyFile: process.env.certKeyFile,
				sendX5C: process.env.sendX5C === "true",
				connectionName: process.env.connectionName,
				FICClientId: process.env.MicrosoftAppClientId,
				authority,
				scope: process.env.scope,
				issuers: getDefaultIssuers((_b = process.env.MicrosoftAppTenantId) !== null && _b !== void 0 ? _b : "", authority),
				altBlueprintConnectionName: process.env.altBlueprintConnectionName,
				WIDAssertionFile: process.env.WIDAssertionFile
			};
			envConnections.connections.set(DEFAULT_CONNECTION, authConfig);
			envConnections.connectionsMap.push({
				serviceUrl: "*",
				connection: DEFAULT_CONNECTION
			});
		} else {
			const defaultItem = envConnections.connectionsMap.find((item) => item.serviceUrl === "*");
			const defaultConn = defaultItem ? envConnections.connections.get(defaultItem.connection) : void 0;
			if (!defaultConn) throw new Error("No default connection found in environment connections.");
			authConfig = defaultConn;
		}
		(_c = authConfig.authority) !== null && _c !== void 0 || (authConfig.authority = "https://login.microsoftonline.com");
		(_d = authConfig.issuers) !== null && _d !== void 0 || (authConfig.issuers = getDefaultIssuers((_e = authConfig.tenantId) !== null && _e !== void 0 ? _e : "", authConfig.authority));
		return {
			...authConfig,
			...envConnections
		};
	};
	exports.loadPrevAuthConfigFromEnv = loadPrevAuthConfigFromEnv;
	function loadConnectionsMapFromEnv() {
		const envVars = process.env;
		const connectionsObj = {};
		const connectionsMap = [];
		const CONNECTIONS_PREFIX = "connections__";
		const CONNECTIONS_MAP_PREFIX = "connectionsMap__";
		for (const [key, rawValue] of Object.entries(envVars)) if (key.startsWith(CONNECTIONS_PREFIX)) {
			let path = key.substring(13).replace(/__/g, ".");
			path = path.replace(".settings.", ".");
			const value = rawValue === "true" ? true : rawValue === "false" ? false : rawValue;
			object_path_1.default.set(connectionsObj, path, value);
		} else if (key.startsWith(CONNECTIONS_MAP_PREFIX)) {
			const path = key.substring(16).replace(/__/g, ".");
			object_path_1.default.set(connectionsMap, path, rawValue);
		}
		const connections = new Map(Object.entries(connectionsObj));
		if (connections.size === 0) logger.warn("No connections found in configuration.");
		if (connectionsMap.length === 0) {
			logger.warn("No connections map found in configuration.");
			if (connections.size > 0) {
				const firstEntry = connections.entries().next().value;
				if (firstEntry) {
					const [firstKey] = firstEntry;
					connectionsMap.push({
						serviceUrl: "*",
						connection: firstKey
					});
				}
			}
		}
		return {
			connections,
			connectionsMap
		};
	}
	/**
	* Loads the authentication configuration from the provided config or from the environment variables
	* providing default values for authority and issuers.
	*
	* @returns The authentication configuration.
	* @throws Will throw an error if clientId is not provided in production.
	*
	* @example
	* ```
	* tenantId=your-tenant-id
	* clientId=your-client-id
	* clientSecret=your-client-secret
	*
	* certPemFile=your-cert-pem-file
	* certKeyFile=your-cert-key-file
	* sendX5C=false
	*
	* FICClientId=your-FIC-client-id
	*
	* connectionName=your-connection-name
	* authority=your-authority-endpoint
	* ```
	*
	*/
	function getAuthConfigWithDefaults(config) {
		var _a, _b, _c, _d;
		if (!config) return (0, exports.loadAuthConfigFromEnv)();
		const providedConnections = config.connections && config.connectionsMap ? {
			connections: config.connections,
			connectionsMap: config.connectionsMap
		} : void 0;
		const connections = providedConnections !== null && providedConnections !== void 0 ? providedConnections : loadConnectionsMapFromEnv();
		let mergedConfig;
		if (connections && ((_a = connections.connectionsMap) === null || _a === void 0 ? void 0 : _a.length) === 0) {
			mergedConfig = buildLegacyAuthConfig(void 0, config);
			(_b = connections.connections) === null || _b === void 0 || _b.set(DEFAULT_CONNECTION, mergedConfig);
			connections.connectionsMap.push({
				serviceUrl: "*",
				connection: DEFAULT_CONNECTION
			});
		} else {
			const defaultItem = (_c = connections.connectionsMap) === null || _c === void 0 ? void 0 : _c.find((item) => item.serviceUrl === "*");
			const defaultConn = defaultItem ? (_d = connections.connections) === null || _d === void 0 ? void 0 : _d.get(defaultItem.connection) : void 0;
			if (!defaultConn) throw new Error("No default connection found in environment connections.");
			mergedConfig = buildLegacyAuthConfig(void 0, defaultConn);
		}
		return {
			...mergedConfig,
			...connections
		};
	}
	function buildLegacyAuthConfig(envPrefix = "", customConfig) {
		var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
		const prefix = envPrefix ? `${envPrefix}_` : "";
		const authority = (_b = (_a = customConfig === null || customConfig === void 0 ? void 0 : customConfig.authority) !== null && _a !== void 0 ? _a : process.env[`${prefix}authorityEndpoint`]) !== null && _b !== void 0 ? _b : "https://login.microsoftonline.com";
		const clientId = (_c = customConfig === null || customConfig === void 0 ? void 0 : customConfig.clientId) !== null && _c !== void 0 ? _c : process.env[`${prefix}clientId`];
		if (!clientId && !envPrefix && true) throw new Error("ClientId required in production");
		if (!clientId && envPrefix) throw new Error(`ClientId not found for connection: ${envPrefix}`);
		const tenantId = (_d = customConfig === null || customConfig === void 0 ? void 0 : customConfig.tenantId) !== null && _d !== void 0 ? _d : process.env[`${prefix}tenantId`];
		return {
			tenantId,
			clientId,
			clientSecret: (_e = customConfig === null || customConfig === void 0 ? void 0 : customConfig.clientSecret) !== null && _e !== void 0 ? _e : process.env[`${prefix}clientSecret`],
			certPemFile: (_f = customConfig === null || customConfig === void 0 ? void 0 : customConfig.certPemFile) !== null && _f !== void 0 ? _f : process.env[`${prefix}certPemFile`],
			certKeyFile: (_g = customConfig === null || customConfig === void 0 ? void 0 : customConfig.certKeyFile) !== null && _g !== void 0 ? _g : process.env[`${prefix}certKeyFile`],
			sendX5C: (_h = customConfig === null || customConfig === void 0 ? void 0 : customConfig.sendX5C) !== null && _h !== void 0 ? _h : process.env[`${prefix}sendX5C`] === "true",
			connectionName: (_j = customConfig === null || customConfig === void 0 ? void 0 : customConfig.connectionName) !== null && _j !== void 0 ? _j : process.env[`${prefix}connectionName`],
			FICClientId: (_k = customConfig === null || customConfig === void 0 ? void 0 : customConfig.FICClientId) !== null && _k !== void 0 ? _k : process.env[`${prefix}FICClientId`],
			authority,
			scope: (_l = customConfig === null || customConfig === void 0 ? void 0 : customConfig.scope) !== null && _l !== void 0 ? _l : process.env[`${prefix}scope`],
			issuers: (_m = customConfig === null || customConfig === void 0 ? void 0 : customConfig.issuers) !== null && _m !== void 0 ? _m : getDefaultIssuers(tenantId, authority),
			altBlueprintConnectionName: (_o = customConfig === null || customConfig === void 0 ? void 0 : customConfig.altBlueprintConnectionName) !== null && _o !== void 0 ? _o : process.env[`${prefix}altBlueprintConnectionName`],
			WIDAssertionFile: (_p = customConfig === null || customConfig === void 0 ? void 0 : customConfig.WIDAssertionFile) !== null && _p !== void 0 ? _p : process.env[`${prefix}WIDAssertionFile`]
		};
	}
	function getDefaultIssuers(tenantId, authority) {
		return [
			"https://api.botframework.com",
			`https://sts.windows.net/${tenantId}/`,
			`${authority}/${tenantId}/v2.0`
		];
	}
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/authConstants.js
var require_authConstants = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ApxGallatinScope = exports.ApxDoDScope = exports.ApxGCCHScope = exports.ApxGCCScope = exports.ApxProductionScope = exports.ApxDevScope = exports.ApxLocalScope = void 0;
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	exports.ApxLocalScope = "c16e153d-5d2b-4c21-b7f4-b05ee5d516f1/.default";
	exports.ApxDevScope = "0d94caae-b412-4943-8a68-83135ad6d35f/.default";
	exports.ApxProductionScope = "5a807f24-c9de-44ee-a3a7-329e88a00ffc/.default";
	exports.ApxGCCScope = "c9475445-9789-4fef-9ec5-cde4a9bcd446/.default";
	exports.ApxGCCHScope = "6f669b9e-7701-4e2b-b624-82c9207fde26/.default";
	exports.ApxDoDScope = "0a069c81-8c7c-4712-886b-9c542d673ffb/.default";
	exports.ApxGallatinScope = "bd004c8e-5acf-4c48-8570-4e7d46b2f63b/.default";
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/authProvider.js
var require_authProvider = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@azure+msal-node@5.0.5/node_modules/@azure/msal-node/lib/msal-node.cjs
/*! @azure/msal-node v5.0.5 2026-02-24 */
var require_msal_node = /* @__PURE__ */ __commonJSMin(((exports) => {
	var uuid$1 = __require("uuid");
	var crypto$3 = __require("crypto");
	var jwt = require_jsonwebtoken();
	var http$2 = __require("http");
	var fs = __require("fs");
	var path = __require("path");
	/**
	* This class serializes cache entities to be saved into in-memory object types defined internally
	* @internal
	*/
	var Serializer = class {
		/**
		* serialize the JSON blob
		* @param data - JSON blob cache
		*/
		static serializeJSONBlob(data) {
			return JSON.stringify(data);
		}
		/**
		* Serialize Accounts
		* @param accCache - cache of accounts
		*/
		static serializeAccounts(accCache) {
			const accounts = {};
			Object.keys(accCache).map(function(key) {
				const accountEntity = accCache[key];
				accounts[key] = {
					home_account_id: accountEntity.homeAccountId,
					environment: accountEntity.environment,
					realm: accountEntity.realm,
					local_account_id: accountEntity.localAccountId,
					username: accountEntity.username,
					authority_type: accountEntity.authorityType,
					name: accountEntity.name,
					client_info: accountEntity.clientInfo,
					last_modification_time: accountEntity.lastModificationTime,
					last_modification_app: accountEntity.lastModificationApp,
					tenantProfiles: accountEntity.tenantProfiles?.map((tenantProfile) => {
						return JSON.stringify(tenantProfile);
					})
				};
			});
			return accounts;
		}
		/**
		* Serialize IdTokens
		* @param idTCache - cache of ID tokens
		*/
		static serializeIdTokens(idTCache) {
			const idTokens = {};
			Object.keys(idTCache).map(function(key) {
				const idTEntity = idTCache[key];
				idTokens[key] = {
					home_account_id: idTEntity.homeAccountId,
					environment: idTEntity.environment,
					credential_type: idTEntity.credentialType,
					client_id: idTEntity.clientId,
					secret: idTEntity.secret,
					realm: idTEntity.realm
				};
			});
			return idTokens;
		}
		/**
		* Serializes AccessTokens
		* @param atCache - cache of access tokens
		*/
		static serializeAccessTokens(atCache) {
			const accessTokens = {};
			Object.keys(atCache).map(function(key) {
				const atEntity = atCache[key];
				accessTokens[key] = {
					home_account_id: atEntity.homeAccountId,
					environment: atEntity.environment,
					credential_type: atEntity.credentialType,
					client_id: atEntity.clientId,
					secret: atEntity.secret,
					realm: atEntity.realm,
					target: atEntity.target,
					cached_at: atEntity.cachedAt,
					expires_on: atEntity.expiresOn,
					extended_expires_on: atEntity.extendedExpiresOn,
					refresh_on: atEntity.refreshOn,
					key_id: atEntity.keyId,
					token_type: atEntity.tokenType,
					userAssertionHash: atEntity.userAssertionHash
				};
			});
			return accessTokens;
		}
		/**
		* Serialize refreshTokens
		* @param rtCache - cache of refresh tokens
		*/
		static serializeRefreshTokens(rtCache) {
			const refreshTokens = {};
			Object.keys(rtCache).map(function(key) {
				const rtEntity = rtCache[key];
				refreshTokens[key] = {
					home_account_id: rtEntity.homeAccountId,
					environment: rtEntity.environment,
					credential_type: rtEntity.credentialType,
					client_id: rtEntity.clientId,
					secret: rtEntity.secret,
					family_id: rtEntity.familyId,
					target: rtEntity.target,
					realm: rtEntity.realm
				};
			});
			return refreshTokens;
		}
		/**
		* Serialize amdtCache
		* @param amdtCache - cache of app metadata
		*/
		static serializeAppMetadata(amdtCache) {
			const appMetadata = {};
			Object.keys(amdtCache).map(function(key) {
				const amdtEntity = amdtCache[key];
				appMetadata[key] = {
					client_id: amdtEntity.clientId,
					environment: amdtEntity.environment,
					family_id: amdtEntity.familyId
				};
			});
			return appMetadata;
		}
		/**
		* Serialize the cache
		* @param inMemCache - itemised cache read from the JSON
		*/
		static serializeAllCache(inMemCache) {
			return {
				Account: this.serializeAccounts(inMemCache.accounts),
				IdToken: this.serializeIdTokens(inMemCache.idTokens),
				AccessToken: this.serializeAccessTokens(inMemCache.accessTokens),
				RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens),
				AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata)
			};
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const SKU = "msal.js.common";
	const DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common/";
	const DEFAULT_AUTHORITY_HOST = "login.microsoftonline.com";
	const DEFAULT_COMMON_TENANT = "common";
	const ADFS = "adfs";
	const DSTS = "dstsv2";
	const AAD_INSTANCE_DISCOVERY_ENDPT = `${DEFAULT_AUTHORITY}discovery/instance?api-version=1.1&authorization_endpoint=`;
	const CIAM_AUTH_URL = ".ciamlogin.com";
	const AAD_TENANT_DOMAIN_SUFFIX = ".onmicrosoft.com";
	const RESOURCE_DELIM = "|";
	const OPENID_SCOPE = "openid";
	const PROFILE_SCOPE = "profile";
	const OFFLINE_ACCESS_SCOPE = "offline_access";
	const EMAIL_SCOPE = "email";
	const URL_FORM_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8";
	const AUTHORIZATION_PENDING = "authorization_pending";
	const NOT_APPLICABLE = "N/A";
	const NOT_AVAILABLE = "Not Available";
	const FORWARD_SLASH = "/";
	const IMDS_ENDPOINT = "http://169.254.169.254/metadata/instance/compute/location";
	const IMDS_VERSION = "2020-06-01";
	const IMDS_TIMEOUT = 2e3;
	const AZURE_REGION_AUTO_DISCOVER_FLAG = "TryAutoDetect";
	const REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX = "login.microsoft.com";
	const KNOWN_PUBLIC_CLOUDS = [
		"login.microsoftonline.com",
		"login.windows.net",
		"login.microsoft.com",
		"sts.windows.net"
	];
	const INVALID_INSTANCE = "invalid_instance";
	const HTTP_SUCCESS = 200;
	const HTTP_REDIRECT = 302;
	const HTTP_CLIENT_ERROR_RANGE_START = 400;
	const HTTP_BAD_REQUEST = 400;
	const HTTP_UNAUTHORIZED = 401;
	const HTTP_NOT_FOUND = 404;
	const HTTP_REQUEST_TIMEOUT = 408;
	const HTTP_GONE = 410;
	const HTTP_TOO_MANY_REQUESTS = 429;
	const HTTP_CLIENT_ERROR_RANGE_END = 499;
	const HTTP_SERVER_ERROR = 500;
	const HTTP_SERVER_ERROR_RANGE_START = 500;
	const HTTP_SERVICE_UNAVAILABLE = 503;
	const HTTP_GATEWAY_TIMEOUT = 504;
	const HTTP_SERVER_ERROR_RANGE_END = 599;
	const OIDC_DEFAULT_SCOPES = [
		OPENID_SCOPE,
		PROFILE_SCOPE,
		OFFLINE_ACCESS_SCOPE
	];
	const OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES, EMAIL_SCOPE];
	/**
	* Request header names
	*/
	const HeaderNames = {
		CONTENT_TYPE: "Content-Type",
		CONTENT_LENGTH: "Content-Length",
		RETRY_AFTER: "Retry-After",
		CCS_HEADER: "X-AnchorMailbox",
		WWWAuthenticate: "WWW-Authenticate",
		AuthenticationInfo: "Authentication-Info",
		X_MS_REQUEST_ID: "x-ms-request-id",
		X_MS_HTTP_VERSION: "x-ms-httpver"
	};
	/**
	* String constants related to AAD Authority
	*/
	const AADAuthority = {
		COMMON: "common",
		ORGANIZATIONS: "organizations",
		CONSUMERS: "consumers"
	};
	/**
	* Claims request keys
	*/
	const ClaimsRequestKeys = {
		ACCESS_TOKEN: "access_token",
		XMS_CC: "xms_cc"
	};
	/**
	* we considered making this "enum" in the request instead of string, however it looks like the allowed list of
	* prompt values kept changing over past couple of years. There are some undocumented prompt values for some
	* internal partners too, hence the choice of generic "string" type instead of the "enum"
	*/
	const PromptValue$1 = {
		LOGIN: "login",
		SELECT_ACCOUNT: "select_account",
		CONSENT: "consent",
		NONE: "none",
		CREATE: "create",
		NO_SESSION: "no_session"
	};
	/**
	* allowed values for codeVerifier
	*/
	const CodeChallengeMethodValues = { S256: "S256" };
	/**
	* Allowed values for response_type
	*/
	const OAuthResponseType = {
		CODE: "code",
		IDTOKEN_TOKEN: "id_token token"
	};
	/**
	* allowed values for response_mode
	*/
	const ResponseMode$1 = {
		QUERY: "query",
		FRAGMENT: "fragment",
		FORM_POST: "form_post"
	};
	/**
	* allowed grant_type
	*/
	const GrantType = {
		AUTHORIZATION_CODE_GRANT: "authorization_code",
		CLIENT_CREDENTIALS_GRANT: "client_credentials",
		RESOURCE_OWNER_PASSWORD_GRANT: "password",
		REFRESH_TOKEN_GRANT: "refresh_token",
		DEVICE_CODE_GRANT: "device_code",
		JWT_BEARER: "urn:ietf:params:oauth:grant-type:jwt-bearer"
	};
	/**
	* Account types in Cache
	*/
	const CACHE_ACCOUNT_TYPE_MSSTS = "MSSTS";
	const CACHE_ACCOUNT_TYPE_ADFS = "ADFS";
	const CACHE_ACCOUNT_TYPE_GENERIC = "Generic";
	/**
	* Separators used in cache
	*/
	const CACHE_KEY_SEPARATOR = "-";
	const CLIENT_INFO_SEPARATOR = ".";
	/**
	* Credential Type stored in the cache
	*/
	const CredentialType = {
		ID_TOKEN: "IdToken",
		ACCESS_TOKEN: "AccessToken",
		ACCESS_TOKEN_WITH_AUTH_SCHEME: "AccessToken_With_AuthScheme",
		REFRESH_TOKEN: "RefreshToken"
	};
	/**
	* More Cache related constants
	*/
	const APP_METADATA = "appmetadata";
	const CLIENT_INFO = "client_info";
	const THE_FAMILY_ID = "1";
	const AUTHORITY_METADATA_CACHE_KEY = "authority-metadata";
	const AUTHORITY_METADATA_REFRESH_TIME_SECONDS = 3600 * 24;
	const AuthorityMetadataSource = {
		CONFIG: "config",
		CACHE: "cache",
		NETWORK: "network",
		HARDCODED_VALUES: "hardcoded_values"
	};
	const SERVER_TELEM_SCHEMA_VERSION = 5;
	const SERVER_TELEM_MAX_LAST_HEADER_BYTES = 330;
	const SERVER_TELEM_MAX_CACHED_ERRORS = 50;
	const SERVER_TELEM_CACHE_KEY = "server-telemetry";
	const SERVER_TELEM_CATEGORY_SEPARATOR = "|";
	const SERVER_TELEM_VALUE_SEPARATOR = ",";
	const SERVER_TELEM_OVERFLOW_TRUE = "1";
	const SERVER_TELEM_OVERFLOW_FALSE = "0";
	const SERVER_TELEM_UNKNOWN_ERROR = "unknown_error";
	/**
	* Type of the authentication request
	*/
	const AuthenticationScheme = {
		BEARER: "Bearer",
		POP: "pop",
		SSH: "ssh-cert"
	};
	/**
	* Constants related to throttling
	*/
	const DEFAULT_THROTTLE_TIME_SECONDS = 60;
	const DEFAULT_MAX_THROTTLE_TIME_SECONDS = 3600;
	const THROTTLING_PREFIX = "throttling";
	const X_MS_LIB_CAPABILITY_VALUE = "retry-after, h429";
	/**
	* Errors
	*/
	const INVALID_GRANT_ERROR = "invalid_grant";
	const CLIENT_MISMATCH_ERROR = "client_mismatch";
	/**
	* Password grant parameters
	*/
	const PasswordGrantConstants = {
		username: "username",
		password: "password"
	};
	/**
	* Region Discovery Sources
	*/
	const RegionDiscoverySources = {
		FAILED_AUTO_DETECTION: "1",
		INTERNAL_CACHE: "2",
		ENVIRONMENT_VARIABLE: "3",
		IMDS: "4"
	};
	/**
	* Region Discovery Outcomes
	*/
	const RegionDiscoveryOutcomes = {
		CONFIGURED_NO_AUTO_DETECTION: "2",
		AUTO_DETECTION_REQUESTED_SUCCESSFUL: "4",
		AUTO_DETECTION_REQUESTED_FAILED: "5"
	};
	/**
	* Specifies the reason for fetching the access token from the identity provider
	*/
	const CacheOutcome = {
		NOT_APPLICABLE: "0",
		FORCE_REFRESH_OR_CLAIMS: "1",
		NO_CACHED_ACCESS_TOKEN: "2",
		CACHED_ACCESS_TOKEN_EXPIRED: "3",
		PROACTIVELY_REFRESHED: "4"
	};
	const DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;
	const EncodingTypes = {
		BASE64: "base64",
		HEX: "hex",
		UTF8: "utf-8"
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const CLIENT_ID = "client_id";
	const REDIRECT_URI = "redirect_uri";
	const RESPONSE_TYPE = "response_type";
	const RESPONSE_MODE = "response_mode";
	const GRANT_TYPE = "grant_type";
	const CLAIMS = "claims";
	const SCOPE = "scope";
	const REFRESH_TOKEN = "refresh_token";
	const STATE = "state";
	const NONCE = "nonce";
	const PROMPT = "prompt";
	const CODE = "code";
	const CODE_CHALLENGE = "code_challenge";
	const CODE_CHALLENGE_METHOD = "code_challenge_method";
	const CODE_VERIFIER = "code_verifier";
	const CLIENT_REQUEST_ID = "client-request-id";
	const X_CLIENT_SKU = "x-client-SKU";
	const X_CLIENT_VER = "x-client-VER";
	const X_CLIENT_OS = "x-client-OS";
	const X_CLIENT_CPU = "x-client-CPU";
	const X_CLIENT_CURR_TELEM = "x-client-current-telemetry";
	const X_CLIENT_LAST_TELEM = "x-client-last-telemetry";
	const X_MS_LIB_CAPABILITY = "x-ms-lib-capability";
	const X_APP_NAME = "x-app-name";
	const X_APP_VER = "x-app-ver";
	const POST_LOGOUT_URI = "post_logout_redirect_uri";
	const ID_TOKEN_HINT = "id_token_hint";
	const DEVICE_CODE = "device_code";
	const CLIENT_SECRET = "client_secret";
	const CLIENT_ASSERTION = "client_assertion";
	const CLIENT_ASSERTION_TYPE = "client_assertion_type";
	const TOKEN_TYPE = "token_type";
	const REQ_CNF = "req_cnf";
	const OBO_ASSERTION = "assertion";
	const REQUESTED_TOKEN_USE = "requested_token_use";
	const ON_BEHALF_OF = "on_behalf_of";
	const RETURN_SPA_CODE = "return_spa_code";
	const LOGOUT_HINT = "logout_hint";
	const SID = "sid";
	const LOGIN_HINT = "login_hint";
	const DOMAIN_HINT = "domain_hint";
	const X_CLIENT_EXTRA_SKU = "x-client-xtra-sku";
	const BROKER_CLIENT_ID = "brk_client_id";
	const BROKER_REDIRECT_URI = "brk_redirect_uri";
	const INSTANCE_AWARE = "instance_aware";
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	function getDefaultErrorMessage(code) {
		return `See https://aka.ms/msal.js.errors#${code} for details`;
	}
	/**
	* General error class thrown by the MSAL.js library.
	*/
	var AuthError = class AuthError extends Error {
		constructor(errorCode, errorMessage, suberror) {
			const message = errorMessage || (errorCode ? getDefaultErrorMessage(errorCode) : "");
			const errorString = message ? `${errorCode}: ${message}` : errorCode;
			super(errorString);
			Object.setPrototypeOf(this, AuthError.prototype);
			this.errorCode = errorCode || "";
			this.errorMessage = message || "";
			this.subError = suberror || "";
			this.name = "AuthError";
		}
		setCorrelationId(correlationId) {
			this.correlationId = correlationId;
		}
	};
	function createAuthError(code, additionalMessage) {
		return new AuthError(code, additionalMessage || getDefaultErrorMessage(code));
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Error thrown when there is an error in configuration of the MSAL.js library.
	*/
	var ClientConfigurationError = class ClientConfigurationError extends AuthError {
		constructor(errorCode) {
			super(errorCode);
			this.name = "ClientConfigurationError";
			Object.setPrototypeOf(this, ClientConfigurationError.prototype);
		}
	};
	function createClientConfigurationError(errorCode) {
		return new ClientConfigurationError(errorCode);
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* @hidden
	*/
	var StringUtils = class {
		/**
		* Check if stringified object is empty
		* @param strObj
		*/
		static isEmptyObj(strObj) {
			if (strObj) try {
				const obj = JSON.parse(strObj);
				return Object.keys(obj).length === 0;
			} catch (e) {}
			return true;
		}
		static startsWith(str, search) {
			return str.indexOf(search) === 0;
		}
		static endsWith(str, search) {
			return str.length >= search.length && str.lastIndexOf(search) === str.length - search.length;
		}
		/**
		* Parses string into an object.
		*
		* @param query
		*/
		static queryStringToObject(query) {
			const obj = {};
			const params = query.split("&");
			const decode = (s) => decodeURIComponent(s.replace(/\+/g, " "));
			params.forEach((pair) => {
				if (pair.trim()) {
					const [key, value] = pair.split(/=(.+)/g, 2);
					if (key && value) obj[decode(key)] = decode(value);
				}
			});
			return obj;
		}
		/**
		* Trims entries in an array.
		*
		* @param arr
		*/
		static trimArrayEntries(arr) {
			return arr.map((entry) => entry.trim());
		}
		/**
		* Removes empty strings from array
		* @param arr
		*/
		static removeEmptyStringsFromArray(arr) {
			return arr.filter((entry) => {
				return !!entry;
			});
		}
		/**
		* Attempts to parse a string into JSON
		* @param str
		*/
		static jsonParseHelper(str) {
			try {
				return JSON.parse(str);
			} catch (e) {
				return null;
			}
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* ClientAuthErrorMessage class containing string constants used by error codes and messages.
	*/
	/**
	* Error thrown when there is an error in the client code running on the browser.
	*/
	var ClientAuthError = class ClientAuthError extends AuthError {
		constructor(errorCode, additionalMessage) {
			super(errorCode, additionalMessage);
			this.name = "ClientAuthError";
			Object.setPrototypeOf(this, ClientAuthError.prototype);
		}
	};
	function createClientAuthError(errorCode, additionalMessage) {
		return new ClientAuthError(errorCode, additionalMessage);
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const redirectUriEmpty = "redirect_uri_empty";
	const claimsRequestParsingError = "claims_request_parsing_error";
	const authorityUriInsecure = "authority_uri_insecure";
	const urlParseError = "url_parse_error";
	const urlEmptyError = "empty_url_error";
	const emptyInputScopesError = "empty_input_scopes_error";
	const invalidClaims = "invalid_claims";
	const tokenRequestEmpty = "token_request_empty";
	const logoutRequestEmpty = "logout_request_empty";
	const invalidCodeChallengeMethod = "invalid_code_challenge_method";
	const pkceParamsMissing = "pkce_params_missing";
	const invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata";
	const invalidAuthorityMetadata = "invalid_authority_metadata";
	const untrustedAuthority = "untrusted_authority";
	const missingSshJwk = "missing_ssh_jwk";
	var ClientConfigurationErrorCodes = /* @__PURE__ */ Object.freeze({
		__proto__: null,
		authorityMismatch: "authority_mismatch",
		authorityUriInsecure,
		cannotAllowPlatformBroker: "cannot_allow_platform_broker",
		cannotSetOIDCOptions: "cannot_set_OIDCOptions",
		claimsRequestParsingError,
		emptyInputScopesError,
		invalidAuthenticationHeader: "invalid_authentication_header",
		invalidAuthorityMetadata,
		invalidClaims,
		invalidCloudDiscoveryMetadata,
		invalidCodeChallengeMethod,
		invalidRequestMethodForEAR: "invalid_request_method_for_EAR",
		logoutRequestEmpty,
		missingNonceAuthenticationHeader: "missing_nonce_authentication_header",
		missingSshJwk,
		missingSshKid: "missing_ssh_kid",
		pkceParamsMissing,
		redirectUriEmpty,
		tokenRequestEmpty,
		untrustedAuthority,
		urlEmptyError,
		urlParseError
	});
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const clientInfoDecodingError = "client_info_decoding_error";
	const clientInfoEmptyError = "client_info_empty_error";
	const tokenParsingError = "token_parsing_error";
	const nullOrEmptyToken = "null_or_empty_token";
	const endpointResolutionError = "endpoints_resolution_error";
	const networkError = "network_error";
	const openIdConfigError = "openid_config_error";
	const hashNotDeserialized = "hash_not_deserialized";
	const invalidState = "invalid_state";
	const stateMismatch = "state_mismatch";
	const stateNotFound = "state_not_found";
	const nonceMismatch = "nonce_mismatch";
	const authTimeNotFound = "auth_time_not_found";
	const maxAgeTranspired = "max_age_transpired";
	const multipleMatchingTokens = "multiple_matching_tokens";
	const multipleMatchingAppMetadata = "multiple_matching_appMetadata";
	const requestCannotBeMade = "request_cannot_be_made";
	const cannotRemoveEmptyScope = "cannot_remove_empty_scope";
	const cannotAppendScopeSet = "cannot_append_scopeset";
	const emptyInputScopeSet = "empty_input_scopeset";
	const noAccountInSilentRequest = "no_account_in_silent_request";
	const invalidCacheRecord = "invalid_cache_record";
	const invalidCacheEnvironment = "invalid_cache_environment";
	const noAccountFound = "no_account_found";
	const noCryptoObject = "no_crypto_object";
	const unexpectedCredentialType = "unexpected_credential_type";
	const tokenRefreshRequired = "token_refresh_required";
	const tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt";
	const authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response";
	const bindingKeyNotRemoved = "binding_key_not_removed";
	const endSessionEndpointNotSupported = "end_session_endpoint_not_supported";
	const keyIdMissing = "key_id_missing";
	const noNetworkConnectivity = "no_network_connectivity";
	const userCanceled = "user_canceled";
	const methodNotImplemented = "method_not_implemented";
	var ClientAuthErrorCodes = /* @__PURE__ */ Object.freeze({
		__proto__: null,
		authTimeNotFound,
		authorizationCodeMissingFromServerResponse,
		bindingKeyNotRemoved,
		cannotAppendScopeSet,
		cannotRemoveEmptyScope,
		clientInfoDecodingError,
		clientInfoEmptyError,
		emptyInputScopeSet,
		endSessionEndpointNotSupported,
		endpointResolutionError,
		hashNotDeserialized,
		invalidCacheEnvironment,
		invalidCacheRecord,
		invalidState,
		keyIdMissing,
		maxAgeTranspired,
		methodNotImplemented,
		multipleMatchingAppMetadata,
		multipleMatchingTokens,
		nestedAppAuthBridgeDisabled: "nested_app_auth_bridge_disabled",
		networkError,
		noAccountFound,
		noAccountInSilentRequest,
		noCryptoObject,
		noNetworkConnectivity,
		nonceMismatch,
		nullOrEmptyToken,
		openIdConfigError,
		platformBrokerError: "platform_broker_error",
		requestCannotBeMade,
		stateMismatch,
		stateNotFound,
		tokenClaimsCnfRequiredForSignedJwt,
		tokenParsingError,
		tokenRefreshRequired,
		unexpectedCredentialType,
		userCanceled
	});
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* The ScopeSet class creates a set of scopes. Scopes are case-insensitive, unique values, so the Set object in JS makes
	* the most sense to implement for this class. All scopes are trimmed and converted to lower case strings in intersection and union functions
	* to ensure uniqueness of strings.
	*/
	var ScopeSet = class ScopeSet {
		constructor(inputScopes) {
			const scopeArr = inputScopes ? StringUtils.trimArrayEntries([...inputScopes]) : [];
			const filteredInput = scopeArr ? StringUtils.removeEmptyStringsFromArray(scopeArr) : [];
			if (!filteredInput || !filteredInput.length) throw createClientConfigurationError(emptyInputScopesError);
			this.scopes = /* @__PURE__ */ new Set();
			filteredInput.forEach((scope) => this.scopes.add(scope));
		}
		/**
		* Factory method to create ScopeSet from space-delimited string
		* @param inputScopeString
		* @param appClientId
		* @param scopesRequired
		*/
		static fromString(inputScopeString) {
			return new ScopeSet((inputScopeString || "").split(" "));
		}
		/**
		* Creates the set of scopes to search for in cache lookups
		* @param inputScopeString
		* @returns
		*/
		static createSearchScopes(inputScopeString) {
			const scopeSet = new ScopeSet(inputScopeString && inputScopeString.length > 0 ? inputScopeString : [...OIDC_DEFAULT_SCOPES]);
			if (!scopeSet.containsOnlyOIDCScopes()) scopeSet.removeOIDCScopes();
			else scopeSet.removeScope(OFFLINE_ACCESS_SCOPE);
			return scopeSet;
		}
		/**
		* Check if a given scope is present in this set of scopes.
		* @param scope
		*/
		containsScope(scope) {
			const lowerCaseScopesSet = new ScopeSet(this.printScopesLowerCase().split(" "));
			return scope ? lowerCaseScopesSet.scopes.has(scope.toLowerCase()) : false;
		}
		/**
		* Check if a set of scopes is present in this set of scopes.
		* @param scopeSet
		*/
		containsScopeSet(scopeSet) {
			if (!scopeSet || scopeSet.scopes.size <= 0) return false;
			return this.scopes.size >= scopeSet.scopes.size && scopeSet.asArray().every((scope) => this.containsScope(scope));
		}
		/**
		* Check if set of scopes contains only the defaults
		*/
		containsOnlyOIDCScopes() {
			let defaultScopeCount = 0;
			OIDC_SCOPES.forEach((defaultScope) => {
				if (this.containsScope(defaultScope)) defaultScopeCount += 1;
			});
			return this.scopes.size === defaultScopeCount;
		}
		/**
		* Appends single scope if passed
		* @param newScope
		*/
		appendScope(newScope) {
			if (newScope) this.scopes.add(newScope.trim());
		}
		/**
		* Appends multiple scopes if passed
		* @param newScopes
		*/
		appendScopes(newScopes) {
			try {
				newScopes.forEach((newScope) => this.appendScope(newScope));
			} catch (e) {
				throw createClientAuthError(cannotAppendScopeSet);
			}
		}
		/**
		* Removes element from set of scopes.
		* @param scope
		*/
		removeScope(scope) {
			if (!scope) throw createClientAuthError(cannotRemoveEmptyScope);
			this.scopes.delete(scope.trim());
		}
		/**
		* Removes default scopes from set of scopes
		* Primarily used to prevent cache misses if the default scopes are not returned from the server
		*/
		removeOIDCScopes() {
			OIDC_SCOPES.forEach((defaultScope) => {
				this.scopes.delete(defaultScope);
			});
		}
		/**
		* Combines an array of scopes with the current set of scopes.
		* @param otherScopes
		*/
		unionScopeSets(otherScopes) {
			if (!otherScopes) throw createClientAuthError(emptyInputScopeSet);
			const unionScopes = /* @__PURE__ */ new Set();
			otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
			this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
			return unionScopes;
		}
		/**
		* Check if scopes intersect between this set and another.
		* @param otherScopes
		*/
		intersectingScopeSets(otherScopes) {
			if (!otherScopes) throw createClientAuthError(emptyInputScopeSet);
			if (!otherScopes.containsOnlyOIDCScopes()) otherScopes.removeOIDCScopes();
			const unionScopes = this.unionScopeSets(otherScopes);
			const sizeOtherScopes = otherScopes.getScopeCount();
			const sizeThisScopes = this.getScopeCount();
			return unionScopes.size < sizeThisScopes + sizeOtherScopes;
		}
		/**
		* Returns size of set of scopes.
		*/
		getScopeCount() {
			return this.scopes.size;
		}
		/**
		* Returns the scopes as an array of string values
		*/
		asArray() {
			const array = [];
			this.scopes.forEach((val) => array.push(val));
			return array;
		}
		/**
		* Prints scopes into a space-delimited string
		*/
		printScopes() {
			if (this.scopes) return this.asArray().join(" ");
			return "";
		}
		/**
		* Prints scopes into a space-delimited lower-case string (used for caching)
		*/
		printScopesLowerCase() {
			return this.printScopes().toLowerCase();
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	function instrumentBrokerParams(parameters, correlationId, performanceClient) {
		if (!correlationId) return;
		const clientId = parameters.get(CLIENT_ID);
		if (clientId && parameters.has(BROKER_CLIENT_ID)) performanceClient?.addFields({
			embeddedClientId: clientId,
			embeddedRedirectUri: parameters.get(REDIRECT_URI)
		}, correlationId);
	}
	/**
	* Add the given response_type
	* @param parameters
	* @param responseType
	*/
	function addResponseType(parameters, responseType) {
		parameters.set(RESPONSE_TYPE, responseType);
	}
	/**
	* add response_mode. defaults to query.
	* @param responseMode
	*/
	function addResponseMode(parameters, responseMode) {
		parameters.set(RESPONSE_MODE, responseMode ? responseMode : ResponseMode$1.QUERY);
	}
	/**
	* add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios
	* @param scopeSet
	* @param addOidcScopes
	*/
	function addScopes(parameters, scopes, addOidcScopes = true, defaultScopes = OIDC_DEFAULT_SCOPES) {
		if (addOidcScopes && !defaultScopes.includes("openid") && !scopes.includes("openid")) defaultScopes.push("openid");
		const scopeSet = new ScopeSet(addOidcScopes ? [...scopes || [], ...defaultScopes] : scopes || []);
		parameters.set(SCOPE, scopeSet.printScopes());
	}
	/**
	* add clientId
	* @param clientId
	*/
	function addClientId(parameters, clientId) {
		parameters.set(CLIENT_ID, clientId);
	}
	/**
	* add redirect_uri
	* @param redirectUri
	*/
	function addRedirectUri(parameters, redirectUri) {
		parameters.set(REDIRECT_URI, redirectUri);
	}
	/**
	* add post logout redirectUri
	* @param redirectUri
	*/
	function addPostLogoutRedirectUri(parameters, redirectUri) {
		parameters.set(POST_LOGOUT_URI, redirectUri);
	}
	/**
	* add id_token_hint to logout request
	* @param idTokenHint
	*/
	function addIdTokenHint(parameters, idTokenHint) {
		parameters.set(ID_TOKEN_HINT, idTokenHint);
	}
	/**
	* add domain_hint
	* @param domainHint
	*/
	function addDomainHint(parameters, domainHint) {
		parameters.set(DOMAIN_HINT, domainHint);
	}
	/**
	* add login_hint
	* @param loginHint
	*/
	function addLoginHint(parameters, loginHint) {
		parameters.set(LOGIN_HINT, loginHint);
	}
	/**
	* Adds the CCS (Cache Credential Service) query parameter for login_hint
	* @param loginHint
	*/
	function addCcsUpn(parameters, loginHint) {
		parameters.set(HeaderNames.CCS_HEADER, `UPN:${loginHint}`);
	}
	/**
	* Adds the CCS (Cache Credential Service) query parameter for account object
	* @param loginHint
	*/
	function addCcsOid(parameters, clientInfo) {
		parameters.set(HeaderNames.CCS_HEADER, `Oid:${clientInfo.uid}@${clientInfo.utid}`);
	}
	/**
	* add sid
	* @param sid
	*/
	function addSid(parameters, sid) {
		parameters.set(SID, sid);
	}
	/**
	* add claims
	* @param claims
	*/
	function addClaims(parameters, claims, clientCapabilities) {
		const mergedClaims = addClientCapabilitiesToClaims(claims, clientCapabilities);
		try {
			JSON.parse(mergedClaims);
		} catch (e) {
			throw createClientConfigurationError(invalidClaims);
		}
		parameters.set(CLAIMS, mergedClaims);
	}
	/**
	* add correlationId
	* @param correlationId
	*/
	function addCorrelationId(parameters, correlationId) {
		parameters.set(CLIENT_REQUEST_ID, correlationId);
	}
	/**
	* add library info query params
	* @param libraryInfo
	*/
	function addLibraryInfo(parameters, libraryInfo) {
		parameters.set(X_CLIENT_SKU, libraryInfo.sku);
		parameters.set(X_CLIENT_VER, libraryInfo.version);
		if (libraryInfo.os) parameters.set(X_CLIENT_OS, libraryInfo.os);
		if (libraryInfo.cpu) parameters.set(X_CLIENT_CPU, libraryInfo.cpu);
	}
	/**
	* Add client telemetry parameters
	* @param appTelemetry
	*/
	function addApplicationTelemetry(parameters, appTelemetry) {
		if (appTelemetry?.appName) parameters.set(X_APP_NAME, appTelemetry.appName);
		if (appTelemetry?.appVersion) parameters.set(X_APP_VER, appTelemetry.appVersion);
	}
	/**
	* add prompt
	* @param prompt
	*/
	function addPrompt(parameters, prompt) {
		parameters.set(PROMPT, prompt);
	}
	/**
	* add state
	* @param state
	*/
	function addState(parameters, state) {
		if (state) parameters.set(STATE, state);
	}
	/**
	* add nonce
	* @param nonce
	*/
	function addNonce(parameters, nonce) {
		parameters.set(NONCE, nonce);
	}
	/**
	* add code_challenge and code_challenge_method
	* - throw if either of them are not passed
	* @param codeChallenge
	* @param codeChallengeMethod
	*/
	function addCodeChallengeParams(parameters, codeChallenge, codeChallengeMethod) {
		if (codeChallenge && codeChallengeMethod) {
			parameters.set(CODE_CHALLENGE, codeChallenge);
			parameters.set(CODE_CHALLENGE_METHOD, codeChallengeMethod);
		} else throw createClientConfigurationError(pkceParamsMissing);
	}
	/**
	* add the `authorization_code` passed by the user to exchange for a token
	* @param code
	*/
	function addAuthorizationCode(parameters, code) {
		parameters.set(CODE, code);
	}
	/**
	* add the `authorization_code` passed by the user to exchange for a token
	* @param code
	*/
	function addDeviceCode(parameters, code) {
		parameters.set(DEVICE_CODE, code);
	}
	/**
	* add the `refreshToken` passed by the user
	* @param refreshToken
	*/
	function addRefreshToken(parameters, refreshToken) {
		parameters.set(REFRESH_TOKEN, refreshToken);
	}
	/**
	* add the `code_verifier` passed by the user to exchange for a token
	* @param codeVerifier
	*/
	function addCodeVerifier(parameters, codeVerifier) {
		parameters.set(CODE_VERIFIER, codeVerifier);
	}
	/**
	* add client_secret
	* @param clientSecret
	*/
	function addClientSecret(parameters, clientSecret) {
		parameters.set(CLIENT_SECRET, clientSecret);
	}
	/**
	* add clientAssertion for confidential client flows
	* @param clientAssertion
	*/
	function addClientAssertion(parameters, clientAssertion) {
		if (clientAssertion) parameters.set(CLIENT_ASSERTION, clientAssertion);
	}
	/**
	* add clientAssertionType for confidential client flows
	* @param clientAssertionType
	*/
	function addClientAssertionType(parameters, clientAssertionType) {
		if (clientAssertionType) parameters.set(CLIENT_ASSERTION_TYPE, clientAssertionType);
	}
	/**
	* add OBO assertion for confidential client flows
	* @param clientAssertion
	*/
	function addOboAssertion(parameters, oboAssertion) {
		parameters.set(OBO_ASSERTION, oboAssertion);
	}
	/**
	* add grant type
	* @param grantType
	*/
	function addRequestTokenUse(parameters, tokenUse) {
		parameters.set(REQUESTED_TOKEN_USE, tokenUse);
	}
	/**
	* add grant type
	* @param grantType
	*/
	function addGrantType(parameters, grantType) {
		parameters.set(GRANT_TYPE, grantType);
	}
	/**
	* add client info
	*
	*/
	function addClientInfo(parameters) {
		parameters.set(CLIENT_INFO, "1");
	}
	function addInstanceAware(parameters) {
		if (!parameters.has(INSTANCE_AWARE)) parameters.set(INSTANCE_AWARE, "true");
	}
	/**
	* Add extraParameters
	* @param extraParams - String dictionary containing extra parameters to be added.
	*/
	function addExtraParameters(parameters, extraParams) {
		Object.entries(extraParams).forEach(([key, value]) => {
			if (!parameters.has(key) && value) parameters.set(key, value);
		});
	}
	function addClientCapabilitiesToClaims(claims, clientCapabilities) {
		let mergedClaims;
		if (!claims) mergedClaims = {};
		else try {
			mergedClaims = JSON.parse(claims);
		} catch (e) {
			throw createClientConfigurationError(invalidClaims);
		}
		if (clientCapabilities && clientCapabilities.length > 0) {
			if (!mergedClaims.hasOwnProperty(ClaimsRequestKeys.ACCESS_TOKEN)) mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {};
			mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = { values: clientCapabilities };
		}
		return JSON.stringify(mergedClaims);
	}
	/**
	* adds `username` for Password Grant flow
	* @param username
	*/
	function addUsername(parameters, username) {
		parameters.set(PasswordGrantConstants.username, username);
	}
	/**
	* adds `password` for Password Grant flow
	* @param password
	*/
	function addPassword(parameters, password) {
		parameters.set(PasswordGrantConstants.password, password);
	}
	/**
	* add pop_jwk to query params
	* @param cnfString
	*/
	function addPopToken(parameters, cnfString) {
		if (cnfString) {
			parameters.set(TOKEN_TYPE, AuthenticationScheme.POP);
			parameters.set(REQ_CNF, cnfString);
		}
	}
	/**
	* add SSH JWK and key ID to query params
	*/
	function addSshJwk(parameters, sshJwkString) {
		if (sshJwkString) {
			parameters.set(TOKEN_TYPE, AuthenticationScheme.SSH);
			parameters.set(REQ_CNF, sshJwkString);
		}
	}
	/**
	* add server telemetry fields
	* @param serverTelemetryManager
	*/
	function addServerTelemetry(parameters, serverTelemetryManager) {
		parameters.set(X_CLIENT_CURR_TELEM, serverTelemetryManager.generateCurrentRequestHeaderValue());
		parameters.set(X_CLIENT_LAST_TELEM, serverTelemetryManager.generateLastRequestHeaderValue());
	}
	/**
	* Adds parameter that indicates to the server that throttling is supported
	*/
	function addThrottling(parameters) {
		parameters.set(X_MS_LIB_CAPABILITY, X_MS_LIB_CAPABILITY_VALUE);
	}
	/**
	* Adds logout_hint parameter for "silent" logout which prevent server account picker
	*/
	function addLogoutHint(parameters, logoutHint) {
		parameters.set(LOGOUT_HINT, logoutHint);
	}
	function addBrokerParameters(parameters, brokerClientId, brokerRedirectUri) {
		if (!parameters.has(BROKER_CLIENT_ID)) parameters.set(BROKER_CLIENT_ID, brokerClientId);
		if (!parameters.has(BROKER_REDIRECT_URI)) parameters.set(BROKER_REDIRECT_URI, brokerRedirectUri);
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Parses hash string from given string. Returns empty string if no hash symbol is found.
	* @param hashString
	*/
	function stripLeadingHashOrQuery(responseString) {
		if (responseString.startsWith("#/")) return responseString.substring(2);
		else if (responseString.startsWith("#") || responseString.startsWith("?")) return responseString.substring(1);
		return responseString;
	}
	/**
	* Returns URL hash as server auth code response object.
	*/
	function getDeserializedResponse(responseString) {
		if (!responseString || responseString.indexOf("=") < 0) return null;
		try {
			const normalizedResponse = stripLeadingHashOrQuery(responseString);
			const deserializedHash = Object.fromEntries(new URLSearchParams(normalizedResponse));
			if (deserializedHash.code || deserializedHash.ear_jwe || deserializedHash.error || deserializedHash.error_description || deserializedHash.state) return deserializedHash;
		} catch (e) {
			throw createClientAuthError(hashNotDeserialized);
		}
		return null;
	}
	/**
	* Utility to create a URL from the params map
	*/
	function mapToQueryString(parameters) {
		const queryParameterArray = new Array();
		parameters.forEach((value, key) => {
			queryParameterArray.push(`${key}=${encodeURIComponent(value)}`);
		});
		return queryParameterArray.join("&");
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const DEFAULT_CRYPTO_IMPLEMENTATION = {
		createNewGuid: () => {
			throw createClientAuthError(methodNotImplemented);
		},
		base64Decode: () => {
			throw createClientAuthError(methodNotImplemented);
		},
		base64Encode: () => {
			throw createClientAuthError(methodNotImplemented);
		},
		base64UrlEncode: () => {
			throw createClientAuthError(methodNotImplemented);
		},
		encodeKid: () => {
			throw createClientAuthError(methodNotImplemented);
		},
		async getPublicKeyThumbprint() {
			throw createClientAuthError(methodNotImplemented);
		},
		async removeTokenBindingKey() {
			throw createClientAuthError(methodNotImplemented);
		},
		async clearKeystore() {
			throw createClientAuthError(methodNotImplemented);
		},
		async signJwt() {
			throw createClientAuthError(methodNotImplemented);
		},
		async hashString() {
			throw createClientAuthError(methodNotImplemented);
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Log message level.
	*/
	exports.LogLevel = void 0;
	(function(LogLevel) {
		LogLevel[LogLevel["Error"] = 0] = "Error";
		LogLevel[LogLevel["Warning"] = 1] = "Warning";
		LogLevel[LogLevel["Info"] = 2] = "Info";
		LogLevel[LogLevel["Verbose"] = 3] = "Verbose";
		LogLevel[LogLevel["Trace"] = 4] = "Trace";
	})(exports.LogLevel || (exports.LogLevel = {}));
	const CACHE_CAPACITY = 50;
	const MAX_LOGS_PER_CORRELATION = 500;
	const correlationCache = /* @__PURE__ */ new Map();
	/**
	* Mark correlation ID as recently used by moving it to end of Map
	* @param correlationId
	* @param {CorrelationLogData} data
	*/
	function markAsRecentlyUsed(correlationId, data) {
		correlationCache.delete(correlationId);
		correlationCache.set(correlationId, data);
	}
	/**
	* Add log message to cache for specific correlation ID
	* @param correlationId
	* @param {LoggedMessage} loggedMessage
	*/
	function addLogToCache(correlationId, loggedMessage) {
		const currentTime = Date.now();
		let data = correlationCache.get(correlationId);
		if (data) markAsRecentlyUsed(correlationId, data);
		else {
			data = {
				logs: [],
				firstEventTime: currentTime
			};
			correlationCache.set(correlationId, data);
			if (correlationCache.size > CACHE_CAPACITY) {
				const firstKey = correlationCache.keys().next().value;
				if (firstKey) correlationCache.delete(firstKey);
			}
		}
		data.logs.push({
			...loggedMessage,
			milliseconds: currentTime - data.firstEventTime
		});
		if (data.logs.length > MAX_LOGS_PER_CORRELATION) data.logs.shift();
	}
	/**
	* Checks if a string is already a hashed logging string (6 alphanumeric characters)
	*/
	function isHashedString(str) {
		if (str.length !== 6) return false;
		for (let i = 0; i < str.length; i++) {
			const char = str[i];
			if (!(char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char >= "0" && char <= "9")) return false;
		}
		return true;
	}
	/**
	* Class which facilitates logging of messages to a specific place.
	*/
	var Logger = class Logger {
		constructor(loggerOptions, packageName, packageVersion) {
			this.level = exports.LogLevel.Info;
			const defaultLoggerCallback = () => {};
			const setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions();
			this.localCallback = setLoggerOptions.loggerCallback || defaultLoggerCallback;
			this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false;
			this.level = typeof setLoggerOptions.logLevel === "number" ? setLoggerOptions.logLevel : exports.LogLevel.Info;
			this.packageName = packageName || "";
			this.packageVersion = packageVersion || "";
		}
		static createDefaultLoggerOptions() {
			return {
				loggerCallback: () => {},
				piiLoggingEnabled: false,
				logLevel: exports.LogLevel.Info
			};
		}
		/**
		* Create new Logger with existing configurations.
		*/
		clone(packageName, packageVersion) {
			return new Logger({
				loggerCallback: this.localCallback,
				piiLoggingEnabled: this.piiLoggingEnabled,
				logLevel: this.level
			}, packageName, packageVersion);
		}
		/**
		* Log message with required options.
		*/
		logMessage(logMessage, options) {
			const correlationId = options.correlationId;
			if (isHashedString(logMessage)) addLogToCache(correlationId, {
				hash: logMessage,
				level: options.logLevel,
				containsPii: options.containsPii || false,
				milliseconds: 0
			});
			if (options.logLevel > this.level || !this.piiLoggingEnabled && options.containsPii) return;
			const log = `${`[${(/* @__PURE__ */ new Date()).toUTCString()}] : [${correlationId}]`} : ${this.packageName}@${this.packageVersion} : ${exports.LogLevel[options.logLevel]} - ${logMessage}`;
			this.executeCallback(options.logLevel, log, options.containsPii || false);
		}
		/**
		* Execute callback with message.
		*/
		executeCallback(level, message, containsPii) {
			if (this.localCallback) this.localCallback(level, message, containsPii);
		}
		/**
		* Logs error messages.
		*/
		error(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Error,
				containsPii: false,
				correlationId
			});
		}
		/**
		* Logs error messages with PII.
		*/
		errorPii(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Error,
				containsPii: true,
				correlationId
			});
		}
		/**
		* Logs warning messages.
		*/
		warning(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Warning,
				containsPii: false,
				correlationId
			});
		}
		/**
		* Logs warning messages with PII.
		*/
		warningPii(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Warning,
				containsPii: true,
				correlationId
			});
		}
		/**
		* Logs info messages.
		*/
		info(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Info,
				containsPii: false,
				correlationId
			});
		}
		/**
		* Logs info messages with PII.
		*/
		infoPii(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Info,
				containsPii: true,
				correlationId
			});
		}
		/**
		* Logs verbose messages.
		*/
		verbose(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Verbose,
				containsPii: false,
				correlationId
			});
		}
		/**
		* Logs verbose messages with PII.
		*/
		verbosePii(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Verbose,
				containsPii: true,
				correlationId
			});
		}
		/**
		* Logs trace messages.
		*/
		trace(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Trace,
				containsPii: false,
				correlationId
			});
		}
		/**
		* Logs trace messages with PII.
		*/
		tracePii(message, correlationId) {
			this.logMessage(message, {
				logLevel: exports.LogLevel.Trace,
				containsPii: true,
				correlationId
			});
		}
		/**
		* Returns whether PII Logging is enabled or not.
		*/
		isPiiLoggingEnabled() {
			return this.piiLoggingEnabled || false;
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const name$1 = "@azure/msal-common";
	const version$1 = "16.1.0";
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const AzureCloudInstance = {
		None: "none",
		AzurePublic: "https://login.microsoftonline.com",
		AzurePpe: "https://login.windows-ppe.net",
		AzureChina: "https://login.chinacloudapi.cn",
		AzureGermany: "https://login.microsoftonline.de",
		AzureUsGovernment: "https://login.microsoftonline.us"
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Returns true if tenantId matches the utid portion of homeAccountId
	* @param tenantId
	* @param homeAccountId
	* @returns
	*/
	function tenantIdMatchesHomeTenant(tenantId, homeAccountId) {
		return !!tenantId && !!homeAccountId && tenantId === homeAccountId.split(".")[1];
	}
	/**
	* Build tenant profile
	* @param homeAccountId - Home account identifier for this account object
	* @param localAccountId - Local account identifer for this account object
	* @param tenantId - Full tenant or organizational id that this account belongs to
	* @param idTokenClaims - Claims from the ID token
	* @returns
	*/
	function buildTenantProfile(homeAccountId, localAccountId, tenantId, idTokenClaims) {
		if (idTokenClaims) {
			const { oid, sub, tid, name, tfp, acr, preferred_username, upn, login_hint } = idTokenClaims;
			/**
			* Since there is no way to determine if the authority is AAD or B2C, we exhaust all the possible claims that can serve as tenant ID with the following precedence:
			* tid - TenantID claim that identifies the tenant that issued the token in AAD. Expected in all AAD ID tokens, not present in B2C ID Tokens.
			* tfp - Trust Framework Policy claim that identifies the policy that was used to authenticate the user. Functions as tenant for B2C scenarios.
			* acr - Authentication Context Class Reference claim used only with older B2C policies. Fallback in case tfp is not present, but likely won't be present anyway.
			*/
			const tenantId = tid || tfp || acr || "";
			return {
				tenantId,
				localAccountId: oid || sub || "",
				name,
				username: preferred_username || upn || "",
				loginHint: login_hint,
				isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId)
			};
		} else return {
			tenantId,
			localAccountId,
			username: "",
			isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId)
		};
	}
	/**
	* Replaces account info that varies by tenant profile sourced from the ID token claims passed in with the tenant-specific account info
	* @param baseAccountInfo
	* @param idTokenClaims
	* @returns
	*/
	function updateAccountTenantProfileData(baseAccountInfo, tenantProfile, idTokenClaims, idTokenSecret) {
		let updatedAccountInfo = baseAccountInfo;
		if (tenantProfile) {
			const { isHomeTenant, ...tenantProfileOverride } = tenantProfile;
			updatedAccountInfo = {
				...baseAccountInfo,
				...tenantProfileOverride
			};
		}
		if (idTokenClaims) {
			const { isHomeTenant, ...claimsSourcedTenantProfile } = buildTenantProfile(baseAccountInfo.homeAccountId, baseAccountInfo.localAccountId, baseAccountInfo.tenantId, idTokenClaims);
			updatedAccountInfo = {
				...updatedAccountInfo,
				...claimsSourcedTenantProfile,
				idTokenClaims,
				idToken: idTokenSecret
			};
			return updatedAccountInfo;
		}
		return updatedAccountInfo;
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Extract token by decoding the rawToken
	*
	* @param encodedToken
	*/
	function extractTokenClaims(encodedToken, base64Decode) {
		const jswPayload = getJWSPayload(encodedToken);
		try {
			const base64Decoded = base64Decode(jswPayload);
			return JSON.parse(base64Decoded);
		} catch (err) {
			throw createClientAuthError(tokenParsingError);
		}
	}
	/**
	* Check if the signin_state claim contains "kmsi"
	* @param idTokenClaims
	* @returns
	*/
	function isKmsi(idTokenClaims) {
		if (!idTokenClaims.signin_state) return false;
		/**
		* Signin_state claim known values:
		* dvc_mngd - device is managed
		* dvc_dmjd - device is domain joined
		* kmsi - user opted to "keep me signed in"
		* inknownntwk - Request made inside a known network. Don't use this, use CAE instead.
		*/
		const kmsiClaims = ["kmsi", "dvc_dmjd"];
		return idTokenClaims.signin_state.some((value) => kmsiClaims.includes(value.trim().toLowerCase()));
	}
	/**
	* decode a JWT
	*
	* @param authToken
	*/
	function getJWSPayload(authToken) {
		if (!authToken) throw createClientAuthError(nullOrEmptyToken);
		const matches = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(authToken);
		if (!matches || matches.length < 4) throw createClientAuthError(tokenParsingError);
		/**
		* const crackedToken = {
		*  header: matches[1],
		*  JWSPayload: matches[2],
		*  JWSSig: matches[3],
		* };
		*/
		return matches[2];
	}
	/**
	* Determine if the token's max_age has transpired
	*/
	function checkMaxAge(authTime, maxAge) {
		if (maxAge === 0 || Date.now() - 3e5 > authTime + maxAge) throw createClientAuthError(maxAgeTranspired);
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Url object class which can perform various transformations on url strings.
	*/
	var UrlString = class UrlString {
		get urlString() {
			return this._urlString;
		}
		constructor(url) {
			this._urlString = url;
			if (!this._urlString) throw createClientConfigurationError(urlEmptyError);
			if (!url.includes("#")) this._urlString = UrlString.canonicalizeUri(url);
		}
		/**
		* Ensure urls are lower case and end with a / character.
		* @param url
		*/
		static canonicalizeUri(url) {
			if (url) {
				let lowerCaseUrl = url.toLowerCase();
				if (StringUtils.endsWith(lowerCaseUrl, "?")) lowerCaseUrl = lowerCaseUrl.slice(0, -1);
				else if (StringUtils.endsWith(lowerCaseUrl, "?/")) lowerCaseUrl = lowerCaseUrl.slice(0, -2);
				if (!StringUtils.endsWith(lowerCaseUrl, "/")) lowerCaseUrl += "/";
				return lowerCaseUrl;
			}
			return url;
		}
		/**
		* Throws if urlString passed is not a valid authority URI string.
		*/
		validateAsUri() {
			let components;
			try {
				components = this.getUrlComponents();
			} catch (e) {
				throw createClientConfigurationError(urlParseError);
			}
			if (!components.HostNameAndPort || !components.PathSegments) throw createClientConfigurationError(urlParseError);
			if (!components.Protocol || components.Protocol.toLowerCase() !== "https:") throw createClientConfigurationError(authorityUriInsecure);
		}
		/**
		* Given a url and a query string return the url with provided query string appended
		* @param url
		* @param queryString
		*/
		static appendQueryString(url, queryString) {
			if (!queryString) return url;
			return url.indexOf("?") < 0 ? `${url}?${queryString}` : `${url}&${queryString}`;
		}
		/**
		* Returns a url with the hash removed
		* @param url
		*/
		static removeHashFromUrl(url) {
			return UrlString.canonicalizeUri(url.split("#")[0]);
		}
		/**
		* Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d
		* @param href The url
		* @param tenantId The tenant id to replace
		*/
		replaceTenantPath(tenantId) {
			const urlObject = this.getUrlComponents();
			const pathArray = urlObject.PathSegments;
			if (tenantId && pathArray.length !== 0 && (pathArray[0] === AADAuthority.COMMON || pathArray[0] === AADAuthority.ORGANIZATIONS)) pathArray[0] = tenantId;
			return UrlString.constructAuthorityUriFromObject(urlObject);
		}
		/**
		* Parses out the components from a url string.
		* @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.
		*/
		getUrlComponents() {
			const regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
			const match = this.urlString.match(regEx);
			if (!match) throw createClientConfigurationError(urlParseError);
			const urlComponents = {
				Protocol: match[1],
				HostNameAndPort: match[4],
				AbsolutePath: match[5],
				QueryString: match[7]
			};
			let pathSegments = urlComponents.AbsolutePath.split("/");
			pathSegments = pathSegments.filter((val) => val && val.length > 0);
			urlComponents.PathSegments = pathSegments;
			if (urlComponents.QueryString && urlComponents.QueryString.endsWith("/")) urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1);
			return urlComponents;
		}
		static getDomainFromUrl(url) {
			const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
			const match = url.match(regEx);
			if (!match) throw createClientConfigurationError(urlParseError);
			return match[2];
		}
		static getAbsoluteUrl(relativeUrl, baseUrl) {
			if (relativeUrl[0] === FORWARD_SLASH) {
				const baseComponents = new UrlString(baseUrl).getUrlComponents();
				return baseComponents.Protocol + "//" + baseComponents.HostNameAndPort + relativeUrl;
			}
			return relativeUrl;
		}
		static constructAuthorityUriFromObject(urlObject) {
			return new UrlString(urlObject.Protocol + "//" + urlObject.HostNameAndPort + "/" + urlObject.PathSegments.join("/"));
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const endpointHosts = [
		{ host: "login.microsoftonline.com" },
		{
			host: "login.chinacloudapi.cn",
			issuerHost: "login.partner.microsoftonline.cn"
		},
		{ host: "login.microsoftonline.us" },
		{ host: "login.sovcloud-identity.fr" },
		{ host: "login.sovcloud-identity.de" },
		{ host: "login.sovcloud-identity.sg" }
	];
	function buildOpenIdConfig(host, issuerHost) {
		return {
			token_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/token`,
			jwks_uri: `https://${host}/{tenantid}/discovery/v2.0/keys`,
			issuer: `https://${issuerHost}/{tenantid}/v2.0`,
			authorization_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/authorize`,
			end_session_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/logout`
		};
	}
	const rawMetdataJSON = {
		endpointMetadata: endpointHosts.reduce((acc, { host, issuerHost }) => {
			acc[host] = buildOpenIdConfig(host, issuerHost || host);
			return acc;
		}, {}),
		instanceDiscoveryMetadata: { metadata: [
			{
				preferred_network: "login.microsoftonline.com",
				preferred_cache: "login.windows.net",
				aliases: [
					"login.microsoftonline.com",
					"login.windows.net",
					"login.microsoft.com",
					"sts.windows.net"
				]
			},
			{
				preferred_network: "login.partner.microsoftonline.cn",
				preferred_cache: "login.partner.microsoftonline.cn",
				aliases: ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"]
			},
			{
				preferred_network: "login.microsoftonline.de",
				preferred_cache: "login.microsoftonline.de",
				aliases: ["login.microsoftonline.de"]
			},
			{
				preferred_network: "login.microsoftonline.us",
				preferred_cache: "login.microsoftonline.us",
				aliases: ["login.microsoftonline.us", "login.usgovcloudapi.net"]
			},
			{
				preferred_network: "login-us.microsoftonline.com",
				preferred_cache: "login-us.microsoftonline.com",
				aliases: ["login-us.microsoftonline.com"]
			},
			{
				preferred_network: "login.sovcloud-identity.fr",
				preferred_cache: "login.sovcloud-identity.fr",
				aliases: ["login.sovcloud-identity.fr"]
			},
			{
				preferred_network: "login.sovcloud-identity.de",
				preferred_cache: "login.sovcloud-identity.de",
				aliases: ["login.sovcloud-identity.de"]
			},
			{
				preferred_network: "login.sovcloud-identity.sg",
				preferred_cache: "login.sovcloud-identity.sg",
				aliases: ["login.sovcloud-identity.sg"]
			}
		] }
	};
	const EndpointMetadata = rawMetdataJSON.endpointMetadata;
	const InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata;
	const InstanceDiscoveryMetadataAliases = /* @__PURE__ */ new Set();
	InstanceDiscoveryMetadata.metadata.forEach((metadataEntry) => {
		metadataEntry.aliases.forEach((alias) => {
			InstanceDiscoveryMetadataAliases.add(alias);
		});
	});
	/**
	* Attempts to get an aliases array from the static authority metadata sources based on the canonical authority host
	* @param staticAuthorityOptions
	* @param logger
	* @returns
	*/
	function getAliasesFromStaticSources(staticAuthorityOptions, logger, correlationId) {
		let staticAliases;
		const canonicalAuthority = staticAuthorityOptions.canonicalAuthority;
		if (canonicalAuthority) {
			const authorityHost = new UrlString(canonicalAuthority).getUrlComponents().HostNameAndPort;
			staticAliases = getAliasesFromMetadata(logger, correlationId, authorityHost, staticAuthorityOptions.cloudDiscoveryMetadata?.metadata, AuthorityMetadataSource.CONFIG) || getAliasesFromMetadata(logger, correlationId, authorityHost, InstanceDiscoveryMetadata.metadata, AuthorityMetadataSource.HARDCODED_VALUES) || staticAuthorityOptions.knownAuthorities;
		}
		return staticAliases || [];
	}
	/**
	* Returns aliases for from the raw cloud discovery metadata passed in
	* @param authorityHost
	* @param rawCloudDiscoveryMetadata
	* @returns
	*/
	function getAliasesFromMetadata(logger, correlationId, authorityHost, cloudDiscoveryMetadata, source) {
		logger.trace(`getAliasesFromMetadata called with source: '${source}'`, correlationId);
		if (authorityHost && cloudDiscoveryMetadata) {
			const metadata = getCloudDiscoveryMetadataFromNetworkResponse(cloudDiscoveryMetadata, authorityHost);
			if (metadata) {
				logger.trace(`getAliasesFromMetadata: found cloud discovery metadata in '${source}', returning aliases`, correlationId);
				return metadata.aliases;
			} else logger.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in '${source}'`, correlationId);
		}
		return null;
	}
	/**
	* Get cloud discovery metadata for common authorities
	*/
	function getCloudDiscoveryMetadataFromHardcodedValues(authorityHost) {
		return getCloudDiscoveryMetadataFromNetworkResponse(InstanceDiscoveryMetadata.metadata, authorityHost);
	}
	/**
	* Searches instance discovery network response for the entry that contains the host in the aliases list
	* @param response
	* @param authority
	*/
	function getCloudDiscoveryMetadataFromNetworkResponse(response, authorityHost) {
		for (let i = 0; i < response.length; i++) {
			const metadata = response[i];
			if (metadata.aliases.includes(authorityHost)) return metadata;
		}
		return null;
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const cacheQuotaExceeded = "cache_quota_exceeded";
	const cacheErrorUnknown = "cache_error_unknown";
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Error thrown when there is an error with the cache
	*/
	var CacheError = class CacheError extends Error {
		constructor(errorCode, errorMessage) {
			const message = errorMessage || getDefaultErrorMessage(errorCode);
			super(message);
			Object.setPrototypeOf(this, CacheError.prototype);
			this.name = "CacheError";
			this.errorCode = errorCode;
			this.errorMessage = message;
		}
	};
	/**
	* Helper function to wrap browser errors in a CacheError object
	* @param e
	* @returns
	*/
	function createCacheError(e) {
		if (!(e instanceof Error)) return new CacheError(cacheErrorUnknown);
		if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED" || e.message.includes("exceeded the quota")) return new CacheError(cacheQuotaExceeded);
		else return new CacheError(e.name, e.message);
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Function to build a client info object from server clientInfo string
	* @param rawClientInfo
	* @param crypto
	*/
	function buildClientInfo(rawClientInfo, base64Decode) {
		if (!rawClientInfo) throw createClientAuthError(clientInfoEmptyError);
		try {
			const decodedClientInfo = base64Decode(rawClientInfo);
			return JSON.parse(decodedClientInfo);
		} catch (e) {
			throw createClientAuthError(clientInfoDecodingError);
		}
	}
	/**
	* Function to build a client info object from cached homeAccountId string
	* @param homeAccountId
	*/
	function buildClientInfoFromHomeAccountId(homeAccountId) {
		if (!homeAccountId) throw createClientAuthError(clientInfoDecodingError);
		const clientInfoParts = homeAccountId.split(CLIENT_INFO_SEPARATOR, 2);
		return {
			uid: clientInfoParts[0],
			utid: clientInfoParts.length < 2 ? "" : clientInfoParts[1]
		};
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Authority types supported by MSAL.
	*/
	const AuthorityType = {
		Default: 0,
		Adfs: 1,
		Dsts: 2,
		Ciam: 3
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Gets tenantId from available ID token claims to set as credential realm with the following precedence:
	* 1. tid - if the token is acquired from an Azure AD tenant tid will be present
	* 2. tfp - if the token is acquired from a modern B2C tenant tfp should be present
	* 3. acr - if the token is acquired from a legacy B2C tenant acr should be present
	* Downcased to match the realm case-insensitive comparison requirements
	* @param idTokenClaims
	* @returns
	*/
	function getTenantIdFromIdTokenClaims(idTokenClaims) {
		if (idTokenClaims) return idTokenClaims.tid || idTokenClaims.tfp || idTokenClaims.acr || null;
		return null;
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Protocol modes supported by MSAL.
	*/
	const ProtocolMode = {
		AAD: "AAD",
		OIDC: "OIDC",
		EAR: "EAR"
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Returns the AccountInfo interface for this account.
	*/
	function getAccountInfo(accountEntity) {
		const tenantProfiles = accountEntity.tenantProfiles || [];
		if (tenantProfiles.length === 0 && accountEntity.realm && accountEntity.localAccountId) tenantProfiles.push(buildTenantProfile(accountEntity.homeAccountId, accountEntity.localAccountId, accountEntity.realm));
		return {
			homeAccountId: accountEntity.homeAccountId,
			environment: accountEntity.environment,
			tenantId: accountEntity.realm,
			username: accountEntity.username,
			localAccountId: accountEntity.localAccountId,
			loginHint: accountEntity.loginHint,
			name: accountEntity.name,
			nativeAccountId: accountEntity.nativeAccountId,
			authorityType: accountEntity.authorityType,
			tenantProfiles: new Map(tenantProfiles.map((tenantProfile) => {
				return [tenantProfile.tenantId, tenantProfile];
			})),
			dataBoundary: accountEntity.dataBoundary
		};
	}
	/**
	* Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD.
	* @param accountDetails
	*/
	function createAccountEntity(accountDetails, authority, base64Decode) {
		let authorityType;
		if (authority.authorityType === AuthorityType.Adfs) authorityType = CACHE_ACCOUNT_TYPE_ADFS;
		else if (authority.protocolMode === ProtocolMode.OIDC) authorityType = CACHE_ACCOUNT_TYPE_GENERIC;
		else authorityType = CACHE_ACCOUNT_TYPE_MSSTS;
		let clientInfo;
		let dataBoundary;
		if (accountDetails.clientInfo && base64Decode) {
			clientInfo = buildClientInfo(accountDetails.clientInfo, base64Decode);
			if (clientInfo.xms_tdbr) dataBoundary = clientInfo.xms_tdbr === "EU" ? "EU" : "None";
		}
		const env = accountDetails.environment || authority && authority.getPreferredCache();
		if (!env) throw createClientAuthError(invalidCacheEnvironment);
		const preferredUsername = accountDetails.idTokenClaims?.preferred_username || accountDetails.idTokenClaims?.upn;
		const email = accountDetails.idTokenClaims?.emails ? accountDetails.idTokenClaims.emails[0] : null;
		const username = preferredUsername || email || "";
		const loginHint = accountDetails.idTokenClaims?.login_hint;
		const realm = clientInfo?.utid || getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) || "";
		const localAccountId = clientInfo?.uid || accountDetails.idTokenClaims?.oid || accountDetails.idTokenClaims?.sub || "";
		let tenantProfiles;
		if (accountDetails.tenantProfiles) tenantProfiles = accountDetails.tenantProfiles;
		else tenantProfiles = [buildTenantProfile(accountDetails.homeAccountId, localAccountId, realm, accountDetails.idTokenClaims)];
		return {
			homeAccountId: accountDetails.homeAccountId,
			environment: env,
			realm,
			localAccountId,
			username,
			authorityType,
			loginHint,
			clientInfo: accountDetails.clientInfo,
			name: accountDetails.idTokenClaims?.name || "",
			lastModificationTime: void 0,
			lastModificationApp: void 0,
			cloudGraphHostName: accountDetails.cloudGraphHostName,
			msGraphHost: accountDetails.msGraphHost,
			nativeAccountId: accountDetails.nativeAccountId,
			tenantProfiles,
			dataBoundary
		};
	}
	/**
	* Generate HomeAccountId from server response
	* @param serverClientInfo
	* @param authType
	*/
	function generateHomeAccountId(serverClientInfo, authType, logger, cryptoObj, correlationId, idTokenClaims) {
		if (!(authType === AuthorityType.Adfs || authType === AuthorityType.Dsts)) {
			if (serverClientInfo) try {
				const clientInfo = buildClientInfo(serverClientInfo, cryptoObj.base64Decode);
				if (clientInfo.uid && clientInfo.utid) return `${clientInfo.uid}.${clientInfo.utid}`;
			} catch (e) {}
			logger.warning("No client info in response", correlationId);
		}
		return idTokenClaims?.sub || "";
	}
	/**
	* Validates an entity: checks for all expected params
	* @param entity
	*/
	function isAccountEntity(entity) {
		if (!entity) return false;
		return entity.hasOwnProperty("homeAccountId") && entity.hasOwnProperty("environment") && entity.hasOwnProperty("realm") && entity.hasOwnProperty("localAccountId") && entity.hasOwnProperty("username") && entity.hasOwnProperty("authorityType");
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Interface class which implement cache storage functions used by MSAL to perform validity checks, and store tokens.
	* @internal
	*/
	var CacheManager = class {
		constructor(clientId, cryptoImpl, logger, performanceClient, staticAuthorityOptions) {
			this.clientId = clientId;
			this.cryptoImpl = cryptoImpl;
			this.commonLogger = logger.clone(name$1, version$1);
			this.staticAuthorityOptions = staticAuthorityOptions;
			this.performanceClient = performanceClient;
		}
		/**
		* Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
		* @param accountFilter - (Optional) filter to narrow down the accounts returned
		* @returns Array of AccountInfo objects in cache
		*/
		getAllAccounts(accountFilter = {}, correlationId) {
			return this.buildTenantProfiles(this.getAccountsFilteredBy(accountFilter, correlationId), correlationId, accountFilter);
		}
		/**
		* Gets first tenanted AccountInfo object found based on provided filters
		*/
		getAccountInfoFilteredBy(accountFilter, correlationId) {
			const allAccounts = this.getAllAccounts(accountFilter, correlationId);
			if (allAccounts.length > 1) return allAccounts.sort((account) => {
				return account.idTokenClaims ? -1 : 1;
			})[0];
			else if (allAccounts.length === 1) return allAccounts[0];
			else return null;
		}
		/**
		* Returns a single matching
		* @param accountFilter
		* @returns
		*/
		getBaseAccountInfo(accountFilter, correlationId) {
			const accountEntities = this.getAccountsFilteredBy(accountFilter, correlationId);
			if (accountEntities.length > 0) return getAccountInfo(accountEntities[0]);
			else return null;
		}
		/**
		* Matches filtered account entities with cached ID tokens that match the tenant profile-specific account filters
		* and builds the account info objects from the matching ID token's claims
		* @param cachedAccounts
		* @param accountFilter
		* @returns Array of AccountInfo objects that match account and tenant profile filters
		*/
		buildTenantProfiles(cachedAccounts, correlationId, accountFilter) {
			return cachedAccounts.flatMap((accountEntity) => {
				return this.getTenantProfilesFromAccountEntity(accountEntity, correlationId, accountFilter?.tenantId, accountFilter);
			});
		}
		getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter) {
			let tenantedAccountInfo = null;
			let idTokenClaims;
			if (tenantProfileFilter) {
				if (!this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter)) return null;
			}
			const idToken = this.getIdToken(accountInfo, correlationId, tokenKeys, tenantProfile.tenantId);
			if (idToken) {
				idTokenClaims = extractTokenClaims(idToken.secret, this.cryptoImpl.base64Decode);
				if (!this.idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter)) return null;
			}
			tenantedAccountInfo = updateAccountTenantProfileData(accountInfo, tenantProfile, idTokenClaims, idToken?.secret);
			return tenantedAccountInfo;
		}
		getTenantProfilesFromAccountEntity(accountEntity, correlationId, targetTenantId, tenantProfileFilter) {
			const accountInfo = getAccountInfo(accountEntity);
			let searchTenantProfiles = accountInfo.tenantProfiles || /* @__PURE__ */ new Map();
			const tokenKeys = this.getTokenKeys();
			if (targetTenantId) {
				const tenantProfile = searchTenantProfiles.get(targetTenantId);
				if (tenantProfile) searchTenantProfiles = new Map([[targetTenantId, tenantProfile]]);
				else return [];
			}
			const matchingTenantProfiles = [];
			searchTenantProfiles.forEach((tenantProfile) => {
				const tenantedAccountInfo = this.getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter);
				if (tenantedAccountInfo) matchingTenantProfiles.push(tenantedAccountInfo);
			});
			return matchingTenantProfiles;
		}
		tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter) {
			if (!!tenantProfileFilter.localAccountId && !this.matchLocalAccountIdFromTenantProfile(tenantProfile, tenantProfileFilter.localAccountId)) return false;
			if (!!tenantProfileFilter.name && !(tenantProfile.name === tenantProfileFilter.name)) return false;
			if (tenantProfileFilter.isHomeTenant !== void 0 && !(tenantProfile.isHomeTenant === tenantProfileFilter.isHomeTenant)) return false;
			return true;
		}
		idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter) {
			if (tenantProfileFilter) {
				if (!!tenantProfileFilter.localAccountId && !this.matchLocalAccountIdFromTokenClaims(idTokenClaims, tenantProfileFilter.localAccountId)) return false;
				if (!!tenantProfileFilter.loginHint && !this.matchLoginHintFromTokenClaims(idTokenClaims, tenantProfileFilter.loginHint)) return false;
				if (!!tenantProfileFilter.username && !this.matchUsername(idTokenClaims.preferred_username, tenantProfileFilter.username)) return false;
				if (!!tenantProfileFilter.name && !this.matchName(idTokenClaims, tenantProfileFilter.name)) return false;
				if (!!tenantProfileFilter.sid && !this.matchSid(idTokenClaims, tenantProfileFilter.sid)) return false;
			}
			return true;
		}
		/**
		* saves a cache record
		* @param cacheRecord {CacheRecord}
		* @param storeInCache {?StoreInCache}
		* @param correlationId {?string} correlation id
		*/
		async saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache) {
			if (!cacheRecord) throw createClientAuthError(invalidCacheRecord);
			try {
				if (!!cacheRecord.account) await this.setAccount(cacheRecord.account, correlationId, kmsi, apiId);
				if (!!cacheRecord.idToken && storeInCache?.idToken !== false) await this.setIdTokenCredential(cacheRecord.idToken, correlationId, kmsi);
				if (!!cacheRecord.accessToken && storeInCache?.accessToken !== false) await this.saveAccessToken(cacheRecord.accessToken, correlationId, kmsi);
				if (!!cacheRecord.refreshToken && storeInCache?.refreshToken !== false) await this.setRefreshTokenCredential(cacheRecord.refreshToken, correlationId, kmsi);
				if (!!cacheRecord.appMetadata) this.setAppMetadata(cacheRecord.appMetadata, correlationId);
			} catch (e) {
				this.commonLogger?.error(`CacheManager.saveCacheRecord: failed`, correlationId);
				if (e instanceof AuthError) throw e;
				else throw createCacheError(e);
			}
		}
		/**
		* saves access token credential
		* @param credential
		*/
		async saveAccessToken(credential, correlationId, kmsi) {
			const accessTokenFilter = {
				clientId: credential.clientId,
				credentialType: credential.credentialType,
				environment: credential.environment,
				homeAccountId: credential.homeAccountId,
				realm: credential.realm,
				tokenType: credential.tokenType
			};
			const tokenKeys = this.getTokenKeys();
			const currentScopes = ScopeSet.fromString(credential.target);
			tokenKeys.accessToken.forEach((key) => {
				if (!this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) return;
				const tokenEntity = this.getAccessTokenCredential(key, correlationId);
				if (tokenEntity && this.credentialMatchesFilter(tokenEntity, accessTokenFilter, correlationId)) {
					if (ScopeSet.fromString(tokenEntity.target).intersectingScopeSets(currentScopes)) this.removeAccessToken(key, correlationId);
				}
			});
			await this.setAccessTokenCredential(credential, correlationId, kmsi);
		}
		/**
		* Retrieve account entities matching all provided tenant-agnostic filters; if no filter is set, get all account entities in the cache
		* Not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared
		* @param accountFilter - An object containing Account properties to filter by
		*/
		getAccountsFilteredBy(accountFilter, correlationId) {
			const allAccountKeys = this.getAccountKeys();
			const matchingAccounts = [];
			allAccountKeys.forEach((cacheKey) => {
				const entity = this.getAccount(cacheKey, correlationId);
				if (!entity) return;
				if (!!accountFilter.homeAccountId && !this.matchHomeAccountId(entity, accountFilter.homeAccountId)) return;
				if (!!accountFilter.username && !this.matchUsername(entity.username, accountFilter.username)) return;
				if (!!accountFilter.environment && !this.matchEnvironment(entity, accountFilter.environment, correlationId)) return;
				if (!!accountFilter.realm && !this.matchRealm(entity, accountFilter.realm)) return;
				if (!!accountFilter.nativeAccountId && !this.matchNativeAccountId(entity, accountFilter.nativeAccountId)) return;
				if (!!accountFilter.authorityType && !this.matchAuthorityType(entity, accountFilter.authorityType)) return;
				const tenantProfileFilter = {
					localAccountId: accountFilter?.localAccountId,
					name: accountFilter?.name
				};
				const matchingTenantProfiles = entity.tenantProfiles?.filter((tenantProfile) => {
					return this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter);
				});
				if (matchingTenantProfiles && matchingTenantProfiles.length === 0) return;
				matchingAccounts.push(entity);
			});
			return matchingAccounts;
		}
		/**
		* Returns whether or not the given credential entity matches the filter
		* @param entity
		* @param filter
		* @param correlationId
		* @returns
		*/
		credentialMatchesFilter(entity, filter, correlationId) {
			if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) return false;
			if (!!filter.userAssertionHash && !this.matchUserAssertionHash(entity, filter.userAssertionHash)) return false;
			if (typeof filter.homeAccountId === "string" && !this.matchHomeAccountId(entity, filter.homeAccountId)) return false;
			if (!!filter.environment && !this.matchEnvironment(entity, filter.environment, correlationId)) return false;
			if (!!filter.realm && !this.matchRealm(entity, filter.realm)) return false;
			if (!!filter.credentialType && !this.matchCredentialType(entity, filter.credentialType)) return false;
			if (!!filter.familyId && !this.matchFamilyId(entity, filter.familyId)) return false;
			if (!!filter.target && !this.matchTarget(entity, filter.target)) return false;
			if (entity.credentialType === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) {
				if (!!filter.tokenType && !this.matchTokenType(entity, filter.tokenType)) return false;
				if (filter.tokenType === AuthenticationScheme.SSH) {
					if (filter.keyId && !this.matchKeyId(entity, filter.keyId)) return false;
				}
			}
			return true;
		}
		/**
		* retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata
		* @param filter
		* @param correlationId
		*/
		getAppMetadataFilteredBy(filter, correlationId) {
			const allCacheKeys = this.getKeys();
			const matchingAppMetadata = {};
			allCacheKeys.forEach((cacheKey) => {
				if (!this.isAppMetadata(cacheKey)) return;
				const entity = this.getAppMetadata(cacheKey, correlationId);
				if (!entity) return;
				if (!!filter.environment && !this.matchEnvironment(entity, filter.environment, correlationId)) return;
				if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) return;
				matchingAppMetadata[cacheKey] = entity;
			});
			return matchingAppMetadata;
		}
		/**
		* retrieve authorityMetadata that contains a matching alias
		* @param host
		* @param correlationId
		*/
		getAuthorityMetadataByAlias(host, correlationId) {
			const allCacheKeys = this.getAuthorityMetadataKeys();
			let matchedEntity = null;
			allCacheKeys.forEach((cacheKey) => {
				if (!this.isAuthorityMetadata(cacheKey) || cacheKey.indexOf(this.clientId) === -1) return;
				const entity = this.getAuthorityMetadata(cacheKey, correlationId);
				if (!entity) return;
				if (entity.aliases.indexOf(host) === -1) return;
				matchedEntity = entity;
			});
			return matchedEntity;
		}
		/**
		* Removes all accounts and related tokens from cache.
		*/
		removeAllAccounts(correlationId) {
			this.getAllAccounts({}, correlationId).forEach((account) => {
				this.removeAccount(account, correlationId);
			});
		}
		/**
		* Removes the account and related tokens for a given account key
		* @param account
		*/
		removeAccount(account, correlationId) {
			this.removeAccountContext(account, correlationId);
			const accountKeys = this.getAccountKeys();
			const keyFilter = (key) => {
				return key.includes(account.homeAccountId) && key.includes(account.environment);
			};
			accountKeys.filter(keyFilter).forEach((key) => {
				this.removeItem(key, correlationId);
				this.performanceClient.incrementFields({ accountsRemoved: 1 }, correlationId);
			});
		}
		/**
		* Removes credentials associated with the provided account
		* @param account
		*/
		removeAccountContext(account, correlationId) {
			const allTokenKeys = this.getTokenKeys();
			const keyFilter = (key) => {
				return key.includes(account.homeAccountId) && key.includes(account.environment);
			};
			allTokenKeys.idToken.filter(keyFilter).forEach((key) => {
				this.removeIdToken(key, correlationId);
			});
			allTokenKeys.accessToken.filter(keyFilter).forEach((key) => {
				this.removeAccessToken(key, correlationId);
			});
			allTokenKeys.refreshToken.filter(keyFilter).forEach((key) => {
				this.removeRefreshToken(key, correlationId);
			});
		}
		/**
		* returns a boolean if the given credential is removed
		* @param key
		* @param correlationId
		*/
		removeAccessToken(key, correlationId) {
			const credential = this.getAccessTokenCredential(key, correlationId);
			if (!credential) return;
			this.removeItem(key, correlationId);
			this.performanceClient.incrementFields({ accessTokensRemoved: 1 }, correlationId);
			if (credential.credentialType.toLowerCase() === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()) {
				if (credential.tokenType === AuthenticationScheme.POP) {
					const kid = credential.keyId;
					if (kid) this.cryptoImpl.removeTokenBindingKey(kid, correlationId).catch(() => {
						this.commonLogger.error(`Failed to remove token binding key '${kid}'`, correlationId);
						this.performanceClient?.incrementFields({ removeTokenBindingKeyFailure: 1 }, correlationId);
					});
				}
			}
		}
		/**
		* Removes all app metadata objects from cache.
		*/
		removeAppMetadata(correlationId) {
			this.getKeys().forEach((cacheKey) => {
				if (this.isAppMetadata(cacheKey)) this.removeItem(cacheKey, correlationId);
			});
			return true;
		}
		/**
		* Retrieve IdTokenEntity from cache
		* @param account {AccountInfo}
		* @param tokenKeys {?TokenKeys}
		* @param targetRealm {?string}
		* @param performanceClient {?IPerformanceClient}
		* @param correlationId {?string}
		*/
		getIdToken(account, correlationId, tokenKeys, targetRealm) {
			this.commonLogger.trace("CacheManager - getIdToken called", correlationId);
			const idTokenFilter = {
				homeAccountId: account.homeAccountId,
				environment: account.environment,
				credentialType: CredentialType.ID_TOKEN,
				clientId: this.clientId,
				realm: targetRealm
			};
			const idTokenMap = this.getIdTokensByFilter(idTokenFilter, correlationId, tokenKeys);
			const numIdTokens = idTokenMap.size;
			if (numIdTokens < 1) {
				this.commonLogger.info("CacheManager:getIdToken - No token found", correlationId);
				return null;
			} else if (numIdTokens > 1) {
				let tokensToBeRemoved = idTokenMap;
				if (!targetRealm) {
					const homeIdTokenMap = /* @__PURE__ */ new Map();
					idTokenMap.forEach((idToken, key) => {
						if (idToken.realm === account.tenantId) homeIdTokenMap.set(key, idToken);
					});
					const numHomeIdTokens = homeIdTokenMap.size;
					if (numHomeIdTokens < 1) {
						this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result", correlationId);
						return idTokenMap.values().next().value;
					} else if (numHomeIdTokens === 1) {
						this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile", correlationId);
						return homeIdTokenMap.values().next().value;
					} else tokensToBeRemoved = homeIdTokenMap;
				}
				this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them", correlationId);
				tokensToBeRemoved.forEach((idToken, key) => {
					this.removeIdToken(key, correlationId);
				});
				this.performanceClient.addFields({ multiMatchedID: idTokenMap.size }, correlationId);
				return null;
			}
			this.commonLogger.info("CacheManager:getIdToken - Returning ID token", correlationId);
			return idTokenMap.values().next().value;
		}
		/**
		* Gets all idTokens matching the given filter
		* @param filter
		* @returns
		*/
		getIdTokensByFilter(filter, correlationId, tokenKeys) {
			const idTokenKeys = tokenKeys && tokenKeys.idToken || this.getTokenKeys().idToken;
			const idTokens = /* @__PURE__ */ new Map();
			idTokenKeys.forEach((key) => {
				if (!this.idTokenKeyMatchesFilter(key, {
					clientId: this.clientId,
					...filter
				})) return;
				const idToken = this.getIdTokenCredential(key, correlationId);
				if (idToken && this.credentialMatchesFilter(idToken, filter, correlationId)) idTokens.set(key, idToken);
			});
			return idTokens;
		}
		/**
		* Validate the cache key against filter before retrieving and parsing cache value
		* @param key
		* @param filter
		* @returns
		*/
		idTokenKeyMatchesFilter(inputKey, filter) {
			const key = inputKey.toLowerCase();
			if (filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) return false;
			if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) return false;
			return true;
		}
		/**
		* Removes idToken from the cache
		* @param key
		*/
		removeIdToken(key, correlationId) {
			this.removeItem(key, correlationId);
		}
		/**
		* Removes refresh token from the cache
		* @param key
		*/
		removeRefreshToken(key, correlationId) {
			this.removeItem(key, correlationId);
		}
		/**
		* Retrieve AccessTokenEntity from cache
		* @param account {AccountInfo}
		* @param request {BaseAuthRequest}
		* @param tokenKeys {?TokenKeys}
		* @param performanceClient {?IPerformanceClient}
		*/
		getAccessToken(account, request, tokenKeys, targetRealm) {
			const correlationId = request.correlationId;
			this.commonLogger.trace("CacheManager - getAccessToken called", correlationId);
			const scopes = ScopeSet.createSearchScopes(request.scopes);
			const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER;
			const credentialType = authScheme.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase() ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME : CredentialType.ACCESS_TOKEN;
			const accessTokenFilter = {
				homeAccountId: account.homeAccountId,
				environment: account.environment,
				credentialType,
				clientId: this.clientId,
				realm: targetRealm || account.tenantId,
				target: scopes,
				tokenType: authScheme,
				keyId: request.sshKid
			};
			const accessTokenKeys = tokenKeys && tokenKeys.accessToken || this.getTokenKeys().accessToken;
			const accessTokens = [];
			accessTokenKeys.forEach((key) => {
				if (this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) {
					const accessToken = this.getAccessTokenCredential(key, correlationId);
					if (accessToken && this.credentialMatchesFilter(accessToken, accessTokenFilter, correlationId)) accessTokens.push(accessToken);
				}
			});
			const numAccessTokens = accessTokens.length;
			if (numAccessTokens < 1) {
				this.commonLogger.info("CacheManager:getAccessToken - No token found", correlationId);
				return null;
			} else if (numAccessTokens > 1) {
				this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them", correlationId);
				accessTokens.forEach((accessToken) => {
					this.removeAccessToken(this.generateCredentialKey(accessToken), correlationId);
				});
				this.performanceClient.addFields({ multiMatchedAT: accessTokens.length }, correlationId);
				return null;
			}
			this.commonLogger.info("CacheManager:getAccessToken - Returning access token", correlationId);
			return accessTokens[0];
		}
		/**
		* Validate the cache key against filter before retrieving and parsing cache value
		* @param key
		* @param filter
		* @param keyMustContainAllScopes
		* @returns
		*/
		accessTokenKeyMatchesFilter(inputKey, filter, keyMustContainAllScopes) {
			const key = inputKey.toLowerCase();
			if (filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) return false;
			if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) return false;
			if (filter.realm && key.indexOf(filter.realm.toLowerCase()) === -1) return false;
			if (filter.target) {
				const scopes = filter.target.asArray();
				for (let i = 0; i < scopes.length; i++) if (keyMustContainAllScopes && !key.includes(scopes[i].toLowerCase())) return false;
				else if (!keyMustContainAllScopes && key.includes(scopes[i].toLowerCase())) return true;
			}
			return true;
		}
		/**
		* Gets all access tokens matching the filter
		* @param filter
		* @returns
		*/
		getAccessTokensByFilter(filter, correlationId) {
			const tokenKeys = this.getTokenKeys();
			const accessTokens = [];
			tokenKeys.accessToken.forEach((key) => {
				if (!this.accessTokenKeyMatchesFilter(key, filter, true)) return;
				const accessToken = this.getAccessTokenCredential(key, correlationId);
				if (accessToken && this.credentialMatchesFilter(accessToken, filter, correlationId)) accessTokens.push(accessToken);
			});
			return accessTokens;
		}
		/**
		* Helper to retrieve the appropriate refresh token from cache
		* @param account {AccountInfo}
		* @param familyRT {boolean}
		* @param tokenKeys {?TokenKeys}
		* @param performanceClient {?IPerformanceClient}
		* @param correlationId {?string}
		*/
		getRefreshToken(account, familyRT, correlationId, tokenKeys) {
			this.commonLogger.trace("CacheManager - getRefreshToken called", correlationId);
			const id = familyRT ? THE_FAMILY_ID : void 0;
			const refreshTokenFilter = {
				homeAccountId: account.homeAccountId,
				environment: account.environment,
				credentialType: CredentialType.REFRESH_TOKEN,
				clientId: this.clientId,
				familyId: id
			};
			const refreshTokenKeys = tokenKeys && tokenKeys.refreshToken || this.getTokenKeys().refreshToken;
			const refreshTokens = [];
			refreshTokenKeys.forEach((key) => {
				if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) {
					const refreshToken = this.getRefreshTokenCredential(key, correlationId);
					if (refreshToken && this.credentialMatchesFilter(refreshToken, refreshTokenFilter, correlationId)) refreshTokens.push(refreshToken);
				}
			});
			const numRefreshTokens = refreshTokens.length;
			if (numRefreshTokens < 1) {
				this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found.", correlationId);
				return null;
			}
			if (numRefreshTokens > 1) this.performanceClient.addFields({ multiMatchedRT: numRefreshTokens }, correlationId);
			this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token", correlationId);
			return refreshTokens[0];
		}
		/**
		* Validate the cache key against filter before retrieving and parsing cache value
		* @param key
		* @param filter
		*/
		refreshTokenKeyMatchesFilter(inputKey, filter) {
			const key = inputKey.toLowerCase();
			if (filter.familyId && key.indexOf(filter.familyId.toLowerCase()) === -1) return false;
			if (!filter.familyId && filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) return false;
			if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) return false;
			return true;
		}
		/**
		* Retrieve AppMetadataEntity from cache
		*/
		readAppMetadataFromCache(environment, correlationId) {
			const appMetadataFilter = {
				environment,
				clientId: this.clientId
			};
			const appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter, correlationId);
			const appMetadataEntries = Object.keys(appMetadata).map((key) => appMetadata[key]);
			const numAppMetadata = appMetadataEntries.length;
			if (numAppMetadata < 1) return null;
			else if (numAppMetadata > 1) throw createClientAuthError(multipleMatchingAppMetadata);
			return appMetadataEntries[0];
		}
		/**
		* Return the family_id value associated  with FOCI
		* @param environment
		* @param clientId
		*/
		isAppMetadataFOCI(environment, correlationId) {
			const appMetadata = this.readAppMetadataFromCache(environment, correlationId);
			return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID);
		}
		/**
		* helper to match account ids
		* @param value
		* @param homeAccountId
		*/
		matchHomeAccountId(entity, homeAccountId) {
			return !!(typeof entity.homeAccountId === "string" && homeAccountId === entity.homeAccountId);
		}
		/**
		* helper to match account ids
		* @param entity
		* @param localAccountId
		* @returns
		*/
		matchLocalAccountIdFromTokenClaims(tokenClaims, localAccountId) {
			return localAccountId === (tokenClaims.oid || tokenClaims.sub);
		}
		matchLocalAccountIdFromTenantProfile(tenantProfile, localAccountId) {
			return tenantProfile.localAccountId === localAccountId;
		}
		/**
		* helper to match names
		* @param entity
		* @param name
		* @returns true if the downcased name properties are present and match in the filter and the entity
		*/
		matchName(claims, name) {
			return !!(name.toLowerCase() === claims.name?.toLowerCase());
		}
		/**
		* helper to match usernames
		* @param entity
		* @param username
		* @returns
		*/
		matchUsername(cachedUsername, filterUsername) {
			return !!(cachedUsername && typeof cachedUsername === "string" && filterUsername?.toLowerCase() === cachedUsername.toLowerCase());
		}
		/**
		* helper to match assertion
		* @param value
		* @param oboAssertion
		*/
		matchUserAssertionHash(entity, userAssertionHash) {
			return !!(entity.userAssertionHash && userAssertionHash === entity.userAssertionHash);
		}
		/**
		* helper to match environment
		* @param value
		* @param environment
		*/
		matchEnvironment(entity, environment, correlationId) {
			if (this.staticAuthorityOptions) {
				const staticAliases = getAliasesFromStaticSources(this.staticAuthorityOptions, this.commonLogger, correlationId);
				if (staticAliases.includes(environment) && staticAliases.includes(entity.environment)) return true;
			}
			const cloudMetadata = this.getAuthorityMetadataByAlias(environment, correlationId);
			if (cloudMetadata && cloudMetadata.aliases.indexOf(entity.environment) > -1) return true;
			return false;
		}
		/**
		* helper to match credential type
		* @param entity
		* @param credentialType
		*/
		matchCredentialType(entity, credentialType) {
			return entity.credentialType && credentialType.toLowerCase() === entity.credentialType.toLowerCase();
		}
		/**
		* helper to match client ids
		* @param entity
		* @param clientId
		*/
		matchClientId(entity, clientId) {
			return !!(entity.clientId && clientId === entity.clientId);
		}
		/**
		* helper to match family ids
		* @param entity
		* @param familyId
		*/
		matchFamilyId(entity, familyId) {
			return !!(entity.familyId && familyId === entity.familyId);
		}
		/**
		* helper to match realm
		* @param entity
		* @param realm
		*/
		matchRealm(entity, realm) {
			return !!(entity.realm?.toLowerCase() === realm.toLowerCase());
		}
		/**
		* helper to match nativeAccountId
		* @param entity
		* @param nativeAccountId
		* @returns boolean indicating the match result
		*/
		matchNativeAccountId(entity, nativeAccountId) {
			return !!(entity.nativeAccountId && nativeAccountId === entity.nativeAccountId);
		}
		/**
		* helper to match loginHint which can be either:
		* 1. login_hint ID token claim
		* 2. username in cached account object
		* 3. upn in ID token claims
		* @param entity
		* @param loginHint
		* @returns
		*/
		matchLoginHintFromTokenClaims(tokenClaims, loginHint) {
			if (tokenClaims.login_hint === loginHint) return true;
			if (tokenClaims.preferred_username === loginHint) return true;
			if (tokenClaims.upn === loginHint) return true;
			return false;
		}
		/**
		* Helper to match sid
		* @param entity
		* @param sid
		* @returns true if the sid claim is present and matches the filter
		*/
		matchSid(idTokenClaims, sid) {
			return idTokenClaims.sid === sid;
		}
		matchAuthorityType(entity, authorityType) {
			return !!(entity.authorityType && authorityType.toLowerCase() === entity.authorityType.toLowerCase());
		}
		/**
		* Returns true if the target scopes are a subset of the current entity's scopes, false otherwise.
		* @param entity
		* @param target
		*/
		matchTarget(entity, target) {
			if (entity.credentialType !== CredentialType.ACCESS_TOKEN && entity.credentialType !== CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME || !entity.target) return false;
			return ScopeSet.fromString(entity.target).containsScopeSet(target);
		}
		/**
		* Returns true if the credential's tokenType or Authentication Scheme matches the one in the request, false otherwise
		* @param entity
		* @param tokenType
		*/
		matchTokenType(entity, tokenType) {
			return !!(entity.tokenType && entity.tokenType === tokenType);
		}
		/**
		* Returns true if the credential's keyId matches the one in the request, false otherwise
		* @param entity
		* @param keyId
		*/
		matchKeyId(entity, keyId) {
			return !!(entity.keyId && entity.keyId === keyId);
		}
		/**
		* returns if a given cache entity is of the type appmetadata
		* @param key
		*/
		isAppMetadata(key) {
			return key.indexOf(APP_METADATA) !== -1;
		}
		/**
		* returns if a given cache entity is of the type authoritymetadata
		* @param key
		*/
		isAuthorityMetadata(key) {
			return key.indexOf(AUTHORITY_METADATA_CACHE_KEY) !== -1;
		}
		/**
		* returns cache key used for cloud instance metadata
		*/
		generateAuthorityMetadataCacheKey(authority) {
			return `${AUTHORITY_METADATA_CACHE_KEY}-${this.clientId}-${authority}`;
		}
		/**
		* Helper to convert serialized data to object
		* @param obj
		* @param json
		*/
		static toObject(obj, json) {
			for (const propertyName in json) obj[propertyName] = json[propertyName];
			return obj;
		}
	};
	/** @internal */
	var DefaultStorageClass = class extends CacheManager {
		async setAccount() {
			throw createClientAuthError(methodNotImplemented);
		}
		getAccount() {
			throw createClientAuthError(methodNotImplemented);
		}
		async setIdTokenCredential() {
			throw createClientAuthError(methodNotImplemented);
		}
		getIdTokenCredential() {
			throw createClientAuthError(methodNotImplemented);
		}
		async setAccessTokenCredential() {
			throw createClientAuthError(methodNotImplemented);
		}
		getAccessTokenCredential() {
			throw createClientAuthError(methodNotImplemented);
		}
		async setRefreshTokenCredential() {
			throw createClientAuthError(methodNotImplemented);
		}
		getRefreshTokenCredential() {
			throw createClientAuthError(methodNotImplemented);
		}
		setAppMetadata() {
			throw createClientAuthError(methodNotImplemented);
		}
		getAppMetadata() {
			throw createClientAuthError(methodNotImplemented);
		}
		setServerTelemetry() {
			throw createClientAuthError(methodNotImplemented);
		}
		getServerTelemetry() {
			throw createClientAuthError(methodNotImplemented);
		}
		setAuthorityMetadata() {
			throw createClientAuthError(methodNotImplemented);
		}
		getAuthorityMetadata() {
			throw createClientAuthError(methodNotImplemented);
		}
		getAuthorityMetadataKeys() {
			throw createClientAuthError(methodNotImplemented);
		}
		setThrottlingCache() {
			throw createClientAuthError(methodNotImplemented);
		}
		getThrottlingCache() {
			throw createClientAuthError(methodNotImplemented);
		}
		removeItem() {
			throw createClientAuthError(methodNotImplemented);
		}
		getKeys() {
			throw createClientAuthError(methodNotImplemented);
		}
		getAccountKeys() {
			throw createClientAuthError(methodNotImplemented);
		}
		getTokenKeys() {
			throw createClientAuthError(methodNotImplemented);
		}
		generateCredentialKey() {
			throw createClientAuthError(methodNotImplemented);
		}
		generateAccountKey() {
			throw createClientAuthError(methodNotImplemented);
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* State of the performance event.
	*
	* @export
	* @enum {number}
	*/
	const PerformanceEventStatus = { InProgress: 1 };
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	var StubPerformanceClient = class {
		generateId() {
			return "callback-id";
		}
		startMeasurement(measureName, correlationId) {
			return {
				end: () => null,
				discard: () => {},
				add: () => {},
				increment: () => {},
				event: {
					eventId: this.generateId(),
					status: PerformanceEventStatus.InProgress,
					authority: "",
					libraryName: "",
					libraryVersion: "",
					clientId: "",
					name: measureName,
					startTimeMs: Date.now(),
					correlationId: correlationId || ""
				}
			};
		}
		endMeasurement() {
			return null;
		}
		discardMeasurements() {}
		removePerformanceCallback() {
			return true;
		}
		addPerformanceCallback() {
			return "";
		}
		emitEvents() {}
		addFields() {}
		incrementFields() {}
		cacheEventByCorrelationId() {}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const DEFAULT_SYSTEM_OPTIONS$1 = {
		tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,
		preventCorsPreflight: false
	};
	const DEFAULT_LOGGER_IMPLEMENTATION = {
		loggerCallback: () => {},
		piiLoggingEnabled: false,
		logLevel: exports.LogLevel.Info,
		correlationId: ""
	};
	const DEFAULT_NETWORK_IMPLEMENTATION = {
		async sendGetRequestAsync() {
			throw createClientAuthError(methodNotImplemented);
		},
		async sendPostRequestAsync() {
			throw createClientAuthError(methodNotImplemented);
		}
	};
	const DEFAULT_LIBRARY_INFO = {
		sku: SKU,
		version: version$1,
		cpu: "",
		os: ""
	};
	const DEFAULT_CLIENT_CREDENTIALS = {
		clientSecret: "",
		clientAssertion: void 0
	};
	const DEFAULT_AZURE_CLOUD_OPTIONS = {
		azureCloudInstance: AzureCloudInstance.None,
		tenant: `${DEFAULT_COMMON_TENANT}`
	};
	const DEFAULT_TELEMETRY_OPTIONS$1 = { application: {
		appName: "",
		appVersion: ""
	} };
	/**
	* Function that sets the default options when not explicitly configured from app developer
	*
	* @param Configuration
	*
	* @returns Configuration
	*/
	function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials, libraryInfo, telemetry, serverTelemetryManager, persistencePlugin, serializableCache }) {
		const loggerOptions = {
			...DEFAULT_LOGGER_IMPLEMENTATION,
			...userLoggerOption
		};
		return {
			authOptions: buildAuthOptions(userAuthOptions),
			systemOptions: {
				...DEFAULT_SYSTEM_OPTIONS$1,
				...userSystemOptions
			},
			loggerOptions,
			storageInterface: storageImplementation || new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions), new StubPerformanceClient()),
			networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,
			cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,
			clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,
			libraryInfo: {
				...DEFAULT_LIBRARY_INFO,
				...libraryInfo
			},
			telemetry: {
				...DEFAULT_TELEMETRY_OPTIONS$1,
				...telemetry
			},
			serverTelemetryManager: serverTelemetryManager || null,
			persistencePlugin: persistencePlugin || null,
			serializableCache: serializableCache || null
		};
	}
	/**
	* Construct authoptions from the client and platform passed values
	* @param authOptions
	*/
	function buildAuthOptions(authOptions) {
		return {
			clientCapabilities: [],
			azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS,
			instanceAware: false,
			...authOptions
		};
	}
	/**
	* Returns true if config has protocolMode set to ProtocolMode.OIDC, false otherwise
	* @param ClientConfiguration
	*/
	function isOidcProtocolMode(config) {
		return config.authOptions.authority.options.protocolMode === ProtocolMode.OIDC;
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Error thrown when there is an error with the server code, for example, unavailability.
	*/
	var ServerError = class ServerError extends AuthError {
		constructor(errorCode, errorMessage, subError, errorNo, status) {
			super(errorCode, errorMessage, subError);
			this.name = "ServerError";
			this.errorNo = errorNo;
			this.status = status;
			Object.setPrototypeOf(this, ServerError.prototype);
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* MSAL-defined interaction required error code indicating no tokens are found in cache.
	* @public
	*/
	const noTokensFound = "no_tokens_found";
	/**
	* MSAL-defined error code indicating a native account is unavailable on the platform.
	* @public
	*/
	const nativeAccountUnavailable = "native_account_unavailable";
	/**
	* MSAL-defined error code indicating the refresh token has expired and user interaction is needed.
	* @public
	*/
	const refreshTokenExpired = "refresh_token_expired";
	/**
	* MSAL-defined error code indicating UI/UX is not allowed (e.g., blocked by policy), requiring alternate interaction.
	* @public
	*/
	const uxNotAllowed = "ux_not_allowed";
	/**
	* Server-originated error code indicating interaction is required to complete the request.
	* @public
	*/
	const interactionRequired = "interaction_required";
	/**
	* Server-originated error code indicating user consent is required.
	* @public
	*/
	const consentRequired = "consent_required";
	/**
	* Server-originated error code indicating user login is required.
	* @public
	*/
	const loginRequired = "login_required";
	/**
	* Server-originated error code indicating the token is invalid or corrupted.
	* @public
	*/
	const badToken = "bad_token";
	/**
	* Server-originated error code indicating the user is in an interrupted state and interaction is required.
	* @public
	*/
	const interruptedUser = "interrupted_user";
	var InteractionRequiredAuthErrorCodes = /* @__PURE__ */ Object.freeze({
		__proto__: null,
		badToken,
		consentRequired,
		interactionRequired,
		interruptedUser,
		loginRequired,
		nativeAccountUnavailable,
		noTokensFound,
		refreshTokenExpired,
		uxNotAllowed
	});
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* InteractionRequiredServerErrorMessage contains string constants used by error codes and messages returned by the server indicating interaction is required
	*/
	const InteractionRequiredServerErrorMessage = [
		interactionRequired,
		consentRequired,
		loginRequired,
		badToken,
		uxNotAllowed,
		interruptedUser
	];
	const InteractionRequiredAuthSubErrorMessage = [
		"message_only",
		"additional_action",
		"basic_action",
		"user_password_expired",
		"consent_required",
		"bad_token",
		"ux_not_allowed",
		"interrupted_user"
	];
	/**
	* Error thrown when user interaction is required.
	*/
	var InteractionRequiredAuthError = class InteractionRequiredAuthError extends AuthError {
		constructor(errorCode, errorMessage, subError, timestamp, traceId, correlationId, claims, errorNo) {
			super(errorCode, errorMessage, subError);
			Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype);
			this.timestamp = timestamp || "";
			this.traceId = traceId || "";
			this.correlationId = correlationId || "";
			this.claims = claims || "";
			this.name = "InteractionRequiredAuthError";
			this.errorNo = errorNo;
		}
	};
	/**
	* Helper function used to determine if an error thrown by the server requires interaction to resolve
	* @param errorCode
	* @param errorString
	* @param subError
	*/
	function isInteractionRequiredError(errorCode, errorString, subError) {
		const isInteractionRequiredErrorCode = !!errorCode && InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;
		const isInteractionRequiredSubError = !!subError && InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
		const isInteractionRequiredErrorDesc = !!errorString && InteractionRequiredServerErrorMessage.some((irErrorCode) => {
			return errorString.indexOf(irErrorCode) > -1;
		});
		return isInteractionRequiredErrorCode || isInteractionRequiredErrorDesc || isInteractionRequiredSubError;
	}
	/**
	* Creates an InteractionRequiredAuthError
	*/
	function createInteractionRequiredAuthError(errorCode, errorMessage) {
		return new InteractionRequiredAuthError(errorCode, errorMessage);
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user.
	* @param base64Decode
	* @param state
	*/
	function parseRequestState(base64Decode, state) {
		if (!base64Decode) throw createClientAuthError(noCryptoObject);
		if (!state) throw createClientAuthError(invalidState);
		try {
			const splitState = state.split(RESOURCE_DELIM);
			const libraryState = splitState[0];
			const userState = splitState.length > 1 ? splitState.slice(1).join(RESOURCE_DELIM) : "";
			const libraryStateString = base64Decode(libraryState);
			const libraryStateObj = JSON.parse(libraryStateString);
			return {
				userRequestState: userState || "",
				libraryState: libraryStateObj
			};
		} catch (e) {
			throw createClientAuthError(invalidState);
		}
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Utility functions for managing date and time operations.
	*/
	/**
	* return the current time in Unix time (seconds).
	*/
	function nowSeconds() {
		return Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3);
	}
	/**
	* Convert seconds to JS Date object. Seconds can be in a number or string format or undefined (will still return a date).
	* @param seconds
	*/
	function toDateFromSeconds(seconds) {
		if (seconds) return /* @__PURE__ */ new Date(Number(seconds) * 1e3);
		return /* @__PURE__ */ new Date();
	}
	/**
	* check if a token is expired based on given UTC time in seconds.
	* @param expiresOn
	*/
	function isTokenExpired(expiresOn, offset) {
		const expirationSec = Number(expiresOn) || 0;
		return nowSeconds() + offset > expirationSec;
	}
	/**
	* If the current time is earlier than the time that a token was cached at, we must discard the token
	* i.e. The system clock was turned back after acquiring the cached token
	* @param cachedAt
	* @param offset
	*/
	function wasClockTurnedBack(cachedAt) {
		return Number(cachedAt) > nowSeconds();
	}
	/**
	* Waits for t number of milliseconds
	* @param t number
	* @param value T
	*/
	function delay(t, value) {
		return new Promise((resolve) => setTimeout(() => resolve(value), t));
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Time spent sending/waiting for the response of a request to the token endpoint
	*/
	const NetworkClientSendPostRequestAsync = "networkClientSendPostRequestAsync";
	const RefreshTokenClientExecutePostToTokenEndpoint = "refreshTokenClientExecutePostToTokenEndpoint";
	const AuthorizationCodeClientExecutePostToTokenEndpoint = "authorizationCodeClientExecutePostToTokenEndpoint";
	/**
	* Time spent on the network for refresh token acquisition
	*/
	const RefreshTokenClientExecuteTokenRequest = "refreshTokenClientExecuteTokenRequest";
	/**
	* Time taken for acquiring refresh token , records RT size
	*/
	const RefreshTokenClientAcquireToken = "refreshTokenClientAcquireToken";
	/**
	* Time taken for acquiring cached refresh token
	*/
	const RefreshTokenClientAcquireTokenWithCachedRefreshToken = "refreshTokenClientAcquireTokenWithCachedRefreshToken";
	/**
	* Helper function to create token request body in RefreshTokenClient (msal-common).
	*/
	const RefreshTokenClientCreateTokenRequestBody = "refreshTokenClientCreateTokenRequestBody";
	const SilentFlowClientGenerateResultFromCacheRecord = "silentFlowClientGenerateResultFromCacheRecord";
	/**
	* APIs in Authorization Code Client (msal-common)
	*/
	const AuthClientExecuteTokenRequest = "authClientExecuteTokenRequest";
	const AuthClientCreateTokenRequestBody = "authClientCreateTokenRequestBody";
	const UpdateTokenEndpointAuthority = "updateTokenEndpointAuthority";
	/**
	* Generate functions in PopTokenGenerator (msal-common)
	*/
	const PopTokenGenerateCnf = "popTokenGenerateCnf";
	/**
	* handleServerTokenResponse API in ResponseHandler (msal-common)
	*/
	const HandleServerTokenResponse = "handleServerTokenResponse";
	/**
	* Authority functions
	*/
	const AuthorityResolveEndpointsAsync = "authorityResolveEndpointsAsync";
	const AuthorityGetCloudDiscoveryMetadataFromNetwork = "authorityGetCloudDiscoveryMetadataFromNetwork";
	const AuthorityUpdateCloudDiscoveryMetadata = "authorityUpdateCloudDiscoveryMetadata";
	const AuthorityGetEndpointMetadataFromNetwork = "authorityGetEndpointMetadataFromNetwork";
	const AuthorityUpdateEndpointMetadata = "authorityUpdateEndpointMetadata";
	const AuthorityUpdateMetadataWithRegionalInformation = "authorityUpdateMetadataWithRegionalInformation";
	/**
	* Region Discovery functions
	*/
	const RegionDiscoveryDetectRegion = "regionDiscoveryDetectRegion";
	const RegionDiscoveryGetRegionFromIMDS = "regionDiscoveryGetRegionFromIMDS";
	const RegionDiscoveryGetCurrentVersion = "regionDiscoveryGetCurrentVersion";
	/**
	* Cache operations
	*/
	const CacheManagerGetRefreshToken = "cacheManagerGetRefreshToken";
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Wraps a function with a performance measurement.
	* Usage: invoke(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
	* @param callback
	* @param eventName
	* @param logger
	* @param telemetryClient
	* @param correlationId
	* @returns
	* @internal
	*/
	const invoke = (callback, eventName, logger, telemetryClient, correlationId) => {
		return (...args) => {
			logger.trace(`Executing function '${eventName}'`, correlationId);
			const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);
			if (correlationId) {
				const eventCount = eventName + "CallCount";
				telemetryClient.incrementFields({ [eventCount]: 1 }, correlationId);
			}
			try {
				const result = callback(...args);
				inProgressEvent.end({ success: true });
				logger.trace(`Returning result from '${eventName}'`, correlationId);
				return result;
			} catch (e) {
				logger.trace(`Error occurred in '${eventName}'`, correlationId);
				try {
					logger.trace(JSON.stringify(e), correlationId);
				} catch (e) {
					logger.trace("Unable to print error message.", correlationId);
				}
				inProgressEvent.end({ success: false }, e);
				throw e;
			}
		};
	};
	/**
	* Wraps an async function with a performance measurement.
	* Usage: invokeAsync(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
	* @param callback
	* @param eventName
	* @param logger
	* @param telemetryClient
	* @param correlationId
	* @returns
	* @internal
	*
	*/
	const invokeAsync = (callback, eventName, logger, telemetryClient, correlationId) => {
		return (...args) => {
			logger.trace(`Executing function '${eventName}'`, correlationId);
			const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);
			if (correlationId) {
				const eventCount = eventName + "CallCount";
				telemetryClient.incrementFields({ [eventCount]: 1 }, correlationId);
			}
			return callback(...args).then((response) => {
				logger.trace(`Returning result from '${eventName}'`, correlationId);
				inProgressEvent.end({ success: true });
				return response;
			}).catch((e) => {
				logger.trace(`Error occurred in '${eventName}'`, correlationId);
				try {
					logger.trace(JSON.stringify(e), correlationId);
				} catch (e) {
					logger.trace("Unable to print error message.", correlationId);
				}
				inProgressEvent.end({ success: false }, e);
				throw e;
			});
		};
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const KeyLocation = { SW: "sw" };
	/** @internal */
	var PopTokenGenerator = class {
		constructor(cryptoUtils, performanceClient) {
			this.cryptoUtils = cryptoUtils;
			this.performanceClient = performanceClient;
		}
		/**
		* Generates the req_cnf validated at the RP in the POP protocol for SHR parameters
		* and returns an object containing the keyid, the full req_cnf string and the req_cnf string hash
		* @param request
		* @returns
		*/
		async generateCnf(request, logger) {
			const reqCnf = await invokeAsync(this.generateKid.bind(this), PopTokenGenerateCnf, logger, this.performanceClient, request.correlationId)(request);
			const reqCnfString = this.cryptoUtils.base64UrlEncode(JSON.stringify(reqCnf));
			return {
				kid: reqCnf.kid,
				reqCnfString
			};
		}
		/**
		* Generates key_id for a SHR token request
		* @param request
		* @returns
		*/
		async generateKid(request) {
			return {
				kid: await this.cryptoUtils.getPublicKeyThumbprint(request),
				xms_ksl: KeyLocation.SW
			};
		}
		/**
		* Signs the POP access_token with the local generated key-pair
		* @param accessToken
		* @param request
		* @returns
		*/
		async signPopToken(accessToken, keyId, request) {
			return this.signPayload(accessToken, keyId, request);
		}
		/**
		* Utility function to generate the signed JWT for an access_token
		* @param payload
		* @param kid
		* @param request
		* @param claims
		* @returns
		*/
		async signPayload(payload, keyId, request, claims) {
			const { resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, shrOptions } = request;
			const resourceUrlComponents = (resourceRequestUri ? new UrlString(resourceRequestUri) : void 0)?.getUrlComponents();
			return this.cryptoUtils.signJwt({
				at: payload,
				ts: nowSeconds(),
				m: resourceRequestMethod?.toUpperCase(),
				u: resourceUrlComponents?.HostNameAndPort,
				nonce: shrNonce || this.cryptoUtils.createNewGuid(),
				p: resourceUrlComponents?.AbsolutePath,
				q: resourceUrlComponents?.QueryString ? [[], resourceUrlComponents.QueryString] : void 0,
				client_claims: shrClaims || void 0,
				...claims
			}, keyId, shrOptions, request.correlationId);
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* This class instance helps track the memory changes facilitating
	* decisions to read from and write to the persistent cache
	*/ var TokenCacheContext = class {
		constructor(tokenCache, hasChanged) {
			this.cache = tokenCache;
			this.hasChanged = hasChanged;
		}
		/**
		* boolean which indicates the changes in cache
		*/
		get cacheHasChanged() {
			return this.hasChanged;
		}
		/**
		* function to retrieve the token cache
		*/
		get tokenCache() {
			return this.cache;
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Create IdTokenEntity
	* @param homeAccountId
	* @param authenticationResult
	* @param clientId
	* @param authority
	*/
	function createIdTokenEntity(homeAccountId, environment, idToken, clientId, tenantId) {
		return {
			credentialType: CredentialType.ID_TOKEN,
			homeAccountId,
			environment,
			clientId,
			secret: idToken,
			realm: tenantId,
			lastUpdatedAt: Date.now().toString()
		};
	}
	/**
	* Create AccessTokenEntity
	* @param homeAccountId
	* @param environment
	* @param accessToken
	* @param clientId
	* @param tenantId
	* @param scopes
	* @param expiresOn
	* @param extExpiresOn
	*/
	function createAccessTokenEntity(homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, base64Decode, refreshOn, tokenType, userAssertionHash, keyId) {
		const atEntity = {
			homeAccountId,
			credentialType: CredentialType.ACCESS_TOKEN,
			secret: accessToken,
			cachedAt: nowSeconds().toString(),
			expiresOn: expiresOn.toString(),
			extendedExpiresOn: extExpiresOn.toString(),
			environment,
			clientId,
			realm: tenantId,
			target: scopes,
			tokenType: tokenType || AuthenticationScheme.BEARER,
			lastUpdatedAt: Date.now().toString()
		};
		if (userAssertionHash) atEntity.userAssertionHash = userAssertionHash;
		if (refreshOn) atEntity.refreshOn = refreshOn.toString();
		if (atEntity.tokenType?.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase()) {
			atEntity.credentialType = CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
			switch (atEntity.tokenType) {
				case AuthenticationScheme.POP:
					const tokenClaims = extractTokenClaims(accessToken, base64Decode);
					if (!tokenClaims?.cnf?.kid) throw createClientAuthError(tokenClaimsCnfRequiredForSignedJwt);
					atEntity.keyId = tokenClaims.cnf.kid;
					break;
				case AuthenticationScheme.SSH: atEntity.keyId = keyId;
			}
		}
		return atEntity;
	}
	/**
	* Create RefreshTokenEntity
	* @param homeAccountId
	* @param authenticationResult
	* @param clientId
	* @param authority
	*/
	function createRefreshTokenEntity(homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash, expiresOn) {
		const rtEntity = {
			credentialType: CredentialType.REFRESH_TOKEN,
			homeAccountId,
			environment,
			clientId,
			secret: refreshToken,
			lastUpdatedAt: Date.now().toString()
		};
		if (userAssertionHash) rtEntity.userAssertionHash = userAssertionHash;
		if (familyId) rtEntity.familyId = familyId;
		if (expiresOn) rtEntity.expiresOn = expiresOn.toString();
		return rtEntity;
	}
	function isCredentialEntity(entity) {
		return entity.hasOwnProperty("homeAccountId") && entity.hasOwnProperty("environment") && entity.hasOwnProperty("credentialType") && entity.hasOwnProperty("clientId") && entity.hasOwnProperty("secret");
	}
	/**
	* Validates an entity: checks for all expected params
	* @param entity
	*/
	function isAccessTokenEntity(entity) {
		if (!entity) return false;
		return isCredentialEntity(entity) && entity.hasOwnProperty("realm") && entity.hasOwnProperty("target") && (entity["credentialType"] === CredentialType.ACCESS_TOKEN || entity["credentialType"] === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME);
	}
	/**
	* Validates an entity: checks for all expected params
	* @param entity
	*/
	function isIdTokenEntity(entity) {
		if (!entity) return false;
		return isCredentialEntity(entity) && entity.hasOwnProperty("realm") && entity["credentialType"] === CredentialType.ID_TOKEN;
	}
	/**
	* Validates an entity: checks for all expected params
	* @param entity
	*/
	function isRefreshTokenEntity(entity) {
		if (!entity) return false;
		return isCredentialEntity(entity) && entity["credentialType"] === CredentialType.REFRESH_TOKEN;
	}
	/**
	* validates if a given cache entry is "Telemetry", parses <key,value>
	* @param key
	* @param entity
	*/
	function isServerTelemetryEntity(key, entity) {
		const validateKey = key.indexOf(SERVER_TELEM_CACHE_KEY) === 0;
		let validateEntity = true;
		if (entity) validateEntity = entity.hasOwnProperty("failedRequests") && entity.hasOwnProperty("errors") && entity.hasOwnProperty("cacheHits");
		return validateKey && validateEntity;
	}
	/**
	* validates if a given cache entry is "Throttling", parses <key,value>
	* @param key
	* @param entity
	*/
	function isThrottlingEntity(key, entity) {
		let validateKey = false;
		if (key) validateKey = key.indexOf(THROTTLING_PREFIX) === 0;
		let validateEntity = true;
		if (entity) validateEntity = entity.hasOwnProperty("throttleTime");
		return validateKey && validateEntity;
	}
	/**
	* Generate AppMetadata Cache Key as per the schema: appmetadata-<environment>-<client_id>
	*/
	function generateAppMetadataKey({ environment, clientId }) {
		return [
			APP_METADATA,
			environment,
			clientId
		].join(CACHE_KEY_SEPARATOR).toLowerCase();
	}
	function isAppMetadataEntity(key, entity) {
		if (!entity) return false;
		return key.indexOf(APP_METADATA) === 0 && entity.hasOwnProperty("clientId") && entity.hasOwnProperty("environment");
	}
	/**
	* Validates an entity: checks for all expected params
	* @param entity
	*/
	function isAuthorityMetadataEntity(key, entity) {
		if (!entity) return false;
		return key.indexOf(AUTHORITY_METADATA_CACHE_KEY) === 0 && entity.hasOwnProperty("aliases") && entity.hasOwnProperty("preferred_cache") && entity.hasOwnProperty("preferred_network") && entity.hasOwnProperty("canonical_authority") && entity.hasOwnProperty("authorization_endpoint") && entity.hasOwnProperty("token_endpoint") && entity.hasOwnProperty("issuer") && entity.hasOwnProperty("aliasesFromNetwork") && entity.hasOwnProperty("endpointsFromNetwork") && entity.hasOwnProperty("expiresAt") && entity.hasOwnProperty("jwks_uri");
	}
	/**
	* Reset the exiresAt value
	*/
	function generateAuthorityMetadataExpiresAt() {
		return nowSeconds() + AUTHORITY_METADATA_REFRESH_TIME_SECONDS;
	}
	function updateAuthorityEndpointMetadata(authorityMetadata, updatedValues, fromNetwork) {
		authorityMetadata.authorization_endpoint = updatedValues.authorization_endpoint;
		authorityMetadata.token_endpoint = updatedValues.token_endpoint;
		authorityMetadata.end_session_endpoint = updatedValues.end_session_endpoint;
		authorityMetadata.issuer = updatedValues.issuer;
		authorityMetadata.endpointsFromNetwork = fromNetwork;
		authorityMetadata.jwks_uri = updatedValues.jwks_uri;
	}
	function updateCloudDiscoveryMetadata(authorityMetadata, updatedValues, fromNetwork) {
		authorityMetadata.aliases = updatedValues.aliases;
		authorityMetadata.preferred_cache = updatedValues.preferred_cache;
		authorityMetadata.preferred_network = updatedValues.preferred_network;
		authorityMetadata.aliasesFromNetwork = fromNetwork;
	}
	/**
	* Returns whether or not the data needs to be refreshed
	*/
	function isAuthorityMetadataExpired(metadata) {
		return metadata.expiresAt <= nowSeconds();
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Class that handles response parsing.
	* @internal
	*/
	var ResponseHandler = class ResponseHandler {
		constructor(clientId, cacheStorage, cryptoObj, logger, performanceClient, serializableCache, persistencePlugin) {
			this.clientId = clientId;
			this.cacheStorage = cacheStorage;
			this.cryptoObj = cryptoObj;
			this.logger = logger;
			this.performanceClient = performanceClient;
			this.serializableCache = serializableCache;
			this.persistencePlugin = persistencePlugin;
		}
		/**
		* Function which validates server authorization token response.
		* @param serverResponse
		* @param correlationId
		* @param refreshAccessToken
		*/
		validateTokenResponse(serverResponse, correlationId, refreshAccessToken) {
			if (serverResponse.error || serverResponse.error_description || serverResponse.suberror) {
				const errString = `Error(s): ${serverResponse.error_codes || NOT_AVAILABLE} - Timestamp: ${serverResponse.timestamp || NOT_AVAILABLE} - Description: ${serverResponse.error_description || NOT_AVAILABLE} - Correlation ID: ${serverResponse.correlation_id || NOT_AVAILABLE} - Trace ID: ${serverResponse.trace_id || NOT_AVAILABLE}`;
				const serverErrorNo = serverResponse.error_codes?.length ? serverResponse.error_codes[0] : void 0;
				const serverError = new ServerError(serverResponse.error, errString, serverResponse.suberror, serverErrorNo, serverResponse.status);
				if (refreshAccessToken && serverResponse.status && serverResponse.status >= HTTP_SERVER_ERROR_RANGE_START && serverResponse.status <= HTTP_SERVER_ERROR_RANGE_END) {
					this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.\n${serverError}`, correlationId);
					return;
				} else if (refreshAccessToken && serverResponse.status && serverResponse.status >= HTTP_CLIENT_ERROR_RANGE_START && serverResponse.status <= HTTP_CLIENT_ERROR_RANGE_END) {
					this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.\n${serverError}`, correlationId);
					return;
				}
				if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) throw new InteractionRequiredAuthError(serverResponse.error, serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.correlation_id || "", serverResponse.claims || "", serverErrorNo);
				throw serverError;
			}
		}
		/**
		* Returns a constructed token response based on given string. Also manages the cache updates and cleanups.
		* @param serverTokenResponse
		* @param authority
		*/
		async handleServerTokenResponse(serverTokenResponse, authority, reqTimestamp, request, apiId, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId) {
			let idTokenClaims;
			if (serverTokenResponse.id_token) {
				idTokenClaims = extractTokenClaims(serverTokenResponse.id_token || "", this.cryptoObj.base64Decode);
				if (authCodePayload && authCodePayload.nonce) {
					if (idTokenClaims.nonce !== authCodePayload.nonce) throw createClientAuthError(nonceMismatch);
				}
				if (request.maxAge || request.maxAge === 0) {
					const authTime = idTokenClaims.auth_time;
					if (!authTime) throw createClientAuthError(authTimeNotFound);
					checkMaxAge(authTime, request.maxAge);
				}
			}
			this.homeAccountIdentifier = generateHomeAccountId(serverTokenResponse.client_info || "", authority.authorityType, this.logger, this.cryptoObj, request.correlationId, idTokenClaims);
			let requestStateObj;
			if (!!authCodePayload && !!authCodePayload.state) requestStateObj = parseRequestState(this.cryptoObj.base64Decode, authCodePayload.state);
			serverTokenResponse.key_id = serverTokenResponse.key_id || request.sshKid || void 0;
			const cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload);
			let cacheContext;
			try {
				if (this.persistencePlugin && this.serializableCache) {
					this.logger.verbose("Persistence enabled, calling beforeCacheAccess", request.correlationId);
					cacheContext = new TokenCacheContext(this.serializableCache, true);
					await this.persistencePlugin.beforeCacheAccess(cacheContext);
				}
				if (handlingRefreshTokenResponse && !forceCacheRefreshTokenResponse && cacheRecord.account) {
					if (this.cacheStorage.getAllAccounts({
						homeAccountId: cacheRecord.account.homeAccountId,
						environment: cacheRecord.account.environment
					}, request.correlationId).length < 1) {
						this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache", request.correlationId);
						this.performanceClient?.addFields({ acntLoggedOut: true }, request.correlationId);
						return await ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, this.performanceClient, idTokenClaims, requestStateObj, void 0, serverRequestId);
					}
				}
				await this.cacheStorage.saveCacheRecord(cacheRecord, request.correlationId, isKmsi(idTokenClaims || {}), apiId, request.storeInCache);
			} finally {
				if (this.persistencePlugin && this.serializableCache && cacheContext) {
					this.logger.verbose("Persistence enabled, calling afterCacheAccess", request.correlationId);
					await this.persistencePlugin.afterCacheAccess(cacheContext);
				}
			}
			return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, this.performanceClient, idTokenClaims, requestStateObj, serverTokenResponse, serverRequestId);
		}
		/**
		* Generates CacheRecord
		* @param serverTokenResponse
		* @param idTokenObj
		* @param authority
		*/
		generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload) {
			const env = authority.getPreferredCache();
			if (!env) throw createClientAuthError(invalidCacheEnvironment);
			const claimsTenantId = getTenantIdFromIdTokenClaims(idTokenClaims);
			let cachedIdToken;
			let cachedAccount;
			if (serverTokenResponse.id_token && !!idTokenClaims) {
				cachedIdToken = createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token, this.clientId, claimsTenantId || "");
				cachedAccount = buildAccountToCache(this.cacheStorage, authority, this.homeAccountIdentifier, this.cryptoObj.base64Decode, request.correlationId, idTokenClaims, serverTokenResponse.client_info, env, claimsTenantId, authCodePayload, void 0, this.logger);
			}
			let cachedAccessToken = null;
			if (serverTokenResponse.access_token) {
				const responseScopes = serverTokenResponse.scope ? ScopeSet.fromString(serverTokenResponse.scope) : new ScopeSet(request.scopes || []);
				const expiresIn = (typeof serverTokenResponse.expires_in === "string" ? parseInt(serverTokenResponse.expires_in, 10) : serverTokenResponse.expires_in) || 0;
				const extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string" ? parseInt(serverTokenResponse.ext_expires_in, 10) : serverTokenResponse.ext_expires_in) || 0;
				const refreshIn = (typeof serverTokenResponse.refresh_in === "string" ? parseInt(serverTokenResponse.refresh_in, 10) : serverTokenResponse.refresh_in) || void 0;
				const tokenExpirationSeconds = reqTimestamp + expiresIn;
				const extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn;
				const refreshOnSeconds = refreshIn && refreshIn > 0 ? reqTimestamp + refreshIn : void 0;
				cachedAccessToken = createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token, this.clientId, claimsTenantId || authority.tenant || "", responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj.base64Decode, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id);
			}
			let cachedRefreshToken = null;
			if (serverTokenResponse.refresh_token) {
				let rtExpiresOn;
				if (serverTokenResponse.refresh_token_expires_in) {
					rtExpiresOn = reqTimestamp + (typeof serverTokenResponse.refresh_token_expires_in === "string" ? parseInt(serverTokenResponse.refresh_token_expires_in, 10) : serverTokenResponse.refresh_token_expires_in);
					this.performanceClient?.addFields({ ntwkRtExpiresOnSeconds: rtExpiresOn }, request.correlationId);
				}
				cachedRefreshToken = createRefreshTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.refresh_token, this.clientId, serverTokenResponse.foci, userAssertionHash, rtExpiresOn);
			}
			let cachedAppMetadata = null;
			if (serverTokenResponse.foci) cachedAppMetadata = {
				clientId: this.clientId,
				environment: env,
				familyId: serverTokenResponse.foci
			};
			return {
				account: cachedAccount,
				idToken: cachedIdToken,
				accessToken: cachedAccessToken,
				refreshToken: cachedRefreshToken,
				appMetadata: cachedAppMetadata
			};
		}
		/**
		* Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache.
		*
		* Optionally takes a state string that is set as-is in the response.
		*
		* @param cacheRecord
		* @param idTokenObj
		* @param fromTokenCache
		* @param stateString
		*/
		static async generateAuthenticationResult(cryptoObj, authority, cacheRecord, fromTokenCache, request, performanceClient, idTokenClaims, requestState, serverTokenResponse, requestId) {
			let accessToken = "";
			let responseScopes = [];
			let expiresOn = null;
			let extExpiresOn;
			let refreshOn;
			let familyId = "";
			if (cacheRecord.accessToken) {
				if (cacheRecord.accessToken.tokenType === AuthenticationScheme.POP && !request.popKid) {
					const popTokenGenerator = new PopTokenGenerator(cryptoObj, performanceClient);
					const { secret, keyId } = cacheRecord.accessToken;
					if (!keyId) throw createClientAuthError(keyIdMissing);
					accessToken = await popTokenGenerator.signPopToken(secret, keyId, request);
				} else accessToken = cacheRecord.accessToken.secret;
				responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray();
				expiresOn = toDateFromSeconds(cacheRecord.accessToken.expiresOn);
				extExpiresOn = toDateFromSeconds(cacheRecord.accessToken.extendedExpiresOn);
				if (cacheRecord.accessToken.refreshOn) refreshOn = toDateFromSeconds(cacheRecord.accessToken.refreshOn);
			}
			if (cacheRecord.appMetadata) familyId = cacheRecord.appMetadata.familyId === THE_FAMILY_ID ? THE_FAMILY_ID : "";
			const uid = idTokenClaims?.oid || idTokenClaims?.sub || "";
			const tid = idTokenClaims?.tid || "";
			if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) cacheRecord.account.nativeAccountId = serverTokenResponse?.spa_accountid;
			const accountInfo = cacheRecord.account ? updateAccountTenantProfileData(getAccountInfo(cacheRecord.account), void 0, idTokenClaims, cacheRecord.idToken?.secret) : null;
			return {
				authority: authority.canonicalAuthority,
				uniqueId: uid,
				tenantId: tid,
				scopes: responseScopes,
				account: accountInfo,
				idToken: cacheRecord?.idToken?.secret || "",
				idTokenClaims: idTokenClaims || {},
				accessToken,
				fromCache: fromTokenCache,
				expiresOn,
				extExpiresOn,
				refreshOn,
				correlationId: request.correlationId,
				requestId: requestId || "",
				familyId,
				tokenType: cacheRecord.accessToken?.tokenType || "",
				state: requestState ? requestState.userRequestState : "",
				cloudGraphHostName: cacheRecord.account?.cloudGraphHostName || "",
				msGraphHost: cacheRecord.account?.msGraphHost || "",
				code: serverTokenResponse?.spa_code,
				fromPlatformBroker: false
			};
		}
	};
	function buildAccountToCache(cacheStorage, authority, homeAccountId, base64Decode, correlationId, idTokenClaims, clientInfo, environment, claimsTenantId, authCodePayload, nativeAccountId, logger) {
		logger?.verbose("setCachedAccount called", correlationId);
		const baseAccountKey = cacheStorage.getAccountKeys().find((accountKey) => {
			return accountKey.startsWith(homeAccountId);
		});
		let cachedAccount = null;
		if (baseAccountKey) cachedAccount = cacheStorage.getAccount(baseAccountKey, correlationId);
		const baseAccount = cachedAccount || createAccountEntity({
			homeAccountId,
			idTokenClaims,
			clientInfo,
			environment,
			cloudGraphHostName: authCodePayload?.cloud_graph_host_name,
			msGraphHost: authCodePayload?.msgraph_host,
			nativeAccountId
		}, authority, base64Decode);
		const tenantProfiles = baseAccount.tenantProfiles || [];
		const tenantId = claimsTenantId || baseAccount.realm;
		if (tenantId && !tenantProfiles.find((tenantProfile) => {
			return tenantProfile.tenantId === tenantId;
		})) {
			const newTenantProfile = buildTenantProfile(homeAccountId, baseAccount.localAccountId, tenantId, idTokenClaims);
			tenantProfiles.push(newTenantProfile);
		}
		baseAccount.tenantProfiles = tenantProfiles;
		return baseAccount;
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const CcsCredentialType = {
		HOME_ACCOUNT_ID: "home_account_id",
		UPN: "UPN"
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	async function getClientAssertion(clientAssertion, clientId, tokenEndpoint) {
		if (typeof clientAssertion === "string") return clientAssertion;
		else return clientAssertion({
			clientId,
			tokenEndpoint
		});
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	function getRequestThumbprint(clientId, request, homeAccountId) {
		return {
			clientId,
			authority: request.authority,
			scopes: request.scopes,
			homeAccountIdentifier: homeAccountId,
			claims: request.claims,
			authenticationScheme: request.authenticationScheme,
			resourceRequestMethod: request.resourceRequestMethod,
			resourceRequestUri: request.resourceRequestUri,
			shrClaims: request.shrClaims,
			sshKid: request.sshKid,
			embeddedClientId: request.embeddedClientId || request.extraParameters?.clientId
		};
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/** @internal */
	var ThrottlingUtils = class ThrottlingUtils {
		/**
		* Prepares a RequestThumbprint to be stored as a key.
		* @param thumbprint
		*/
		static generateThrottlingStorageKey(thumbprint) {
			return `${THROTTLING_PREFIX}.${JSON.stringify(thumbprint)}`;
		}
		/**
		* Performs necessary throttling checks before a network request.
		* @param cacheManager
		* @param thumbprint
		*/
		static preProcess(cacheManager, thumbprint, correlationId) {
			const key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint);
			const value = cacheManager.getThrottlingCache(key, correlationId);
			if (value) {
				if (value.throttleTime < Date.now()) {
					cacheManager.removeItem(key, correlationId);
					return;
				}
				throw new ServerError(value.errorCodes?.join(" ") || "", value.errorMessage, value.subError);
			}
		}
		/**
		* Performs necessary throttling checks after a network request.
		* @param cacheManager
		* @param thumbprint
		* @param response
		*/
		static postProcess(cacheManager, thumbprint, response, correlationId) {
			if (ThrottlingUtils.checkResponseStatus(response) || ThrottlingUtils.checkResponseForRetryAfter(response)) {
				const thumbprintValue = {
					throttleTime: ThrottlingUtils.calculateThrottleTime(parseInt(response.headers[HeaderNames.RETRY_AFTER])),
					error: response.body.error,
					errorCodes: response.body.error_codes,
					errorMessage: response.body.error_description,
					subError: response.body.suberror
				};
				cacheManager.setThrottlingCache(ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue, correlationId);
			}
		}
		/**
		* Checks a NetworkResponse object's status codes against 429 or 5xx
		* @param response
		*/
		static checkResponseStatus(response) {
			return response.status === 429 || response.status >= 500 && response.status < 600;
		}
		/**
		* Checks a NetworkResponse object's RetryAfter header
		* @param response
		*/
		static checkResponseForRetryAfter(response) {
			if (response.headers) return response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) && (response.status < 200 || response.status >= 300);
			return false;
		}
		/**
		* Calculates the Unix-time value for a throttle to expire given throttleTime in seconds.
		* @param throttleTime
		*/
		static calculateThrottleTime(throttleTime) {
			const time = throttleTime <= 0 ? 0 : throttleTime;
			const currentSeconds = Date.now() / 1e3;
			return Math.floor(Math.min(currentSeconds + (time || DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1e3);
		}
		static removeThrottle(cacheManager, clientId, request, homeAccountIdentifier) {
			const thumbprint = getRequestThumbprint(clientId, request, homeAccountIdentifier);
			const key = this.generateThrottlingStorageKey(thumbprint);
			cacheManager.removeItem(key, request.correlationId);
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Represents network related errors
	*/
	var NetworkError = class NetworkError extends AuthError {
		constructor(error, httpStatus, responseHeaders) {
			super(error.errorCode, error.errorMessage, error.subError);
			Object.setPrototypeOf(this, NetworkError.prototype);
			this.name = "NetworkError";
			this.error = error;
			this.httpStatus = httpStatus;
			this.responseHeaders = responseHeaders;
		}
	};
	/**
	* Creates NetworkError object for a failed network request
	* @param error - Error to be thrown back to the caller
	* @param httpStatus - Status code of the network request
	* @param responseHeaders - Response headers of the network request, when available
	* @returns NetworkError object
	*/
	function createNetworkError(error, httpStatus, responseHeaders, additionalError) {
		error.errorMessage = `${error.errorMessage}, additionalErrorInfo: error.name:${additionalError?.name}, error.message:${additionalError?.message}`;
		return new NetworkError(error, httpStatus, responseHeaders);
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Creates default headers for requests to token endpoint
	*/
	function createTokenRequestHeaders(logger, preventCorsPreflight, ccsCred) {
		const headers = {};
		headers[HeaderNames.CONTENT_TYPE] = URL_FORM_CONTENT_TYPE;
		if (!preventCorsPreflight && ccsCred) switch (ccsCred.type) {
			case CcsCredentialType.HOME_ACCOUNT_ID:
				try {
					const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
					headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;
				} catch (e) {
					logger.verbose(`Could not parse home account ID for CCS Header: '${e}'`, "");
				}
				break;
			case CcsCredentialType.UPN:
				headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`;
				break;
		}
		return headers;
	}
	/**
	* Creates query string for the /token request
	* @param request
	*/
	function createTokenQueryParameters(request, clientId, redirectUri, performanceClient) {
		const parameters = /* @__PURE__ */ new Map();
		if (request.embeddedClientId) addBrokerParameters(parameters, clientId, redirectUri);
		if (request.extraQueryParameters) addExtraParameters(parameters, request.extraQueryParameters);
		addCorrelationId(parameters, request.correlationId);
		instrumentBrokerParams(parameters, request.correlationId, performanceClient);
		return mapToQueryString(parameters);
	}
	/**
	* Http post to token endpoint
	* @param tokenEndpoint
	* @param queryString
	* @param headers
	* @param thumbprint
	*/
	async function executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, cacheManager, networkClient, logger, performanceClient, serverTelemetryManager) {
		const response = await sendPostRequest(thumbprint, tokenEndpoint, {
			body: queryString,
			headers
		}, correlationId, cacheManager, networkClient, logger, performanceClient);
		if (serverTelemetryManager && response.status < 500 && response.status !== 429) serverTelemetryManager.clearTelemetryCache();
		return response;
	}
	/**
	* Wraps sendPostRequestAsync with necessary preflight and postflight logic
	* @param thumbprint - Request thumbprint for throttling
	* @param tokenEndpoint - Endpoint to make the POST to
	* @param options - Body and Headers to include on the POST request
	* @param correlationId - CorrelationId for telemetry
	* @param cacheManager - Cache manager instance
	* @param networkClient - Network module instance
	* @param logger - Logger instance
	* @param performanceClient - Performance client instance
	*/
	async function sendPostRequest(thumbprint, tokenEndpoint, options, correlationId, cacheManager, networkClient, logger, performanceClient) {
		ThrottlingUtils.preProcess(cacheManager, thumbprint, correlationId);
		let response;
		try {
			response = await invokeAsync(networkClient.sendPostRequestAsync.bind(networkClient), NetworkClientSendPostRequestAsync, logger, performanceClient, correlationId)(tokenEndpoint, options);
			const responseHeaders = response.headers || {};
			performanceClient?.addFields({
				refreshTokenSize: response.body.refresh_token?.length || 0,
				httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
				requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || ""
			}, correlationId);
		} catch (e) {
			if (e instanceof NetworkError) {
				const responseHeaders = e.responseHeaders;
				if (responseHeaders) performanceClient?.addFields({
					httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
					requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
					contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] || void 0,
					contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] || void 0,
					httpStatus: e.httpStatus
				}, correlationId);
				throw e.error;
			}
			if (e instanceof AuthError) throw e;
			else throw createClientAuthError(networkError);
		}
		ThrottlingUtils.postProcess(cacheManager, thumbprint, response, correlationId);
		return response;
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	function isOpenIdConfigResponse(response) {
		return response.hasOwnProperty("authorization_endpoint") && response.hasOwnProperty("token_endpoint") && response.hasOwnProperty("issuer") && response.hasOwnProperty("jwks_uri");
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	function isCloudInstanceDiscoveryResponse(response) {
		return response.hasOwnProperty("tenant_discovery_endpoint") && response.hasOwnProperty("metadata");
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	function isCloudInstanceDiscoveryErrorResponse(response) {
		return response.hasOwnProperty("error") && response.hasOwnProperty("error_description");
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	var RegionDiscovery = class RegionDiscovery {
		constructor(networkInterface, logger, performanceClient, correlationId) {
			this.networkInterface = networkInterface;
			this.logger = logger;
			this.performanceClient = performanceClient;
			this.correlationId = correlationId;
		}
		/**
		* Detect the region from the application's environment.
		*
		* @returns Promise<string | null>
		*/
		async detectRegion(environmentRegion, regionDiscoveryMetadata) {
			let autodetectedRegionName = environmentRegion;
			if (!autodetectedRegionName) {
				const options = RegionDiscovery.IMDS_OPTIONS;
				try {
					const localIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(IMDS_VERSION, options);
					if (localIMDSVersionResponse.status === HTTP_SUCCESS) {
						autodetectedRegionName = localIMDSVersionResponse.body;
						regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;
					}
					if (localIMDSVersionResponse.status === HTTP_BAD_REQUEST) {
						const currentIMDSVersion = await invokeAsync(this.getCurrentVersion.bind(this), RegionDiscoveryGetCurrentVersion, this.logger, this.performanceClient, this.correlationId)(options);
						if (!currentIMDSVersion) {
							regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
							return null;
						}
						const currentIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(currentIMDSVersion, options);
						if (currentIMDSVersionResponse.status === HTTP_SUCCESS) {
							autodetectedRegionName = currentIMDSVersionResponse.body;
							regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;
						}
					}
				} catch (e) {
					regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
					return null;
				}
			} else regionDiscoveryMetadata.region_source = RegionDiscoverySources.ENVIRONMENT_VARIABLE;
			if (!autodetectedRegionName) regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
			return autodetectedRegionName || null;
		}
		/**
		* Make the call to the IMDS endpoint
		*
		* @param imdsEndpointUrl
		* @returns Promise<NetworkResponse<string>>
		*/
		async getRegionFromIMDS(version, options) {
			return this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?api-version=${version}&format=text`, options, IMDS_TIMEOUT);
		}
		/**
		* Get the most recent version of the IMDS endpoint available
		*
		* @returns Promise<string | null>
		*/
		async getCurrentVersion(options) {
			try {
				const response = await this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?format=json`, options);
				if (response.status === HTTP_BAD_REQUEST && response.body && response.body["newest-versions"] && response.body["newest-versions"].length > 0) return response.body["newest-versions"][0];
				return null;
			} catch (e) {
				return null;
			}
		}
	};
	RegionDiscovery.IMDS_OPTIONS = { headers: { Metadata: "true" } };
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the
	* endpoint. It will store the pertinent config data in this object for use during token calls.
	* @internal
	*/
	var Authority = class Authority {
		constructor(authority, networkInterface, cacheManager, authorityOptions, logger, correlationId, performanceClient, managedIdentity) {
			this.canonicalAuthority = authority;
			this._canonicalAuthority.validateAsUri();
			this.networkInterface = networkInterface;
			this.cacheManager = cacheManager;
			this.authorityOptions = authorityOptions;
			this.regionDiscoveryMetadata = {
				region_used: void 0,
				region_source: void 0,
				region_outcome: void 0
			};
			this.logger = logger;
			this.performanceClient = performanceClient;
			this.correlationId = correlationId;
			this.managedIdentity = managedIdentity || false;
			this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId);
		}
		/**
		* Get {@link AuthorityType}
		* @param authorityUri {@link IUri}
		* @private
		*/
		getAuthorityType(authorityUri) {
			if (authorityUri.HostNameAndPort.endsWith(CIAM_AUTH_URL)) return AuthorityType.Ciam;
			const pathSegments = authorityUri.PathSegments;
			if (pathSegments.length) switch (pathSegments[0].toLowerCase()) {
				case ADFS: return AuthorityType.Adfs;
				case DSTS: return AuthorityType.Dsts;
			}
			return AuthorityType.Default;
		}
		get authorityType() {
			return this.getAuthorityType(this.canonicalAuthorityUrlComponents);
		}
		/**
		* ProtocolMode enum representing the way endpoints are constructed.
		*/
		get protocolMode() {
			return this.authorityOptions.protocolMode;
		}
		/**
		* Returns authorityOptions which can be used to reinstantiate a new authority instance
		*/
		get options() {
			return this.authorityOptions;
		}
		/**
		* A URL that is the authority set by the developer
		*/
		get canonicalAuthority() {
			return this._canonicalAuthority.urlString;
		}
		/**
		* Sets canonical authority.
		*/
		set canonicalAuthority(url) {
			this._canonicalAuthority = new UrlString(url);
			this._canonicalAuthority.validateAsUri();
			this._canonicalAuthorityUrlComponents = null;
		}
		/**
		* Get authority components.
		*/
		get canonicalAuthorityUrlComponents() {
			if (!this._canonicalAuthorityUrlComponents) this._canonicalAuthorityUrlComponents = this._canonicalAuthority.getUrlComponents();
			return this._canonicalAuthorityUrlComponents;
		}
		/**
		* Get hostname and port i.e. login.microsoftonline.com
		*/
		get hostnameAndPort() {
			return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
		}
		/**
		* Get tenant for authority.
		*/
		get tenant() {
			return this.canonicalAuthorityUrlComponents.PathSegments[0];
		}
		/**
		* OAuth /authorize endpoint for requests
		*/
		get authorizationEndpoint() {
			if (this.discoveryComplete()) return this.replacePath(this.metadata.authorization_endpoint);
			else throw createClientAuthError(endpointResolutionError);
		}
		/**
		* OAuth /token endpoint for requests
		*/
		get tokenEndpoint() {
			if (this.discoveryComplete()) return this.replacePath(this.metadata.token_endpoint);
			else throw createClientAuthError(endpointResolutionError);
		}
		get deviceCodeEndpoint() {
			if (this.discoveryComplete()) return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
			else throw createClientAuthError(endpointResolutionError);
		}
		/**
		* OAuth logout endpoint for requests
		*/
		get endSessionEndpoint() {
			if (this.discoveryComplete()) {
				if (!this.metadata.end_session_endpoint) throw createClientAuthError(endSessionEndpointNotSupported);
				return this.replacePath(this.metadata.end_session_endpoint);
			} else throw createClientAuthError(endpointResolutionError);
		}
		/**
		* OAuth issuer for requests
		*/
		get selfSignedJwtAudience() {
			if (this.discoveryComplete()) return this.replacePath(this.metadata.issuer);
			else throw createClientAuthError(endpointResolutionError);
		}
		/**
		* Jwks_uri for token signing keys
		*/
		get jwksUri() {
			if (this.discoveryComplete()) return this.replacePath(this.metadata.jwks_uri);
			else throw createClientAuthError(endpointResolutionError);
		}
		/**
		* Returns a flag indicating that tenant name can be replaced in authority {@link IUri}
		* @param authorityUri {@link IUri}
		* @private
		*/
		canReplaceTenant(authorityUri) {
			return authorityUri.PathSegments.length === 1 && !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) && this.getAuthorityType(authorityUri) === AuthorityType.Default && this.protocolMode !== ProtocolMode.OIDC;
		}
		/**
		* Replaces tenant in url path with current tenant. Defaults to common.
		* @param urlString
		*/
		replaceTenant(urlString) {
			return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
		}
		/**
		* Replaces path such as tenant or policy with the current tenant or policy.
		* @param urlString
		*/
		replacePath(urlString) {
			let endpoint = urlString;
			const cachedAuthorityUrlComponents = new UrlString(this.metadata.canonical_authority).getUrlComponents();
			const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;
			this.canonicalAuthorityUrlComponents.PathSegments.forEach((currentPart, index) => {
				let cachedPart = cachedAuthorityParts[index];
				if (index === 0 && this.canReplaceTenant(cachedAuthorityUrlComponents)) {
					const tenantId = new UrlString(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];
					/**
					* Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com",
					* by comparing its first path segment to the corresponding authorization endpoint path segment, which is
					* always resolved with tenant id by OIDC.
					*/
					if (cachedPart !== tenantId) {
						this.logger.verbose(`Replacing tenant domain name '${cachedPart}' with id '${tenantId}'`, this.correlationId);
						cachedPart = tenantId;
					}
				}
				if (currentPart !== cachedPart) endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`);
			});
			return this.replaceTenant(endpoint);
		}
		/**
		* The default open id configuration endpoint for any canonical authority.
		*/
		get defaultOpenIdConfigurationEndpoint() {
			const canonicalAuthorityHost = this.hostnameAndPort;
			if (this.canonicalAuthority.endsWith("v2.0/") || this.authorityType === AuthorityType.Adfs || this.protocolMode === ProtocolMode.OIDC && !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost)) return `${this.canonicalAuthority}.well-known/openid-configuration`;
			return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
		}
		/**
		* Boolean that returns whether or not tenant discovery has been completed.
		*/
		discoveryComplete() {
			return !!this.metadata;
		}
		/**
		* Perform endpoint discovery to discover aliases, preferred_cache, preferred_network
		* and the /authorize, /token and logout endpoints.
		*/
		async resolveEndpointsAsync() {
			const metadataEntity = this.getCurrentMetadataEntity();
			const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
			this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
			const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
			this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, { source: endpointSource });
			this.performanceClient?.addFields({
				cloudDiscoverySource,
				authorityEndpointSource: endpointSource
			}, this.correlationId);
		}
		/**
		* Returns metadata entity from cache if it exists, otherwiser returns a new metadata entity built
		* from the configured canonical authority
		* @returns
		*/
		getCurrentMetadataEntity() {
			let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort, this.correlationId);
			if (!metadataEntity) metadataEntity = {
				aliases: [],
				preferred_cache: this.hostnameAndPort,
				preferred_network: this.hostnameAndPort,
				canonical_authority: this.canonicalAuthority,
				authorization_endpoint: "",
				token_endpoint: "",
				end_session_endpoint: "",
				issuer: "",
				aliasesFromNetwork: false,
				endpointsFromNetwork: false,
				expiresAt: generateAuthorityMetadataExpiresAt(),
				jwks_uri: ""
			};
			return metadataEntity;
		}
		/**
		* Updates cached metadata based on metadata source and sets the instance's metadata
		* property to the same value
		* @param metadataEntity
		* @param cloudDiscoverySource
		* @param endpointMetadataResult
		*/
		updateCachedMetadata(metadataEntity, cloudDiscoverySource, endpointMetadataResult) {
			if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE && endpointMetadataResult?.source !== AuthorityMetadataSource.CACHE) {
				metadataEntity.expiresAt = generateAuthorityMetadataExpiresAt();
				metadataEntity.canonical_authority = this.canonicalAuthority;
			}
			const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache, this.correlationId);
			this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity, this.correlationId);
			this.metadata = metadataEntity;
		}
		/**
		* Update AuthorityMetadataEntity with new endpoints and return where the information came from
		* @param metadataEntity
		*/
		async updateEndpointMetadata(metadataEntity) {
			const localMetadata = this.updateEndpointMetadataFromLocalSources(metadataEntity);
			if (localMetadata) {
				if (localMetadata.source === AuthorityMetadataSource.HARDCODED_VALUES) {
					if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
						if (localMetadata.metadata) {
							updateAuthorityEndpointMetadata(metadataEntity, await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(localMetadata.metadata), false);
							metadataEntity.canonical_authority = this.canonicalAuthority;
						}
					}
				}
				return localMetadata.source;
			}
			let metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
			if (metadata) {
				if (this.authorityOptions.azureRegionConfiguration?.azureRegion) metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata);
				updateAuthorityEndpointMetadata(metadataEntity, metadata, true);
				return AuthorityMetadataSource.NETWORK;
			} else throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint);
		}
		/**
		* Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config
		* response if the source is hardcoded metadata
		* @param metadataEntity
		* @returns
		*/
		updateEndpointMetadataFromLocalSources(metadataEntity) {
			this.logger.verbose("Attempting to get endpoint metadata from authority configuration", this.correlationId);
			const configMetadata = this.getEndpointMetadataFromConfig();
			if (configMetadata) {
				this.logger.verbose("Found endpoint metadata in authority configuration", this.correlationId);
				updateAuthorityEndpointMetadata(metadataEntity, configMetadata, false);
				return { source: AuthorityMetadataSource.CONFIG };
			}
			this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values.", this.correlationId);
			const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
			if (hardcodedMetadata) {
				updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);
				return {
					source: AuthorityMetadataSource.HARDCODED_VALUES,
					metadata: hardcodedMetadata
				};
			} else this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.", this.correlationId);
			const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);
			if (this.isAuthoritySameType(metadataEntity) && metadataEntity.endpointsFromNetwork && !metadataEntityExpired) {
				this.logger.verbose("Found endpoint metadata in the cache.", "");
				return { source: AuthorityMetadataSource.CACHE };
			} else if (metadataEntityExpired) this.logger.verbose("The metadata entity is expired.", "");
			return null;
		}
		/**
		* Compares the number of url components after the domain to determine if the cached
		* authority metadata can be used for the requested authority. Protects against same domain different
		* authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy
		* @param metadataEntity
		*/
		isAuthoritySameType(metadataEntity) {
			return new UrlString(metadataEntity.canonical_authority).getUrlComponents().PathSegments.length === this.canonicalAuthorityUrlComponents.PathSegments.length;
		}
		/**
		* Parse authorityMetadata config option
		*/
		getEndpointMetadataFromConfig() {
			if (this.authorityOptions.authorityMetadata) try {
				return JSON.parse(this.authorityOptions.authorityMetadata);
			} catch (e) {
				throw createClientConfigurationError(invalidAuthorityMetadata);
			}
			return null;
		}
		/**
		* Gets OAuth endpoints from the given OpenID configuration endpoint.
		*
		* @param hasHardcodedMetadata boolean
		*/
		async getEndpointMetadataFromNetwork() {
			const options = {};
			const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint;
			this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from '${openIdConfigurationEndpoint}'`, this.correlationId);
			try {
				const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);
				if (isOpenIdConfigResponse(response.body)) return response.body;
				else {
					this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`, this.correlationId);
					return null;
				}
			} catch (e) {
				this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: '${e}'`, this.correlationId);
				return null;
			}
		}
		/**
		* Get OAuth endpoints for common authorities.
		*/
		getEndpointMetadataFromHardcodedValues() {
			if (this.hostnameAndPort in EndpointMetadata) return EndpointMetadata[this.hostnameAndPort];
			return null;
		}
		/**
		* Update the retrieved metadata with regional information.
		* User selected Azure region will be used if configured.
		*/
		async updateMetadataWithRegionalInformation(metadata) {
			const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion;
			if (userConfiguredAzureRegion) {
				if (userConfiguredAzureRegion !== AZURE_REGION_AUTO_DISCOVER_FLAG) {
					this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
					this.regionDiscoveryMetadata.region_used = userConfiguredAzureRegion;
					return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion);
				}
				const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion, this.regionDiscoveryMetadata);
				if (autodetectedRegionName) {
					this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;
					this.regionDiscoveryMetadata.region_used = autodetectedRegionName;
					return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName);
				}
				this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
			}
			return metadata;
		}
		/**
		* Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache
		* and returns where the information was retrieved from
		* @param metadataEntity
		* @returns AuthorityMetadataSource
		*/
		async updateCloudDiscoveryMetadata(metadataEntity) {
			const localMetadataSource = this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity);
			if (localMetadataSource) return localMetadataSource;
			const metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
			if (metadata) {
				updateCloudDiscoveryMetadata(metadataEntity, metadata, true);
				return AuthorityMetadataSource.NETWORK;
			}
			throw createClientConfigurationError(untrustedAuthority);
		}
		updateCloudDiscoveryMetadataFromLocalSources(metadataEntity) {
			this.logger.verbose("Attempting to get cloud discovery metadata  from authority configuration", this.correlationId);
			this.logger.verbosePii(`Known Authorities: '${this.authorityOptions.knownAuthorities || NOT_APPLICABLE}'`, this.correlationId);
			this.logger.verbosePii(`Authority Metadata: '${this.authorityOptions.authorityMetadata || NOT_APPLICABLE}'`, this.correlationId);
			this.logger.verbosePii(`Canonical Authority: '${metadataEntity.canonical_authority || NOT_APPLICABLE}'`, this.correlationId);
			const metadata = this.getCloudDiscoveryMetadataFromConfig();
			if (metadata) {
				this.logger.verbose("Found cloud discovery metadata in authority configuration", this.correlationId);
				updateCloudDiscoveryMetadata(metadataEntity, metadata, false);
				return AuthorityMetadataSource.CONFIG;
			}
			this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values.", this.correlationId);
			const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(this.hostnameAndPort);
			if (hardcodedMetadata) {
				this.logger.verbose("Found cloud discovery metadata from hardcoded values.", this.correlationId);
				updateCloudDiscoveryMetadata(metadataEntity, hardcodedMetadata, false);
				return AuthorityMetadataSource.HARDCODED_VALUES;
			}
			this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.", this.correlationId);
			const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);
			if (this.isAuthoritySameType(metadataEntity) && metadataEntity.aliasesFromNetwork && !metadataEntityExpired) {
				this.logger.verbose("Found cloud discovery metadata in the cache.", "");
				return AuthorityMetadataSource.CACHE;
			} else if (metadataEntityExpired) this.logger.verbose("The metadata entity is expired.", "");
			return null;
		}
		/**
		* Parse cloudDiscoveryMetadata config or check knownAuthorities
		*/
		getCloudDiscoveryMetadataFromConfig() {
			if (this.authorityType === AuthorityType.Ciam) {
				this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host.", this.correlationId);
				return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
			}
			if (this.authorityOptions.cloudDiscoveryMetadata) {
				this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.", this.correlationId);
				try {
					this.logger.verbose("Attempting to parse the cloud discovery metadata.", this.correlationId);
					const metadata = getCloudDiscoveryMetadataFromNetworkResponse(JSON.parse(this.authorityOptions.cloudDiscoveryMetadata).metadata, this.hostnameAndPort);
					this.logger.verbose("Parsed the cloud discovery metadata.", "");
					if (metadata) {
						this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata.", this.correlationId);
						return metadata;
					} else this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.", this.correlationId);
				} catch (e) {
					this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error.", this.correlationId);
					throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
				}
			}
			if (this.isInKnownAuthorities()) {
				this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host.", this.correlationId);
				return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
			}
			return null;
		}
		/**
		* Called to get metadata from network if CloudDiscoveryMetadata was not populated by config
		*
		* @param hasHardcodedMetadata boolean
		*/
		async getCloudDiscoveryMetadataFromNetwork() {
			const instanceDiscoveryEndpoint = `${AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;
			const options = {};
			let match = null;
			try {
				const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options);
				let typedResponseBody;
				let metadata;
				if (isCloudInstanceDiscoveryResponse(response.body)) {
					typedResponseBody = response.body;
					metadata = typedResponseBody.metadata;
					this.logger.verbosePii(`tenant_discovery_endpoint is: '${typedResponseBody.tenant_discovery_endpoint}'`, this.correlationId);
				} else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {
					this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: '${response.status}'`, this.correlationId);
					typedResponseBody = response.body;
					if (typedResponseBody.error === INVALID_INSTANCE) {
						this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance.", this.correlationId);
						return null;
					}
					this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is '${typedResponseBody.error}'`, this.correlationId);
					this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is '${typedResponseBody.error_description}'`, this.correlationId);
					this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network, correlationId) to []", this.correlationId);
					metadata = [];
				} else {
					this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse", this.correlationId);
					return null;
				}
				this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.", this.correlationId);
				match = getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);
			} catch (error) {
				if (error instanceof AuthError) this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: '${error.errorCode}'\nError Description: '${error.errorMessage}'`, this.correlationId);
				else {
					const typedError = error;
					this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: '${typedError.name}'\nError Description: '${typedError.message}'`, this.correlationId);
				}
				return null;
			}
			if (!match) {
				this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.", this.correlationId);
				this.logger.verbose("Creating custom Authority for custom domain scenario.", this.correlationId);
				match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
			}
			return match;
		}
		/**
		* Helper function to determine if this host is included in the knownAuthorities config option
		*/
		isInKnownAuthorities() {
			return this.authorityOptions.knownAuthorities.filter((authority) => {
				return authority && UrlString.getDomainFromUrl(authority).toLowerCase() === this.hostnameAndPort;
			}).length > 0;
		}
		/**
		* helper function to populate the authority based on azureCloudOptions
		* @param authorityString
		* @param azureCloudOptions
		*/
		static generateAuthority(authorityString, azureCloudOptions) {
			let authorityAzureCloudInstance;
			if (azureCloudOptions && azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {
				const tenant = azureCloudOptions.tenant ? azureCloudOptions.tenant : DEFAULT_COMMON_TENANT;
				authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;
			}
			return authorityAzureCloudInstance ? authorityAzureCloudInstance : authorityString;
		}
		/**
		* Creates cloud discovery metadata object from a given host
		* @param host
		*/
		static createCloudDiscoveryMetadataFromHost(host) {
			return {
				preferred_network: host,
				preferred_cache: host,
				aliases: [host]
			};
		}
		/**
		* helper function to generate environment from authority object
		*/
		getPreferredCache() {
			if (this.managedIdentity) return DEFAULT_AUTHORITY_HOST;
			else if (this.discoveryComplete()) return this.metadata.preferred_cache;
			else throw createClientAuthError(endpointResolutionError);
		}
		/**
		* Returns whether or not the provided host is an alias of this authority instance
		* @param host
		*/
		isAlias(host) {
			return this.metadata.aliases.indexOf(host) > -1;
		}
		/**
		* Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery
		* @param host
		*/
		isAliasOfKnownMicrosoftAuthority(host) {
			return InstanceDiscoveryMetadataAliases.has(host);
		}
		/**
		* Checks whether the provided host is that of a public cloud authority
		*
		* @param authority string
		* @returns bool
		*/
		static isPublicCloudAuthority(host) {
			return KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;
		}
		/**
		* Rebuild the authority string with the region
		*
		* @param host string
		* @param region string
		*/
		static buildRegionalAuthorityString(host, region, queryString) {
			const authorityUrlInstance = new UrlString(host);
			authorityUrlInstance.validateAsUri();
			const authorityUrlParts = authorityUrlInstance.getUrlComponents();
			let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;
			if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) hostNameAndPort = `${region}.${REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;
			const url = UrlString.constructAuthorityUriFromObject({
				...authorityUrlInstance.getUrlComponents(),
				HostNameAndPort: hostNameAndPort
			}).urlString;
			if (queryString) return `${url}?${queryString}`;
			return url;
		}
		/**
		* Replace the endpoints in the metadata object with their regional equivalents.
		*
		* @param metadata OpenIdConfigResponse
		* @param azureRegion string
		*/
		static replaceWithRegionalInformation(metadata, azureRegion) {
			const regionalMetadata = { ...metadata };
			regionalMetadata.authorization_endpoint = Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion);
			regionalMetadata.token_endpoint = Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion);
			if (regionalMetadata.end_session_endpoint) regionalMetadata.end_session_endpoint = Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion);
			return regionalMetadata;
		}
		/**
		* Transform CIAM_AUTHORIY as per the below rules:
		* If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it
		*
		* NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com`
		* `ciamlogin.com` can also change in the future and we should accommodate the same
		*
		* @param authority
		*/
		static transformCIAMAuthority(authority) {
			let ciamAuthority = authority;
			const authorityUrlComponents = new UrlString(authority).getUrlComponents();
			if (authorityUrlComponents.PathSegments.length === 0 && authorityUrlComponents.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {
				const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
				ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${AAD_TENANT_DOMAIN_SUFFIX}`;
			}
			return ciamAuthority;
		}
	};
	Authority.reservedTenantDomains = new Set([
		"{tenant}",
		"{tenantid}",
		AADAuthority.COMMON,
		AADAuthority.CONSUMERS,
		AADAuthority.ORGANIZATIONS
	]);
	/**
	* Extract tenantId from authority
	*/
	function getTenantFromAuthorityString(authority) {
		/**
		* For credential matching purposes, tenantId is the last path segment of the authority URL:
		*  AAD Authority - domain/tenantId -> Credentials are cached with realm = tenantId
		*  B2C Authority - domain/{tenantId}?/.../policy -> Credentials are cached with realm = policy
		*  tenantId is downcased because B2C policies can have mixed case but tfp claim is downcased
		*
		* Note that we may not have any path segments in certain OIDC scenarios.
		*/
		const tenantId = new UrlString(authority).getUrlComponents().PathSegments.slice(-1)[0]?.toLowerCase();
		switch (tenantId) {
			case AADAuthority.COMMON:
			case AADAuthority.ORGANIZATIONS:
			case AADAuthority.CONSUMERS: return;
			default: return tenantId;
		}
	}
	function formatAuthorityUri(authorityUri) {
		return authorityUri.endsWith(FORWARD_SLASH) ? authorityUri : `${authorityUri}${FORWARD_SLASH}`;
	}
	function buildStaticAuthorityOptions(authOptions) {
		const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata;
		let cloudDiscoveryMetadata = void 0;
		if (rawCloudDiscoveryMetadata) try {
			cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata);
		} catch (e) {
			throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
		}
		return {
			canonicalAuthority: authOptions.authority ? formatAuthorityUri(authOptions.authority) : void 0,
			knownAuthorities: authOptions.knownAuthorities,
			cloudDiscoveryMetadata
		};
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Create an authority object of the correct type based on the url
	* Performs basic authority validation - checks to see if the authority is of a valid type (i.e. aad, b2c, adfs)
	*
	* Also performs endpoint discovery.
	*
	* @param authorityUri
	* @param networkClient
	* @param cacheManager
	* @param authorityOptions
	* @param logger
	* @param correlationId
	* @param performanceClient
	* @internal
	*/
	async function createDiscoveredInstance(authorityUri, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient) {
		const acquireTokenAuthority = new Authority(Authority.transformCIAMAuthority(formatAuthorityUri(authorityUri)), networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient);
		try {
			await invokeAsync(acquireTokenAuthority.resolveEndpointsAsync.bind(acquireTokenAuthority), AuthorityResolveEndpointsAsync, logger, performanceClient, correlationId)();
			return acquireTokenAuthority;
		} catch (e) {
			throw createClientAuthError(endpointResolutionError);
		}
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Oauth2.0 Authorization Code client
	* @internal
	*/
	var AuthorizationCodeClient = class {
		constructor(configuration, performanceClient) {
			this.includeRedirectUri = true;
			this.config = buildClientConfiguration(configuration);
			this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
			this.cryptoUtils = this.config.cryptoInterface;
			this.cacheManager = this.config.storageInterface;
			this.networkClient = this.config.networkInterface;
			this.serverTelemetryManager = this.config.serverTelemetryManager;
			this.authority = this.config.authOptions.authority;
			this.performanceClient = performanceClient;
			this.oidcDefaultScopes = this.config.authOptions.authority.options.OIDCOptions?.defaultScopes;
		}
		/**
		* API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the
		* authorization_code_grant
		* @param request
		*/
		async acquireToken(request, apiId, authCodePayload) {
			if (!request.code) throw createClientAuthError(requestCannotBeMade);
			if (authCodePayload && authCodePayload.cloud_instance_host_name) await invokeAsync(this.updateTokenEndpointAuthority.bind(this), UpdateTokenEndpointAuthority, this.logger, this.performanceClient, request.correlationId)(authCodePayload.cloud_instance_host_name, request.correlationId);
			const reqTimestamp = nowSeconds();
			const response = await invokeAsync(this.executeTokenRequest.bind(this), AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(this.authority, request, this.serverTelemetryManager);
			const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
			const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
			responseHandler.validateTokenResponse(response.body, request.correlationId);
			return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, apiId, authCodePayload, void 0, void 0, void 0, requestId);
		}
		/**
		* Used to log out the current user, and redirect the user to the postLogoutRedirectUri.
		* Default behaviour is to redirect the user to `window.location.href`.
		* @param authorityUri
		*/
		getLogoutUri(logoutRequest) {
			if (!logoutRequest) throw createClientConfigurationError(logoutRequestEmpty);
			const queryString = this.createLogoutUrlQueryString(logoutRequest);
			return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString);
		}
		/**
		* Executes POST request to token endpoint
		* @param authority
		* @param request
		*/
		async executeTokenRequest(authority, request, serverTelemetryManager) {
			const queryParametersString = createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
			const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
			const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), AuthClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
			let ccsCredential = void 0;
			if (request.clientInfo) try {
				const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);
				ccsCredential = {
					credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
					type: CcsCredentialType.HOME_ACCOUNT_ID
				};
			} catch (e) {
				this.logger.verbose(`Could not parse client info for CCS Header: '${e}'`, request.correlationId);
			}
			const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, ccsCredential || request.ccsCredential);
			const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request);
			return invokeAsync(executePostToTokenEndpoint, AuthorizationCodeClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, serverTelemetryManager);
		}
		/**
		* Generates a map for all the params to be sent to the service
		* @param request
		*/
		async createTokenRequestBody(request) {
			const parameters = /* @__PURE__ */ new Map();
			addClientId(parameters, request.embeddedClientId || request.extraParameters?.[CLIENT_ID] || this.config.authOptions.clientId);
			if (!this.includeRedirectUri) {
				if (!request.redirectUri) throw createClientConfigurationError(redirectUriEmpty);
			} else addRedirectUri(parameters, request.redirectUri);
			addScopes(parameters, request.scopes, true, this.oidcDefaultScopes);
			addAuthorizationCode(parameters, request.code);
			addLibraryInfo(parameters, this.config.libraryInfo);
			addApplicationTelemetry(parameters, this.config.telemetry.application);
			addThrottling(parameters);
			if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) addServerTelemetry(parameters, this.serverTelemetryManager);
			if (request.codeVerifier) addCodeVerifier(parameters, request.codeVerifier);
			if (this.config.clientCredentials.clientSecret) addClientSecret(parameters, this.config.clientCredentials.clientSecret);
			if (this.config.clientCredentials.clientAssertion) {
				const clientAssertion = this.config.clientCredentials.clientAssertion;
				addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
				addClientAssertionType(parameters, clientAssertion.assertionType);
			}
			addGrantType(parameters, GrantType.AUTHORIZATION_CODE_GRANT);
			addClientInfo(parameters);
			if (request.authenticationScheme === AuthenticationScheme.POP) {
				const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
				let reqCnfData;
				if (!request.popKid) reqCnfData = (await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger)).reqCnfString;
				else reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
				addPopToken(parameters, reqCnfData);
			} else if (request.authenticationScheme === AuthenticationScheme.SSH) if (request.sshJwk) addSshJwk(parameters, request.sshJwk);
			else throw createClientConfigurationError(missingSshJwk);
			if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities);
			let ccsCred = void 0;
			if (request.clientInfo) try {
				const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);
				ccsCred = {
					credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
					type: CcsCredentialType.HOME_ACCOUNT_ID
				};
			} catch (e) {
				this.logger.verbose(`Could not parse client info for CCS Header: '${e}'`, request.correlationId);
			}
			else ccsCred = request.ccsCredential;
			if (this.config.systemOptions.preventCorsPreflight && ccsCred) switch (ccsCred.type) {
				case CcsCredentialType.HOME_ACCOUNT_ID:
					try {
						addCcsOid(parameters, buildClientInfoFromHomeAccountId(ccsCred.credential));
					} catch (e) {
						this.logger.verbose(`Could not parse home account ID for CCS Header: '${e}'`, request.correlationId);
					}
					break;
				case CcsCredentialType.UPN:
					addCcsUpn(parameters, ccsCred.credential);
					break;
			}
			if (request.embeddedClientId) addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);
			if (request.extraParameters) addExtraParameters(parameters, request.extraParameters);
			if (request.enableSpaAuthorizationCode && (!request.extraParameters || !request.extraParameters[RETURN_SPA_CODE])) addExtraParameters(parameters, { [RETURN_SPA_CODE]: "1" });
			instrumentBrokerParams(parameters, request.correlationId, this.performanceClient);
			return mapToQueryString(parameters);
		}
		/**
		* This API validates the `EndSessionRequest` and creates a URL
		* @param request
		*/
		createLogoutUrlQueryString(request) {
			const parameters = /* @__PURE__ */ new Map();
			if (request.postLogoutRedirectUri) addPostLogoutRedirectUri(parameters, request.postLogoutRedirectUri);
			if (request.correlationId) addCorrelationId(parameters, request.correlationId);
			if (request.idTokenHint) addIdTokenHint(parameters, request.idTokenHint);
			if (request.state) addState(parameters, request.state);
			if (request.logoutHint) addLogoutHint(parameters, request.logoutHint);
			if (request.extraQueryParameters) addExtraParameters(parameters, request.extraQueryParameters);
			if (this.config.authOptions.instanceAware) addInstanceAware(parameters);
			return mapToQueryString(parameters);
		}
		/**
		* Updates the authority to the cloud instance provided in the authorization response
		* @param cloudInstanceHostName - cloud instance host name from authorization code payload
		* @param correlationId - request correlation id
		*/
		async updateTokenEndpointAuthority(cloudInstanceHostName, correlationId) {
			this.authority = await createDiscoveredInstance(`https://${cloudInstanceHostName}/${this.authority.tenant}/`, this.networkClient, this.cacheManager, this.authority.options, this.logger, correlationId, this.performanceClient);
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300;
	/**
	* OAuth2.0 refresh token client
	* @internal
	*/
	var RefreshTokenClient = class {
		constructor(configuration, performanceClient) {
			this.config = buildClientConfiguration(configuration);
			this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
			this.cryptoUtils = this.config.cryptoInterface;
			this.cacheManager = this.config.storageInterface;
			this.networkClient = this.config.networkInterface;
			this.serverTelemetryManager = this.config.serverTelemetryManager;
			this.authority = this.config.authOptions.authority;
			this.performanceClient = performanceClient;
		}
		async acquireToken(request, apiId) {
			const reqTimestamp = nowSeconds();
			const response = await invokeAsync(this.executeTokenRequest.bind(this), RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(request, this.authority);
			const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
			const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
			responseHandler.validateTokenResponse(response.body, request.correlationId);
			return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, apiId, void 0, void 0, true, request.forceCache, requestId);
		}
		/**
		* Gets cached refresh token and attaches to request, then calls acquireToken API
		* @param request
		*/
		async acquireTokenByRefreshToken(request, apiId) {
			if (!request) throw createClientConfigurationError(tokenRequestEmpty);
			if (!request.account) throw createClientAuthError(noAccountInSilentRequest);
			if (this.cacheManager.isAppMetadataFOCI(request.account.environment, request.correlationId)) try {
				return await invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, true, apiId);
			} catch (e) {
				const noFamilyRTInCache = e instanceof InteractionRequiredAuthError && e.errorCode === noTokensFound;
				const clientMismatchErrorWithFamilyRT = e instanceof ServerError && e.errorCode === INVALID_GRANT_ERROR && e.subError === CLIENT_MISMATCH_ERROR;
				if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false, apiId);
				else throw e;
			}
			return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false, apiId);
		}
		/**
		* makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached
		* @param request
		*/
		async acquireTokenWithCachedRefreshToken(request, foci, apiId) {
			const refreshToken = invoke(this.cacheManager.getRefreshToken.bind(this.cacheManager), CacheManagerGetRefreshToken, this.logger, this.performanceClient, request.correlationId)(request.account, foci, request.correlationId, void 0);
			if (!refreshToken) throw createInteractionRequiredAuthError(noTokensFound);
			if (refreshToken.expiresOn) {
				const offset = request.refreshTokenExpirationOffsetSeconds || DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS;
				this.performanceClient?.addFields({
					cacheRtExpiresOnSeconds: Number(refreshToken.expiresOn),
					rtOffsetSeconds: offset
				}, request.correlationId);
				if (isTokenExpired(refreshToken.expiresOn, offset)) throw createInteractionRequiredAuthError(refreshTokenExpired);
			}
			const refreshTokenRequest = {
				...request,
				refreshToken: refreshToken.secret,
				authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER,
				ccsCredential: {
					credential: request.account.homeAccountId,
					type: CcsCredentialType.HOME_ACCOUNT_ID
				}
			};
			try {
				return await invokeAsync(this.acquireToken.bind(this), RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(refreshTokenRequest, apiId);
			} catch (e) {
				if (e instanceof InteractionRequiredAuthError) {
					if (e.subError === badToken) {
						this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache", request.correlationId);
						const badRefreshTokenKey = this.cacheManager.generateCredentialKey(refreshToken);
						this.cacheManager.removeRefreshToken(badRefreshTokenKey, request.correlationId);
					}
				}
				throw e;
			}
		}
		/**
		* Constructs the network message and makes a NW call to the underlying secure token service
		* @param request
		* @param authority
		*/
		async executeTokenRequest(request, authority) {
			const queryParametersString = createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
			const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
			const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
			const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, request.ccsCredential);
			const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request);
			return invokeAsync(executePostToTokenEndpoint, RefreshTokenClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, this.serverTelemetryManager);
		}
		/**
		* Helper function to create the token request body
		* @param request
		*/
		async createTokenRequestBody(request) {
			const parameters = /* @__PURE__ */ new Map();
			addClientId(parameters, request.embeddedClientId || request.extraParameters?.[CLIENT_ID] || this.config.authOptions.clientId);
			if (request.redirectUri) addRedirectUri(parameters, request.redirectUri);
			addScopes(parameters, request.scopes, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);
			addGrantType(parameters, GrantType.REFRESH_TOKEN_GRANT);
			addClientInfo(parameters);
			addLibraryInfo(parameters, this.config.libraryInfo);
			addApplicationTelemetry(parameters, this.config.telemetry.application);
			addThrottling(parameters);
			if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) addServerTelemetry(parameters, this.serverTelemetryManager);
			addRefreshToken(parameters, request.refreshToken);
			if (this.config.clientCredentials.clientSecret) addClientSecret(parameters, this.config.clientCredentials.clientSecret);
			if (this.config.clientCredentials.clientAssertion) {
				const clientAssertion = this.config.clientCredentials.clientAssertion;
				addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
				addClientAssertionType(parameters, clientAssertion.assertionType);
			}
			if (request.authenticationScheme === AuthenticationScheme.POP) {
				const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
				let reqCnfData;
				if (!request.popKid) reqCnfData = (await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger)).reqCnfString;
				else reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
				addPopToken(parameters, reqCnfData);
			} else if (request.authenticationScheme === AuthenticationScheme.SSH) if (request.sshJwk) addSshJwk(parameters, request.sshJwk);
			else throw createClientConfigurationError(missingSshJwk);
			if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities);
			if (this.config.systemOptions.preventCorsPreflight && request.ccsCredential) switch (request.ccsCredential.type) {
				case CcsCredentialType.HOME_ACCOUNT_ID:
					try {
						addCcsOid(parameters, buildClientInfoFromHomeAccountId(request.ccsCredential.credential));
					} catch (e) {
						this.logger.verbose(`Could not parse home account ID for CCS Header: '${e}'`, request.correlationId);
					}
					break;
				case CcsCredentialType.UPN:
					addCcsUpn(parameters, request.ccsCredential.credential);
					break;
			}
			if (request.embeddedClientId) addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);
			if (request.extraParameters) addExtraParameters(parameters, { ...request.extraParameters });
			instrumentBrokerParams(parameters, request.correlationId, this.performanceClient);
			return mapToQueryString(parameters);
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/** @internal */
	var SilentFlowClient = class {
		constructor(configuration, performanceClient) {
			this.config = buildClientConfiguration(configuration);
			this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
			this.cryptoUtils = this.config.cryptoInterface;
			this.cacheManager = this.config.storageInterface;
			this.networkClient = this.config.networkInterface;
			this.serverTelemetryManager = this.config.serverTelemetryManager;
			this.authority = this.config.authOptions.authority;
			this.performanceClient = performanceClient;
		}
		/**
		* Retrieves token from cache or throws an error if it must be refreshed.
		* @param request
		*/
		async acquireCachedToken(request) {
			let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;
			if (request.forceRefresh || !StringUtils.isEmptyObj(request.claims)) {
				this.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS, request.correlationId);
				throw createClientAuthError(tokenRefreshRequired);
			}
			if (!request.account) throw createClientAuthError(noAccountInSilentRequest);
			const requestTenantId = request.account.tenantId || getTenantFromAuthorityString(request.authority);
			const tokenKeys = this.cacheManager.getTokenKeys();
			const cachedAccessToken = this.cacheManager.getAccessToken(request.account, request, tokenKeys, requestTenantId);
			if (!cachedAccessToken) {
				this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);
				throw createClientAuthError(tokenRefreshRequired);
			} else if (wasClockTurnedBack(cachedAccessToken.cachedAt) || isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
				this.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED, request.correlationId);
				throw createClientAuthError(tokenRefreshRequired);
			} else if (cachedAccessToken.refreshOn && isTokenExpired(cachedAccessToken.refreshOn, 0)) lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
			const environment = request.authority || this.authority.getPreferredCache();
			const cacheRecord = {
				account: this.cacheManager.getAccount(this.cacheManager.generateAccountKey(request.account), request.correlationId),
				accessToken: cachedAccessToken,
				idToken: this.cacheManager.getIdToken(request.account, request.correlationId, tokenKeys, requestTenantId),
				refreshToken: null,
				appMetadata: this.cacheManager.readAppMetadataFromCache(environment, request.correlationId)
			};
			this.setCacheOutcome(lastCacheOutcome, request.correlationId);
			if (this.config.serverTelemetryManager) this.config.serverTelemetryManager.incrementCacheHits();
			return [await invokeAsync(this.generateResultFromCacheRecord.bind(this), SilentFlowClientGenerateResultFromCacheRecord, this.logger, this.performanceClient, request.correlationId)(cacheRecord, request), lastCacheOutcome];
		}
		setCacheOutcome(cacheOutcome, correlationId) {
			this.serverTelemetryManager?.setCacheOutcome(cacheOutcome);
			this.performanceClient?.addFields({ cacheOutcome }, correlationId);
			if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) this.logger.info(`Token refresh is required due to cache outcome: '${cacheOutcome}'`, correlationId);
		}
		/**
		* Helper function to build response object from the CacheRecord
		* @param cacheRecord
		*/
		async generateResultFromCacheRecord(cacheRecord, request) {
			let idTokenClaims;
			if (cacheRecord.idToken) idTokenClaims = extractTokenClaims(cacheRecord.idToken.secret, this.config.cryptoInterface.base64Decode);
			if (request.maxAge || request.maxAge === 0) {
				const authTime = idTokenClaims?.auth_time;
				if (!authTime) throw createClientAuthError(authTimeNotFound);
				checkMaxAge(authTime, request.maxAge);
			}
			return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, this.performanceClient, idTokenClaims);
		}
	};
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* Returns map of parameters that are applicable to all calls to /authorize whether using PKCE or EAR
	* @param config
	* @param request
	* @param logger
	* @param performanceClient
	* @returns
	*/
	function getStandardAuthorizeRequestParameters(authOptions, request, logger, performanceClient) {
		const correlationId = request.correlationId;
		const parameters = /* @__PURE__ */ new Map();
		addClientId(parameters, request.embeddedClientId || request.extraQueryParameters?.[CLIENT_ID] || authOptions.clientId);
		addScopes(parameters, [...request.scopes || [], ...request.extraScopesToConsent || []], true, authOptions.authority.options.OIDCOptions?.defaultScopes);
		addRedirectUri(parameters, request.redirectUri);
		addCorrelationId(parameters, correlationId);
		addResponseMode(parameters, request.responseMode);
		addClientInfo(parameters);
		if (request.prompt) addPrompt(parameters, request.prompt);
		if (request.domainHint) addDomainHint(parameters, request.domainHint);
		if (request.prompt !== PromptValue$1.SELECT_ACCOUNT) {
			if (request.sid && request.prompt === PromptValue$1.NONE) {
				logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request", request.correlationId);
				addSid(parameters, request.sid);
			} else if (request.account) {
				const accountSid = extractAccountSid(request.account);
				let accountLoginHintClaim = extractLoginHint(request.account);
				if (accountLoginHintClaim && request.domainHint) {
					logger.warning(`AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint`, request.correlationId);
					accountLoginHintClaim = null;
				}
				if (accountLoginHintClaim) {
					logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account", request.correlationId);
					addLoginHint(parameters, accountLoginHintClaim);
					try {
						addCcsOid(parameters, buildClientInfoFromHomeAccountId(request.account.homeAccountId));
					} catch (e) {
						logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request.correlationId);
					}
				} else if (accountSid && request.prompt === PromptValue$1.NONE) {
					logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account", request.correlationId);
					addSid(parameters, accountSid);
					try {
						addCcsOid(parameters, buildClientInfoFromHomeAccountId(request.account.homeAccountId));
					} catch (e) {
						logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request.correlationId);
					}
				} else if (request.loginHint) {
					logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from request", request.correlationId);
					addLoginHint(parameters, request.loginHint);
					addCcsUpn(parameters, request.loginHint);
				} else if (request.account.username) {
					logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from account", request.correlationId);
					addLoginHint(parameters, request.account.username);
					try {
						addCcsOid(parameters, buildClientInfoFromHomeAccountId(request.account.homeAccountId));
					} catch (e) {
						logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request.correlationId);
					}
				}
			} else if (request.loginHint) {
				logger.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request", request.correlationId);
				addLoginHint(parameters, request.loginHint);
				addCcsUpn(parameters, request.loginHint);
			}
		} else logger.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints", request.correlationId);
		if (request.nonce) addNonce(parameters, request.nonce);
		if (request.state) addState(parameters, request.state);
		if (request.claims || authOptions.clientCapabilities && authOptions.clientCapabilities.length > 0) addClaims(parameters, request.claims, authOptions.clientCapabilities);
		if (request.embeddedClientId) addBrokerParameters(parameters, authOptions.clientId, authOptions.redirectUri);
		if (authOptions.instanceAware && (!request.extraQueryParameters || !Object.keys(request.extraQueryParameters).includes(INSTANCE_AWARE))) addInstanceAware(parameters);
		return parameters;
	}
	/**
	* Returns authorize endpoint with given request parameters in the query string
	* @param authority
	* @param requestParameters
	* @returns
	*/
	function getAuthorizeUrl(authority, requestParameters) {
		const queryString = mapToQueryString(requestParameters);
		return UrlString.appendQueryString(authority.authorizationEndpoint, queryString);
	}
	/**
	* Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present.
	* @param account
	*/
	function extractAccountSid(account) {
		return account.idTokenClaims?.sid || null;
	}
	function extractLoginHint(account) {
		return account.loginHint || account.idTokenClaims?.login_hint || null;
	}
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	/**
	* AuthErrorMessage class containing string constants used by error codes and messages.
	*/
	const unexpectedError = "unexpected_error";
	const postRequestFailed = "post_request_failed";
	var AuthErrorCodes = /* @__PURE__ */ Object.freeze({
		__proto__: null,
		postRequestFailed,
		unexpectedError
	});
	/*! @azure/msal-common v16.1.0 2026-02-24 */
	const skuGroupSeparator = ",";
	const skuValueSeparator = "|";
	function makeExtraSkuString(params) {
		const { skus, libraryName, libraryVersion, extensionName, extensionVersion } = params;
		const skuMap = new Map([[0, [libraryName, libraryVersion]], [2, [extensionName, extensionVersion]]]);
		let skuArr = [];
		if (skus?.length) {
			skuArr = skus.split(skuGroupSeparator);
			if (skuArr.length < 4) return skus;
		} else skuArr = Array.from({ length: 4 }, () => skuValueSeparator);
		skuMap.forEach((value, key) => {
			if (value.length === 2 && value[0]?.length && value[1]?.length) setSku({
				skuArr,
				index: key,
				skuName: value[0],
				skuVersion: value[1]
			});
		});
		return skuArr.join(skuGroupSeparator);
	}
	function setSku(params) {
		const { skuArr, index, skuName, skuVersion } = params;
		if (index >= skuArr.length) return;
		skuArr[index] = [skuName, skuVersion].join(skuValueSeparator);
	}
	/** @internal */
	var ServerTelemetryManager = class ServerTelemetryManager {
		constructor(telemetryRequest, cacheManager) {
			this.cacheOutcome = CacheOutcome.NOT_APPLICABLE;
			this.cacheManager = cacheManager;
			this.apiId = telemetryRequest.apiId;
			this.correlationId = telemetryRequest.correlationId;
			this.wrapperSKU = telemetryRequest.wrapperSKU || "";
			this.wrapperVer = telemetryRequest.wrapperVer || "";
			this.telemetryCacheKey = SERVER_TELEM_CACHE_KEY + CACHE_KEY_SEPARATOR + telemetryRequest.clientId;
		}
		/**
		* API to add MSER Telemetry to request
		*/
		generateCurrentRequestHeaderValue() {
			const request = `${this.apiId}${SERVER_TELEM_VALUE_SEPARATOR}${this.cacheOutcome}`;
			const platformFieldsArr = [this.wrapperSKU, this.wrapperVer];
			const nativeBrokerErrorCode = this.getNativeBrokerErrorCode();
			if (nativeBrokerErrorCode?.length) platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`);
			const platformFields = platformFieldsArr.join(SERVER_TELEM_VALUE_SEPARATOR);
			return [
				SERVER_TELEM_SCHEMA_VERSION,
				[request, this.getRegionDiscoveryFields()].join(SERVER_TELEM_VALUE_SEPARATOR),
				platformFields
			].join(SERVER_TELEM_CATEGORY_SEPARATOR);
		}
		/**
		* API to add MSER Telemetry for the last failed request
		*/
		generateLastRequestHeaderValue() {
			const lastRequests = this.getLastRequests();
			const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
			const failedRequests = lastRequests.failedRequests.slice(0, 2 * maxErrors).join(SERVER_TELEM_VALUE_SEPARATOR);
			const errors = lastRequests.errors.slice(0, maxErrors).join(SERVER_TELEM_VALUE_SEPARATOR);
			const errorCount = lastRequests.errors.length;
			const platformFields = [errorCount, maxErrors < errorCount ? SERVER_TELEM_OVERFLOW_TRUE : SERVER_TELEM_OVERFLOW_FALSE].join(SERVER_TELEM_VALUE_SEPARATOR);
			return [
				SERVER_TELEM_SCHEMA_VERSION,
				lastRequests.cacheHits,
				failedRequests,
				errors,
				platformFields
			].join(SERVER_TELEM_CATEGORY_SEPARATOR);
		}
		/**
		* API to cache token failures for MSER data capture
		* @param error
		*/
		cacheFailedRequest(error) {
			const lastRequests = this.getLastRequests();
			if (lastRequests.errors.length >= SERVER_TELEM_MAX_CACHED_ERRORS) {
				lastRequests.failedRequests.shift();
				lastRequests.failedRequests.shift();
				lastRequests.errors.shift();
			}
			lastRequests.failedRequests.push(this.apiId, this.correlationId);
			if (error instanceof Error && !!error && error.toString()) if (error instanceof AuthError) if (error.subError) lastRequests.errors.push(error.subError);
			else if (error.errorCode) lastRequests.errors.push(error.errorCode);
			else lastRequests.errors.push(error.toString());
			else lastRequests.errors.push(error.toString());
			else lastRequests.errors.push(SERVER_TELEM_UNKNOWN_ERROR);
			this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
		}
		/**
		* Update server telemetry cache entry by incrementing cache hit counter
		*/
		incrementCacheHits() {
			const lastRequests = this.getLastRequests();
			lastRequests.cacheHits += 1;
			this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
			return lastRequests.cacheHits;
		}
		/**
		* Get the server telemetry entity from cache or initialize a new one
		*/
		getLastRequests() {
			return this.cacheManager.getServerTelemetry(this.telemetryCacheKey, this.correlationId) || {
				failedRequests: [],
				errors: [],
				cacheHits: 0
			};
		}
		/**
		* Remove server telemetry cache entry
		*/
		clearTelemetryCache() {
			const lastRequests = this.getLastRequests();
			const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
			if (numErrorsFlushed === lastRequests.errors.length) this.cacheManager.removeItem(this.telemetryCacheKey, this.correlationId);
			else {
				const serverTelemEntity = {
					failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2),
					errors: lastRequests.errors.slice(numErrorsFlushed),
					cacheHits: 0
				};
				this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity, this.correlationId);
			}
		}
		/**
		* Returns the maximum number of errors that can be flushed to the server in the next network request
		* @param serverTelemetryEntity
		*/
		static maxErrorsToSend(serverTelemetryEntity) {
			let i;
			let maxErrors = 0;
			let dataSize = 0;
			const errorCount = serverTelemetryEntity.errors.length;
			for (i = 0; i < errorCount; i++) {
				const apiId = serverTelemetryEntity.failedRequests[2 * i] || "";
				const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] || "";
				const errorCode = serverTelemetryEntity.errors[i] || "";
				dataSize += apiId.toString().length + correlationId.toString().length + errorCode.length + 3;
				if (dataSize < SERVER_TELEM_MAX_LAST_HEADER_BYTES) maxErrors += 1;
				else break;
			}
			return maxErrors;
		}
		/**
		* Get the region discovery fields
		*
		* @returns string
		*/
		getRegionDiscoveryFields() {
			const regionDiscoveryFields = [];
			regionDiscoveryFields.push(this.regionUsed || "");
			regionDiscoveryFields.push(this.regionSource || "");
			regionDiscoveryFields.push(this.regionOutcome || "");
			return regionDiscoveryFields.join(",");
		}
		/**
		* Update the region discovery metadata
		*
		* @param regionDiscoveryMetadata
		* @returns void
		*/
		updateRegionDiscoveryMetadata(regionDiscoveryMetadata) {
			this.regionUsed = regionDiscoveryMetadata.region_used;
			this.regionSource = regionDiscoveryMetadata.region_source;
			this.regionOutcome = regionDiscoveryMetadata.region_outcome;
		}
		/**
		* Set cache outcome
		*/
		setCacheOutcome(cacheOutcome) {
			this.cacheOutcome = cacheOutcome;
		}
		setNativeBrokerErrorCode(errorCode) {
			const lastRequests = this.getLastRequests();
			lastRequests.nativeBrokerErrorCode = errorCode;
			this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
		}
		getNativeBrokerErrorCode() {
			return this.getLastRequests().nativeBrokerErrorCode;
		}
		clearNativeBrokerErrorCode() {
			const lastRequests = this.getLastRequests();
			delete lastRequests.nativeBrokerErrorCode;
			this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
		}
		static makeExtraSkuString(params) {
			return makeExtraSkuString(params);
		}
	};
	/**
	* This class deserializes cache entities read from the file into in-memory object types defined internally
	* @internal
	*/
	var Deserializer = class {
		/**
		* Parse the JSON blob in memory and deserialize the content
		* @param cachedJson - JSON blob cache
		*/
		static deserializeJSONBlob(jsonFile) {
			return !jsonFile ? {} : JSON.parse(jsonFile);
		}
		/**
		* Deserializes accounts to AccountEntity objects
		* @param accounts - accounts of type SerializedAccountEntity
		*/
		static deserializeAccounts(accounts) {
			const accountObjects = {};
			if (accounts) Object.keys(accounts).map(function(key) {
				const serializedAcc = accounts[key];
				const mappedAcc = {
					homeAccountId: serializedAcc.home_account_id,
					environment: serializedAcc.environment,
					realm: serializedAcc.realm,
					localAccountId: serializedAcc.local_account_id,
					username: serializedAcc.username,
					authorityType: serializedAcc.authority_type,
					name: serializedAcc.name,
					clientInfo: serializedAcc.client_info,
					lastModificationTime: serializedAcc.last_modification_time,
					lastModificationApp: serializedAcc.last_modification_app,
					tenantProfiles: serializedAcc.tenantProfiles?.map((serializedTenantProfile) => {
						return JSON.parse(serializedTenantProfile);
					}),
					lastUpdatedAt: Date.now().toString()
				};
				const account = {};
				CacheManager.toObject(account, mappedAcc);
				accountObjects[key] = account;
			});
			return accountObjects;
		}
		/**
		* Deserializes id tokens to IdTokenEntity objects
		* @param idTokens - credentials of type SerializedIdTokenEntity
		*/
		static deserializeIdTokens(idTokens) {
			const idObjects = {};
			if (idTokens) Object.keys(idTokens).map(function(key) {
				const serializedIdT = idTokens[key];
				idObjects[key] = {
					homeAccountId: serializedIdT.home_account_id,
					environment: serializedIdT.environment,
					credentialType: serializedIdT.credential_type,
					clientId: serializedIdT.client_id,
					secret: serializedIdT.secret,
					realm: serializedIdT.realm,
					lastUpdatedAt: Date.now().toString()
				};
			});
			return idObjects;
		}
		/**
		* Deserializes access tokens to AccessTokenEntity objects
		* @param accessTokens - access tokens of type SerializedAccessTokenEntity
		*/
		static deserializeAccessTokens(accessTokens) {
			const atObjects = {};
			if (accessTokens) Object.keys(accessTokens).map(function(key) {
				const serializedAT = accessTokens[key];
				atObjects[key] = {
					homeAccountId: serializedAT.home_account_id,
					environment: serializedAT.environment,
					credentialType: serializedAT.credential_type,
					clientId: serializedAT.client_id,
					secret: serializedAT.secret,
					realm: serializedAT.realm,
					target: serializedAT.target,
					cachedAt: serializedAT.cached_at,
					expiresOn: serializedAT.expires_on,
					extendedExpiresOn: serializedAT.extended_expires_on,
					refreshOn: serializedAT.refresh_on,
					keyId: serializedAT.key_id,
					tokenType: serializedAT.token_type,
					userAssertionHash: serializedAT.userAssertionHash,
					lastUpdatedAt: Date.now().toString()
				};
			});
			return atObjects;
		}
		/**
		* Deserializes refresh tokens to RefreshTokenEntity objects
		* @param refreshTokens - refresh tokens of type SerializedRefreshTokenEntity
		*/
		static deserializeRefreshTokens(refreshTokens) {
			const rtObjects = {};
			if (refreshTokens) Object.keys(refreshTokens).map(function(key) {
				const serializedRT = refreshTokens[key];
				rtObjects[key] = {
					homeAccountId: serializedRT.home_account_id,
					environment: serializedRT.environment,
					credentialType: serializedRT.credential_type,
					clientId: serializedRT.client_id,
					secret: serializedRT.secret,
					familyId: serializedRT.family_id,
					target: serializedRT.target,
					realm: serializedRT.realm,
					lastUpdatedAt: Date.now().toString()
				};
			});
			return rtObjects;
		}
		/**
		* Deserializes appMetadata to AppMetaData objects
		* @param appMetadata - app metadata of type SerializedAppMetadataEntity
		*/
		static deserializeAppMetadata(appMetadata) {
			const appMetadataObjects = {};
			if (appMetadata) Object.keys(appMetadata).map(function(key) {
				const serializedAmdt = appMetadata[key];
				appMetadataObjects[key] = {
					clientId: serializedAmdt.client_id,
					environment: serializedAmdt.environment,
					familyId: serializedAmdt.family_id
				};
			});
			return appMetadataObjects;
		}
		/**
		* Deserialize an inMemory Cache
		* @param jsonCache - JSON blob cache
		*/
		static deserializeAllCache(jsonCache) {
			return {
				accounts: jsonCache.Account ? this.deserializeAccounts(jsonCache.Account) : {},
				idTokens: jsonCache.IdToken ? this.deserializeIdTokens(jsonCache.IdToken) : {},
				accessTokens: jsonCache.AccessToken ? this.deserializeAccessTokens(jsonCache.AccessToken) : {},
				refreshTokens: jsonCache.RefreshToken ? this.deserializeRefreshTokens(jsonCache.RefreshToken) : {},
				appMetadata: jsonCache.AppMetadata ? this.deserializeAppMetadata(jsonCache.AppMetadata) : {}
			};
		}
	};
	/**
	* Warning: This set of exports is purely intended to be used by other MSAL libraries, and should be considered potentially unstable. We strongly discourage using them directly, you do so at your own risk.
	* Breaking changes to these APIs will be shipped under a minor version, instead of a major version.
	*/
	var internals = /* @__PURE__ */ Object.freeze({
		__proto__: null,
		Deserializer,
		Serializer
	});
	const DEFAULT_MANAGED_IDENTITY_ID = "system_assigned_managed_identity";
	const DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY = `https://login.microsoftonline.com/managed_identity/`;
	/**
	* Managed Identity Headers - used in network requests
	*/
	const ManagedIdentityHeaders = {
		AUTHORIZATION_HEADER_NAME: "Authorization",
		METADATA_HEADER_NAME: "Metadata",
		APP_SERVICE_SECRET_HEADER_NAME: "X-IDENTITY-HEADER",
		ML_AND_SF_SECRET_HEADER_NAME: "secret"
	};
	/**
	* Managed Identity Query Parameters - used in network requests
	*/
	const ManagedIdentityQueryParameters = {
		API_VERSION: "api-version",
		RESOURCE: "resource",
		SHA256_TOKEN_TO_REFRESH: "token_sha256_to_refresh",
		XMS_CC: "xms_cc"
	};
	/**
	* Managed Identity Environment Variable Names
	*/
	const ManagedIdentityEnvironmentVariableNames = {
		AZURE_POD_IDENTITY_AUTHORITY_HOST: "AZURE_POD_IDENTITY_AUTHORITY_HOST",
		DEFAULT_IDENTITY_CLIENT_ID: "DEFAULT_IDENTITY_CLIENT_ID",
		IDENTITY_ENDPOINT: "IDENTITY_ENDPOINT",
		IDENTITY_HEADER: "IDENTITY_HEADER",
		IDENTITY_SERVER_THUMBPRINT: "IDENTITY_SERVER_THUMBPRINT",
		IMDS_ENDPOINT: "IMDS_ENDPOINT",
		MSI_ENDPOINT: "MSI_ENDPOINT",
		MSI_SECRET: "MSI_SECRET"
	};
	/**
	* Managed Identity Source Names
	* @public
	*/
	const ManagedIdentitySourceNames = {
		APP_SERVICE: "AppService",
		AZURE_ARC: "AzureArc",
		CLOUD_SHELL: "CloudShell",
		DEFAULT_TO_IMDS: "DefaultToImds",
		IMDS: "Imds",
		MACHINE_LEARNING: "MachineLearning",
		SERVICE_FABRIC: "ServiceFabric"
	};
	/**
	* Managed Identity Ids
	*/
	const ManagedIdentityIdType = {
		SYSTEM_ASSIGNED: "system-assigned",
		USER_ASSIGNED_CLIENT_ID: "user-assigned-client-id",
		USER_ASSIGNED_RESOURCE_ID: "user-assigned-resource-id",
		USER_ASSIGNED_OBJECT_ID: "user-assigned-object-id"
	};
	/**
	* http methods
	*/
	const HttpMethod = {
		GET: "GET",
		POST: "POST"
	};
	/**
	* Constants used for region discovery
	*/
	const REGION_ENVIRONMENT_VARIABLE = "REGION_NAME";
	const MSAL_FORCE_REGION = "MSAL_FORCE_REGION";
	/**
	* Constant used for PKCE
	*/
	const RANDOM_OCTET_SIZE = 32;
	/**
	* Constants used in PKCE
	*/
	const Hash = { SHA256: "sha256" };
	/**
	* Constants for encoding schemes
	*/
	const CharSet = { CV_CHARSET: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" };
	/**
	* Cache Constants
	*/
	const CACHE = { KEY_SEPARATOR: "-" };
	/**
	* Constants
	*/
	const Constants = {
		MSAL_SKU: "msal.js.node",
		JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
		HTTP_PROTOCOL: "http://",
		LOCALHOST: "localhost"
	};
	/**
	* API Codes for Telemetry purposes.
	* Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs
	* 0-99 Silent Flow
	* 600-699 Device Code Flow
	* 800-899 Auth Code Flow
	*/
	const ApiId = {
		acquireTokenSilent: 62,
		acquireTokenByUsernamePassword: 371,
		acquireTokenByDeviceCode: 671,
		acquireTokenByClientCredential: 771,
		acquireTokenByOBO: 772,
		acquireTokenWithManagedIdentity: 773,
		acquireTokenByCode: 871,
		acquireTokenByRefreshToken: 872
	};
	/**
	* JWT  constants
	*/
	const JwtConstants = {
		RSA_256: "RS256",
		PSS_256: "PS256",
		X5T_256: "x5t#S256",
		X5T: "x5t",
		X5C: "x5c",
		AUDIENCE: "aud",
		EXPIRATION_TIME: "exp",
		ISSUER: "iss",
		SUBJECT: "sub",
		NOT_BEFORE: "nbf",
		JWT_ID: "jti"
	};
	const LOOPBACK_SERVER_CONSTANTS = {
		INTERVAL_MS: 100,
		TIMEOUT_MS: 5e3
	};
	const AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES = 4096;
	/**
	* HTTP client implementation using Node.js native fetch API.
	*
	* This class provides a clean interface for making HTTP requests using the modern
	* fetch API available in Node.js 18+. It replaces the previous implementation that
	* relied on custom proxy handling and the legacy http/https modules.
	*/
	var HttpClient = class {
		/**
		* Sends an HTTP GET request to the specified URL.
		*
		* This method handles GET requests with optional timeout support. The timeout
		* is implemented using AbortController, which provides a clean way to cancel
		* fetch requests that take too long to complete.
		*
		* @param url - The target URL for the GET request
		* @param options - Optional request configuration including headers
		* @param timeout - Optional timeout in milliseconds. If specified, the request
		*                  will be aborted if it doesn't complete within this time
		* @returns Promise that resolves to a NetworkResponse containing headers, body, and status
		* @throws {AuthError} When the request times out or response parsing fails
		* @throws {NetworkError} When the network request fails
		*/
		async sendGetRequestAsync(url, options, timeout) {
			return this.sendRequest(url, HttpMethod.GET, options, timeout);
		}
		/**
		* Sends an HTTP POST request to the specified URL.
		*
		* This method handles POST requests with request body support. Currently,
		* timeout functionality is not exposed for POST requests, but the underlying
		* implementation supports it through the shared sendRequest method.
		*
		* @param url - The target URL for the POST request
		* @param options - Optional request configuration including headers and body
		* @returns Promise that resolves to a NetworkResponse containing headers, body, and status
		* @throws {AuthError} When the request times out or response parsing fails
		* @throws {NetworkError} When the network request fails
		*/
		async sendPostRequestAsync(url, options) {
			return this.sendRequest(url, HttpMethod.POST, options);
		}
		/**
		* Core HTTP request implementation using native fetch API.
		*
		* This method handles GET and POST HTTP requests with comprehensive
		* timeout support and error handling. The timeout mechanism works as follows:
		*
		* 1. An AbortController is created for each request
		* 2. If a timeout is specified, setTimeout is used to call abort() after the delay
		* 3. The abort signal is passed to fetch, which will reject the promise if aborted
		* 4. Cleanup occurs in both success and error cases to prevent timer leaks
		*
		* Error handling priority:
		* 1. Timeout errors (AbortError) are converted to "Request timeout" messages
		* 2. Network/connection errors are wrapped with "Network request failed" prefix
		* 3. JSON parsing errors are wrapped with "Failed to parse response" prefix
		*
		* @param url - The target URL for the request
		* @param method - HTTP method (GET or POST)
		* @param options - Optional request configuration (headers, body)
		* @param timeout - Optional timeout in milliseconds for request cancellation
		* @returns Promise resolving to NetworkResponse with parsed JSON body
		* @throws {AuthError} For timeouts or JSON parsing errors
		* @throws {NetworkError} For network failures
		*/
		async sendRequest(url, method, options, timeout) {
			const controller = new AbortController();
			let timeoutId;
			if (timeout) timeoutId = setTimeout(() => {
				controller.abort();
			}, timeout);
			const fetchOptions = {
				method,
				headers: getFetchHeaders(options),
				signal: controller.signal
			};
			if (method === HttpMethod.POST) fetchOptions.body = options?.body || "";
			let response;
			try {
				response = await fetch(url, fetchOptions);
			} catch (error) {
				if (timeoutId) clearTimeout(timeoutId);
				if (error instanceof Error && error.name === "AbortError") throw createAuthError(networkError, "Request timeout");
				throw createNetworkError(createAuthError(networkError, `Network request failed: ${error instanceof Error ? error.message : "unknown"}`), void 0, void 0, error instanceof Error ? error : void 0);
			}
			if (timeoutId) clearTimeout(timeoutId);
			try {
				return {
					headers: getHeaderDict(response.headers),
					body: await response.json(),
					status: response.status
				};
			} catch (error) {
				throw createAuthError(tokenParsingError, `Failed to parse response: ${error instanceof Error ? error.message : "unknown"}`);
			}
		}
	};
	/**
	* Converts a fetch Headers object to a plain JavaScript object.
	*
	* The fetch API returns headers as a Headers object with methods like get(), has(),
	* etc. However, the rest of the MSAL codebase expects headers as a simple key-value
	* object. This function performs that conversion.
	*
	* @param headers - The Headers object returned by fetch response
	* @returns A plain object with header names as keys and values as strings
	*/
	function getHeaderDict(headers) {
		const headerDict = {};
		headers.forEach((value, key) => {
			headerDict[key] = value;
		});
		return headerDict;
	}
	/**
	* Converts NetworkRequestOptions headers to a fetch-compatible Headers object.
	*
	* The MSAL library uses plain objects for headers in NetworkRequestOptions,
	* but the fetch API expects either a Headers object, plain object, or array
	* of arrays. Using the Headers constructor provides better compatibility
	* and validation.
	*
	* @param options - Optional NetworkRequestOptions containing headers
	* @returns A Headers object ready for use with fetch API
	*/
	function getFetchHeaders(options) {
		const headers = new Headers();
		if (!(options && options.headers)) return headers;
		Object.entries(options.headers).forEach(([key, value]) => {
			headers.append(key, value);
		});
		return headers;
	}
	const invalidFileExtension = "invalid_file_extension";
	const invalidFilePath = "invalid_file_path";
	const invalidManagedIdentityIdType = "invalid_managed_identity_id_type";
	const invalidSecret = "invalid_secret";
	const missingId = "missing_client_id";
	const networkUnavailable = "network_unavailable";
	const platformNotSupported = "platform_not_supported";
	const unableToCreateAzureArc = "unable_to_create_azure_arc";
	const unableToCreateCloudShell = "unable_to_create_cloud_shell";
	const unableToCreateSource = "unable_to_create_source";
	const unableToReadSecretFile = "unable_to_read_secret_file";
	const userAssignedNotAvailableAtRuntime = "user_assigned_not_available_at_runtime";
	const wwwAuthenticateHeaderMissing = "www_authenticate_header_missing";
	const wwwAuthenticateHeaderUnsupportedFormat = "www_authenticate_header_unsupported_format";
	const MsiEnvironmentVariableUrlMalformedErrorCodes = {
		[ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]: "azure_pod_identity_authority_host_url_malformed",
		[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]: "identity_endpoint_url_malformed",
		[ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT]: "imds_endpoint_url_malformed",
		[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]: "msi_endpoint_url_malformed"
	};
	/**
	* ManagedIdentityErrorMessage class containing string constants used by error codes and messages.
	*/
	const ManagedIdentityErrorMessages = {
		[invalidFileExtension]: "The file path in the WWW-Authenticate header does not contain a .key file.",
		[invalidFilePath]: "The file path in the WWW-Authenticate header is not in a valid Windows or Linux Format.",
		[invalidManagedIdentityIdType]: "More than one ManagedIdentityIdType was provided.",
		[invalidSecret]: "The secret in the file on the file path in the WWW-Authenticate header is greater than 4096 bytes.",
		[platformNotSupported]: "The platform is not supported by Azure Arc. Azure Arc only supports Windows and Linux.",
		[missingId]: "A ManagedIdentityId id was not provided.",
		[MsiEnvironmentVariableUrlMalformedErrorCodes.AZURE_POD_IDENTITY_AUTHORITY_HOST]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST}' environment variable is malformed.`,
		[MsiEnvironmentVariableUrlMalformedErrorCodes.IDENTITY_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variable is malformed.`,
		[MsiEnvironmentVariableUrlMalformedErrorCodes.IMDS_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' environment variable is malformed.`,
		[MsiEnvironmentVariableUrlMalformedErrorCodes.MSI_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' environment variable is malformed.`,
		[networkUnavailable]: "Authentication unavailable. The request to the managed identity endpoint timed out.",
		[unableToCreateAzureArc]: "Azure Arc Managed Identities can only be system assigned.",
		[unableToCreateCloudShell]: "Cloud Shell Managed Identities can only be system assigned.",
		[unableToCreateSource]: "Unable to create a Managed Identity source based on environment variables.",
		[unableToReadSecretFile]: "Unable to read the secret file.",
		[userAssignedNotAvailableAtRuntime]: "Service Fabric user assigned managed identity ClientId or ResourceId is not configurable at runtime.",
		[wwwAuthenticateHeaderMissing]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is missing.",
		[wwwAuthenticateHeaderUnsupportedFormat]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is in an unsupported format."
	};
	var ManagedIdentityError = class ManagedIdentityError extends AuthError {
		constructor(errorCode) {
			super(errorCode, ManagedIdentityErrorMessages[errorCode]);
			this.name = "ManagedIdentityError";
			Object.setPrototypeOf(this, ManagedIdentityError.prototype);
		}
	};
	function createManagedIdentityError(errorCode) {
		return new ManagedIdentityError(errorCode);
	}
	var ManagedIdentityId = class {
		get id() {
			return this._id;
		}
		set id(value) {
			this._id = value;
		}
		get idType() {
			return this._idType;
		}
		set idType(value) {
			this._idType = value;
		}
		constructor(managedIdentityIdParams) {
			const userAssignedClientId = managedIdentityIdParams?.userAssignedClientId;
			const userAssignedResourceId = managedIdentityIdParams?.userAssignedResourceId;
			const userAssignedObjectId = managedIdentityIdParams?.userAssignedObjectId;
			if (userAssignedClientId) {
				if (userAssignedResourceId || userAssignedObjectId) throw createManagedIdentityError(invalidManagedIdentityIdType);
				this.id = userAssignedClientId;
				this.idType = ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID;
			} else if (userAssignedResourceId) {
				if (userAssignedClientId || userAssignedObjectId) throw createManagedIdentityError(invalidManagedIdentityIdType);
				this.id = userAssignedResourceId;
				this.idType = ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID;
			} else if (userAssignedObjectId) {
				if (userAssignedClientId || userAssignedResourceId) throw createManagedIdentityError(invalidManagedIdentityIdType);
				this.id = userAssignedObjectId;
				this.idType = ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID;
			} else {
				this.id = DEFAULT_MANAGED_IDENTITY_ID;
				this.idType = ManagedIdentityIdType.SYSTEM_ASSIGNED;
			}
		}
	};
	/**
	* NodeAuthErrorMessage class containing string constants used by error codes and messages.
	*/
	const NodeAuthErrorMessage = {
		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."
		}
	};
	var NodeAuthError = class NodeAuthError extends AuthError {
		constructor(errorCode, errorMessage) {
			super(errorCode, errorMessage);
			this.name = "NodeAuthError";
		}
		/**
		* Creates an error thrown if loopback server address is of type string.
		*/
		static createInvalidLoopbackAddressTypeError() {
			return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code, `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);
		}
		/**
		* Creates an error thrown if the loopback server is unable to get a url.
		*/
		static createUnableToLoadRedirectUrlError() {
			return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code, `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);
		}
		/**
		* Creates an error thrown if the server response does not contain an auth code.
		*/
		static createNoAuthCodeInResponseError() {
			return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code, `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);
		}
		/**
		* Creates an error thrown if the loopback server has not been spun up yet.
		*/
		static createNoLoopbackServerExistsError() {
			return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code, `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);
		}
		/**
		* Creates an error thrown if a loopback server already exists when attempting to create another one.
		*/
		static createLoopbackServerAlreadyExistsError() {
			return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code, `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);
		}
		/**
		* Creates an error thrown if the loopback server times out registering the auth code listener.
		*/
		static createLoopbackServerTimeoutError() {
			return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code, `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);
		}
		/**
		* Creates an error thrown when the state is not present.
		*/
		static createStateNotFoundError() {
			return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc);
		}
		/**
		* Creates an error thrown when client certificate was provided, but neither the SHA-1 or SHA-256 thumbprints were provided
		*/
		static createThumbprintMissingError() {
			return new NodeAuthError(NodeAuthErrorMessage.thumbprintMissing.code, NodeAuthErrorMessage.thumbprintMissing.desc);
		}
		/**
		* Creates an error thrown when redirectUri is provided in an unsupported scenario
		*/
		static createRedirectUriNotSupportedError() {
			return new NodeAuthError(NodeAuthErrorMessage.redirectUriNotSupported.code, NodeAuthErrorMessage.redirectUriNotSupported.desc);
		}
	};
	const DEFAULT_AUTH_OPTIONS = {
		clientId: "",
		authority: DEFAULT_AUTHORITY,
		clientSecret: "",
		clientAssertion: "",
		clientCertificate: {
			thumbprint: "",
			thumbprintSha256: "",
			privateKey: "",
			x5c: ""
		},
		knownAuthorities: [],
		cloudDiscoveryMetadata: "",
		authorityMetadata: "",
		clientCapabilities: [],
		azureCloudOptions: {
			azureCloudInstance: AzureCloudInstance.None,
			tenant: ""
		}
	};
	const DEFAULT_LOGGER_OPTIONS = {
		loggerCallback: () => {},
		piiLoggingEnabled: false,
		logLevel: exports.LogLevel.Info
	};
	const DEFAULT_SYSTEM_OPTIONS = {
		loggerOptions: DEFAULT_LOGGER_OPTIONS,
		networkClient: new HttpClient(),
		disableInternalRetries: false,
		protocolMode: ProtocolMode.AAD
	};
	const DEFAULT_TELEMETRY_OPTIONS = { application: {
		appName: "",
		appVersion: ""
	} };
	/**
	* Sets the default options when not explicitly configured from app developer
	*
	* @param auth - Authentication options
	* @param cache - Cache options
	* @param system - System options
	* @param telemetry - Telemetry options
	*
	* @returns Configuration
	* @internal
	*/
	function buildAppConfiguration({ auth, broker, cache, system, telemetry }) {
		const systemOptions = {
			...DEFAULT_SYSTEM_OPTIONS,
			networkClient: new HttpClient(),
			loggerOptions: system?.loggerOptions || DEFAULT_LOGGER_OPTIONS,
			disableInternalRetries: system?.disableInternalRetries || false
		};
		if (!!auth.clientCertificate && !!!auth.clientCertificate.thumbprint && !!!auth.clientCertificate.thumbprintSha256) throw NodeAuthError.createStateNotFoundError();
		return {
			auth: {
				...DEFAULT_AUTH_OPTIONS,
				...auth
			},
			broker: { ...broker },
			cache: { ...cache },
			system: {
				...systemOptions,
				...system
			},
			telemetry: {
				...DEFAULT_TELEMETRY_OPTIONS,
				...telemetry
			}
		};
	}
	function buildManagedIdentityConfiguration({ clientCapabilities, managedIdentityIdParams, system }) {
		const managedIdentityId = new ManagedIdentityId(managedIdentityIdParams);
		const loggerOptions = system?.loggerOptions || DEFAULT_LOGGER_OPTIONS;
		let networkClient;
		if (system?.networkClient) networkClient = system.networkClient;
		else networkClient = new HttpClient();
		return {
			clientCapabilities: clientCapabilities || [],
			managedIdentityId,
			system: {
				loggerOptions,
				networkClient
			},
			disableInternalRetries: system?.disableInternalRetries || false
		};
	}
	var GuidGenerator = class {
		/**
		*
		* RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers.
		* uuidv4 generates guids from cryprtographically-string random
		*/
		generateGuid() {
			return uuid$1.v4();
		}
		/**
		* verifies if a string is  GUID
		* @param guid
		*/
		isGuid(guid) {
			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(guid);
		}
	};
	var EncodingUtils = class EncodingUtils {
		/**
		* 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
		* 'base64': Base64 encoding.
		*
		* @param str text
		*/
		static base64Encode(str, encoding) {
			return Buffer.from(str, encoding).toString(EncodingTypes.BASE64);
		}
		/**
		* encode a URL
		* @param str
		*/
		static base64EncodeUrl(str, encoding) {
			return EncodingUtils.base64Encode(str, encoding).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
		}
		/**
		* 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
		* 'base64': Base64 encoding.
		*
		* @param base64Str Base64 encoded text
		*/
		static base64Decode(base64Str) {
			return Buffer.from(base64Str, EncodingTypes.BASE64).toString("utf8");
		}
		/**
		* @param base64Str Base64 encoded Url
		*/
		static base64DecodeUrl(base64Str) {
			let str = base64Str.replace(/-/g, "+").replace(/_/g, "/");
			while (str.length % 4) str += "=";
			return EncodingUtils.base64Decode(str);
		}
	};
	var HashUtils = class {
		/**
		* generate 'SHA256' hash
		* @param buffer
		*/
		sha256(buffer) {
			return crypto$3.createHash(Hash.SHA256).update(buffer).digest();
		}
	};
	/**
	* https://tools.ietf.org/html/rfc7636#page-8
	*/
	var PkceGenerator = class {
		constructor() {
			this.hashUtils = new HashUtils();
		}
		/**
		* generates the codeVerfier and the challenge from the codeVerfier
		* reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2
		*/
		async generatePkceCodes() {
			const verifier = this.generateCodeVerifier();
			return {
				verifier,
				challenge: this.generateCodeChallengeFromVerifier(verifier)
			};
		}
		/**
		* generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1
		*/
		generateCodeVerifier() {
			const charArr = [];
			const maxNumber = 256 - 256 % CharSet.CV_CHARSET.length;
			while (charArr.length <= RANDOM_OCTET_SIZE) {
				const byte = crypto$3.randomBytes(1)[0];
				if (byte >= maxNumber) continue;
				const index = byte % CharSet.CV_CHARSET.length;
				charArr.push(CharSet.CV_CHARSET[index]);
			}
			const verifier = charArr.join("");
			return EncodingUtils.base64EncodeUrl(verifier);
		}
		/**
		* generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2
		* @param codeVerifier
		*/
		generateCodeChallengeFromVerifier(codeVerifier) {
			return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(codeVerifier).toString(EncodingTypes.BASE64), EncodingTypes.BASE64);
		}
	};
	/**
	* This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
	* implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
	* @public
	*/
	var CryptoProvider = class {
		constructor() {
			this.pkceGenerator = new PkceGenerator();
			this.guidGenerator = new GuidGenerator();
			this.hashUtils = new HashUtils();
		}
		/**
		* base64 URL safe encoded string
		*/
		base64UrlEncode() {
			throw new Error("Method not implemented.");
		}
		/**
		* Stringifies and base64Url encodes input public key
		* @param inputKid - public key id
		* @returns Base64Url encoded public key
		*/
		encodeKid() {
			throw new Error("Method not implemented.");
		}
		/**
		* Creates a new random GUID - used to populate state and nonce.
		* @returns string (GUID)
		*/
		createNewGuid() {
			return this.guidGenerator.generateGuid();
		}
		/**
		* Encodes input string to base64.
		* @param input - string to be encoded
		*/
		base64Encode(input) {
			return EncodingUtils.base64Encode(input);
		}
		/**
		* Decodes input string from base64.
		* @param input - string to be decoded
		*/
		base64Decode(input) {
			return EncodingUtils.base64Decode(input);
		}
		/**
		* Generates PKCE codes used in Authorization Code Flow.
		*/
		generatePkceCodes() {
			return this.pkceGenerator.generatePkceCodes();
		}
		/**
		* Generates a keypair, stores it and returns a thumbprint - not yet implemented for node
		*/
		getPublicKeyThumbprint() {
			throw new Error("Method not implemented.");
		}
		/**
		* Removes cryptographic keypair from key store matching the keyId passed in
		* @param kid - public key id
		*/
		removeTokenBindingKey() {
			throw new Error("Method not implemented.");
		}
		/**
		* Removes all cryptographic keys from Keystore
		*/
		clearKeystore() {
			throw new Error("Method not implemented.");
		}
		/**
		* Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node
		*/
		signJwt() {
			throw new Error("Method not implemented.");
		}
		/**
		* Returns the SHA-256 hash of an input string
		*/
		async hashString(plainText) {
			return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(plainText).toString(EncodingTypes.BASE64), EncodingTypes.BASE64);
		}
	};
	function generateCredentialKey(credential) {
		const familyId = credential.credentialType === CredentialType.REFRESH_TOKEN && credential.familyId || credential.clientId;
		const scheme = credential.tokenType && credential.tokenType.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase() ? credential.tokenType.toLowerCase() : "";
		return [
			credential.homeAccountId,
			credential.environment,
			credential.credentialType,
			familyId,
			credential.realm || "",
			credential.target || "",
			scheme
		].join(CACHE.KEY_SEPARATOR).toLowerCase();
	}
	function generateAccountKey(account) {
		const homeTenantId = account.homeAccountId.split(".")[1];
		return [
			account.homeAccountId,
			account.environment,
			homeTenantId || account.tenantId || ""
		].join(CACHE.KEY_SEPARATOR).toLowerCase();
	}
	/**
	* This class implements Storage for node, reading cache from user specified storage location or an  extension library
	* @public
	*/
	var NodeStorage = class extends CacheManager {
		constructor(logger, clientId, cryptoImpl, staticAuthorityOptions) {
			super(clientId, cryptoImpl, logger, new StubPerformanceClient(), staticAuthorityOptions);
			this.cache = {};
			this.changeEmitters = [];
			this.logger = logger;
		}
		/**
		* Queue up callbacks
		* @param func - a callback function for cache change indication
		*/
		registerChangeEmitter(func) {
			this.changeEmitters.push(func);
		}
		/**
		* Invoke the callback when cache changes
		*/
		emitChange() {
			this.changeEmitters.forEach((func) => func.call(null));
		}
		/**
		* Converts cacheKVStore to InMemoryCache
		* @param cache - key value store
		*/
		cacheToInMemoryCache(cache) {
			const inMemoryCache = {
				accounts: {},
				idTokens: {},
				accessTokens: {},
				refreshTokens: {},
				appMetadata: {}
			};
			for (const key in cache) {
				const value = cache[key];
				if (typeof value !== "object") continue;
				if (isAccountEntity(value)) inMemoryCache.accounts[key] = value;
				else if (isIdTokenEntity(value)) inMemoryCache.idTokens[key] = value;
				else if (isAccessTokenEntity(value)) inMemoryCache.accessTokens[key] = value;
				else if (isRefreshTokenEntity(value)) inMemoryCache.refreshTokens[key] = value;
				else if (isAppMetadataEntity(key, value)) inMemoryCache.appMetadata[key] = value;
				else continue;
			}
			return inMemoryCache;
		}
		/**
		* converts inMemoryCache to CacheKVStore
		* @param inMemoryCache - kvstore map for inmemory
		*/
		inMemoryCacheToCache(inMemoryCache) {
			let cache = this.getCache();
			cache = {
				...cache,
				...inMemoryCache.accounts,
				...inMemoryCache.idTokens,
				...inMemoryCache.accessTokens,
				...inMemoryCache.refreshTokens,
				...inMemoryCache.appMetadata
			};
			return cache;
		}
		/**
		* gets the current in memory cache for the client
		*/
		getInMemoryCache() {
			this.logger.trace("Getting in-memory cache", "");
			return this.cacheToInMemoryCache(this.getCache());
		}
		/**
		* sets the current in memory cache for the client
		* @param inMemoryCache - key value map in memory
		*/
		setInMemoryCache(inMemoryCache) {
			this.logger.trace("Setting in-memory cache", "");
			const cache = this.inMemoryCacheToCache(inMemoryCache);
			this.setCache(cache);
			this.emitChange();
		}
		/**
		* get the current cache key-value store
		*/
		getCache() {
			this.logger.trace("Getting cache key-value store", "");
			return this.cache;
		}
		/**
		* sets the current cache (key value store)
		* @param cacheMap - key value map
		*/
		setCache(cache) {
			this.logger.trace("Setting cache key value store", "");
			this.cache = cache;
			this.emitChange();
		}
		/**
		* Gets cache item with given key.
		* @param key - lookup key for the cache entry
		*/
		getItem(key) {
			this.logger.tracePii(`Item key: ${key}`, "");
			return this.getCache()[key];
		}
		/**
		* Gets cache item with given key-value
		* @param key - lookup key for the cache entry
		* @param value - value of the cache entry
		*/
		setItem(key, value) {
			this.logger.tracePii(`Item key: ${key}`, "");
			const cache = this.getCache();
			cache[key] = value;
			this.setCache(cache);
		}
		generateCredentialKey(credential) {
			return generateCredentialKey(credential);
		}
		generateAccountKey(account) {
			return generateAccountKey(account);
		}
		getAccountKeys() {
			const inMemoryCache = this.getInMemoryCache();
			return Object.keys(inMemoryCache.accounts);
		}
		getTokenKeys() {
			const inMemoryCache = this.getInMemoryCache();
			return {
				idToken: Object.keys(inMemoryCache.idTokens),
				accessToken: Object.keys(inMemoryCache.accessTokens),
				refreshToken: Object.keys(inMemoryCache.refreshTokens)
			};
		}
		/**
		* Reads account from cache, builds it into an account entity and returns it.
		* @param accountKey - lookup key to fetch cache type AccountEntity
		* @returns
		*/
		getAccount(accountKey) {
			const cachedAccount = this.getItem(accountKey);
			return cachedAccount && typeof cachedAccount === "object" ? { ...cachedAccount } : null;
		}
		/**
		* set account entity
		* @param account - cache value to be set of type AccountEntity
		*/
		async setAccount(account) {
			const accountKey = this.generateAccountKey(getAccountInfo(account));
			this.setItem(accountKey, account);
		}
		/**
		* fetch the idToken credential
		* @param idTokenKey - lookup key to fetch cache type IdTokenEntity
		*/
		getIdTokenCredential(idTokenKey) {
			const idToken = this.getItem(idTokenKey);
			if (isIdTokenEntity(idToken)) return idToken;
			return null;
		}
		/**
		* set idToken credential
		* @param idToken - cache value to be set of type IdTokenEntity
		*/
		async setIdTokenCredential(idToken) {
			const idTokenKey = this.generateCredentialKey(idToken);
			this.setItem(idTokenKey, idToken);
		}
		/**
		* fetch the accessToken credential
		* @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity
		*/
		getAccessTokenCredential(accessTokenKey) {
			const accessToken = this.getItem(accessTokenKey);
			if (isAccessTokenEntity(accessToken)) return accessToken;
			return null;
		}
		/**
		* set accessToken credential
		* @param accessToken -  cache value to be set of type AccessTokenEntity
		*/
		async setAccessTokenCredential(accessToken) {
			const accessTokenKey = this.generateCredentialKey(accessToken);
			this.setItem(accessTokenKey, accessToken);
		}
		/**
		* fetch the refreshToken credential
		* @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity
		*/
		getRefreshTokenCredential(refreshTokenKey) {
			const refreshToken = this.getItem(refreshTokenKey);
			if (isRefreshTokenEntity(refreshToken)) return refreshToken;
			return null;
		}
		/**
		* set refreshToken credential
		* @param refreshToken - cache value to be set of type RefreshTokenEntity
		*/
		async setRefreshTokenCredential(refreshToken) {
			const refreshTokenKey = this.generateCredentialKey(refreshToken);
			this.setItem(refreshTokenKey, refreshToken);
		}
		/**
		* fetch appMetadata entity from the platform cache
		* @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity
		*/
		getAppMetadata(appMetadataKey) {
			const appMetadata = this.getItem(appMetadataKey);
			if (isAppMetadataEntity(appMetadataKey, appMetadata)) return appMetadata;
			return null;
		}
		/**
		* set appMetadata entity to the platform cache
		* @param appMetadata - cache value to be set of type AppMetadataEntity
		*/
		setAppMetadata(appMetadata) {
			const appMetadataKey = generateAppMetadataKey(appMetadata);
			this.setItem(appMetadataKey, appMetadata);
		}
		/**
		* fetch server telemetry entity from the platform cache
		* @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity
		*/
		getServerTelemetry(serverTelemetrykey) {
			const serverTelemetryEntity = this.getItem(serverTelemetrykey);
			if (serverTelemetryEntity && isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) return serverTelemetryEntity;
			return null;
		}
		/**
		* set server telemetry entity to the platform cache
		* @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity
		* @param serverTelemetry - cache value to be set of type ServerTelemetryEntity
		*/
		setServerTelemetry(serverTelemetryKey, serverTelemetry) {
			this.setItem(serverTelemetryKey, serverTelemetry);
		}
		/**
		* fetch authority metadata entity from the platform cache
		* @param key - lookup key to fetch cache type AuthorityMetadataEntity
		*/
		getAuthorityMetadata(key) {
			const authorityMetadataEntity = this.getItem(key);
			if (authorityMetadataEntity && isAuthorityMetadataEntity(key, authorityMetadataEntity)) return authorityMetadataEntity;
			return null;
		}
		/**
		* Get all authority metadata keys
		*/
		getAuthorityMetadataKeys() {
			return this.getKeys().filter((key) => {
				return this.isAuthorityMetadata(key);
			});
		}
		/**
		* set authority metadata entity to the platform cache
		* @param key - lookup key to fetch cache type AuthorityMetadataEntity
		* @param metadata - cache value to be set of type AuthorityMetadataEntity
		*/
		setAuthorityMetadata(key, metadata) {
			this.setItem(key, metadata);
		}
		/**
		* fetch throttling entity from the platform cache
		* @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
		*/
		getThrottlingCache(throttlingCacheKey) {
			const throttlingCache = this.getItem(throttlingCacheKey);
			if (throttlingCache && isThrottlingEntity(throttlingCacheKey, throttlingCache)) return throttlingCache;
			return null;
		}
		/**
		* set throttling entity to the platform cache
		* @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
		* @param throttlingCache - cache value to be set of type ThrottlingEntity
		*/
		setThrottlingCache(throttlingCacheKey, throttlingCache) {
			this.setItem(throttlingCacheKey, throttlingCache);
		}
		/**
		* Removes the cache item from memory with the given key.
		* @param key - lookup key to remove a cache entity
		* @param inMemory - key value map of the cache
		*/
		removeItem(key) {
			this.logger.tracePii(`Item key: ${key}`, "");
			let result = false;
			const cache = this.getCache();
			if (!!cache[key]) {
				delete cache[key];
				result = true;
			}
			if (result) {
				this.setCache(cache);
				this.emitChange();
			}
			return result;
		}
		/**
		* Remove account entity from the platform cache if it's outdated
		* @param accountKey - lookup key to fetch cache type AccountEntity
		*/
		removeOutdatedAccount(accountKey) {
			this.removeItem(accountKey);
		}
		/**
		* Checks whether key is in cache.
		* @param key - look up key for a cache entity
		*/
		containsKey(key) {
			return this.getKeys().includes(key);
		}
		/**
		* Gets all keys in window.
		*/
		getKeys() {
			this.logger.trace("Retrieving all cache keys", "");
			const cache = this.getCache();
			return [...Object.keys(cache)];
		}
		/**
		* Clears all cache entries created by MSAL (except tokens).
		*/
		clear() {
			this.logger.trace("Clearing cache entries created by MSAL", "");
			this.getKeys().forEach((key) => {
				this.removeItem(key);
			});
			this.emitChange();
		}
		/**
		* Initialize in memory cache from an exisiting cache vault
		* @param cache - blob formatted cache (JSON)
		*/
		static generateInMemoryCache(cache) {
			return Deserializer.deserializeAllCache(Deserializer.deserializeJSONBlob(cache));
		}
		/**
		* retrieves the final JSON
		* @param inMemoryCache - itemised cache read from the JSON
		*/
		static generateJsonCache(inMemoryCache) {
			return Serializer.serializeAllCache(inMemoryCache);
		}
		/**
		* Updates a credential's cache key if the current cache key is outdated
		*/
		updateCredentialCacheKey(currentCacheKey, credential) {
			const updatedCacheKey = this.generateCredentialKey(credential);
			if (currentCacheKey !== updatedCacheKey) {
				const cacheItem = this.getItem(currentCacheKey);
				if (cacheItem) {
					this.removeItem(currentCacheKey);
					this.setItem(updatedCacheKey, cacheItem);
					this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`, "");
					return updatedCacheKey;
				} else this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`, "");
			}
			return currentCacheKey;
		}
	};
	const defaultSerializedCache = {
		Account: {},
		IdToken: {},
		AccessToken: {},
		RefreshToken: {},
		AppMetadata: {}
	};
	/**
	* In-memory token cache manager
	* @public
	*/
	var TokenCache = class {
		constructor(storage, logger, cachePlugin) {
			this.cacheHasChanged = false;
			this.storage = storage;
			this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));
			if (cachePlugin) this.persistence = cachePlugin;
			this.logger = logger;
		}
		/**
		* Set to true if cache state has changed since last time serialize or writeToPersistence was called
		*/
		hasChanged() {
			return this.cacheHasChanged;
		}
		/**
		* Serializes in memory cache to JSON
		*/
		serialize() {
			this.logger.trace("Serializing in-memory cache", "");
			let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache());
			if (this.cacheSnapshot) {
				this.logger.trace("Reading cache snapshot from disk", "");
				finalState = this.mergeState(JSON.parse(this.cacheSnapshot), finalState);
			} else this.logger.trace("No cache snapshot to merge", "");
			this.cacheHasChanged = false;
			return JSON.stringify(finalState);
		}
		/**
		* Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format
		* @param cache - blob formatted cache
		*/
		deserialize(cache) {
			this.logger.trace("Deserializing JSON to in-memory cache", "");
			this.cacheSnapshot = cache;
			if (this.cacheSnapshot) {
				this.logger.trace("Reading cache snapshot from disk", "");
				const deserializedCache = Deserializer.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));
				this.storage.setInMemoryCache(deserializedCache);
			} else this.logger.trace("No cache snapshot to deserialize", "");
		}
		/**
		* Fetches the cache key-value map
		*/
		getKVStore() {
			return this.storage.getCache();
		}
		/**
		* Gets cache snapshot in CacheKVStore format
		*/
		getCacheSnapshot() {
			const deserializedPersistentStorage = NodeStorage.generateInMemoryCache(this.cacheSnapshot);
			return this.storage.inMemoryCacheToCache(deserializedPersistentStorage);
		}
		/**
		* API that retrieves all accounts currently in cache to the user
		*/
		async getAllAccounts(correlationId = new CryptoProvider().createNewGuid()) {
			this.logger.trace("getAllAccounts called", correlationId);
			let cacheContext;
			try {
				if (this.persistence) {
					cacheContext = new TokenCacheContext(this, false);
					await this.persistence.beforeCacheAccess(cacheContext);
				}
				return this.storage.getAllAccounts({}, correlationId);
			} finally {
				if (this.persistence && cacheContext) await this.persistence.afterCacheAccess(cacheContext);
			}
		}
		/**
		* Returns the signed in account matching homeAccountId.
		* (the account object is created at the time of successful login)
		* or null when no matching account is found
		* @param homeAccountId - unique identifier for an account (uid.utid)
		*/
		async getAccountByHomeId(homeAccountId) {
			const allAccounts = await this.getAllAccounts();
			if (homeAccountId && allAccounts && allAccounts.length) return allAccounts.filter((accountObj) => accountObj.homeAccountId === homeAccountId)[0] || null;
			else return null;
		}
		/**
		* Returns the signed in account matching localAccountId.
		* (the account object is created at the time of successful login)
		* or null when no matching account is found
		* @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)
		*/
		async getAccountByLocalId(localAccountId) {
			const allAccounts = await this.getAllAccounts();
			if (localAccountId && allAccounts && allAccounts.length) return allAccounts.filter((accountObj) => accountObj.localAccountId === localAccountId)[0] || null;
			else return null;
		}
		/**
		* API to remove a specific account and the relevant data from cache
		* @param account - AccountInfo passed by the user
		*/
		async removeAccount(account, correlationId) {
			this.logger.trace("removeAccount called", correlationId || "");
			let cacheContext;
			try {
				if (this.persistence) {
					cacheContext = new TokenCacheContext(this, true);
					await this.persistence.beforeCacheAccess(cacheContext);
				}
				this.storage.removeAccount(account, correlationId || new GuidGenerator().generateGuid());
			} finally {
				if (this.persistence && cacheContext) await this.persistence.afterCacheAccess(cacheContext);
			}
		}
		/**
		* Overwrites in-memory cache with persistent cache
		*/
		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();
			const cacheContext = new TokenCacheContext(this, false);
			await this.persistence.beforeCacheAccess(cacheContext);
			const cacheSnapshot = this.getCacheSnapshot();
			this.storage.setCache(cacheSnapshot);
			await this.persistence.afterCacheAccess(cacheContext);
		}
		/**
		* Called when the cache has changed state.
		*/
		handleChangeEvent() {
			this.cacheHasChanged = true;
		}
		/**
		* Merge in memory cache with the cache snapshot.
		* @param oldState - cache before changes
		* @param currentState - current cache state in the library
		*/
		mergeState(oldState, currentState) {
			this.logger.trace("Merging in-memory cache with cache snapshot", "");
			const stateAfterRemoval = this.mergeRemovals(oldState, currentState);
			return this.mergeUpdates(stateAfterRemoval, currentState);
		}
		/**
		* Deep update of oldState based on newState values
		* @param oldState - cache before changes
		* @param newState - updated cache
		*/
		mergeUpdates(oldState, newState) {
			Object.keys(newState).forEach((newKey) => {
				const newValue = newState[newKey];
				if (!oldState.hasOwnProperty(newKey)) {
					if (newValue !== null) oldState[newKey] = newValue;
				} else {
					const newValueNotNull = newValue !== null;
					const newValueIsObject = typeof newValue === "object";
					const newValueIsNotArray = !Array.isArray(newValue);
					const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== "undefined" && oldState[newKey] !== null;
					if (newValueNotNull && newValueIsObject && newValueIsNotArray && oldStateNotUndefinedOrNull) this.mergeUpdates(oldState[newKey], newValue);
					else oldState[newKey] = newValue;
				}
			});
			return oldState;
		}
		/**
		* Removes entities in oldState that the were removed from newState. If there are any unknown values in root of
		* oldState that are not recognized, they are left untouched.
		* @param oldState - cache before changes
		* @param newState - updated cache
		*/
		mergeRemovals(oldState, newState) {
			this.logger.trace("Remove updated entries in cache", "");
			const accounts = oldState.Account ? this.mergeRemovalsDict(oldState.Account, newState.Account) : oldState.Account;
			const accessTokens = oldState.AccessToken ? this.mergeRemovalsDict(oldState.AccessToken, newState.AccessToken) : oldState.AccessToken;
			const refreshTokens = oldState.RefreshToken ? this.mergeRemovalsDict(oldState.RefreshToken, newState.RefreshToken) : oldState.RefreshToken;
			const idTokens = oldState.IdToken ? this.mergeRemovalsDict(oldState.IdToken, newState.IdToken) : oldState.IdToken;
			const appMetadata = oldState.AppMetadata ? this.mergeRemovalsDict(oldState.AppMetadata, newState.AppMetadata) : oldState.AppMetadata;
			return {
				...oldState,
				Account: accounts,
				AccessToken: accessTokens,
				RefreshToken: refreshTokens,
				IdToken: idTokens,
				AppMetadata: appMetadata
			};
		}
		/**
		* Helper to merge new cache with the old one
		* @param oldState - cache before changes
		* @param newState - updated cache
		*/
		mergeRemovalsDict(oldState, newState) {
			const finalState = { ...oldState };
			Object.keys(oldState).forEach((oldKey) => {
				if (!newState || !newState.hasOwnProperty(oldKey)) delete finalState[oldKey];
			});
			return finalState;
		}
		/**
		* Helper to overlay as a part of cache merge
		* @param passedInCache - cache read from the blob
		*/
		overlayDefaults(passedInCache) {
			this.logger.trace("Overlaying input cache with the default cache", "");
			return {
				Account: {
					...defaultSerializedCache.Account,
					...passedInCache.Account
				},
				IdToken: {
					...defaultSerializedCache.IdToken,
					...passedInCache.IdToken
				},
				AccessToken: {
					...defaultSerializedCache.AccessToken,
					...passedInCache.AccessToken
				},
				RefreshToken: {
					...defaultSerializedCache.RefreshToken,
					...passedInCache.RefreshToken
				},
				AppMetadata: {
					...defaultSerializedCache.AppMetadata,
					...passedInCache.AppMetadata
				}
			};
		}
	};
	const missingTenantIdError = "missing_tenant_id_error";
	const userTimeoutReached = "user_timeout_reached";
	const invalidAssertion = "invalid_assertion";
	const invalidClientCredential = "invalid_client_credential";
	const deviceCodePollingCancelled = "device_code_polling_cancelled";
	const deviceCodeExpired = "device_code_expired";
	const deviceCodeUnknownError = "device_code_unknown_error";
	/**
	* Client assertion of type jwt-bearer used in confidential client flows
	* @public
	*/
	var ClientAssertion = class ClientAssertion {
		/**
		* Initialize the ClientAssertion class from the clientAssertion passed by the user
		* @param assertion - refer https://tools.ietf.org/html/rfc7521
		*/
		static fromAssertion(assertion) {
			const clientAssertion = new ClientAssertion();
			clientAssertion.jwt = assertion;
			return clientAssertion;
		}
		/**
		* @deprecated Use fromCertificateWithSha256Thumbprint instead, with a SHA-256 thumprint
		* Initialize the ClientAssertion class from the certificate passed by the user
		* @param thumbprint - identifier of a certificate
		* @param privateKey - secret key
		* @param publicCertificate - electronic document provided to prove the ownership of the public key
		*/
		static fromCertificate(thumbprint, privateKey, publicCertificate) {
			const clientAssertion = new ClientAssertion();
			clientAssertion.privateKey = privateKey;
			clientAssertion.thumbprint = thumbprint;
			clientAssertion.useSha256 = false;
			if (publicCertificate) clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);
			return clientAssertion;
		}
		/**
		* Initialize the ClientAssertion class from the certificate passed by the user
		* @param thumbprint - identifier of a certificate
		* @param privateKey - secret key
		* @param publicCertificate - electronic document provided to prove the ownership of the public key
		*/
		static fromCertificateWithSha256Thumbprint(thumbprint, privateKey, publicCertificate) {
			const clientAssertion = new ClientAssertion();
			clientAssertion.privateKey = privateKey;
			clientAssertion.thumbprint = thumbprint;
			clientAssertion.useSha256 = true;
			if (publicCertificate) clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);
			return clientAssertion;
		}
		/**
		* Update JWT for certificate based clientAssertion, if passed by the user, uses it as is
		* @param cryptoProvider - library's crypto helper
		* @param issuer - iss claim
		* @param jwtAudience - aud claim
		*/
		getJwt(cryptoProvider, issuer, jwtAudience) {
			if (this.privateKey && this.thumbprint) {
				if (this.jwt && !this.isExpired() && issuer === this.issuer && jwtAudience === this.jwtAudience) return this.jwt;
				return this.createJwt(cryptoProvider, issuer, jwtAudience);
			}
			if (this.jwt) return this.jwt;
			throw createClientAuthError(invalidAssertion);
		}
		/**
		* JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3
		*/
		createJwt(cryptoProvider, issuer, jwtAudience) {
			this.issuer = issuer;
			this.jwtAudience = jwtAudience;
			const issuedAt = nowSeconds();
			this.expirationTime = issuedAt + 600;
			const header = { alg: this.useSha256 ? JwtConstants.PSS_256 : JwtConstants.RSA_256 };
			const thumbprintHeader = this.useSha256 ? JwtConstants.X5T_256 : JwtConstants.X5T;
			Object.assign(header, { [thumbprintHeader]: EncodingUtils.base64EncodeUrl(this.thumbprint, EncodingTypes.HEX) });
			if (this.publicCertificate) Object.assign(header, { [JwtConstants.X5C]: this.publicCertificate });
			const payload = {
				[JwtConstants.AUDIENCE]: this.jwtAudience,
				[JwtConstants.EXPIRATION_TIME]: this.expirationTime,
				[JwtConstants.ISSUER]: this.issuer,
				[JwtConstants.SUBJECT]: this.issuer,
				[JwtConstants.NOT_BEFORE]: issuedAt,
				[JwtConstants.JWT_ID]: cryptoProvider.createNewGuid()
			};
			this.jwt = jwt.sign(payload, this.privateKey, { header });
			return this.jwt;
		}
		/**
		* Utility API to check expiration
		*/
		isExpired() {
			return this.expirationTime < nowSeconds();
		}
		/**
		* Extracts the raw certs from a given certificate string and returns them in an array.
		* @param publicCertificate - electronic document provided to prove the ownership of the public key
		*/
		static parseCertificate(publicCertificate) {
			/**
			* This is regex to identify the certs in a given certificate string.
			* We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines.
			* The information in parens "(.+?)" is the capture group to represent the cert we want isolated.
			* "." means any string character, "+" means match 1 or more times, and "?" means the shortest match.
			* The "g" at the end of the regex means search the string globally, and the "s" enables the "." to match newlines.
			*/
			const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;
			const certs = [];
			let matches;
			while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) certs.push(matches[1].replace(/\r*\n/g, ""));
			return certs;
		}
	};
	const name = "@azure/msal-node";
	const version = "5.0.5";
	/**
	* Base application class which will construct requests to send to and handle responses from the Microsoft STS using the authorization code flow.
	* @internal
	*/
	var BaseClient = class {
		constructor(configuration) {
			this.config = buildClientConfiguration(configuration);
			this.logger = new Logger(this.config.loggerOptions, name, version);
			this.cryptoUtils = this.config.cryptoInterface;
			this.cacheManager = this.config.storageInterface;
			this.networkClient = this.config.networkInterface;
			this.serverTelemetryManager = this.config.serverTelemetryManager;
			this.authority = this.config.authOptions.authority;
			this.performanceClient = new StubPerformanceClient();
		}
		/**
		* Creates default headers for requests to token endpoint
		*/
		createTokenRequestHeaders(ccsCred) {
			return createTokenRequestHeaders(this.logger, false, ccsCred);
		}
		/**
		* Http post to token endpoint
		* @param tokenEndpoint
		* @param queryString
		* @param headers
		* @param thumbprint
		*/
		async executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId) {
			return executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, this.serverTelemetryManager);
		}
		/**
		* Wraps sendPostRequestAsync with necessary preflight and postflight logic
		* @param thumbprint - Request thumbprint for throttling
		* @param tokenEndpoint - Endpoint to make the POST to
		* @param options - Body and Headers to include on the POST request
		* @param correlationId - CorrelationId for telemetry
		*/
		async sendPostRequest(thumbprint, tokenEndpoint, options, correlationId) {
			return sendPostRequest(thumbprint, tokenEndpoint, options, correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient);
		}
		/**
		* Creates query string for the /token request
		* @param request
		*/
		createTokenQueryParameters(request) {
			return createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
		}
	};
	/**
	* Oauth2.0 Password grant client
	* Note: We are only supporting public clients for password grant and for purely testing purposes
	* @public
	* @deprecated - Use a more secure flow instead
	*/
	var UsernamePasswordClient = class extends BaseClient {
		constructor(configuration) {
			super(configuration);
		}
		/**
		* API to acquire a token by passing the username and password to the service in exchage of credentials
		* password_grant
		* @param request - CommonUsernamePasswordRequest
		*/
		async acquireToken(request) {
			this.logger.info("in acquireToken call in username-password client", request.correlationId);
			const reqTimestamp = nowSeconds();
			const response = await this.executeTokenRequest(this.authority, request);
			const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
			responseHandler.validateTokenResponse(response.body, request.correlationId);
			return responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, ApiId.acquireTokenByUsernamePassword);
		}
		/**
		* Executes POST request to token endpoint
		* @param authority - authority object
		* @param request - CommonUsernamePasswordRequest provided by the developer
		*/
		async executeTokenRequest(authority, request) {
			const queryParametersString = this.createTokenQueryParameters(request);
			const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
			const requestBody = await this.createTokenRequestBody(request);
			const headers = this.createTokenRequestHeaders({
				credential: request.username,
				type: CcsCredentialType.UPN
			});
			const thumbprint = {
				clientId: this.config.authOptions.clientId,
				authority: authority.canonicalAuthority,
				scopes: request.scopes,
				claims: request.claims,
				authenticationScheme: request.authenticationScheme,
				resourceRequestMethod: request.resourceRequestMethod,
				resourceRequestUri: request.resourceRequestUri,
				shrClaims: request.shrClaims,
				sshKid: request.sshKid
			};
			return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);
		}
		/**
		* Generates a map for all the params to be sent to the service
		* @param request - CommonUsernamePasswordRequest provided by the developer
		*/
		async createTokenRequestBody(request) {
			const parameters = /* @__PURE__ */ new Map();
			addClientId(parameters, this.config.authOptions.clientId);
			addUsername(parameters, request.username);
			addPassword(parameters, request.password);
			addScopes(parameters, request.scopes);
			addResponseType(parameters, OAuthResponseType.IDTOKEN_TOKEN);
			addGrantType(parameters, GrantType.RESOURCE_OWNER_PASSWORD_GRANT);
			addClientInfo(parameters);
			addLibraryInfo(parameters, this.config.libraryInfo);
			addApplicationTelemetry(parameters, this.config.telemetry.application);
			addThrottling(parameters);
			if (this.serverTelemetryManager) addServerTelemetry(parameters, this.serverTelemetryManager);
			addCorrelationId(parameters, request.correlationId || this.config.cryptoInterface.createNewGuid());
			if (this.config.clientCredentials.clientSecret) addClientSecret(parameters, this.config.clientCredentials.clientSecret);
			const clientAssertion = this.config.clientCredentials.clientAssertion;
			if (clientAssertion) {
				addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
				addClientAssertionType(parameters, clientAssertion.assertionType);
			}
			if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities);
			if (this.config.systemOptions.preventCorsPreflight && request.username) addCcsUpn(parameters, request.username);
			return mapToQueryString(parameters);
		}
	};
	/**
	* Constructs the full /authorize URL with request parameters
	* @param config
	* @param authority
	* @param request
	* @param logger
	* @returns
	*/
	function getAuthCodeRequestUrl(config, authority, request, logger) {
		const parameters = getStandardAuthorizeRequestParameters({
			...config.auth,
			authority,
			redirectUri: request.redirectUri || ""
		}, request, logger);
		addLibraryInfo(parameters, {
			sku: Constants.MSAL_SKU,
			version,
			cpu: process.arch || "",
			os: process.platform || ""
		});
		if (config.system.protocolMode !== ProtocolMode.OIDC) addApplicationTelemetry(parameters, config.telemetry.application);
		addResponseType(parameters, OAuthResponseType.CODE);
		if (request.codeChallenge && request.codeChallengeMethod) addCodeChallengeParams(parameters, request.codeChallenge, request.codeChallengeMethod);
		addExtraParameters(parameters, request.extraQueryParameters || {});
		return getAuthorizeUrl(authority, parameters);
	}
	/**
	* Base abstract class for all ClientApplications - public and confidential
	* @public
	*/
	var ClientApplication = class {
		/**
		* Constructor for the ClientApplication
		*/
		constructor(configuration) {
			this.config = buildAppConfiguration(configuration);
			this.cryptoProvider = new CryptoProvider();
			this.logger = new Logger(this.config.system.loggerOptions, name, version);
			this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider, buildStaticAuthorityOptions(this.config.auth));
			this.tokenCache = new TokenCache(this.storage, this.logger, this.config.cache.cachePlugin);
		}
		/**
		* Creates the URL of the authorization request, letting the user input credentials and consent to the
		* application. The URL targets the /authorize endpoint of the authority configured in the
		* application object.
		*
		* Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
		* sent in the request and should contain an authorization code, which can then be used to acquire tokens via
		* `acquireTokenByCode(AuthorizationCodeRequest)`.
		*/
		async getAuthCodeUrl(request) {
			this.logger.info("getAuthCodeUrl called", request.correlationId || "");
			const validRequest = {
				...request,
				...await this.initializeBaseRequest(request),
				responseMode: request.responseMode || ResponseMode$1.QUERY,
				authenticationScheme: AuthenticationScheme.BEARER,
				state: request.state || "",
				nonce: request.nonce || ""
			};
			const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);
			return getAuthCodeRequestUrl(this.config, discoveredAuthority, validRequest, this.logger);
		}
		/**
		* Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0
		* Authorization Code flow.
		*
		* `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0
		* Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and
		* AuthorizationCodeRequest are the same.
		*/
		async acquireTokenByCode(request, authCodePayLoad) {
			this.logger.info("acquireTokenByCode called", request.correlationId || "");
			if (request.state && authCodePayLoad) {
				this.logger.info("acquireTokenByCode - validating state", request.correlationId || "");
				this.validateState(request.state, authCodePayLoad.state || "");
				authCodePayLoad = {
					...authCodePayLoad,
					state: ""
				};
			}
			const validRequest = {
				...request,
				...await this.initializeBaseRequest(request),
				authenticationScheme: AuthenticationScheme.BEARER
			};
			const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);
			try {
				const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);
				const authorizationCodeClient = new AuthorizationCodeClient(await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri, serverTelemetryManager), new StubPerformanceClient());
				this.logger.verbose("Auth code client created", validRequest.correlationId);
				return await authorizationCodeClient.acquireToken(validRequest, ApiId.acquireTokenByCode, authCodePayLoad);
			} catch (e) {
				if (e instanceof AuthError) e.setCorrelationId(validRequest.correlationId);
				serverTelemetryManager.cacheFailedRequest(e);
				throw e;
			}
		}
		/**
		* Acquires a token by exchanging the refresh token provided for a new set of tokens.
		*
		* This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is
		* recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will
		* handle the caching and refreshing of tokens automatically.
		*/
		async acquireTokenByRefreshToken(request) {
			this.logger.info("acquireTokenByRefreshToken called", request.correlationId || "");
			const validRequest = {
				...request,
				...await this.initializeBaseRequest(request),
				authenticationScheme: AuthenticationScheme.BEARER
			};
			const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);
			try {
				const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);
				const refreshTokenClient = new RefreshTokenClient(await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager), new StubPerformanceClient());
				this.logger.verbose("Refresh token client created", validRequest.correlationId);
				return await refreshTokenClient.acquireToken(validRequest, ApiId.acquireTokenByRefreshToken);
			} catch (e) {
				if (e instanceof AuthError) e.setCorrelationId(validRequest.correlationId);
				serverTelemetryManager.cacheFailedRequest(e);
				throw e;
			}
		}
		/**
		* Acquires a token silently when a user specifies the account the token is requested for.
		*
		* This API expects the user to provide an account object and looks into the cache to retrieve the token if present.
		* There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token.
		* In case the refresh_token is expired or not found, an error is thrown
		* and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).
		*/
		async acquireTokenSilent(request) {
			const validRequest = {
				...request,
				...await this.initializeBaseRequest(request),
				forceRefresh: request.forceRefresh || false
			};
			const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);
			try {
				const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);
				const clientConfiguration = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager);
				const silentFlowClient = new SilentFlowClient(clientConfiguration, new StubPerformanceClient());
				this.logger.verbose("Silent flow client created", validRequest.correlationId);
				try {
					await this.tokenCache.overwriteCache();
					return await this.acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration);
				} catch (error) {
					if (error instanceof ClientAuthError && error.errorCode === tokenRefreshRequired) return new RefreshTokenClient(clientConfiguration, new StubPerformanceClient()).acquireTokenByRefreshToken(validRequest, ApiId.acquireTokenSilent);
					throw error;
				}
			} catch (error) {
				if (error instanceof AuthError) error.setCorrelationId(validRequest.correlationId);
				serverTelemetryManager.cacheFailedRequest(error);
				throw error;
			}
		}
		async acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration) {
			const [authResponse, cacheOutcome] = await silentFlowClient.acquireCachedToken({
				...validRequest,
				scopes: validRequest.scopes?.length ? validRequest.scopes : [...OIDC_DEFAULT_SCOPES]
			});
			if (cacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {
				this.logger.info("ClientApplication:acquireCachedTokenSilent - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.", validRequest.correlationId);
				const refreshTokenClient = new RefreshTokenClient(clientConfiguration, new StubPerformanceClient());
				try {
					await refreshTokenClient.acquireTokenByRefreshToken(validRequest, ApiId.acquireTokenSilent);
				} catch {}
			}
			return authResponse;
		}
		/**
		* Acquires tokens with password grant by exchanging client applications username and password for credentials
		*
		* The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.
		* More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4
		* Microsoft's documentation and recommendations are at:
		* https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword
		*
		* @param request - UsenamePasswordRequest
		* @deprecated - Use a more secure flow instead
		*/
		async acquireTokenByUsernamePassword(request) {
			this.logger.info("acquireTokenByUsernamePassword called", request.correlationId || "");
			const validRequest = {
				...request,
				...await this.initializeBaseRequest(request)
			};
			const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);
			try {
				const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);
				const usernamePasswordClient = new UsernamePasswordClient(await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager));
				this.logger.verbose("Username password client created", validRequest.correlationId);
				return await usernamePasswordClient.acquireToken(validRequest);
			} catch (e) {
				if (e instanceof AuthError) e.setCorrelationId(validRequest.correlationId);
				serverTelemetryManager.cacheFailedRequest(e);
				throw e;
			}
		}
		/**
		* Gets the token cache for the application.
		*/
		getTokenCache() {
			this.logger.info("getTokenCache called", "");
			return this.tokenCache;
		}
		/**
		* Validates OIDC state by comparing the user cached state with the state received from the server.
		*
		* This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against
		* CSRF attacks.
		* For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.
		* @param state - Unique GUID generated by the user that is cached by the user and sent to the server during the first leg of the flow
		* @param cachedState - This string is sent back by the server with the authorization code
		*/
		validateState(state, cachedState) {
			if (!state) throw NodeAuthError.createStateNotFoundError();
			if (state !== cachedState) throw createClientAuthError(stateMismatch);
		}
		/**
		* Returns the logger instance
		*/
		getLogger() {
			return this.logger;
		}
		/**
		* Replaces the default logger set in configurations with new Logger with new configurations
		* @param logger - Logger instance
		*/
		setLogger(logger) {
			this.logger = logger;
		}
		/**
		* Builds the common configuration to be passed to the common component based on the platform configurarion
		* @param authority - user passed authority in configuration
		* @param serverTelemetryManager - initializes servertelemetry if passed
		*/
		async buildOauthClientConfiguration(discoveredAuthority, requestCorrelationId, redirectUri, serverTelemetryManager) {
			this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId);
			this.logger.info(`Building oauth client configuration with the following authority: ${discoveredAuthority.tokenEndpoint}.`, requestCorrelationId);
			serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);
			return {
				authOptions: {
					clientId: this.config.auth.clientId,
					authority: discoveredAuthority,
					clientCapabilities: this.config.auth.clientCapabilities,
					redirectUri
				},
				loggerOptions: {
					logLevel: this.config.system.loggerOptions.logLevel,
					loggerCallback: this.config.system.loggerOptions.loggerCallback,
					piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled,
					correlationId: requestCorrelationId
				},
				cryptoInterface: this.cryptoProvider,
				networkInterface: this.config.system.networkClient,
				storageInterface: this.storage,
				serverTelemetryManager,
				clientCredentials: {
					clientSecret: this.clientSecret,
					clientAssertion: await this.getClientAssertion(discoveredAuthority)
				},
				libraryInfo: {
					sku: Constants.MSAL_SKU,
					version,
					cpu: process.arch || "",
					os: process.platform || ""
				},
				telemetry: this.config.telemetry,
				persistencePlugin: this.config.cache.cachePlugin,
				serializableCache: this.tokenCache
			};
		}
		async getClientAssertion(authority) {
			if (this.developerProvidedClientAssertion) this.clientAssertion = ClientAssertion.fromAssertion(await getClientAssertion(this.developerProvidedClientAssertion, this.config.auth.clientId, authority.tokenEndpoint));
			return this.clientAssertion && {
				assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),
				assertionType: Constants.JWT_BEARER_ASSERTION_TYPE
			};
		}
		/**
		* Generates a request with the default scopes & generates a correlationId.
		* @param authRequest - BaseAuthRequest for initialization
		*/
		async initializeBaseRequest(authRequest) {
			const correlationId = authRequest.correlationId || this.cryptoProvider.createNewGuid();
			this.logger.verbose("initializeRequestScopes called", correlationId);
			if (authRequest.authenticationScheme && authRequest.authenticationScheme === AuthenticationScheme.POP) this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", correlationId);
			authRequest.authenticationScheme = AuthenticationScheme.BEARER;
			return {
				...authRequest,
				scopes: [...authRequest && authRequest.scopes || [], ...OIDC_DEFAULT_SCOPES],
				correlationId,
				authority: authRequest.authority || this.config.auth.authority
			};
		}
		/**
		* Initializes the server telemetry payload
		* @param apiId - Id for a specific request
		* @param correlationId - GUID
		* @param forceRefresh - boolean to indicate network call
		*/
		initializeServerTelemetryManager(apiId, correlationId, forceRefresh) {
			return new ServerTelemetryManager({
				clientId: this.config.auth.clientId,
				correlationId,
				apiId,
				forceRefresh: forceRefresh || false
			}, this.storage);
		}
		/**
		* Create authority instance. If authority not passed in request, default to authority set on the application
		* object. If no authority set in application object, then default to common authority.
		* @param authorityString - authority from user configuration
		*/
		async createAuthority(authorityString, requestCorrelationId, azureRegionConfiguration, azureCloudOptions) {
			this.logger.verbose("createAuthority called", requestCorrelationId);
			const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions || this.config.auth.azureCloudOptions);
			const authorityOptions = {
				protocolMode: this.config.system.protocolMode,
				knownAuthorities: this.config.auth.knownAuthorities,
				cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
				authorityMetadata: this.config.auth.authorityMetadata,
				azureRegionConfiguration
			};
			return createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, requestCorrelationId, new StubPerformanceClient());
		}
		/**
		* Clear the cache
		*/
		clearCache() {
			this.storage.clear();
		}
	};
	var LoopbackClient = class {
		/**
		* Spins up a loopback server which returns the server response when the localhost redirectUri is hit
		* @param successTemplate
		* @param errorTemplate
		* @returns
		*/
		async listenForAuthCode(successTemplate, errorTemplate) {
			if (this.server) throw NodeAuthError.createLoopbackServerAlreadyExistsError();
			return new Promise((resolve, reject) => {
				this.server = http$2.createServer((req, res) => {
					const url = req.url;
					if (!url) {
						res.end(errorTemplate || "Error occurred loading redirectUrl");
						reject(NodeAuthError.createUnableToLoadRedirectUrlError());
						return;
					} else if (url === FORWARD_SLASH) {
						res.end(successTemplate || "Auth code was successfully acquired. You can close this window now.");
						return;
					}
					const redirectUri = this.getRedirectUri();
					const authCodeResponse = getDeserializedResponse(new URL(url, redirectUri).search) || {};
					if (authCodeResponse.code) {
						res.writeHead(HTTP_REDIRECT, { location: redirectUri });
						res.end();
					}
					if (authCodeResponse.error) res.end(errorTemplate || `Error occurred: ${authCodeResponse.error}`);
					resolve(authCodeResponse);
				});
				this.server.listen(0, "127.0.0.1");
			});
		}
		/**
		* Get the port that the loopback server is running on
		* @returns
		*/
		getRedirectUri() {
			if (!this.server || !this.server.listening) throw NodeAuthError.createNoLoopbackServerExistsError();
			const address = this.server.address();
			if (!address || typeof address === "string" || !address.port) {
				this.closeServer();
				throw NodeAuthError.createInvalidLoopbackAddressTypeError();
			}
			const port = address && address.port;
			return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;
		}
		/**
		* Close the loopback server
		*/
		closeServer() {
			if (this.server) {
				this.server.close();
				if (typeof this.server.closeAllConnections === "function") this.server.closeAllConnections();
				this.server.unref();
				this.server = void 0;
			}
		}
	};
	/**
	* OAuth2.0 Device code client
	* @public
	*/
	var DeviceCodeClient = class extends BaseClient {
		constructor(configuration) {
			super(configuration);
		}
		/**
		* Gets device code from device code endpoint, calls back to with device code response, and
		* polls token endpoint to exchange device code for tokens
		* @param request - developer provided CommonDeviceCodeRequest
		*/
		async acquireToken(request) {
			const deviceCodeResponse = await this.getDeviceCode(request);
			request.deviceCodeCallback(deviceCodeResponse);
			const reqTimestamp = nowSeconds();
			const response = await this.acquireTokenWithDeviceCode(request, deviceCodeResponse);
			const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
			responseHandler.validateTokenResponse(response, request.correlationId);
			return responseHandler.handleServerTokenResponse(response, this.authority, reqTimestamp, request, ApiId.acquireTokenByDeviceCode);
		}
		/**
		* Creates device code request and executes http GET
		* @param request - developer provided CommonDeviceCodeRequest
		*/
		async getDeviceCode(request) {
			const queryParametersString = this.createExtraQueryParameters(request);
			const endpoint = UrlString.appendQueryString(this.authority.deviceCodeEndpoint, queryParametersString);
			const queryString = this.createQueryString(request);
			const headers = this.createTokenRequestHeaders();
			const thumbprint = {
				clientId: this.config.authOptions.clientId,
				authority: request.authority,
				scopes: request.scopes,
				claims: request.claims,
				authenticationScheme: request.authenticationScheme,
				resourceRequestMethod: request.resourceRequestMethod,
				resourceRequestUri: request.resourceRequestUri,
				shrClaims: request.shrClaims,
				sshKid: request.sshKid
			};
			return this.executePostRequestToDeviceCodeEndpoint(endpoint, queryString, headers, thumbprint, request.correlationId);
		}
		/**
		* Creates query string for the device code request
		* @param request - developer provided CommonDeviceCodeRequest
		*/
		createExtraQueryParameters(request) {
			const parameters = /* @__PURE__ */ new Map();
			if (request.extraQueryParameters) addExtraParameters(parameters, request.extraQueryParameters);
			return mapToQueryString(parameters);
		}
		/**
		* Executes POST request to device code endpoint
		* @param deviceCodeEndpoint - token endpoint
		* @param queryString - string to be used in the body of the request
		* @param headers - headers for the request
		* @param thumbprint - unique request thumbprint
		* @param correlationId - correlation id to be used in the request
		*/
		async executePostRequestToDeviceCodeEndpoint(deviceCodeEndpoint, queryString, headers, thumbprint, correlationId) {
			const { body: { user_code: userCode, device_code: deviceCode, verification_uri: verificationUri, expires_in: expiresIn, interval, message } } = await this.sendPostRequest(thumbprint, deviceCodeEndpoint, {
				body: queryString,
				headers
			}, correlationId);
			return {
				userCode,
				deviceCode,
				verificationUri,
				expiresIn,
				interval,
				message
			};
		}
		/**
		* Create device code endpoint query parameters and returns string
		* @param request - developer provided CommonDeviceCodeRequest
		*/
		createQueryString(request) {
			const parameters = /* @__PURE__ */ new Map();
			addScopes(parameters, request.scopes);
			addClientId(parameters, this.config.authOptions.clientId);
			if (request.extraQueryParameters) addExtraParameters(parameters, request.extraQueryParameters);
			if (request.claims || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities);
			return mapToQueryString(parameters);
		}
		/**
		* Breaks the polling with specific conditions
		* @param deviceCodeExpirationTime - expiration time for the device code request
		* @param userSpecifiedTimeout - developer provided timeout, to be compared against deviceCodeExpirationTime
		* @param userSpecifiedCancelFlag - boolean indicating the developer would like to cancel the request
		*/
		continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, userSpecifiedCancelFlag) {
			if (userSpecifiedCancelFlag) {
				this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true", "");
				throw createClientAuthError(deviceCodePollingCancelled);
			} else if (userSpecifiedTimeout && userSpecifiedTimeout < deviceCodeExpirationTime && nowSeconds() > userSpecifiedTimeout) {
				this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`, "");
				throw createClientAuthError(userTimeoutReached);
			} else if (nowSeconds() > deviceCodeExpirationTime) {
				if (userSpecifiedTimeout) this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`, "");
				this.logger.error(`Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`, "");
				throw createClientAuthError(deviceCodeExpired);
			}
			return true;
		}
		/**
		* Creates token request with device code response and polls token endpoint at interval set by the device code response
		* @param request - developer provided CommonDeviceCodeRequest
		* @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint
		*/
		async acquireTokenWithDeviceCode(request, deviceCodeResponse) {
			const queryParametersString = this.createTokenQueryParameters(request);
			const endpoint = UrlString.appendQueryString(this.authority.tokenEndpoint, queryParametersString);
			const requestBody = this.createTokenRequestBody(request, deviceCodeResponse);
			const headers = this.createTokenRequestHeaders();
			const userSpecifiedTimeout = request.timeout ? nowSeconds() + request.timeout : void 0;
			const deviceCodeExpirationTime = nowSeconds() + deviceCodeResponse.expiresIn;
			const pollingIntervalMilli = deviceCodeResponse.interval * 1e3;
			while (this.continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, request.cancel)) {
				const thumbprint = {
					clientId: this.config.authOptions.clientId,
					authority: request.authority,
					scopes: request.scopes,
					claims: request.claims,
					authenticationScheme: request.authenticationScheme,
					resourceRequestMethod: request.resourceRequestMethod,
					resourceRequestUri: request.resourceRequestUri,
					shrClaims: request.shrClaims,
					sshKid: request.sshKid
				};
				const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);
				if (response.body && response.body.error) if (response.body.error === AUTHORIZATION_PENDING) {
					this.logger.info("Authorization pending. Continue polling.", request.correlationId);
					await delay(pollingIntervalMilli);
				} else {
					this.logger.info("Unexpected error in polling from the server", request.correlationId);
					throw createAuthError(postRequestFailed, response.body.error);
				}
				else {
					this.logger.verbose("Authorization completed successfully. Polling stopped.", request.correlationId);
					return response.body;
				}
			}
			this.logger.error("Polling stopped for unknown reasons.", request.correlationId);
			throw createClientAuthError(deviceCodeUnknownError);
		}
		/**
		* Creates query parameters and converts to string.
		* @param request - developer provided CommonDeviceCodeRequest
		* @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint
		*/
		createTokenRequestBody(request, deviceCodeResponse) {
			const parameters = /* @__PURE__ */ new Map();
			addScopes(parameters, request.scopes);
			addClientId(parameters, this.config.authOptions.clientId);
			addGrantType(parameters, GrantType.DEVICE_CODE_GRANT);
			addDeviceCode(parameters, deviceCodeResponse.deviceCode);
			addCorrelationId(parameters, request.correlationId || this.config.cryptoInterface.createNewGuid());
			addClientInfo(parameters);
			addLibraryInfo(parameters, this.config.libraryInfo);
			addApplicationTelemetry(parameters, this.config.telemetry.application);
			addThrottling(parameters);
			if (this.serverTelemetryManager) addServerTelemetry(parameters, this.serverTelemetryManager);
			if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities);
			return mapToQueryString(parameters);
		}
	};
	/**
	* This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications
	* are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.
	* @public
	*/
	var PublicClientApplication = class extends ClientApplication {
		/**
		* Important attributes in the Configuration object for auth are:
		* - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.
		* - authority: the authority URL for your application.
		*
		* AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
		* - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
		* - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
		* - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
		* - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
		*
		* Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered
		* its own authority. You will have to set the all of the knownAuthorities at the time of the client application
		* construction.
		*
		* ADFS authorities are of the form https://\{instance\}/adfs.
		*/
		constructor(configuration) {
			super(configuration);
			if (this.config.broker.nativeBrokerPlugin) if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) {
				this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin;
				this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions);
			} else this.logger.warning("NativeBroker implementation was provided but the broker is unavailable.", "");
			this.skus = ServerTelemetryManager.makeExtraSkuString({
				libraryName: Constants.MSAL_SKU,
				libraryVersion: version
			});
		}
		/**
		* Acquires a token from the authority using OAuth2.0 device code flow.
		* This flow is designed for devices that do not have access to a browser or have input constraints.
		* The authorization server issues a DeviceCode object with a verification code, an end-user code,
		* and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be
		* instructed to use another device to navigate to the verification URI to input credentials.
		* Since the client cannot receive incoming requests, it polls the authorization server repeatedly
		* until the end-user completes input of credentials.
		*/
		async acquireTokenByDeviceCode(request) {
			this.logger.info("acquireTokenByDeviceCode called", request.correlationId || "");
			const validRequest = Object.assign(request, await this.initializeBaseRequest(request));
			const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);
			try {
				const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);
				const deviceCodeClient = new DeviceCodeClient(await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager));
				this.logger.verbose("Device code client created", validRequest.correlationId);
				return await deviceCodeClient.acquireToken(validRequest);
			} catch (e) {
				if (e instanceof AuthError) e.setCorrelationId(validRequest.correlationId);
				serverTelemetryManager.cacheFailedRequest(e);
				throw e;
			}
		}
		/**
		* Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token.
		*/
		async acquireTokenInteractive(request) {
			const correlationId = request.correlationId || this.cryptoProvider.createNewGuid();
			this.logger.trace("acquireTokenInteractive called", correlationId);
			const { openBrowser, successTemplate, errorTemplate, windowHandle, loopbackClient: customLoopbackClient, ...remainingProperties } = request;
			if (this.nativeBrokerPlugin) {
				const brokerRequest = {
					...remainingProperties,
					clientId: this.config.auth.clientId,
					scopes: request.scopes || OIDC_DEFAULT_SCOPES,
					redirectUri: request.redirectUri || "",
					authority: request.authority || this.config.auth.authority,
					correlationId,
					extraParameters: {
						...remainingProperties.extraQueryParameters,
						...remainingProperties.extraParameters,
						[X_CLIENT_EXTRA_SKU]: this.skus
					},
					accountId: remainingProperties.account?.nativeAccountId
				};
				return this.nativeBrokerPlugin.acquireTokenInteractive(brokerRequest, windowHandle);
			}
			if (request.redirectUri) {
				if (!this.config.broker.nativeBrokerPlugin) throw NodeAuthError.createRedirectUriNotSupportedError();
				request.redirectUri = "";
			}
			const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes();
			const loopbackClient = customLoopbackClient || new LoopbackClient();
			let authCodeResponse = {};
			let authCodeListenerError = null;
			try {
				const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate).then((response) => {
					authCodeResponse = response;
				}).catch((e) => {
					authCodeListenerError = e;
				});
				const redirectUri = await this.waitForRedirectUri(loopbackClient);
				const validRequest = {
					...remainingProperties,
					correlationId,
					scopes: request.scopes || OIDC_DEFAULT_SCOPES,
					redirectUri,
					responseMode: ResponseMode$1.QUERY,
					codeChallenge: challenge,
					codeChallengeMethod: CodeChallengeMethodValues.S256
				};
				await openBrowser(await this.getAuthCodeUrl(validRequest));
				await authCodeListener;
				if (authCodeListenerError) throw authCodeListenerError;
				if (authCodeResponse.error) throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);
				else if (!authCodeResponse.code) throw NodeAuthError.createNoAuthCodeInResponseError();
				const clientInfo = authCodeResponse.client_info;
				const tokenRequest = {
					code: authCodeResponse.code,
					codeVerifier: verifier,
					clientInfo: clientInfo || "",
					...validRequest
				};
				return await this.acquireTokenByCode(tokenRequest);
			} finally {
				loopbackClient.closeServer();
			}
		}
		/**
		* Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker.
		* @param request - developer provided SilentFlowRequest
		* @returns
		*/
		async acquireTokenSilent(request) {
			const correlationId = request.correlationId || this.cryptoProvider.createNewGuid();
			this.logger.trace("acquireTokenSilent called", correlationId);
			if (this.nativeBrokerPlugin) {
				const brokerRequest = {
					...request,
					clientId: this.config.auth.clientId,
					scopes: request.scopes || OIDC_DEFAULT_SCOPES,
					redirectUri: request.redirectUri || "",
					authority: request.authority || this.config.auth.authority,
					correlationId,
					extraParameters: {
						...request.extraQueryParameters,
						...request.extraParameters,
						[X_CLIENT_EXTRA_SKU]: this.skus
					},
					accountId: request.account.nativeAccountId,
					forceRefresh: request.forceRefresh || false
				};
				return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest);
			}
			if (request.redirectUri) {
				if (!this.config.broker.nativeBrokerPlugin) throw NodeAuthError.createRedirectUriNotSupportedError();
				request.redirectUri = "";
			}
			return super.acquireTokenSilent(request);
		}
		/**
		* Removes cache artifacts associated with the given account
		* @param request - developer provided SignOutRequest
		* @returns
		*/
		async signOut(request) {
			if (this.nativeBrokerPlugin && request.account.nativeAccountId) {
				const signoutRequest = {
					clientId: this.config.auth.clientId,
					accountId: request.account.nativeAccountId,
					correlationId: request.correlationId || this.cryptoProvider.createNewGuid()
				};
				await this.nativeBrokerPlugin.signOut(signoutRequest);
			}
			await this.getTokenCache().removeAccount(request.account, request.correlationId);
		}
		/**
		* Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker.
		* @returns
		*/
		async getAllAccounts() {
			if (this.nativeBrokerPlugin) {
				const correlationId = this.cryptoProvider.createNewGuid();
				return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId, correlationId);
			}
			return this.getTokenCache().getAllAccounts();
		}
		/**
		* Attempts to retrieve the redirectUri from the loopback server. If the loopback server does not start listening for requests within the timeout this will throw.
		* @param loopbackClient - developer provided custom loopback server implementation
		* @returns
		*/
		async waitForRedirectUri(loopbackClient) {
			return new Promise((resolve, reject) => {
				let ticks = 0;
				const id = setInterval(() => {
					if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS < ticks) {
						clearInterval(id);
						reject(NodeAuthError.createLoopbackServerTimeoutError());
						return;
					}
					try {
						const r = loopbackClient.getRedirectUri();
						clearInterval(id);
						resolve(r);
						return;
					} catch (e) {
						if (e instanceof AuthError && e.errorCode === NodeAuthErrorMessage.noLoopbackServerExists.code) {
							ticks++;
							return;
						}
						clearInterval(id);
						reject(e);
						return;
					}
				}, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);
			});
		}
	};
	/**
	* OAuth2.0 client credential grant
	* @public
	*/
	var ClientCredentialClient = class extends BaseClient {
		constructor(configuration, appTokenProvider) {
			super(configuration);
			this.appTokenProvider = appTokenProvider;
		}
		/**
		* Public API to acquire a token with ClientCredential Flow for Confidential clients
		* @param request - CommonClientCredentialRequest provided by the developer
		*/
		async acquireToken(request) {
			if (request.skipCache || request.claims) return this.executeTokenRequest(request, this.authority);
			const [cachedAuthenticationResult, lastCacheOutcome] = await this.getCachedAuthenticationResult(request, this.config, this.cryptoUtils, this.authority, this.cacheManager, this.serverTelemetryManager);
			if (cachedAuthenticationResult) {
				if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {
					this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.", request.correlationId);
					await this.executeTokenRequest(request, this.authority, true);
				}
				return cachedAuthenticationResult;
			} else return this.executeTokenRequest(request, this.authority);
		}
		/**
		* looks up cache if the tokens are cached already
		*/
		async getCachedAuthenticationResult(request, config, cryptoUtils, authority, cacheManager, serverTelemetryManager) {
			const clientConfiguration = config;
			const managedIdentityConfiguration = config;
			let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;
			let cacheContext;
			if (clientConfiguration.serializableCache && clientConfiguration.persistencePlugin) {
				cacheContext = new TokenCacheContext(clientConfiguration.serializableCache, false);
				await clientConfiguration.persistencePlugin.beforeCacheAccess(cacheContext);
			}
			const cachedAccessToken = this.readAccessTokenFromCache(authority, managedIdentityConfiguration.managedIdentityId?.id || clientConfiguration.authOptions.clientId, new ScopeSet(request.scopes || []), cacheManager, request.correlationId);
			if (clientConfiguration.serializableCache && clientConfiguration.persistencePlugin && cacheContext) await clientConfiguration.persistencePlugin.afterCacheAccess(cacheContext);
			if (!cachedAccessToken) {
				serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
				return [null, CacheOutcome.NO_CACHED_ACCESS_TOKEN];
			}
			if (isTokenExpired(cachedAccessToken.expiresOn, clientConfiguration.systemOptions?.tokenRenewalOffsetSeconds || DEFAULT_TOKEN_RENEWAL_OFFSET_SEC)) {
				serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
				return [null, CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED];
			}
			if (cachedAccessToken.refreshOn && isTokenExpired(cachedAccessToken.refreshOn.toString(), 0)) {
				lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
				serverTelemetryManager?.setCacheOutcome(CacheOutcome.PROACTIVELY_REFRESHED);
			}
			return [await ResponseHandler.generateAuthenticationResult(cryptoUtils, authority, {
				account: null,
				idToken: null,
				accessToken: cachedAccessToken,
				refreshToken: null,
				appMetadata: null
			}, true, request, this.performanceClient), lastCacheOutcome];
		}
		/**
		* Reads access token from the cache
		*/
		readAccessTokenFromCache(authority, id, scopeSet, cacheManager, correlationId) {
			const accessTokenFilter = {
				homeAccountId: "",
				environment: authority.canonicalAuthorityUrlComponents.HostNameAndPort,
				credentialType: CredentialType.ACCESS_TOKEN,
				clientId: id,
				realm: authority.tenant,
				target: ScopeSet.createSearchScopes(scopeSet.asArray())
			};
			const accessTokens = cacheManager.getAccessTokensByFilter(accessTokenFilter, correlationId);
			if (accessTokens.length < 1) return null;
			else if (accessTokens.length > 1) throw createClientAuthError(multipleMatchingTokens);
			return accessTokens[0];
		}
		/**
		* Makes a network call to request the token from the service
		* @param request - CommonClientCredentialRequest provided by the developer
		* @param authority - authority object
		*/
		async executeTokenRequest(request, authority, refreshAccessToken) {
			let serverTokenResponse;
			let reqTimestamp;
			if (this.appTokenProvider) {
				this.logger.info("Using appTokenProvider extensibility.", request.correlationId);
				const appTokenPropviderParameters = {
					correlationId: request.correlationId,
					tenantId: this.config.authOptions.authority.tenant,
					scopes: request.scopes,
					claims: request.claims
				};
				reqTimestamp = nowSeconds();
				const appTokenProviderResult = await this.appTokenProvider(appTokenPropviderParameters);
				serverTokenResponse = {
					access_token: appTokenProviderResult.accessToken,
					expires_in: appTokenProviderResult.expiresInSeconds,
					refresh_in: appTokenProviderResult.refreshInSeconds,
					token_type: AuthenticationScheme.BEARER
				};
			} else {
				const queryParametersString = this.createTokenQueryParameters(request);
				const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
				const requestBody = await this.createTokenRequestBody(request);
				const headers = this.createTokenRequestHeaders();
				const thumbprint = {
					clientId: this.config.authOptions.clientId,
					authority: request.authority,
					scopes: request.scopes,
					claims: request.claims,
					authenticationScheme: request.authenticationScheme,
					resourceRequestMethod: request.resourceRequestMethod,
					resourceRequestUri: request.resourceRequestUri,
					shrClaims: request.shrClaims,
					sshKid: request.sshKid
				};
				this.logger.info("Sending token request to endpoint: " + authority.tokenEndpoint, request.correlationId);
				reqTimestamp = nowSeconds();
				const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);
				serverTokenResponse = response.body;
				serverTokenResponse.status = response.status;
			}
			const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
			responseHandler.validateTokenResponse(serverTokenResponse, request.correlationId, refreshAccessToken);
			return await responseHandler.handleServerTokenResponse(serverTokenResponse, this.authority, reqTimestamp, request, ApiId.acquireTokenByClientCredential);
		}
		/**
		* generate the request to the server in the acceptable format
		* @param request - CommonClientCredentialRequest provided by the developer
		*/
		async createTokenRequestBody(request) {
			const parameters = /* @__PURE__ */ new Map();
			addClientId(parameters, this.config.authOptions.clientId);
			addScopes(parameters, request.scopes, false);
			addGrantType(parameters, GrantType.CLIENT_CREDENTIALS_GRANT);
			addLibraryInfo(parameters, this.config.libraryInfo);
			addApplicationTelemetry(parameters, this.config.telemetry.application);
			addThrottling(parameters);
			if (this.serverTelemetryManager) addServerTelemetry(parameters, this.serverTelemetryManager);
			addCorrelationId(parameters, request.correlationId || this.config.cryptoInterface.createNewGuid());
			if (this.config.clientCredentials.clientSecret) addClientSecret(parameters, this.config.clientCredentials.clientSecret);
			const clientAssertion = request.clientAssertion || this.config.clientCredentials.clientAssertion;
			if (clientAssertion) {
				addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
				addClientAssertionType(parameters, clientAssertion.assertionType);
			}
			if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities);
			return mapToQueryString(parameters);
		}
	};
	/**
	* On-Behalf-Of client
	* @public
	*/
	var OnBehalfOfClient = class extends BaseClient {
		constructor(configuration) {
			super(configuration);
		}
		/**
		* Public API to acquire tokens with on behalf of flow
		* @param request - developer provided CommonOnBehalfOfRequest
		*/
		async acquireToken(request) {
			this.scopeSet = new ScopeSet(request.scopes || []);
			this.userAssertionHash = await this.cryptoUtils.hashString(request.oboAssertion);
			if (request.skipCache || request.claims) return this.executeTokenRequest(request, this.authority, this.userAssertionHash);
			try {
				return await this.getCachedAuthenticationResult(request);
			} catch (e) {
				return await this.executeTokenRequest(request, this.authority, this.userAssertionHash);
			}
		}
		/**
		* look up cache for tokens
		* Find idtoken in the cache
		* Find accessToken based on user assertion and account info in the cache
		* Please note we are not yet supported OBO tokens refreshed with long lived RT. User will have to send a new assertion if the current access token expires
		* This is to prevent security issues when the assertion changes over time, however, longlived RT helps retaining the session
		* @param request - developer provided CommonOnBehalfOfRequest
		*/
		async getCachedAuthenticationResult(request) {
			const cachedAccessToken = this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId, request);
			if (!cachedAccessToken) {
				this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
				this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.", request.correlationId);
				throw createClientAuthError(tokenRefreshRequired);
			} else if (isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
				this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
				this.logger.info(`OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`, request.correlationId);
				throw createClientAuthError(tokenRefreshRequired);
			}
			const cachedIdToken = this.readIdTokenFromCacheForOBO(cachedAccessToken.homeAccountId, request.correlationId);
			let idTokenClaims;
			let cachedAccount = null;
			if (cachedIdToken) {
				idTokenClaims = extractTokenClaims(cachedIdToken.secret, EncodingUtils.base64Decode);
				const localAccountId = idTokenClaims.oid || idTokenClaims.sub;
				const accountInfo = {
					homeAccountId: cachedIdToken.homeAccountId,
					environment: cachedIdToken.environment,
					tenantId: cachedIdToken.realm,
					username: "",
					localAccountId: localAccountId || ""
				};
				cachedAccount = this.cacheManager.getAccount(this.cacheManager.generateAccountKey(accountInfo), request.correlationId);
			}
			if (this.config.serverTelemetryManager) this.config.serverTelemetryManager.incrementCacheHits();
			return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, {
				account: cachedAccount,
				accessToken: cachedAccessToken,
				idToken: cachedIdToken,
				refreshToken: null,
				appMetadata: null
			}, true, request, this.performanceClient, idTokenClaims);
		}
		/**
		* read idtoken from cache, this is a specific implementation for OBO as the requirements differ from a generic lookup in the cacheManager
		* Certain use cases of OBO flow do not expect an idToken in the cache/or from the service
		* @param atHomeAccountId - account id
		*/
		readIdTokenFromCacheForOBO(atHomeAccountId, correlationId) {
			const idTokenFilter = {
				homeAccountId: atHomeAccountId,
				environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
				credentialType: CredentialType.ID_TOKEN,
				clientId: this.config.authOptions.clientId,
				realm: this.authority.tenant
			};
			const idTokenMap = this.cacheManager.getIdTokensByFilter(idTokenFilter, correlationId);
			if (Object.values(idTokenMap).length < 1) return null;
			return Object.values(idTokenMap)[0];
		}
		/**
		* Fetches the cached access token based on incoming assertion
		* @param clientId - client id
		* @param request - developer provided CommonOnBehalfOfRequest
		*/
		readAccessTokenFromCacheForOBO(clientId, request) {
			const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER;
			const accessTokenFilter = {
				credentialType: authScheme.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase() ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME : CredentialType.ACCESS_TOKEN,
				clientId,
				target: ScopeSet.createSearchScopes(this.scopeSet.asArray()),
				tokenType: authScheme,
				keyId: request.sshKid,
				userAssertionHash: this.userAssertionHash
			};
			const accessTokens = this.cacheManager.getAccessTokensByFilter(accessTokenFilter, request.correlationId);
			const numAccessTokens = accessTokens.length;
			if (numAccessTokens < 1) return null;
			else if (numAccessTokens > 1) throw createClientAuthError(multipleMatchingTokens);
			return accessTokens[0];
		}
		/**
		* Make a network call to the server requesting credentials
		* @param request - developer provided CommonOnBehalfOfRequest
		* @param authority - authority object
		*/
		async executeTokenRequest(request, authority, userAssertionHash) {
			const queryParametersString = this.createTokenQueryParameters(request);
			const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
			const requestBody = await this.createTokenRequestBody(request);
			const headers = this.createTokenRequestHeaders();
			const thumbprint = {
				clientId: this.config.authOptions.clientId,
				authority: request.authority,
				scopes: request.scopes,
				claims: request.claims,
				authenticationScheme: request.authenticationScheme,
				resourceRequestMethod: request.resourceRequestMethod,
				resourceRequestUri: request.resourceRequestUri,
				shrClaims: request.shrClaims,
				sshKid: request.sshKid
			};
			const reqTimestamp = nowSeconds();
			const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);
			const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);
			responseHandler.validateTokenResponse(response.body, request.correlationId);
			return await responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, ApiId.acquireTokenByOBO, void 0, userAssertionHash);
		}
		/**
		* generate a server request in accepable format
		* @param request - developer provided CommonOnBehalfOfRequest
		*/
		async createTokenRequestBody(request) {
			const parameters = /* @__PURE__ */ new Map();
			addClientId(parameters, this.config.authOptions.clientId);
			addScopes(parameters, request.scopes);
			addGrantType(parameters, GrantType.JWT_BEARER);
			addClientInfo(parameters);
			addLibraryInfo(parameters, this.config.libraryInfo);
			addApplicationTelemetry(parameters, this.config.telemetry.application);
			addThrottling(parameters);
			if (this.serverTelemetryManager) addServerTelemetry(parameters, this.serverTelemetryManager);
			addCorrelationId(parameters, request.correlationId || this.config.cryptoInterface.createNewGuid());
			addRequestTokenUse(parameters, ON_BEHALF_OF);
			addOboAssertion(parameters, request.oboAssertion);
			if (this.config.clientCredentials.clientSecret) addClientSecret(parameters, this.config.clientCredentials.clientSecret);
			const clientAssertion = this.config.clientCredentials.clientAssertion;
			if (clientAssertion) {
				addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
				addClientAssertionType(parameters, clientAssertion.assertionType);
			}
			if (request.claims || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities);
			return mapToQueryString(parameters);
		}
	};
	/**
	*  This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications
	*  will configure application secrets, client certificates/assertions as applicable
	* @public
	*/
	var ConfidentialClientApplication = class extends ClientApplication {
		/**
		* Constructor for the ConfidentialClientApplication
		*
		* Required attributes in the Configuration object are:
		* - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal
		* - authority: the authority URL for your application.
		* - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal.
		*
		* In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.
		* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
		* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
		* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
		* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
		*
		* In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/
		* Full B2C functionality will be available in this library in future versions.
		*
		* @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance
		*/
		constructor(configuration) {
			super(configuration);
			const clientSecretNotEmpty = !!this.config.auth.clientSecret;
			const clientAssertionNotEmpty = !!this.config.auth.clientAssertion;
			const certificateNotEmpty = (!!this.config.auth.clientCertificate?.thumbprint || !!this.config.auth.clientCertificate?.thumbprintSha256) && !!this.config.auth.clientCertificate?.privateKey;
			if (this.appTokenProvider) return;
			if (clientSecretNotEmpty && clientAssertionNotEmpty || clientAssertionNotEmpty && certificateNotEmpty || clientSecretNotEmpty && certificateNotEmpty) throw createClientAuthError(invalidClientCredential);
			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 (!certificateNotEmpty) throw createClientAuthError(invalidClientCredential);
			else this.clientAssertion = !!this.config.auth.clientCertificate.thumbprintSha256 ? ClientAssertion.fromCertificateWithSha256Thumbprint(this.config.auth.clientCertificate.thumbprintSha256, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c) : ClientAssertion.fromCertificate(this.config.auth.clientCertificate.thumbprint, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c);
			this.appTokenProvider = void 0;
		}
		/**
		* This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and
		* is meant for Azure SDK to enhance Managed Identity support.
		*
		* @param IAppTokenProvider  - Extensibility interface, which allows the app developer to return a token from a custom source.
		*/
		SetAppTokenProvider(provider) {
			this.appTokenProvider = provider;
		}
		/**
		* Acquires tokens from the authority for the application (not for an end user).
		*/
		async acquireTokenByClientCredential(request) {
			this.logger.info("acquireTokenByClientCredential called", request.correlationId || "");
			let clientAssertion;
			if (request.clientAssertion) clientAssertion = {
				assertion: await getClientAssertion(request.clientAssertion, this.config.auth.clientId),
				assertionType: Constants.JWT_BEARER_ASSERTION_TYPE
			};
			const baseRequest = await this.initializeBaseRequest(request);
			const validBaseRequest = {
				...baseRequest,
				scopes: baseRequest.scopes.filter((scope) => !OIDC_DEFAULT_SCOPES.includes(scope))
			};
			const validRequest = {
				...request,
				...validBaseRequest,
				clientAssertion
			};
			const tenantId = new UrlString(validRequest.authority).getUrlComponents().PathSegments[0];
			if (Object.values(AADAuthority).includes(tenantId)) throw createClientAuthError(missingTenantIdError);
			const ENV_MSAL_FORCE_REGION = process.env[MSAL_FORCE_REGION];
			let region;
			if (validRequest.azureRegion !== "DisableMsalForceRegion") if (!validRequest.azureRegion && ENV_MSAL_FORCE_REGION) region = ENV_MSAL_FORCE_REGION;
			else region = validRequest.azureRegion;
			const azureRegionConfiguration = {
				azureRegion: region,
				environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE]
			};
			const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache);
			try {
				const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, azureRegionConfiguration, request.azureCloudOptions);
				const clientCredentialClient = new ClientCredentialClient(await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager), this.appTokenProvider);
				this.logger.verbose("Client credential client created", validRequest.correlationId);
				return await clientCredentialClient.acquireToken(validRequest);
			} catch (e) {
				if (e instanceof AuthError) e.setCorrelationId(validRequest.correlationId);
				serverTelemetryManager.cacheFailedRequest(e);
				throw e;
			}
		}
		/**
		* Acquires tokens from the authority for the application.
		*
		* Used in scenarios where the current app is a middle-tier service which was called with a token
		* representing an end user. The current app can use the token (oboAssertion) to request another
		* token to access downstream web API, on behalf of that user.
		*
		* The current middle-tier app has no user interaction to obtain consent.
		* See how to gain consent upfront for your middle-tier app from this article.
		* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application
		*/
		async acquireTokenOnBehalfOf(request) {
			this.logger.info("acquireTokenOnBehalfOf called", request.correlationId || "");
			const validRequest = {
				...request,
				...await this.initializeBaseRequest(request)
			};
			try {
				const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);
				const oboClient = new OnBehalfOfClient(await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", void 0));
				this.logger.verbose("On behalf of client created", validRequest.correlationId);
				return await oboClient.acquireToken(validRequest);
			} catch (e) {
				if (e instanceof AuthError) e.setCorrelationId(validRequest.correlationId);
				throw e;
			}
		}
	};
	/**
	* @internal
	* Checks if a given date string is in ISO 8601 format.
	*
	* @param dateString - The date string to be checked.
	* @returns boolean - Returns true if the date string is in ISO 8601 format, otherwise false.
	*/
	function isIso8601(dateString) {
		if (typeof dateString !== "string") return false;
		const date = new Date(dateString);
		return !isNaN(date.getTime()) && date.toISOString() === dateString;
	}
	var HttpClientWithRetries = class {
		constructor(httpClientNoRetries, retryPolicy, logger) {
			this.httpClientNoRetries = httpClientNoRetries;
			this.retryPolicy = retryPolicy;
			this.logger = logger;
		}
		async sendNetworkRequestAsyncHelper(httpMethod, url, options) {
			if (httpMethod === HttpMethod.GET) return this.httpClientNoRetries.sendGetRequestAsync(url, options);
			else return this.httpClientNoRetries.sendPostRequestAsync(url, options);
		}
		async sendNetworkRequestAsync(httpMethod, url, options) {
			let response = await this.sendNetworkRequestAsyncHelper(httpMethod, url, options);
			if ("isNewRequest" in this.retryPolicy) this.retryPolicy.isNewRequest = true;
			let currentRetry = 0;
			while (await this.retryPolicy.pauseForRetry(response.status, currentRetry, this.logger, response.headers[HeaderNames.RETRY_AFTER])) {
				response = await this.sendNetworkRequestAsyncHelper(httpMethod, url, options);
				currentRetry++;
			}
			return response;
		}
		async sendGetRequestAsync(url, options) {
			return this.sendNetworkRequestAsync(HttpMethod.GET, url, options);
		}
		async sendPostRequestAsync(url, options) {
			return this.sendNetworkRequestAsync(HttpMethod.POST, url, options);
		}
	};
	/**
	* Managed Identity User Assigned Id Query Parameter Names
	*/
	const ManagedIdentityUserAssignedIdQueryParameterNames = {
		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"
	};
	/**
	* Base class for all Managed Identity sources. Provides common functionality for
	* authenticating with Azure Managed Identity endpoints across different Azure services
	* including IMDS, App Service, Azure Arc, Service Fabric, Cloud Shell, and Machine Learning.
	*
	* This abstract class handles token acquisition, response processing, and network communication
	* while allowing concrete implementations to define source-specific request creation logic.
	*/
	var BaseManagedIdentitySource = class {
		/**
		* Creates an instance of BaseManagedIdentitySource.
		*
		* @param logger - Logger instance for diagnostic information
		* @param nodeStorage - Storage interface for caching tokens
		* @param networkClient - Network client for making HTTP requests
		* @param cryptoProvider - Cryptographic provider for token operations
		* @param disableInternalRetries - Whether to disable automatic retry logic
		*/
		constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
			this.logger = logger;
			this.nodeStorage = nodeStorage;
			this.networkClient = networkClient;
			this.cryptoProvider = cryptoProvider;
			this.disableInternalRetries = disableInternalRetries;
		}
		/**
		* Processes the network response and converts it to a standardized server token response.
		* This async version allows for source-specific response processing logic while maintaining
		* backward compatibility with the synchronous version.
		*
		* @param response - The network response containing the managed identity token
		* @param _networkClient - Network client used for the request (unused in base implementation)
		* @param _networkRequest - The original network request parameters (unused in base implementation)
		* @param _networkRequestOptions - The network request options (unused in base implementation)
		*
		* @returns Promise resolving to a standardized server authorization token response
		*/
		async getServerTokenResponseAsync(response, _networkClient, _networkRequest, _networkRequestOptions) {
			return this.getServerTokenResponse(response);
		}
		/**
		* Converts a managed identity token response to a standardized server authorization token response.
		* Handles time format conversion, expiration calculation, and error mapping to ensure
		* compatibility with the MSAL response handling pipeline.
		*
		* @param response - The network response containing the managed identity token
		*
		* @returns Standardized server authorization token response with normalized fields
		*/
		getServerTokenResponse(response) {
			let refreshIn, expiresIn;
			if (response.body.expires_on) {
				if (isIso8601(response.body.expires_on)) response.body.expires_on = new Date(response.body.expires_on).getTime() / 1e3;
				expiresIn = response.body.expires_on - nowSeconds();
				if (expiresIn > 2 * 3600) refreshIn = expiresIn / 2;
			}
			return {
				status: response.status,
				access_token: response.body.access_token,
				expires_in: expiresIn,
				scope: response.body.resource,
				token_type: response.body.token_type,
				refresh_in: refreshIn,
				correlation_id: response.body.correlation_id || response.body.correlationId,
				error: typeof response.body.error === "string" ? response.body.error : response.body.error?.code,
				error_description: response.body.message || (typeof response.body.error === "string" ? response.body.error_description : response.body.error?.message),
				error_codes: response.body.error_codes,
				timestamp: response.body.timestamp,
				trace_id: response.body.trace_id
			};
		}
		/**
		* Acquires an access token using the managed identity endpoint for the specified resource.
		* This is the primary method for token acquisition, handling the complete flow from
		* request creation through response processing and token caching.
		*
		* @param managedIdentityRequest - The managed identity request containing resource and optional parameters
		* @param managedIdentityId - The managed identity configuration (system or user-assigned)
		* @param fakeAuthority - Authority instance used for token caching (managed identity uses a placeholder authority)
		* @param refreshAccessToken - Whether this is a token refresh operation
		*
		* @returns Promise resolving to an authentication result containing the access token and metadata
		*
		* @throws {AuthError} When network requests fail or token validation fails
		* @throws {ClientAuthError} When network errors occur during the request
		*/
		async acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
			const networkRequest = this.createRequest(managedIdentityRequest.resource, managedIdentityId);
			if (managedIdentityRequest.revokedTokenSha256Hash) {
				this.logger.info(`[Managed Identity] The following claims are present in the request: ${managedIdentityRequest.claims}`, "");
				networkRequest.queryParameters[ManagedIdentityQueryParameters.SHA256_TOKEN_TO_REFRESH] = managedIdentityRequest.revokedTokenSha256Hash;
			}
			if (managedIdentityRequest.clientCapabilities?.length) {
				const clientCapabilities = managedIdentityRequest.clientCapabilities.toString();
				this.logger.info(`[Managed Identity] The following client capabilities are present in the request: ${clientCapabilities}`, "");
				networkRequest.queryParameters[ManagedIdentityQueryParameters.XMS_CC] = clientCapabilities;
			}
			const headers = networkRequest.headers;
			headers[HeaderNames.CONTENT_TYPE] = URL_FORM_CONTENT_TYPE;
			const networkRequestOptions = { headers };
			if (Object.keys(networkRequest.bodyParameters).length) networkRequestOptions.body = networkRequest.computeParametersBodyString();
			/**
			* Initializes the network client helper based on the retry policy configuration.
			* If internal retries are disabled, it uses the provided network client directly.
			* Otherwise, it wraps the network client with an HTTP client that supports retries.
			*/
			const networkClientHelper = this.disableInternalRetries ? this.networkClient : new HttpClientWithRetries(this.networkClient, networkRequest.retryPolicy, this.logger);
			const reqTimestamp = nowSeconds();
			let response;
			try {
				if (networkRequest.httpMethod === HttpMethod.POST) response = await networkClientHelper.sendPostRequestAsync(networkRequest.computeUri(), networkRequestOptions);
				else response = await networkClientHelper.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);
			} catch (error) {
				if (error instanceof AuthError) throw error;
				else throw createClientAuthError(networkError);
			}
			const responseHandler = new ResponseHandler(managedIdentityId.id, this.nodeStorage, this.cryptoProvider, this.logger, new StubPerformanceClient(), null, null);
			const serverTokenResponse = await this.getServerTokenResponseAsync(response, networkClientHelper, networkRequest, networkRequestOptions);
			responseHandler.validateTokenResponse(serverTokenResponse, serverTokenResponse.correlation_id || "", refreshAccessToken);
			return responseHandler.handleServerTokenResponse(serverTokenResponse, fakeAuthority, reqTimestamp, managedIdentityRequest, ApiId.acquireTokenWithManagedIdentity);
		}
		/**
		* Determines the appropriate query parameter name for user-assigned managed identity
		* based on the identity type, API version, and endpoint characteristics.
		* Different Azure services and API versions use different parameter names for the same identity types.
		*
		* @param managedIdentityIdType - The type of user-assigned managed identity (client ID, object ID, or resource ID)
		* @param isImds - Whether the request is being made to the IMDS (Instance Metadata Service) endpoint
		* @param usesApi2017 - Whether the endpoint uses the 2017-09-01 API version (affects client ID parameter name)
		*
		* @returns The correct query parameter name for the specified identity type and endpoint
		*
		* @throws {ManagedIdentityError} When an invalid managed identity ID type is provided
		*/
		getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityIdType, isImds, usesApi2017) {
			switch (managedIdentityIdType) {
				case ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID:
					this.logger.info(`[Managed Identity] [API version ${usesApi2017 ? "2017+" : "2019+"}] Adding user assigned client id to the request.`, "");
					return usesApi2017 ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017 : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID;
				case ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID:
					this.logger.info("[Managed Identity] Adding user assigned resource id to the request.", "");
					return isImds ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_IMDS : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS;
				case ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID:
					this.logger.info("[Managed Identity] Adding user assigned object id to the request.", "");
					return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_OBJECT_ID;
				default: throw createManagedIdentityError(invalidManagedIdentityIdType);
			}
		}
	};
	/**
	* Validates and normalizes an environment variable containing a URL string.
	* This static utility method ensures that environment variables used for managed identity
	* endpoints contain properly formatted URLs and provides informative error messages when validation fails.
	*
	* @param envVariableStringName - The name of the environment variable being validated (for error reporting)
	* @param envVariable - The environment variable value containing the URL string
	* @param sourceName - The name of the managed identity source (for error reporting)
	* @param logger - Logger instance for diagnostic information
	*
	* @returns The validated and normalized URL string
	*
	* @throws {ManagedIdentityError} When the environment variable contains a malformed URL
	*/
	BaseManagedIdentitySource.getValidatedEnvVariableUrlString = (envVariableStringName, envVariable, sourceName, logger) => {
		try {
			return new UrlString(envVariable).urlString;
		} catch (error) {
			logger.info(`[Managed Identity] ${sourceName} managed identity is unavailable because the '${envVariableStringName}' environment variable is malformed.`, "");
			throw createManagedIdentityError(MsiEnvironmentVariableUrlMalformedErrorCodes[envVariableStringName]);
		}
	};
	var LinearRetryStrategy = class {
		/**
		* Calculates the number of milliseconds to sleep based on the `retry-after` HTTP header.
		*
		* @param retryHeader - The value of the `retry-after` HTTP header. This can be either a number of seconds
		*                      or an HTTP date string.
		* @returns The number of milliseconds to sleep before retrying the request. If the `retry-after` header is not
		*          present or cannot be parsed, returns 0.
		*/
		calculateDelay(retryHeader, minimumDelay) {
			if (!retryHeader) return minimumDelay;
			let millisToSleep = Math.round(parseFloat(retryHeader) * 1e3);
			if (isNaN(millisToSleep)) millisToSleep = new Date(retryHeader).valueOf() - (/* @__PURE__ */ new Date()).valueOf();
			return Math.max(minimumDelay, millisToSleep);
		}
	};
	const DEFAULT_MANAGED_IDENTITY_MAX_RETRIES = 3;
	const DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS = 1e3;
	const DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON = [
		HTTP_NOT_FOUND,
		HTTP_REQUEST_TIMEOUT,
		HTTP_TOO_MANY_REQUESTS,
		HTTP_SERVER_ERROR,
		HTTP_SERVICE_UNAVAILABLE,
		HTTP_GATEWAY_TIMEOUT
	];
	var DefaultManagedIdentityRetryPolicy = class DefaultManagedIdentityRetryPolicy {
		constructor() {
			this.linearRetryStrategy = new LinearRetryStrategy();
		}
		static get DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS() {
			return DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS;
		}
		async pauseForRetry(httpStatusCode, currentRetry, logger, retryAfterHeader) {
			if (DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON.includes(httpStatusCode) && currentRetry < DEFAULT_MANAGED_IDENTITY_MAX_RETRIES) {
				const retryAfterDelay = this.linearRetryStrategy.calculateDelay(retryAfterHeader, DefaultManagedIdentityRetryPolicy.DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS);
				logger.verbose(`Retrying request in ${retryAfterDelay}ms (retry attempt: ${currentRetry + 1})`, "");
				await new Promise((resolve) => {
					return setTimeout(resolve, retryAfterDelay);
				});
				return true;
			}
			return false;
		}
	};
	var ManagedIdentityRequestParameters = class {
		constructor(httpMethod, endpoint, retryPolicy) {
			this.httpMethod = httpMethod;
			this._baseEndpoint = endpoint;
			this.headers = {};
			this.bodyParameters = {};
			this.queryParameters = {};
			this.retryPolicy = retryPolicy || new DefaultManagedIdentityRetryPolicy();
		}
		computeUri() {
			const parameters = /* @__PURE__ */ new Map();
			if (this.queryParameters) addExtraParameters(parameters, this.queryParameters);
			const queryParametersString = mapToQueryString(parameters);
			return UrlString.appendQueryString(this._baseEndpoint, queryParametersString);
		}
		computeParametersBodyString() {
			const parameters = /* @__PURE__ */ new Map();
			if (this.bodyParameters) addExtraParameters(parameters, this.bodyParameters);
			return mapToQueryString(parameters);
		}
	};
	const APP_SERVICE_MSI_API_VERSION = "2019-08-01";
	/**
	* Azure App Service Managed Identity Source implementation.
	*
	* This class provides managed identity authentication for applications running in Azure App Service.
	* It uses the local metadata service endpoint available within App Service environments to obtain
	* access tokens without requiring explicit credentials.
	*
	* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AppServiceManagedIdentitySource.cs
	*/
	var AppService = class AppService extends BaseManagedIdentitySource {
		/**
		* Creates a new instance of the AppService managed identity source.
		*
		* @param logger - Logger instance for diagnostic output
		* @param nodeStorage - Node.js storage implementation for caching
		* @param networkClient - Network client for making HTTP requests
		* @param cryptoProvider - Cryptographic operations provider
		* @param disableInternalRetries - Whether to disable internal retry logic
		* @param identityEndpoint - The App Service identity endpoint URL
		* @param identityHeader - The secret header value required for authentication
		*/
		constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) {
			super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
			this.identityEndpoint = identityEndpoint;
			this.identityHeader = identityHeader;
		}
		/**
		* Retrieves the required environment variables for App Service managed identity.
		*
		* App Service managed identity requires two environment variables:
		* - IDENTITY_ENDPOINT: The URL of the local metadata service
		* - IDENTITY_HEADER: A secret header value for authentication
		*
		* @returns An array containing [identityEndpoint, identityHeader] values from environment variables.
		*          Either value may be undefined if the environment variable is not set.
		*/
		static getEnvironmentVariables() {
			return [process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT], process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER]];
		}
		/**
		* Attempts to create an AppService managed identity source if the environment supports it.
		*
		* This method checks for the presence of required environment variables and validates
		* the identity endpoint URL. If the environment is not suitable for App Service managed
		* identity (missing environment variables or invalid endpoint), it returns null.
		*
		* @param logger - Logger instance for diagnostic output
		* @param nodeStorage - Node.js storage implementation for caching
		* @param networkClient - Network client for making HTTP requests
		* @param cryptoProvider - Cryptographic operations provider
		* @param disableInternalRetries - Whether to disable internal retry logic
		*
		* @returns A new AppService instance if the environment is suitable, null otherwise
		*/
		static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
			const [identityEndpoint, identityHeader] = AppService.getEnvironmentVariables();
			if (!identityEndpoint || !identityHeader) {
				logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.APP_SERVICE} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}' and '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variables are not defined.`, "");
				return null;
			}
			const validatedIdentityEndpoint = AppService.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.APP_SERVICE, logger);
			logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.APP_SERVICE} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.APP_SERVICE} managed identity.`, "");
			return new AppService(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader);
		}
		/**
		* Creates a managed identity token request for the App Service environment.
		*
		* This method constructs an HTTP GET request to the App Service identity endpoint
		* with the required headers, query parameters, and managed identity configuration.
		* The request includes the secret header for authentication and appropriate API version.
		*
		* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
		* @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity
		*
		* @returns A configured ManagedIdentityRequestParameters object ready for network execution
		*/
		createRequest(resource, managedIdentityId) {
			const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
			request.headers[ManagedIdentityHeaders.APP_SERVICE_SECRET_HEADER_NAME] = this.identityHeader;
			request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = APP_SERVICE_MSI_API_VERSION;
			request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
			if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
			return request;
		}
	};
	const ARC_API_VERSION = "2019-11-01";
	const DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT = "http://127.0.0.1:40342/metadata/identity/oauth2/token";
	const HIMDS_EXECUTABLE_HELPER_STRING = "N/A: himds executable exists";
	const SUPPORTED_AZURE_ARC_PLATFORMS = {
		win32: `${process.env["ProgramData"]}\\AzureConnectedMachineAgent\\Tokens\\`,
		linux: "/var/opt/azcmagent/tokens/"
	};
	const AZURE_ARC_FILE_DETECTION = {
		win32: `${process.env["ProgramFiles"]}\\AzureConnectedMachineAgent\\himds.exe`,
		linux: "/opt/azcmagent/bin/himds"
	};
	/**
	* Azure Arc managed identity source implementation for acquiring tokens from Azure Arc-enabled servers.
	*
	* This class provides managed identity authentication for applications running on Azure Arc-enabled servers
	* by communicating with the local Hybrid Instance Metadata Service (HIMDS). It supports both environment
	* variable-based configuration and automatic detection through the HIMDS executable.
	*
	* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AzureArcManagedIdentitySource.cs
	*/
	var AzureArc = class AzureArc extends BaseManagedIdentitySource {
		/**
		* Creates a new instance of the AzureArc managed identity source.
		*
		* @param logger - Logger instance for capturing telemetry and diagnostic information
		* @param nodeStorage - Storage implementation for caching tokens and metadata
		* @param networkClient - Network client for making HTTP requests to the identity endpoint
		* @param cryptoProvider - Cryptographic operations provider for token validation and encryption
		* @param disableInternalRetries - Flag to disable automatic retry logic for failed requests
		* @param identityEndpoint - The Azure Arc identity endpoint URL for token requests
		*/
		constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) {
			super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
			this.identityEndpoint = identityEndpoint;
		}
		/**
		* Retrieves and validates Azure Arc environment variables for managed identity configuration.
		*
		* This method checks for IDENTITY_ENDPOINT and IMDS_ENDPOINT environment variables.
		* If either is missing, it attempts to detect the Azure Arc environment by checking for
		* the HIMDS executable at platform-specific paths. On successful detection, it returns
		* the default identity endpoint and a helper string indicating file-based detection.
		*
		* @returns An array containing [identityEndpoint, imdsEndpoint] where both values are
		*          strings if Azure Arc is available, or undefined if not available.
		*/
		static getEnvironmentVariables() {
			let identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT];
			let imdsEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT];
			if (!identityEndpoint || !imdsEndpoint) {
				const fileDetectionPath = AZURE_ARC_FILE_DETECTION[process.platform];
				try {
					fs.accessSync(fileDetectionPath, fs.constants.F_OK | fs.constants.R_OK);
					identityEndpoint = DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT;
					imdsEndpoint = HIMDS_EXECUTABLE_HELPER_STRING;
				} catch (err) {}
			}
			return [identityEndpoint, imdsEndpoint];
		}
		/**
		* Attempts to create an AzureArc managed identity source instance.
		*
		* Validates the Azure Arc environment by checking environment variables
		* and performing file-based detection. It ensures that only system-assigned managed identities
		* are supported for Azure Arc scenarios. The method performs comprehensive validation of
		* endpoint URLs and logs detailed information about the detection process.
		*
		* @param logger - Logger instance for capturing creation and validation steps
		* @param nodeStorage - Storage implementation for the managed identity source
		* @param networkClient - Network client for HTTP communication
		* @param cryptoProvider - Cryptographic operations provider
		* @param disableInternalRetries - Whether to disable automatic retry mechanisms
		* @param managedIdentityId - The managed identity configuration, must be system-assigned
		*
		* @returns AzureArc instance if the environment supports Azure Arc managed identity, null otherwise
		*
		* @throws {ManagedIdentityError} When a user-assigned managed identity is specified (not supported for Azure Arc)
		*/
		static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
			const [identityEndpoint, imdsEndpoint] = AzureArc.getEnvironmentVariables();
			if (!identityEndpoint || !imdsEndpoint) {
				logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is unavailable through environment variables because one or both of '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' are not defined. ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is also unavailable through file detection.`, "");
				return null;
			}
			if (imdsEndpoint === HIMDS_EXECUTABLE_HELPER_STRING) logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is available through file detection. Defaulting to known ${ManagedIdentitySourceNames.AZURE_ARC} endpoint: ${DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`, "");
			else {
				const validatedIdentityEndpoint = AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger);
				validatedIdentityEndpoint.endsWith("/") && validatedIdentityEndpoint.slice(0, -1);
				AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT, imdsEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger);
				logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.AZURE_ARC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`, "");
			}
			if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) throw createManagedIdentityError(unableToCreateAzureArc);
			return new AzureArc(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint);
		}
		/**
		* Creates a properly formatted HTTP request for acquiring tokens from the Azure Arc identity endpoint.
		*
		* This method constructs a GET request to the Azure Arc HIMDS endpoint with the required metadata header
		* and query parameters. The endpoint URL is normalized to use 127.0.0.1 instead of localhost for
		* consistency. Additional body parameters are calculated by the base class during token acquisition.
		*
		* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
		*
		* @returns A configured ManagedIdentityRequestParameters object ready for network execution
		*/
		createRequest(resource) {
			const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint.replace("localhost", "127.0.0.1"));
			request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
			request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = ARC_API_VERSION;
			request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
			return request;
		}
		/**
		* Processes the server response and handles Azure Arc-specific authentication challenges.
		*
		* This method implements the Azure Arc authentication flow which may require reading a secret file
		* for authorization. When the initial request returns HTTP 401 Unauthorized, it extracts the file
		* path from the WWW-Authenticate header, validates the file location and size, reads the secret,
		* and retries the request with Basic authentication. The method includes comprehensive security
		* validations to prevent path traversal and ensure file integrity.
		*
		* @param originalResponse - The initial HTTP response from the identity endpoint
		* @param networkClient - Network client for making the retry request if needed
		* @param networkRequest - The original request parameters (modified with auth header for retry)
		* @param networkRequestOptions - Additional options for network requests
		*
		* @returns A promise that resolves to the server token response with access token and metadata
		*
		* @throws {ManagedIdentityError} When:
		*   - WWW-Authenticate header is missing or has unsupported format
		*   - Platform is not supported (not Windows or Linux)
		*   - Secret file has invalid extension (not .key)
		*   - Secret file path doesn't match expected platform path
		*   - Secret file cannot be read or is too large (>4096 bytes)
		* @throws {ClientAuthError} When network errors occur during retry request
		*/
		async getServerTokenResponseAsync(originalResponse, networkClient, networkRequest, networkRequestOptions) {
			let retryResponse;
			if (originalResponse.status === HTTP_UNAUTHORIZED) {
				const wwwAuthHeader = originalResponse.headers["www-authenticate"];
				if (!wwwAuthHeader) throw createManagedIdentityError(wwwAuthenticateHeaderMissing);
				if (!wwwAuthHeader.includes("Basic realm=")) throw createManagedIdentityError(wwwAuthenticateHeaderUnsupportedFormat);
				const secretFilePath = wwwAuthHeader.split("Basic realm=")[1];
				if (!SUPPORTED_AZURE_ARC_PLATFORMS.hasOwnProperty(process.platform)) throw createManagedIdentityError(platformNotSupported);
				const expectedSecretFilePath = SUPPORTED_AZURE_ARC_PLATFORMS[process.platform];
				const fileName = path.basename(secretFilePath);
				if (!fileName.endsWith(".key")) throw createManagedIdentityError(invalidFileExtension);
				if (expectedSecretFilePath + fileName !== secretFilePath) throw createManagedIdentityError(invalidFilePath);
				let secretFileSize;
				try {
					secretFileSize = await fs.statSync(secretFilePath).size;
				} catch (e) {
					throw createManagedIdentityError(unableToReadSecretFile);
				}
				if (secretFileSize > AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES) throw createManagedIdentityError(invalidSecret);
				let secret;
				try {
					secret = fs.readFileSync(secretFilePath, EncodingTypes.UTF8);
				} catch (e) {
					throw createManagedIdentityError(unableToReadSecretFile);
				}
				const authHeaderValue = `Basic ${secret}`;
				this.logger.info(`[Managed Identity] Adding authorization header to the request.`, "");
				networkRequest.headers[ManagedIdentityHeaders.AUTHORIZATION_HEADER_NAME] = authHeaderValue;
				try {
					retryResponse = await networkClient.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);
				} catch (error) {
					if (error instanceof AuthError) throw error;
					else throw createClientAuthError(networkError);
				}
			}
			return this.getServerTokenResponse(retryResponse || originalResponse);
		}
	};
	/**
	* Azure Cloud Shell managed identity source implementation.
	*
	* This class handles authentication for applications running in Azure Cloud Shell environment.
	* Cloud Shell provides a browser-accessible shell for managing Azure resources and includes
	* a pre-configured managed identity for authentication.
	*
	* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/CloudShellManagedIdentitySource.cs
	*/
	var CloudShell = class CloudShell extends BaseManagedIdentitySource {
		/**
		* Creates a new CloudShell managed identity source instance.
		*
		* @param logger - Logger instance for diagnostic logging
		* @param nodeStorage - Node.js storage implementation for caching
		* @param networkClient - HTTP client for making requests to the managed identity endpoint
		* @param cryptoProvider - Cryptographic operations provider
		* @param disableInternalRetries - Whether to disable automatic retry logic for failed requests
		* @param msiEndpoint - The MSI endpoint URL obtained from environment variables
		*/
		constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint) {
			super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
			this.msiEndpoint = msiEndpoint;
		}
		/**
		* Retrieves the required environment variables for Cloud Shell managed identity.
		*
		* Cloud Shell requires the MSI_ENDPOINT environment variable to be set, which
		* contains the URL of the managed identity service endpoint.
		*
		* @returns An array containing the MSI_ENDPOINT environment variable value (or undefined if not set)
		*/
		static getEnvironmentVariables() {
			return [process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]];
		}
		/**
		* Attempts to create a CloudShell managed identity source instance.
		*
		* This method validates that the required environment variables are present and
		* creates a CloudShell instance if the environment is properly configured.
		* Cloud Shell only supports system-assigned managed identities.
		*
		* @param logger - Logger instance for diagnostic logging
		* @param nodeStorage - Node.js storage implementation for caching
		* @param networkClient - HTTP client for making requests
		* @param cryptoProvider - Cryptographic operations provider
		* @param disableInternalRetries - Whether to disable automatic retry logic
		* @param managedIdentityId - The managed identity configuration (must be system-assigned)
		*
		* @returns A CloudShell instance if the environment is valid, null otherwise
		*
		* @throws {ManagedIdentityError} When a user-assigned managed identity is requested,
		*         as Cloud Shell only supports system-assigned identities
		*/
		static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
			const [msiEndpoint] = CloudShell.getEnvironmentVariables();
			if (!msiEndpoint) {
				logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity is unavailable because the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT} environment variable is not defined.`, "");
				return null;
			}
			const validatedMsiEndpoint = CloudShell.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.CLOUD_SHELL, logger);
			logger.info(`[Managed Identity] Environment variable validation passed for ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity.`, "");
			if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) throw createManagedIdentityError(unableToCreateCloudShell);
			return new CloudShell(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint);
		}
		/**
		* Creates an HTTP request to acquire an access token from the Cloud Shell managed identity endpoint.
		*
		* This method constructs a POST request to the MSI endpoint with the required headers and
		* body parameters for Cloud Shell authentication. The request includes the target resource
		* for which the access token is being requested.
		*
		* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
		*
		* @returns A configured ManagedIdentityRequestParameters object ready for network execution
		*/
		createRequest(resource) {
			const request = new ManagedIdentityRequestParameters(HttpMethod.POST, this.msiEndpoint);
			request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
			request.bodyParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
			return request;
		}
	};
	var ExponentialRetryStrategy = class {
		constructor(minExponentialBackoff, maxExponentialBackoff, exponentialDeltaBackoff) {
			this.minExponentialBackoff = minExponentialBackoff;
			this.maxExponentialBackoff = maxExponentialBackoff;
			this.exponentialDeltaBackoff = exponentialDeltaBackoff;
		}
		/**
		* Calculates the exponential delay based on the current retry attempt.
		*
		* @param {number} currentRetry - The current retry attempt number.
		* @returns {number} - The calculated exponential delay in milliseconds.
		*
		* The delay is calculated using the formula:
		* - If `currentRetry` is 0, it returns the minimum backoff time.
		* - Otherwise, it calculates the delay as the minimum of:
		*   - `(2^(currentRetry - 1)) * deltaBackoff`
		*   - `maxBackoff`
		*
		* This ensures that the delay increases exponentially with each retry attempt,
		* but does not exceed the maximum backoff time.
		*/
		calculateDelay(currentRetry) {
			if (currentRetry === 0) return this.minExponentialBackoff;
			return Math.min(Math.pow(2, currentRetry - 1) * this.exponentialDeltaBackoff, this.maxExponentialBackoff);
		}
	};
	const HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY = [
		HTTP_NOT_FOUND,
		HTTP_REQUEST_TIMEOUT,
		HTTP_GONE,
		HTTP_TOO_MANY_REQUESTS
	];
	const EXPONENTIAL_STRATEGY_NUM_RETRIES = 3;
	const LINEAR_STRATEGY_NUM_RETRIES = 7;
	const MIN_EXPONENTIAL_BACKOFF_MS = 1e3;
	const MAX_EXPONENTIAL_BACKOFF_MS = 4e3;
	const EXPONENTIAL_DELTA_BACKOFF_MS = 2e3;
	const HTTP_STATUS_GONE_RETRY_AFTER_MS = 10 * 1e3;
	var ImdsRetryPolicy = class ImdsRetryPolicy {
		constructor() {
			this.exponentialRetryStrategy = new ExponentialRetryStrategy(ImdsRetryPolicy.MIN_EXPONENTIAL_BACKOFF_MS, ImdsRetryPolicy.MAX_EXPONENTIAL_BACKOFF_MS, ImdsRetryPolicy.EXPONENTIAL_DELTA_BACKOFF_MS);
		}
		static get MIN_EXPONENTIAL_BACKOFF_MS() {
			return MIN_EXPONENTIAL_BACKOFF_MS;
		}
		static get MAX_EXPONENTIAL_BACKOFF_MS() {
			return MAX_EXPONENTIAL_BACKOFF_MS;
		}
		static get EXPONENTIAL_DELTA_BACKOFF_MS() {
			return EXPONENTIAL_DELTA_BACKOFF_MS;
		}
		static get HTTP_STATUS_GONE_RETRY_AFTER_MS() {
			return HTTP_STATUS_GONE_RETRY_AFTER_MS;
		}
		set isNewRequest(value) {
			this._isNewRequest = value;
		}
		/**
		* Pauses execution for a calculated delay before retrying a request.
		*
		* @param httpStatusCode - The HTTP status code of the response.
		* @param currentRetry - The current retry attempt number.
		* @param retryAfterHeader - The value of the "retry-after" header from the response.
		* @returns A promise that resolves to a boolean indicating whether a retry should be attempted.
		*/
		async pauseForRetry(httpStatusCode, currentRetry, logger) {
			if (this._isNewRequest) {
				this._isNewRequest = false;
				this.maxRetries = httpStatusCode === HTTP_GONE ? LINEAR_STRATEGY_NUM_RETRIES : EXPONENTIAL_STRATEGY_NUM_RETRIES;
			}
			/**
			* (status code is one of the retriable 400 status code
			* or
			* status code is >= 500 and <= 599)
			* and
			* current count of retries is less than the max number of retries
			*/
			if ((HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY.includes(httpStatusCode) || httpStatusCode >= HTTP_SERVER_ERROR_RANGE_START && httpStatusCode <= HTTP_SERVER_ERROR_RANGE_END && currentRetry < this.maxRetries) && currentRetry < this.maxRetries) {
				const retryAfterDelay = httpStatusCode === HTTP_GONE ? ImdsRetryPolicy.HTTP_STATUS_GONE_RETRY_AFTER_MS : this.exponentialRetryStrategy.calculateDelay(currentRetry);
				logger.verbose(`Retrying request in ${retryAfterDelay}ms (retry attempt: ${currentRetry + 1})`, "");
				await new Promise((resolve) => {
					return setTimeout(resolve, retryAfterDelay);
				});
				return true;
			}
			return false;
		}
	};
	const IMDS_TOKEN_PATH = "/metadata/identity/oauth2/token";
	const DEFAULT_IMDS_ENDPOINT = `http://169.254.169.254${IMDS_TOKEN_PATH}`;
	const IMDS_API_VERSION = "2018-02-01";
	/**
	* Managed Identity source implementation for Azure Instance Metadata Service (IMDS).
	*
	* IMDS is available on Azure Virtual Machines and Virtual Machine Scale Sets and provides
	* a REST endpoint to obtain OAuth tokens for managed identities. This implementation
	* handles both system-assigned and user-assigned managed identities.
	*
	* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ImdsManagedIdentitySource.cs
	*/
	var Imds = class Imds extends BaseManagedIdentitySource {
		/**
		* Constructs an Imds instance with the specified configuration.
		*
		* @param logger - Logger instance for recording debug information and errors
		* @param nodeStorage - NodeStorage instance used for token caching operations
		* @param networkClient - Network client implementation for making HTTP requests to IMDS
		* @param cryptoProvider - CryptoProvider for generating correlation IDs and other cryptographic operations
		* @param disableInternalRetries - When true, disables the built-in retry logic for IMDS requests
		* @param identityEndpoint - The complete IMDS endpoint URL including the token path
		*/
		constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) {
			super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
			this.identityEndpoint = identityEndpoint;
		}
		/**
		* Creates an Imds instance with the appropriate endpoint configuration.
		*
		* This method checks for the presence of the AZURE_POD_IDENTITY_AUTHORITY_HOST environment
		* variable, which is used in Azure Kubernetes Service (AKS) environments with Azure AD
		* Pod Identity. If found, it uses that endpoint; otherwise, it falls back to the standard
		* IMDS endpoint (169.254.169.254).
		*
		* @param logger - Logger instance for recording endpoint discovery and validation
		* @param nodeStorage - NodeStorage instance for token caching
		* @param networkClient - Network client for HTTP requests
		* @param cryptoProvider - CryptoProvider for cryptographic operations
		* @param disableInternalRetries - Whether to disable built-in retry logic
		*
		* @returns A configured Imds instance ready to make token requests
		*/
		static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
			let validatedIdentityEndpoint;
			if (process.env[ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]) {
				logger.info(`[Managed Identity] Environment variable ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} for ${ManagedIdentitySourceNames.IMDS} returned endpoint: ${process.env[ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]}`, "");
				validatedIdentityEndpoint = Imds.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST, `${process.env[ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]}${IMDS_TOKEN_PATH}`, ManagedIdentitySourceNames.IMDS, logger);
			} else {
				logger.info(`[Managed Identity] Unable to find ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} environment variable for ${ManagedIdentitySourceNames.IMDS}, using the default endpoint.`, "");
				validatedIdentityEndpoint = DEFAULT_IMDS_ENDPOINT;
			}
			return new Imds(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, validatedIdentityEndpoint);
		}
		/**
		* Creates a properly configured HTTP request for acquiring an access token from IMDS.
		*
		* This method builds a complete request object with all necessary headers, query parameters,
		* and retry policies required by the Azure Instance Metadata Service.
		*
		* Key request components:
		* - HTTP GET method to the IMDS token endpoint
		* - Metadata header set to "true" (required by IMDS)
		* - API version parameter (currently "2018-02-01")
		* - Resource parameter specifying the target audience
		* - Identity-specific parameters for user-assigned managed identities
		* - IMDS-specific retry policy
		*
		* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
		* @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity
		*
		* @returns A configured ManagedIdentityRequestParameters object ready for network execution
		*/
		createRequest(resource, managedIdentityId) {
			const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
			request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
			request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = IMDS_API_VERSION;
			request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
			if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, true)] = managedIdentityId.id;
			request.retryPolicy = new ImdsRetryPolicy();
			return request;
		}
	};
	const SERVICE_FABRIC_MSI_API_VERSION = "2019-07-01-preview";
	/**
	* Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ServiceFabricManagedIdentitySource.cs
	*/
	var ServiceFabric = class ServiceFabric extends BaseManagedIdentitySource {
		/**
		* Constructs a new ServiceFabric managed identity source for acquiring tokens from Azure Service Fabric clusters.
		*
		* Service Fabric managed identity allows applications running in Service Fabric clusters to authenticate
		* without storing credentials in code. This source handles token acquisition using the Service Fabric
		* Managed Identity Token Service (MITS).
		*
		* @param logger - Logger instance for logging authentication events and debugging information
		* @param nodeStorage - NodeStorage instance for caching tokens and other authentication artifacts
		* @param networkClient - Network client for making HTTP requests to the Service Fabric identity endpoint
		* @param cryptoProvider - Crypto provider for cryptographic operations like token validation
		* @param disableInternalRetries - Whether to disable internal retry logic for failed requests
		* @param identityEndpoint - The Service Fabric managed identity endpoint URL
		* @param identityHeader - The Service Fabric managed identity secret header value
		*/
		constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) {
			super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
			this.identityEndpoint = identityEndpoint;
			this.identityHeader = identityHeader;
		}
		/**
		* Retrieves the environment variables required for Service Fabric managed identity authentication.
		*
		* Service Fabric managed identity requires three specific environment variables to be set by the
		* Service Fabric runtime:
		* - IDENTITY_ENDPOINT: The endpoint URL for the Managed Identity Token Service (MITS)
		* - IDENTITY_HEADER: A secret value used for authentication with the MITS
		* - IDENTITY_SERVER_THUMBPRINT: The thumbprint of the MITS server certificate for secure communication
		*
		* @returns An array containing the identity endpoint, identity header, and identity server thumbprint values.
		*          Elements will be undefined if the corresponding environment variables are not set.
		*/
		static getEnvironmentVariables() {
			return [
				process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT],
				process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER],
				process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_SERVER_THUMBPRINT]
			];
		}
		/**
		* Attempts to create a ServiceFabric managed identity source if the runtime environment supports it.
		*
		* Checks for the presence of all required Service Fabric environment variables
		* and validates the endpoint URL format. It will only create a ServiceFabric instance if the application
		* is running in a properly configured Service Fabric cluster with managed identity enabled.
		*
		* Note: User-assigned managed identities must be configured at the cluster level, not at runtime.
		* This method will log a warning if a user-assigned identity is requested.
		*
		* @param logger - Logger instance for logging creation events and validation results
		* @param nodeStorage - NodeStorage instance for caching tokens and authentication artifacts
		* @param networkClient - Network client for making HTTP requests to the identity endpoint
		* @param cryptoProvider - Crypto provider for cryptographic operations
		* @param disableInternalRetries - Whether to disable internal retry logic for failed requests
		* @param managedIdentityId - Managed identity identifier specifying system-assigned or user-assigned identity
		*
		* @returns A ServiceFabric instance if all environment variables are valid and present, otherwise null
		*/
		static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
			const [identityEndpoint, identityHeader, identityServerThumbprint] = ServiceFabric.getEnvironmentVariables();
			if (!identityEndpoint || !identityHeader || !identityServerThumbprint) {
				logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity is unavailable because one or all of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}', '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' or '${ManagedIdentityEnvironmentVariableNames.IDENTITY_SERVER_THUMBPRINT}' environment variables are not defined.`, "");
				return null;
			}
			const validatedIdentityEndpoint = ServiceFabric.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.SERVICE_FABRIC, logger);
			logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity.`, "");
			if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) logger.warning(`[Managed Identity] ${ManagedIdentitySourceNames.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.`, "");
			return new ServiceFabric(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader);
		}
		/**
		* Creates HTTP request parameters for acquiring an access token from the Service Fabric Managed Identity Token Service (MITS).
		*
		* This method constructs a properly formatted HTTP GET request that includes:
		* - The secret header for authentication with MITS
		* - API version parameter for the Service Fabric MSI endpoint
		* - Resource parameter specifying the target Azure service
		* - Optional identity parameters for user-assigned managed identities
		*
		* The request follows the Service Fabric managed identity protocol and uses the 2019-07-01-preview API version.
		* For user-assigned identities, the appropriate query parameter (client_id, object_id, or resource_id) is added
		* based on the identity type.
		*
		* @param resource - The Azure resource URI for which the access token is requested (e.g., "https://vault.azure.net/")
		* @param managedIdentityId - The managed identity configuration specifying system-assigned or user-assigned identity details
		*
		* @returns A configured ManagedIdentityRequestParameters object ready for network execution
		*/
		createRequest(resource, managedIdentityId) {
			const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint);
			request.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] = this.identityHeader;
			request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = SERVICE_FABRIC_MSI_API_VERSION;
			request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
			if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id;
			return request;
		}
	};
	const MACHINE_LEARNING_MSI_API_VERSION = "2017-09-01";
	const MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR = `Only client id is supported for user-assigned managed identity in ${ManagedIdentitySourceNames.MACHINE_LEARNING}.`;
	/**
	* Machine Learning Managed Identity Source implementation for Azure Machine Learning environments.
	*
	* This class handles managed identity authentication specifically for Azure Machine Learning services.
	* It supports both system-assigned and user-assigned managed identities, using the MSI_ENDPOINT
	* and MSI_SECRET environment variables that are automatically provided in Azure ML environments.
	*/
	var MachineLearning = class MachineLearning extends BaseManagedIdentitySource {
		/**
		* Creates a new MachineLearning managed identity source instance.
		*
		* @param logger - Logger instance for diagnostic information
		* @param nodeStorage - Node storage implementation for caching
		* @param networkClient - Network client for making HTTP requests
		* @param cryptoProvider - Cryptographic operations provider
		* @param disableInternalRetries - Whether to disable automatic request retries
		* @param msiEndpoint - The MSI endpoint URL from environment variables
		* @param secret - The MSI secret from environment variables
		*/
		constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret) {
			super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
			this.msiEndpoint = msiEndpoint;
			this.secret = secret;
		}
		/**
		* Retrieves the required environment variables for Azure Machine Learning managed identity.
		*
		* This method checks for the presence of MSI_ENDPOINT and MSI_SECRET environment variables
		* that are automatically set by the Azure Machine Learning platform when managed identity
		* is enabled for the compute instance or cluster.
		*
		* @returns An array containing [msiEndpoint, secret] where either value may be undefined
		*          if the corresponding environment variable is not set
		*/
		static getEnvironmentVariables() {
			return [process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT], process.env[ManagedIdentityEnvironmentVariableNames.MSI_SECRET]];
		}
		/**
		* Attempts to create a MachineLearning managed identity source.
		*
		* This method validates the Azure Machine Learning environment by checking for the required
		* MSI_ENDPOINT and MSI_SECRET environment variables. If both are present and valid,
		* it creates and returns a MachineLearning instance. If either is missing or invalid,
		* it returns null, indicating that this managed identity source is not available
		* in the current environment.
		*
		* @param logger - Logger instance for diagnostic information
		* @param nodeStorage - Node storage implementation for caching
		* @param networkClient - Network client for making HTTP requests
		* @param cryptoProvider - Cryptographic operations provider
		* @param disableInternalRetries - Whether to disable automatic request retries
		*
		* @returns A new MachineLearning instance if the environment is valid, null otherwise
		*/
		static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
			const [msiEndpoint, secret] = MachineLearning.getEnvironmentVariables();
			if (!msiEndpoint || !secret) {
				logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.MSI_SECRET}' environment variables are not defined.`, "");
				return null;
			}
			const validatedMsiEndpoint = MachineLearning.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.MACHINE_LEARNING, logger);
			logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity.`, "");
			return new MachineLearning(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret);
		}
		/**
		* Creates a managed identity token request for Azure Machine Learning environments.
		*
		* This method constructs the HTTP request parameters needed to acquire an access token
		* from the Azure Machine Learning managed identity endpoint. It handles both system-assigned
		* and user-assigned managed identities with specific logic for each type:
		*
		* - System-assigned: Uses the DEFAULT_IDENTITY_CLIENT_ID environment variable
		* - User-assigned: Only supports client ID-based identification (not object ID or resource ID)
		*
		* The request uses the 2017-09-01 API version and includes the required secret header
		* for authentication with the MSI endpoint.
		*
		* @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default")
		* @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity
		*
		* @returns A configured ManagedIdentityRequestParameters object ready for network execution
		*
		* @throws Error if an unsupported managed identity ID type is specified (only client ID is supported for user-assigned)
		*/
		createRequest(resource, managedIdentityId) {
			const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.msiEndpoint);
			request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true";
			request.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] = this.secret;
			request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = MACHINE_LEARNING_MSI_API_VERSION;
			request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = resource;
			if (managedIdentityId.idType === ManagedIdentityIdType.SYSTEM_ASSIGNED) request.queryParameters[ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017] = process.env[ManagedIdentityEnvironmentVariableNames.DEFAULT_IDENTITY_CLIENT_ID];
			else if (managedIdentityId.idType === ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID) request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, false, true)] = managedIdentityId.id;
			else throw new Error(MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR);
			return request;
		}
	};
	var ManagedIdentityClient = class ManagedIdentityClient {
		constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {
			this.logger = logger;
			this.nodeStorage = nodeStorage;
			this.networkClient = networkClient;
			this.cryptoProvider = cryptoProvider;
			this.disableInternalRetries = disableInternalRetries;
		}
		async sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
			if (!ManagedIdentityClient.identitySource) ManagedIdentityClient.identitySource = this.selectManagedIdentitySource(this.logger, this.nodeStorage, this.networkClient, this.cryptoProvider, this.disableInternalRetries, managedIdentityId);
			return ManagedIdentityClient.identitySource.acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken);
		}
		allEnvironmentVariablesAreDefined(environmentVariables) {
			return Object.values(environmentVariables).every((environmentVariable) => {
				return environmentVariable !== void 0;
			});
		}
		/**
		* Determine the Managed Identity Source based on available environment variables. This API is consumed by ManagedIdentityApplication's getManagedIdentitySource.
		* @returns ManagedIdentitySourceNames - The Managed Identity source's name
		*/
		getManagedIdentitySource() {
			ManagedIdentityClient.sourceName = this.allEnvironmentVariablesAreDefined(ServiceFabric.getEnvironmentVariables()) ? ManagedIdentitySourceNames.SERVICE_FABRIC : this.allEnvironmentVariablesAreDefined(AppService.getEnvironmentVariables()) ? ManagedIdentitySourceNames.APP_SERVICE : this.allEnvironmentVariablesAreDefined(MachineLearning.getEnvironmentVariables()) ? ManagedIdentitySourceNames.MACHINE_LEARNING : this.allEnvironmentVariablesAreDefined(CloudShell.getEnvironmentVariables()) ? ManagedIdentitySourceNames.CLOUD_SHELL : this.allEnvironmentVariablesAreDefined(AzureArc.getEnvironmentVariables()) ? ManagedIdentitySourceNames.AZURE_ARC : ManagedIdentitySourceNames.DEFAULT_TO_IMDS;
			return ManagedIdentityClient.sourceName;
		}
		/**
		* Tries to create a managed identity source for all sources
		* @returns the managed identity Source
		*/
		selectManagedIdentitySource(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) {
			const source = ServiceFabric.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || AppService.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) || MachineLearning.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) || CloudShell.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || AzureArc.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || Imds.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries);
			if (!source) throw createManagedIdentityError(unableToCreateSource);
			return source;
		}
	};
	const SOURCES_THAT_SUPPORT_TOKEN_REVOCATION = [ManagedIdentitySourceNames.SERVICE_FABRIC];
	/**
	* Class to initialize a managed identity and identify the service
	* @public
	*/
	var ManagedIdentityApplication = class ManagedIdentityApplication {
		constructor(configuration) {
			this.config = buildManagedIdentityConfiguration(configuration || {});
			this.logger = new Logger(this.config.system.loggerOptions, name, version);
			const fakeStatusAuthorityOptions = { canonicalAuthority: DEFAULT_AUTHORITY };
			if (!ManagedIdentityApplication.nodeStorage) ManagedIdentityApplication.nodeStorage = new NodeStorage(this.logger, this.config.managedIdentityId.id, DEFAULT_CRYPTO_IMPLEMENTATION, fakeStatusAuthorityOptions);
			this.networkClient = this.config.system.networkClient;
			this.cryptoProvider = new CryptoProvider();
			const fakeAuthorityOptions = {
				protocolMode: ProtocolMode.AAD,
				knownAuthorities: [DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY],
				cloudDiscoveryMetadata: "",
				authorityMetadata: ""
			};
			this.fakeAuthority = new Authority(DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, this.networkClient, ManagedIdentityApplication.nodeStorage, fakeAuthorityOptions, this.logger, this.cryptoProvider.createNewGuid(), new StubPerformanceClient(), true);
			this.fakeClientCredentialClient = new ClientCredentialClient({ authOptions: {
				clientId: this.config.managedIdentityId.id,
				authority: this.fakeAuthority
			} });
			this.managedIdentityClient = new ManagedIdentityClient(this.logger, ManagedIdentityApplication.nodeStorage, this.networkClient, this.cryptoProvider, this.config.disableInternalRetries);
			this.hashUtils = new HashUtils();
		}
		/**
		* Acquire an access token from the cache or the managed identity
		* @param managedIdentityRequest - the ManagedIdentityRequestParams object passed in by the developer
		* @returns the access token
		*/
		async acquireToken(managedIdentityRequestParams) {
			if (!managedIdentityRequestParams.resource) throw createClientConfigurationError(urlEmptyError);
			const managedIdentityRequest = {
				forceRefresh: managedIdentityRequestParams.forceRefresh,
				resource: managedIdentityRequestParams.resource.replace("/.default", ""),
				scopes: [managedIdentityRequestParams.resource.replace("/.default", "")],
				authority: this.fakeAuthority.canonicalAuthority,
				correlationId: this.cryptoProvider.createNewGuid(),
				claims: managedIdentityRequestParams.claims,
				clientCapabilities: this.config.clientCapabilities
			};
			if (managedIdentityRequest.forceRefresh) return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority);
			const [cachedAuthenticationResult, lastCacheOutcome] = await this.fakeClientCredentialClient.getCachedAuthenticationResult(managedIdentityRequest, this.config, this.cryptoProvider, this.fakeAuthority, ManagedIdentityApplication.nodeStorage);
			if (managedIdentityRequest.claims) {
				const sourceName = this.managedIdentityClient.getManagedIdentitySource();
				if (cachedAuthenticationResult && SOURCES_THAT_SUPPORT_TOKEN_REVOCATION.includes(sourceName)) managedIdentityRequest.revokedTokenSha256Hash = this.hashUtils.sha256(cachedAuthenticationResult.accessToken).toString(EncodingTypes.HEX);
				return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority);
			}
			if (cachedAuthenticationResult) {
				if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {
					this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.", managedIdentityRequest.correlationId);
					await this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority, true);
				}
				return cachedAuthenticationResult;
			} else return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority);
		}
		/**
		* Acquires a token from a managed identity endpoint.
		*
		* @param managedIdentityRequest - The request object containing parameters for the managed identity token request.
		* @param managedIdentityId - The identifier for the managed identity (e.g., client ID or resource ID).
		* @param fakeAuthority - A placeholder authority used for the token request.
		* @param refreshAccessToken - Optional flag indicating whether to force a refresh of the access token.
		* @returns A promise that resolves to an AuthenticationResult containing the acquired token and related information.
		*/
		async acquireTokenFromManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {
			return this.managedIdentityClient.sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken);
		}
		/**
		* Determine the Managed Identity Source based on available environment variables. This API is consumed by Azure Identity SDK.
		* @returns ManagedIdentitySourceNames - The Managed Identity source's name
		*/
		getManagedIdentitySource() {
			return ManagedIdentityClient.sourceName || this.managedIdentityClient.getManagedIdentitySource();
		}
	};
	/**
	* Cache plugin that serializes data to the cache and deserializes data from the cache
	* @public
	*/
	var DistributedCachePlugin = class {
		constructor(client, partitionManager) {
			this.client = client;
			this.partitionManager = partitionManager;
		}
		/**
		* Deserializes the cache before accessing it
		* @param cacheContext - TokenCacheContext
		*/
		async beforeCacheAccess(cacheContext) {
			const partitionKey = await this.partitionManager.getKey();
			const cacheData = await this.client.get(partitionKey);
			cacheContext.tokenCache.deserialize(cacheData);
		}
		/**
		* Serializes the cache after accessing it
		* @param cacheContext - TokenCacheContext
		*/
		async afterCacheAccess(cacheContext) {
			if (cacheContext.cacheHasChanged) {
				const kvStore = cacheContext.tokenCache.getKVStore();
				const accountEntities = Object.values(kvStore).filter((value) => isAccountEntity(value));
				let partitionKey;
				if (accountEntities.length > 0) {
					const accountEntity = accountEntities[0];
					partitionKey = await this.partitionManager.extractKey(accountEntity);
				} else partitionKey = await this.partitionManager.getKey();
				await this.client.set(partitionKey, cacheContext.tokenCache.serialize());
			}
		}
	};
	/**
	* @packageDocumentation
	* @module @azure/msal-node
	*/
	/**
	* Warning: This set of exports is purely intended to be used by other MSAL libraries, and should be considered potentially unstable. We strongly discourage using them directly, you do so at your own risk.
	* Breaking changes to these APIs will be shipped under a minor version, instead of a major version.
	*/
	const PromptValue = PromptValue$1;
	const ResponseMode = ResponseMode$1;
	exports.AuthError = AuthError;
	exports.AuthErrorCodes = AuthErrorCodes;
	exports.AzureCloudInstance = AzureCloudInstance;
	exports.ClientAssertion = ClientAssertion;
	exports.ClientAuthError = ClientAuthError;
	exports.ClientAuthErrorCodes = ClientAuthErrorCodes;
	exports.ClientConfigurationError = ClientConfigurationError;
	exports.ClientConfigurationErrorCodes = ClientConfigurationErrorCodes;
	exports.ConfidentialClientApplication = ConfidentialClientApplication;
	exports.CryptoProvider = CryptoProvider;
	exports.DistributedCachePlugin = DistributedCachePlugin;
	exports.InteractionRequiredAuthError = InteractionRequiredAuthError;
	exports.InteractionRequiredAuthErrorCodes = InteractionRequiredAuthErrorCodes;
	exports.Logger = Logger;
	exports.ManagedIdentityApplication = ManagedIdentityApplication;
	exports.ManagedIdentitySourceNames = ManagedIdentitySourceNames;
	exports.PromptValue = PromptValue;
	exports.ProtocolMode = ProtocolMode;
	exports.PublicClientApplication = PublicClientApplication;
	exports.ResponseMode = ResponseMode;
	exports.ServerError = ServerError;
	exports.TokenCache = TokenCache;
	exports.TokenCacheContext = TokenCacheContext;
	exports.internals = internals;
	exports.version = version;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/MemoryCache.js
var require_MemoryCache = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MemoryCache = void 0;
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	const CACHE_PURGE_INTERVAL = 6e4;
	/**
	* Simple in-memory cache with TTL support.
	* This is used to store authentication tokens for Agentic Identity scenarios only!
	*/
	var MemoryCache = class {
		constructor() {
			this.cache = /* @__PURE__ */ new Map();
		}
		/**
		* Clears the purge interval to allow the process to exit cleanly
		*/
		destroy() {
			if (this.purgeInterval) {
				clearInterval(this.purgeInterval);
				this.purgeInterval = void 0;
			}
		}
		set(key, value, ttlSeconds) {
			const validUntil = Date.now() + ttlSeconds * 1e3;
			this.cache.set(key, {
				value,
				validUntil
			});
			if (!this.purgeInterval) this.purgeInterval = setInterval(() => this.purge(), CACHE_PURGE_INTERVAL);
		}
		get(key) {
			const item = this.cache.get(key);
			if (!item) return;
			if (Date.now() > item.validUntil) {
				this.cache.delete(key);
				return;
			}
			return item.value;
		}
		delete(key) {
			return this.cache.delete(key);
		}
		purge() {
			const now = Date.now();
			for (const [key, { validUntil }] of this.cache.entries()) if (now > validUntil) this.cache.delete(key);
		}
	};
	exports.MemoryCache = MemoryCache;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/msalTokenProvider.js
var require_msalTokenProvider = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MsalTokenProvider = void 0;
	const msal_node_1 = require_msal_node();
	const axios_1 = __importDefault(require_axios());
	const logger_1 = require_logger();
	const uuid_1$3 = __require("uuid");
	const MemoryCache_1 = require_MemoryCache();
	const jsonwebtoken_1 = __importDefault(require_jsonwebtoken());
	const fs_1$1 = __importDefault(__require("fs"));
	const crypto_1$18 = __importDefault(__require("crypto"));
	const audience = "api://AzureADTokenExchange";
	const logger = (0, logger_1.debug)("agents:msal");
	/**
	* Provides tokens using MSAL.
	*/
	var MsalTokenProvider = class {
		constructor(connectionSettings) {
			this.sysOptions = { loggerOptions: {
				logLevel: msal_node_1.LogLevel.Trace,
				loggerCallback: (level, message, containsPii) => {
					if (containsPii) return;
					switch (level) {
						case msal_node_1.LogLevel.Error:
							logger.error(message);
							return;
						case msal_node_1.LogLevel.Info:
							logger.debug(message);
							return;
						case msal_node_1.LogLevel.Warning:
							if (!message.includes("Warning - No client info in response")) logger.warn(message);
							return;
						case msal_node_1.LogLevel.Verbose: logger.debug(message);
					}
				},
				piiLoggingEnabled: false
			} };
			this._agenticTokenCache = new MemoryCache_1.MemoryCache();
			this.connectionSettings = connectionSettings;
		}
		async getAccessToken(authConfigOrScope, scope) {
			let authConfig;
			let actualScope;
			if (typeof authConfigOrScope === "string") {
				if (!this.connectionSettings) throw new Error("Connection settings must be provided to constructor when calling getAccessToken(scope)");
				authConfig = this.connectionSettings;
				actualScope = authConfigOrScope;
			} else {
				authConfig = authConfigOrScope;
				actualScope = scope;
			}
			if (!authConfig.clientId && false);
			let token;
			if (authConfig.WIDAssertionFile !== void 0) token = await this.acquireAccessTokenViaWID(authConfig, actualScope);
			else if (authConfig.FICClientId !== void 0) token = await this.acquireAccessTokenViaFIC(authConfig, actualScope);
			else if (authConfig.clientSecret !== void 0) token = await this.acquireAccessTokenViaSecret(authConfig, actualScope);
			else if (authConfig.certPemFile !== void 0 && authConfig.certKeyFile !== void 0) token = await this.acquireTokenWithCertificate(authConfig, actualScope);
			else if (authConfig.clientSecret === void 0 && authConfig.certPemFile === void 0 && authConfig.certKeyFile === void 0) token = await this.acquireTokenWithUserAssignedIdentity(authConfig, actualScope);
			else throw new Error("Invalid authConfig. ");
			if (token === void 0) throw new Error("Failed to acquire token");
			return token;
		}
		async acquireTokenOnBehalfOf(authConfigOrScopes, scopesOrOboAssertion, oboAssertion) {
			let authConfig;
			let actualScopes;
			let actualOboAssertion;
			if (Array.isArray(authConfigOrScopes)) {
				if (!this.connectionSettings) throw new Error("Connection settings must be provided to constructor when calling acquireTokenOnBehalfOf(scopes, oboAssertion)");
				authConfig = this.connectionSettings;
				actualScopes = authConfigOrScopes;
				actualOboAssertion = scopesOrOboAssertion;
			} else {
				authConfig = authConfigOrScopes;
				actualScopes = scopesOrOboAssertion;
				actualOboAssertion = oboAssertion;
			}
			const token = await new msal_node_1.ConfidentialClientApplication({
				auth: {
					clientId: authConfig.clientId,
					authority: `${authConfig.authority}/${authConfig.tenantId || "botframework.com"}`,
					clientSecret: authConfig.clientSecret
				},
				system: this.sysOptions
			}).acquireTokenOnBehalfOf({
				oboAssertion: actualOboAssertion,
				scopes: actualScopes
			});
			if (!(token === null || token === void 0 ? void 0 : token.accessToken)) throw new Error("Failed to acquire token on behalf of user");
			return token.accessToken;
		}
		async getAgenticInstanceToken(tenantId, agentAppInstanceId) {
			logger.debug("Getting agentic instance token");
			if (!this.connectionSettings) throw new Error("Connection settings must be provided when calling getAgenticInstanceToken");
			const appToken = await this.getAgenticApplicationToken(tenantId, agentAppInstanceId);
			const token = await new msal_node_1.ConfidentialClientApplication({
				auth: {
					clientId: agentAppInstanceId,
					clientAssertion: appToken,
					authority: this.resolveAuthority(tenantId)
				},
				system: this.sysOptions
			}).acquireTokenByClientCredential({
				scopes: ["api://AzureAdTokenExchange/.default"],
				correlationId: (0, uuid_1$3.v4)()
			});
			if (!(token === null || token === void 0 ? void 0 : token.accessToken)) throw new Error(`Failed to acquire instance token for agent instance: ${agentAppInstanceId}`);
			return token.accessToken;
		}
		/**
		* This method can optionally accept a tenant ID that overrides the tenant ID in the connection settings, if the connection settings authority contains "common".
		* @param tenantId
		* @returns
		*/
		resolveAuthority(tenantId) {
			var _a, _b, _c, _d, _e;
			if (!tenantId) return ((_a = this.connectionSettings) === null || _a === void 0 ? void 0 : _a.authority) ? `${this.connectionSettings.authority}/${(_b = this.connectionSettings) === null || _b === void 0 ? void 0 : _b.tenantId}` : `https://login.microsoftonline.com/${((_c = this.connectionSettings) === null || _c === void 0 ? void 0 : _c.tenantId) || "botframework.com"}`;
			const configuredAuth = (_d = this.connectionSettings) === null || _d === void 0 ? void 0 : _d.authority;
			const configuredTenantId = (_e = this.connectionSettings) === null || _e === void 0 ? void 0 : _e.tenantId;
			const finalTenant = configuredTenantId && configuredTenantId !== "common" ? configuredTenantId : tenantId;
			if (!configuredAuth) return `https://login.microsoftonline.com/${finalTenant}`;
			const endsWithCommon = configuredAuth.endsWith("/common");
			const hasTenantGuid = /\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(configuredAuth);
			if (endsWithCommon || hasTenantGuid) return configuredAuth.replace(/\/(?:common|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})(?=\/|$)/, `/${tenantId}`);
			return `${configuredAuth}/${finalTenant}`;
		}
		/**
		* Does a direct HTTP call to acquire a token for agentic scenarios - do not use this directly!
		* This method will be removed once MSAL is updated with the necessary features.
		* (This is required in order to pass additional parameters into the auth call)
		* @param tenantId
		* @param clientId
		* @param clientAssertion
		* @param scopes
		* @param tokenBodyParameters
		* @returns
		*/
		async acquireTokenForAgenticScenarios(tenantId, clientId, clientAssertion, scopes, tokenBodyParameters) {
			if (!this.connectionSettings) throw new Error("Connection settings must be provided when calling getAgenticInstanceToken");
			const cacheKey = `${clientId}/${Object.keys(tokenBodyParameters).map((key) => key !== "user_federated_identity_credential" ? `${key}=${tokenBodyParameters[key]}` : "").join("&")}/${scopes.join(";")}`;
			if (this._agenticTokenCache.get(cacheKey)) return this._agenticTokenCache.get(cacheKey);
			const url = `${this.resolveAuthority(tenantId)}/oauth2/v2.0/token`;
			const data = {
				client_id: clientId,
				scope: scopes.join(" "),
				...tokenBodyParameters
			};
			if (clientAssertion) {
				data.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
				data.client_assertion = clientAssertion;
			} else data.client_secret = this.connectionSettings.clientSecret;
			if (data.grant_type !== "user_fic") data.client_info = "2";
			const token = await axios_1.default.post(url, data, { headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" } }).catch((error) => {
				logger.error("Error acquiring token: ", error.toJSON());
				throw error;
			});
			this._agenticTokenCache.set(cacheKey, token.data.access_token, token.data.expires_in - 300);
			return token.data.access_token;
		}
		async getAgenticUserToken(tenantId, agentAppInstanceId, agenticUserId, scopes) {
			logger.debug("Getting agentic user token");
			const agentToken = await this.getAgenticApplicationToken(tenantId, agentAppInstanceId);
			const instanceToken = await this.getAgenticInstanceToken(tenantId, agentAppInstanceId);
			const token = await this.acquireTokenForAgenticScenarios(tenantId, agentAppInstanceId, agentToken, scopes, {
				user_id: agenticUserId,
				user_federated_identity_credential: instanceToken,
				grant_type: "user_fic"
			});
			if (!token) throw new Error(`Failed to acquire instance token for user token: ${agentAppInstanceId}`);
			return token;
		}
		async getAgenticApplicationToken(tenantId, agentAppInstanceId) {
			var _a;
			if (!((_a = this.connectionSettings) === null || _a === void 0 ? void 0 : _a.clientId)) throw new Error("Connection settings must be provided when calling getAgenticApplicationToken");
			logger.debug("Getting agentic application token");
			let clientAssertion;
			if (this.connectionSettings.WIDAssertionFile !== void 0) clientAssertion = fs_1$1.default.readFileSync(this.connectionSettings.WIDAssertionFile, "utf8");
			else if (this.connectionSettings.FICClientId !== void 0) clientAssertion = await this.fetchExternalToken(this.connectionSettings.FICClientId);
			else if (this.connectionSettings.certPemFile !== void 0 && this.connectionSettings.certKeyFile !== void 0) clientAssertion = this.getAssertionFromCert(this.connectionSettings);
			const token = await this.acquireTokenForAgenticScenarios(tenantId, this.connectionSettings.clientId, clientAssertion, ["api://AzureAdTokenExchange/.default"], {
				grant_type: "client_credentials",
				fmi_path: agentAppInstanceId
			});
			if (!token) throw new Error(`Failed to acquire token for agent instance: ${agentAppInstanceId}`);
			return token;
		}
		/**
		* Generates the client assertion using the provided certificate.
		* @param authConfig The authentication configuration.
		* @returns The client assertion.
		*/
		getAssertionFromCert(authConfig) {
			const base64url = (buf) => buf.toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
			const privateKeyPem = fs_1$1.default.readFileSync(authConfig.certKeyFile);
			const pemFile = fs_1$1.default.readFileSync(authConfig.certPemFile);
			const der = new crypto_1$18.default.X509Certificate(pemFile).raw;
			const x5tS256 = base64url(crypto_1$18.default.createHash("sha256").update(der).digest());
			let x5c;
			if (authConfig.sendX5C) x5c = pemFile.toString();
			const now = Math.floor(Date.now() / 1e3);
			const payload = {
				aud: `${this.resolveAuthority(authConfig.tenantId)}/oauth2/v2.0/token`,
				iss: authConfig.clientId,
				sub: authConfig.clientId,
				jti: (0, uuid_1$3.v4)(),
				nbf: now,
				iat: now,
				exp: now + 600
			};
			return jsonwebtoken_1.default.sign(payload, privateKeyPem, {
				algorithm: "PS256",
				header: {
					alg: "PS256",
					typ: "JWT",
					"x5t#S256": x5tS256,
					x5c
				}
			});
		}
		/**
		* Acquires a token using a user-assigned identity.
		* @param authConfig The authentication configuration.
		* @param scope The scope for the token.
		* @returns A promise that resolves to the access token.
		*/
		async acquireTokenWithUserAssignedIdentity(authConfig, scope) {
			const token = await new msal_node_1.ManagedIdentityApplication({
				managedIdentityIdParams: { userAssignedClientId: authConfig.clientId || "" },
				system: this.sysOptions
			}).acquireToken({ resource: scope });
			return token === null || token === void 0 ? void 0 : token.accessToken;
		}
		/**
		* Acquires a token using a certificate.
		* @param authConfig The authentication configuration.
		* @param scope The scope for the token.
		* @returns A promise that resolves to the access token.
		*/
		async acquireTokenWithCertificate(authConfig, scope) {
			const privateKeySource = fs_1$1.default.readFileSync(authConfig.certKeyFile);
			const privateKey = crypto_1$18.default.createPrivateKey({
				key: privateKeySource,
				format: "pem"
			}).export({
				format: "pem",
				type: "pkcs8"
			});
			const pemFile = fs_1$1.default.readFileSync(authConfig.certPemFile);
			const pubKeyObject = new crypto_1$18.default.X509Certificate(pemFile);
			const token = await new msal_node_1.ConfidentialClientApplication({
				auth: {
					clientId: authConfig.clientId || "",
					authority: `${authConfig.authority}/${authConfig.tenantId || "botframework.com"}`,
					clientCertificate: {
						privateKey,
						thumbprint: pubKeyObject.fingerprint.replaceAll(":", ""),
						x5c: pemFile.toString()
					}
				},
				system: this.sysOptions
			}).acquireTokenByClientCredential({
				scopes: [`${scope}/.default`],
				correlationId: (0, uuid_1$3.v4)()
			});
			if (!(token === null || token === void 0 ? void 0 : token.accessToken)) throw new Error("Failed to acquire token using certificate");
			return token.accessToken;
		}
		/**
		* Acquires a token using a client secret.
		* @param authConfig The authentication configuration.
		* @param scope The scope for the token.
		* @returns A promise that resolves to the access token.
		*/
		async acquireAccessTokenViaSecret(authConfig, scope) {
			const token = await new msal_node_1.ConfidentialClientApplication({
				auth: {
					clientId: authConfig.clientId,
					authority: `${authConfig.authority}/${authConfig.tenantId || "botframework.com"}`,
					clientSecret: authConfig.clientSecret
				},
				system: this.sysOptions
			}).acquireTokenByClientCredential({
				scopes: [`${scope}/.default`],
				correlationId: (0, uuid_1$3.v4)()
			});
			if (!(token === null || token === void 0 ? void 0 : token.accessToken)) throw new Error("Failed to acquire token using client secret");
			return token.accessToken;
		}
		/**
		* Acquires a token using a FIC client assertion.
		* @param authConfig The authentication configuration.
		* @param scope The scope for the token.
		* @returns A promise that resolves to the access token.
		*/
		async acquireAccessTokenViaFIC(authConfig, scope) {
			const scopes = [`${scope}/.default`];
			const clientAssertion = await this.fetchExternalToken(authConfig.FICClientId);
			const token = await new msal_node_1.ConfidentialClientApplication({
				auth: {
					clientId: authConfig.clientId,
					authority: `${authConfig.authority}/${authConfig.tenantId}`,
					clientAssertion
				},
				system: this.sysOptions
			}).acquireTokenByClientCredential({ scopes });
			logger.debug("got token using FIC client assertion");
			if (!(token === null || token === void 0 ? void 0 : token.accessToken)) throw new Error("Failed to acquire token using FIC client assertion");
			return token.accessToken;
		}
		/**
		* Acquires a token using a Workload Identity client assertion.
		* @param authConfig The authentication configuration.
		* @param scope The scope for the token.
		* @returns A promise that resolves to the access token.
		*/
		async acquireAccessTokenViaWID(authConfig, scope) {
			const scopes = [`${scope}/.default`];
			const clientAssertion = fs_1$1.default.readFileSync(authConfig.WIDAssertionFile, "utf8");
			const token = await new msal_node_1.ConfidentialClientApplication({
				auth: {
					clientId: authConfig.clientId,
					authority: `https://login.microsoftonline.com/${authConfig.tenantId}`,
					clientAssertion
				},
				system: this.sysOptions
			}).acquireTokenByClientCredential({ scopes });
			logger.info("got token using WID client assertion");
			if (!(token === null || token === void 0 ? void 0 : token.accessToken)) throw new Error("Failed to acquire token using WID client assertion");
			return token.accessToken;
		}
		/**
		* Fetches an external token.
		* @param FICClientId The FIC client ID.
		* @returns A promise that resolves to the external token.
		*/
		async fetchExternalToken(FICClientId) {
			const response = await new msal_node_1.ManagedIdentityApplication({
				managedIdentityIdParams: { userAssignedClientId: FICClientId },
				system: this.sysOptions
			}).acquireToken({
				resource: audience,
				forceRefresh: true
			});
			logger.debug("got token for FIC");
			if (!(response === null || response === void 0 ? void 0 : response.accessToken)) throw new Error("Failed to acquire external token for FIC client assertion");
			return response.accessToken;
		}
	};
	exports.MsalTokenProvider = MsalTokenProvider;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/request.js
var require_request$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/msalTokenCredential.js
var require_msalTokenCredential = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MsalTokenCredential = void 0;
	const _1 = require_auth$1();
	/**
	* Token credential implementation that uses MSAL (Microsoft Authentication Library) to acquire access tokens.
	* Implements the Azure Core Auth TokenCredential interface for authentication scenarios.
	*/
	var MsalTokenCredential = class {
		/**
		* Creates a new instance of MsalTokenCredential.
		* @param authConfig The authentication configuration to use for token acquisition.
		*/
		constructor(authConfig) {
			this.authConfig = authConfig;
		}
		/**
		* Retrieves an access token for the specified scopes using MSAL authentication.
		* @param scopes Array of scopes for which to request an access token. The first scope is used to determine the resource.
		* @param options Optional parameters for token retrieval (currently unused).
		* @returns Promise that resolves to an access token with expiration timestamp.
		*/
		async getToken(scopes, options) {
			const scope = scopes[0].substring(0, scopes[0].lastIndexOf("/"));
			return {
				token: await new _1.MsalTokenProvider().getAccessToken(this.authConfig, scope),
				expiresOnTimestamp: Date.now() + 1e4
			};
		}
	};
	exports.MsalTokenCredential = MsalTokenCredential;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/action/actionTypes.js
var require_actionTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.actionTypesZodSchema = exports.ActionTypes = void 0;
	const zod_1$26 = __require("zod");
	/**
	* Enum representing the types of actions.
	*/
	var ActionTypes;
	(function(ActionTypes) {
		/**
		* Opens a URL in the default browser.
		*/
		ActionTypes["OpenUrl"] = "openUrl";
		/**
		* Sends a message back to the bot as a simple string.
		*/
		ActionTypes["ImBack"] = "imBack";
		/**
		* Sends a message back to the bot with additional data.
		*/
		ActionTypes["PostBack"] = "postBack";
		/**
		* Plays an audio file.
		*/
		ActionTypes["PlayAudio"] = "playAudio";
		/**
		* Plays a video file.
		*/
		ActionTypes["PlayVideo"] = "playVideo";
		/**
		* Displays an image.
		*/
		ActionTypes["ShowImage"] = "showImage";
		/**
		* Downloads a file.
		*/
		ActionTypes["DownloadFile"] = "downloadFile";
		/**
		* Initiates a sign-in process.
		*/
		ActionTypes["Signin"] = "signin";
		/**
		* Initiates a phone call.
		*/
		ActionTypes["Call"] = "call";
		/**
		* Sends a message back to the bot with additional metadata.
		*/
		ActionTypes["MessageBack"] = "messageBack";
		/**
		* Opens an application.
		*/
		ActionTypes["OpenApp"] = "openApp";
	})(ActionTypes || (exports.ActionTypes = ActionTypes = {}));
	/**
	* Zod schema for validating ActionTypes.
	*/
	exports.actionTypesZodSchema = zod_1$26.z.enum([
		"openUrl",
		"imBack",
		"postBack",
		"playAudio",
		"showImage",
		"downloadFile",
		"signin",
		"call",
		"messageBack",
		"openApp"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/action/semanticActionStateTypes.js
var require_semanticActionStateTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.semanticActionStateTypesZodSchema = exports.SemanticActionStateTypes = void 0;
	const zod_1$25 = __require("zod");
	/**
	* Enum representing the state types of a semantic action.
	*/
	var SemanticActionStateTypes;
	(function(SemanticActionStateTypes) {
		/**
		* Indicates the start of a semantic action.
		*/
		SemanticActionStateTypes["Start"] = "start";
		/**
		* Indicates the continuation of a semantic action.
		*/
		SemanticActionStateTypes["Continue"] = "continue";
		/**
		* Indicates the completion of a semantic action.
		*/
		SemanticActionStateTypes["Done"] = "done";
	})(SemanticActionStateTypes || (exports.SemanticActionStateTypes = SemanticActionStateTypes = {}));
	/**
	* Zod schema for validating SemanticActionStateTypes.
	*/
	exports.semanticActionStateTypesZodSchema = zod_1$25.z.enum([
		"start",
		"continue",
		"done"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/attachment/attachmentLayoutTypes.js
var require_attachmentLayoutTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.attachmentLayoutTypesZodSchema = exports.AttachmentLayoutTypes = void 0;
	const zod_1$24 = __require("zod");
	/**
	* Enum representing the layout types for attachments.
	*/
	var AttachmentLayoutTypes;
	(function(AttachmentLayoutTypes) {
		/**
		* Displays attachments in a list format.
		*/
		AttachmentLayoutTypes["List"] = "list";
		/**
		* Displays attachments in a carousel format.
		*/
		AttachmentLayoutTypes["Carousel"] = "carousel";
	})(AttachmentLayoutTypes || (exports.AttachmentLayoutTypes = AttachmentLayoutTypes = {}));
	/**
	* Zod schema for validating attachment layout types.
	*/
	exports.attachmentLayoutTypesZodSchema = zod_1$24.z.enum(["list", "carousel"]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/conversation/channels.js
var require_channels = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.Channels = void 0;
	/**
	* Enum representing the different channels an agent can communicate through.
	*/
	var Channels;
	(function(Channels) {
		/**
		* Represents an agentic channel
		*/
		Channels["Agents"] = "agents";
		/**
		* Represents the Alexa channel.
		*/
		Channels["Alexa"] = "alexa";
		/**
		* Represents the Console channel.
		*/
		Channels["Console"] = "console";
		/**
		* Represents the Directline channel.
		*/
		Channels["Directline"] = "directline";
		/**
		* Represents the Directline Speech channel.
		*/
		Channels["DirectlineSpeech"] = "directlinespeech";
		/**
		* Represents the Email channel.
		*/
		Channels["Email"] = "email";
		/**
		* Represents the Emulator channel.
		*/
		Channels["Emulator"] = "emulator";
		/**
		* Represents the Facebook channel.
		*/
		Channels["Facebook"] = "facebook";
		/**
		* Represents the GroupMe channel.
		*/
		Channels["Groupme"] = "groupme";
		/**
		* Represents the Line channel.
		*/
		Channels["Line"] = "line";
		/**
		* Represents the Microsoft Teams channel.
		*/
		Channels["Msteams"] = "msteams";
		/**
		* M365 Copilot Teams Subchannel.
		*/
		Channels["M365CopilotSubChannel"] = "COPILOT";
		Channels["M365Copilot"] = "msteams:COPILOT";
		/**
		* Represents the Omnichannel.
		*/
		Channels["Omni"] = "omnichannel";
		/**
		* Represents the Outlook channel.
		*/
		Channels["Outlook"] = "outlook";
		/**
		* Represents the Skype channel.
		*/
		Channels["Skype"] = "skype";
		/**
		* Represents the Slack channel.
		*/
		Channels["Slack"] = "slack";
		/**
		* Represents the SMS channel.
		*/
		Channels["Sms"] = "sms";
		/**
		* Represents the Telegram channel.
		*/
		Channels["Telegram"] = "telegram";
		/**
		* Represents the Telephony channel.
		*/
		Channels["Telephony"] = "telephony";
		/**
		* Represents the Test channel.
		*/
		Channels["Test"] = "test";
		/**
		* Represents the Webchat channel.
		*/
		Channels["Webchat"] = "webchat";
	})(Channels || (exports.Channels = Channels = {}));
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/conversation/endOfConversationCodes.js
var require_endOfConversationCodes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.endOfConversationCodesZodSchema = exports.EndOfConversationCodes = void 0;
	const zod_1$23 = __require("zod");
	/**
	* Enum representing the different end of conversation codes.
	*/
	var EndOfConversationCodes;
	(function(EndOfConversationCodes) {
		/**
		* The end of conversation reason is unknown.
		*/
		EndOfConversationCodes["Unknown"] = "unknown";
		/**
		* The conversation completed successfully.
		*/
		EndOfConversationCodes["CompletedSuccessfully"] = "completedSuccessfully";
		/**
		* The user cancelled the conversation.
		*/
		EndOfConversationCodes["UserCancelled"] = "userCancelled";
		/**
		* The agent timed out during the conversation.
		*/
		EndOfConversationCodes["AgentTimedOut"] = "agentTimedOut";
		/**
		* The agent issued an invalid message.
		*/
		EndOfConversationCodes["AgentIssuedInvalidMessage"] = "agentIssuedInvalidMessage";
		/**
		* The channel failed during the conversation.
		*/
		EndOfConversationCodes["ChannelFailed"] = "channelFailed";
	})(EndOfConversationCodes || (exports.EndOfConversationCodes = EndOfConversationCodes = {}));
	/**
	* Zod schema for validating end of conversation codes.
	*/
	exports.endOfConversationCodesZodSchema = zod_1$23.z.enum([
		"unknown",
		"completedSuccessfully",
		"userCancelled",
		"agentTimedOut",
		"agentIssuedInvalidMessage",
		"channelFailed"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/conversation/membershipSourceTypes.js
var require_membershipSourceTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MembershipSourceTypes = void 0;
	/**
	* Enum defining the type of roster the user is a member of.
	*/
	var MembershipSourceTypes;
	(function(MembershipSourceTypes) {
		/**
		* The source is that of a channel and the user is a member of that channel.
		*/
		MembershipSourceTypes["Channel"] = "channel";
		/**
		* The source is that of a team and the user is a member of that team.
		*/
		MembershipSourceTypes["Team"] = "team";
	})(MembershipSourceTypes || (exports.MembershipSourceTypes = MembershipSourceTypes = {}));
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/conversation/membershipTypes.js
var require_membershipTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MembershipTypes = void 0;
	/**
	* Enum expressing the users relationship to the current channel.
	*/
	var MembershipTypes;
	(function(MembershipTypes) {
		/**
		* The user is a direct member of a channel.
		*/
		MembershipTypes["Direct"] = "direct";
		/**
		* The user is a member of a channel through a group.
		*/
		MembershipTypes["Transitive"] = "transitive";
	})(MembershipTypes || (exports.MembershipTypes = MembershipTypes = {}));
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/conversation/roleTypes.js
var require_roleTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.roleTypeZodSchema = exports.RoleTypes = void 0;
	const zod_1$22 = __require("zod");
	/**
	* Enum representing the different role types in a conversation.
	*/
	var RoleTypes;
	(function(RoleTypes) {
		/**
		* Represents a user in the conversation.
		*/
		RoleTypes["User"] = "user";
		/**
		* Represents an agent or bot in the conversation.
		*/
		RoleTypes["Agent"] = "bot";
		/**
		* Represents a skill in the conversation.
		*/
		RoleTypes["Skill"] = "skill";
		/**
		* Agentic AI - AAI role
		*/
		RoleTypes["AgenticIdentity"] = "agenticAppInstance";
		/**
		* Agentic AI - AAI role.
		*/
		RoleTypes["AgenticUser"] = "agenticUser";
	})(RoleTypes || (exports.RoleTypes = RoleTypes = {}));
	/**
	* Zod schema for validating role types.
	*/
	exports.roleTypeZodSchema = zod_1$22.z.enum([
		"user",
		"bot",
		"skill",
		"agenticAppInstance",
		"agenticUser"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/entity/AIEntity.js
var require_AIEntity = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.addAIToActivity = void 0;
	/**
	* Adds an AI entity to an activity to indicate that the content was generated by AI.
	*
	* @param activity - The activity to which the AI entity will be added. The activity's entities array will be initialized if it doesn't exist.
	* @param citations - Optional array of client citations to include with the AI-generated content.
	*                   Citations provide references to sources used in generating the content and are displayed in Teams.
	* @param usageInfo - Optional sensitivity usage information that provides context about the content's sensitivity level.
	*                   This helps users understand any special handling requirements for the content.
	*
	* @remarks
	* This function enhances the activity with metadata that helps clients (like Microsoft Teams)
	* understand that the content is AI-generated and optionally includes citations and sensitivity information.
	*
	* @example
	* ```typescript
	* import { Activity } from '../activity';
	* import { addAIToActivity, ClientCitation } from './AIEntity';
	*
	* const activity: Activity = {
	*   type: 'message',
	*   text: 'Based on the documents, here are the key findings...'
	* };
	*
	* const citations: ClientCitation[] = [{
	*   '@type': 'Claim',
	*   position: 1,
	*   appearance: {
	*     '@type': 'DigitalDocument',
	*     name: 'Research Report 2024',
	*     abstract: 'Key findings from the annual research report',
	*     url: 'https://example.com/report.pdf',
	*     image: {
	*       '@type': 'ImageObject',
	*       name: 'PDF'
	*     }
	*   }
	* }];
	*
	* // Add AI entity with citations
	* addAIToActivity(activity, citations);
	* ```
	*/
	const addAIToActivity = (activity, citations, usageInfo) => {
		var _a;
		const aiEntity = {
			type: "https://schema.org/Message",
			"@type": "Message",
			"@context": "https://schema.org",
			"@id": "",
			additionalType: ["AIGeneratedContent"],
			citation: citations,
			usageInfo
		};
		(_a = activity.entities) !== null && _a !== void 0 || (activity.entities = []);
		activity.entities.push(aiEntity);
	};
	exports.addAIToActivity = addAIToActivity;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/invoke/adaptiveCardInvokeAction.js
var require_adaptiveCardInvokeAction = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.adaptiveCardInvokeActionZodSchema = void 0;
	const zod_1$21 = __require("zod");
	/**
	* Zod schema for validating an adaptive card invoke action.
	*/
	exports.adaptiveCardInvokeActionZodSchema = zod_1$21.z.object({
		type: zod_1$21.z.string().min(1),
		id: zod_1$21.z.string().optional(),
		verb: zod_1$21.z.string().min(1),
		data: zod_1$21.z.record(zod_1$21.z.string().min(1), zod_1$21.z.any())
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/entity/entity.js
var require_entity = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.entityZodSchema = void 0;
	const zod_1$20 = __require("zod");
	/**
	* Zod schema for validating Entity objects.
	*/
	exports.entityZodSchema = zod_1$20.z.object({ type: zod_1$20.z.string().min(1) }).passthrough();
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/action/semanticAction.js
var require_semanticAction = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.semanticActionZodSchema = void 0;
	const zod_1$19 = __require("zod");
	const entity_1 = require_entity();
	const semanticActionStateTypes_1 = require_semanticActionStateTypes();
	/**
	* Zod schema for validating SemanticAction.
	*/
	exports.semanticActionZodSchema = zod_1$19.z.object({
		id: zod_1$19.z.string().min(1),
		state: zod_1$19.z.union([semanticActionStateTypes_1.semanticActionStateTypesZodSchema, zod_1$19.z.string().min(1)]),
		entities: zod_1$19.z.record(entity_1.entityZodSchema)
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/action/cardAction.js
var require_cardAction = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.cardActionZodSchema = void 0;
	const zod_1$18 = __require("zod");
	const actionTypes_1 = require_actionTypes();
	/**
	* Zod schema for validating CardAction.
	*/
	exports.cardActionZodSchema = zod_1$18.z.object({
		type: zod_1$18.z.union([actionTypes_1.actionTypesZodSchema, zod_1$18.z.string().min(1)]),
		title: zod_1$18.z.string().min(1),
		image: zod_1$18.z.string().min(1).optional(),
		text: zod_1$18.z.string().min(1).optional(),
		displayText: zod_1$18.z.string().min(1).optional(),
		value: zod_1$18.z.any().optional(),
		channelData: zod_1$18.z.unknown().optional(),
		imageAltText: zod_1$18.z.string().min(1).optional()
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/action/suggestedActions.js
var require_suggestedActions = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.suggestedActionsZodSchema = void 0;
	const zod_1$17 = __require("zod");
	const cardAction_1 = require_cardAction();
	/**
	* Zod schema for validating SuggestedActions.
	*/
	exports.suggestedActionsZodSchema = zod_1$17.z.object({
		to: zod_1$17.z.array(zod_1$17.z.string().min(1)),
		actions: zod_1$17.z.array(cardAction_1.cardActionZodSchema)
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/activityEventNames.js
var require_activityEventNames = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.activityEventNamesZodSchema = exports.ActivityEventNames = void 0;
	const zod_1$16 = __require("zod");
	/**
	* Enum representing activity event names.
	*/
	var ActivityEventNames;
	(function(ActivityEventNames) {
		/**
		* Event name for continuing a conversation.
		*/
		ActivityEventNames["ContinueConversation"] = "ContinueConversation";
		/**
		* Event name for creating a new conversation.
		*/
		ActivityEventNames["CreateConversation"] = "CreateConversation";
	})(ActivityEventNames || (exports.ActivityEventNames = ActivityEventNames = {}));
	/**
	* Zod schema for validating an ActivityEventNames enum.
	*/
	exports.activityEventNamesZodSchema = zod_1$16.z.enum(["ContinueConversation", "CreateConversation"]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/activityImportance.js
var require_activityImportance = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.activityImportanceZodSchema = exports.ActivityImportance = void 0;
	const zod_1$15 = __require("zod");
	/**
	* Enum representing activity importance levels.
	*/
	var ActivityImportance;
	(function(ActivityImportance) {
		/**
		* Indicates low importance.
		*/
		ActivityImportance["Low"] = "low";
		/**
		* Indicates normal importance.
		*/
		ActivityImportance["Normal"] = "normal";
		/**
		* Indicates high importance.
		*/
		ActivityImportance["High"] = "high";
	})(ActivityImportance || (exports.ActivityImportance = ActivityImportance = {}));
	/**
	* Zod schema for validating an ActivityImportance enum.
	*/
	exports.activityImportanceZodSchema = zod_1$15.z.enum([
		"low",
		"normal",
		"high"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/activityTypes.js
var require_activityTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.activityTypesZodSchema = exports.ActivityTypes = void 0;
	const zod_1$14 = __require("zod");
	/**
	* Enum representing activity types.
	*/
	var ActivityTypes;
	(function(ActivityTypes) {
		/**
		* A message activity.
		*/
		ActivityTypes["Message"] = "message";
		/**
		* An update to a contact relationship.
		*/
		ActivityTypes["ContactRelationUpdate"] = "contactRelationUpdate";
		/**
		* An update to a conversation.
		*/
		ActivityTypes["ConversationUpdate"] = "conversationUpdate";
		/**
		* A typing indicator activity.
		*/
		ActivityTypes["Typing"] = "typing";
		/**
		* Indicates the end of a conversation.
		*/
		ActivityTypes["EndOfConversation"] = "endOfConversation";
		/**
		* An event activity.
		*/
		ActivityTypes["Event"] = "event";
		/**
		* An invoke activity.
		*/
		ActivityTypes["Invoke"] = "invoke";
		/**
		* A response to an invoke activity.
		*/
		ActivityTypes["InvokeResponse"] = "invokeResponse";
		/**
		* An activity to delete user data.
		*/
		ActivityTypes["DeleteUserData"] = "deleteUserData";
		/**
		* An update to a message.
		*/
		ActivityTypes["MessageUpdate"] = "messageUpdate";
		/**
		* A deletion of a message.
		*/
		ActivityTypes["MessageDelete"] = "messageDelete";
		/**
		* An update to an installation.
		*/
		ActivityTypes["InstallationUpdate"] = "installationUpdate";
		/**
		* A reaction to a message.
		*/
		ActivityTypes["MessageReaction"] = "messageReaction";
		/**
		* A suggestion activity.
		*/
		ActivityTypes["Suggestion"] = "suggestion";
		/**
		* A trace activity for debugging.
		*/
		ActivityTypes["Trace"] = "trace";
		/**
		* A handoff activity to another bot or human.
		*/
		ActivityTypes["Handoff"] = "handoff";
		/**
		* A command activity.
		*/
		ActivityTypes["Command"] = "command";
		/**
		* A result of a command activity.
		*/
		ActivityTypes["CommandResult"] = "commandResult";
	})(ActivityTypes || (exports.ActivityTypes = ActivityTypes = {}));
	/**
	* Zod schema for validating an ActivityTypes enum.
	*/
	exports.activityTypesZodSchema = zod_1$14.z.enum([
		"message",
		"contactRelationUpdate",
		"conversationUpdate",
		"typing",
		"endOfConversation",
		"event",
		"invoke",
		"invokeResponse",
		"deleteUserData",
		"messageUpdate",
		"messageDelete",
		"installationUpdate",
		"messageReaction",
		"suggestion",
		"trace",
		"handoff",
		"command",
		"commandResult"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/attachment/attachment.js
var require_attachment = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.attachmentZodSchema = void 0;
	const zod_1$13 = __require("zod");
	/**
	* Zod schema for validating attachments.
	*/
	exports.attachmentZodSchema = zod_1$13.z.object({
		contentType: zod_1$13.z.string().min(1),
		contentUrl: zod_1$13.z.string().min(1).optional(),
		content: zod_1$13.z.unknown().optional(),
		name: zod_1$13.z.string().min(1).optional(),
		thumbnailUrl: zod_1$13.z.string().min(1).optional()
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/entity/productInfo.js
var require_productInfo = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.addProductInfoToActivity = exports.clearProductInfoFromActivity = void 0;
	/**
	* Remove any ProductInfo entities from the activity
	* @param activity
	*/
	const clearProductInfoFromActivity = (activity) => {
		if (activity && activity.entities && activity.entities.length) activity.entities = activity.entities.filter((e) => e.type !== "ProductInfo");
	};
	exports.clearProductInfoFromActivity = clearProductInfoFromActivity;
	/**
	* Add a new ProductInfo entity to the activity and ensure only one exists
	* @param activity
	* @param id
	*/
	const addProductInfoToActivity = (activity, id) => {
		var _a, _b;
		const productInfo = {
			type: "ProductInfo",
			id
		};
		(_a = activity.entities) !== null && _a !== void 0 || (activity.entities = []);
		(0, exports.clearProductInfoFromActivity)(activity);
		(_b = activity.entities) === null || _b === void 0 || _b.push(productInfo);
	};
	exports.addProductInfoToActivity = addProductInfoToActivity;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/conversation/channelAccount.js
var require_channelAccount = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.channelAccountZodSchema = void 0;
	const zod_1$12 = __require("zod");
	const roleTypes_1 = require_roleTypes();
	/**
	* Zod schema for validating a channel account.
	*/
	exports.channelAccountZodSchema = zod_1$12.z.object({
		id: zod_1$12.z.string().min(1).optional(),
		name: zod_1$12.z.string().optional(),
		aadObjectId: zod_1$12.z.string().min(1).optional(),
		tenantId: zod_1$12.z.string().min(1).optional(),
		agenticUserId: zod_1$12.z.string().min(1).optional(),
		agenticAppId: zod_1$12.z.string().min(1).optional(),
		agenticAppBlueprintId: zod_1$12.z.string().min(1).optional(),
		role: zod_1$12.z.union([roleTypes_1.roleTypeZodSchema, zod_1$12.z.string().min(1)]).optional(),
		properties: zod_1$12.z.unknown().optional()
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/conversation/conversationAccount.js
var require_conversationAccount = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.conversationAccountZodSchema = void 0;
	const zod_1$11 = __require("zod");
	const roleTypes_1 = require_roleTypes();
	/**
	* Zod schema for validating a conversation account.
	*/
	exports.conversationAccountZodSchema = zod_1$11.z.object({
		isGroup: zod_1$11.z.boolean().optional(),
		conversationType: zod_1$11.z.string().min(1).optional(),
		tenantId: zod_1$11.z.string().min(1).optional(),
		id: zod_1$11.z.string().min(1),
		name: zod_1$11.z.string().min(1).optional(),
		aadObjectId: zod_1$11.z.string().min(1).optional(),
		role: zod_1$11.z.union([roleTypes_1.roleTypeZodSchema, zod_1$11.z.string().min(1)]).optional(),
		properties: zod_1$11.z.unknown().optional()
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/conversation/conversationReference.js
var require_conversationReference = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.conversationReferenceZodSchema = void 0;
	const zod_1$10 = __require("zod");
	const channelAccount_1 = require_channelAccount();
	const conversationAccount_1 = require_conversationAccount();
	/**
	* Zod schema for validating a conversation reference.
	*/
	exports.conversationReferenceZodSchema = zod_1$10.z.object({
		activityId: zod_1$10.z.string().min(1).optional(),
		user: channelAccount_1.channelAccountZodSchema.optional(),
		locale: zod_1$10.z.string().min(1).optional(),
		agent: channelAccount_1.channelAccountZodSchema.optional().nullable(),
		conversation: conversationAccount_1.conversationAccountZodSchema,
		channelId: zod_1$10.z.string().min(1),
		serviceUrl: zod_1$10.z.string().min(1).optional()
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/deliveryModes.js
var require_deliveryModes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.deliveryModesZodSchema = exports.DeliveryModes = void 0;
	const zod_1$9 = __require("zod");
	/**
	* Enum representing delivery modes.
	*/
	var DeliveryModes;
	(function(DeliveryModes) {
		/**
		* Represents the normal delivery mode.
		*/
		DeliveryModes["Normal"] = "normal";
		/**
		* Represents a notification delivery mode.
		*/
		DeliveryModes["Notification"] = "notification";
		/**
		* Represents a delivery mode where replies are expected.
		*/
		DeliveryModes["ExpectReplies"] = "expectReplies";
		/**
		* Represents an ephemeral delivery mode.
		*/
		DeliveryModes["Ephemeral"] = "ephemeral";
	})(DeliveryModes || (exports.DeliveryModes = DeliveryModes = {}));
	/**
	* Zod schema for validating a DeliveryModes enum.
	*/
	exports.deliveryModesZodSchema = zod_1$9.z.enum([
		"normal",
		"notification",
		"expectReplies",
		"ephemeral"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/inputHints.js
var require_inputHints = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.inputHintsZodSchema = exports.InputHints = void 0;
	const zod_1$8 = __require("zod");
	/**
	* Enum representing input hints.
	*/
	var InputHints;
	(function(InputHints) {
		/**
		* Indicates that the bot is ready to accept input from the user.
		*/
		InputHints["AcceptingInput"] = "acceptingInput";
		/**
		* Indicates that the bot is ignoring input from the user.
		*/
		InputHints["IgnoringInput"] = "ignoringInput";
		/**
		* Indicates that the bot is expecting input from the user.
		*/
		InputHints["ExpectingInput"] = "expectingInput";
	})(InputHints || (exports.InputHints = InputHints = {}));
	/**
	* Zod schema for validating an InputHints enum.
	*/
	exports.inputHintsZodSchema = zod_1$8.z.enum([
		"acceptingInput",
		"ignoringInput",
		"expectingInput"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/messageReactionTypes.js
var require_messageReactionTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.messageReactionTypesZodSchema = exports.MessageReactionTypes = void 0;
	const zod_1$7 = __require("zod");
	/**
	* Enum representing message reaction types.
	*/
	var MessageReactionTypes;
	(function(MessageReactionTypes) {
		/**
		* Represents a 'like' reaction to a message.
		*/
		MessageReactionTypes["Like"] = "like";
		/**
		* Represents a '+1' reaction to a message.
		*/
		MessageReactionTypes["PlusOne"] = "plusOne";
	})(MessageReactionTypes || (exports.MessageReactionTypes = MessageReactionTypes = {}));
	/**
	* Zod schema for validating MessageReactionTypes enum values.
	*/
	exports.messageReactionTypesZodSchema = zod_1$7.z.enum(["like", "plusOne"]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/messageReaction.js
var require_messageReaction = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.messageReactionZodSchema = void 0;
	const zod_1$6 = __require("zod");
	const messageReactionTypes_1 = require_messageReactionTypes();
	/**
	* Zod schema for validating a MessageReaction object.
	*/
	exports.messageReactionZodSchema = zod_1$6.z.object({ type: zod_1$6.z.union([messageReactionTypes_1.messageReactionTypesZodSchema, zod_1$6.z.string().min(1)]) });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/textFormatTypes.js
var require_textFormatTypes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.textFormatTypesZodSchema = exports.TextFormatTypes = void 0;
	const zod_1$5 = __require("zod");
	/**
	* Enum representing text format types.
	*/
	var TextFormatTypes;
	(function(TextFormatTypes) {
		/**
		* Represents text formatted using Markdown.
		*/
		TextFormatTypes["Markdown"] = "markdown";
		/**
		* Represents plain text without any formatting.
		*/
		TextFormatTypes["Plain"] = "plain";
		/**
		* Represents text formatted using XML.
		*/
		TextFormatTypes["Xml"] = "xml";
	})(TextFormatTypes || (exports.TextFormatTypes = TextFormatTypes = {}));
	/**
	* Zod schema for validating TextFormatTypes enum values.
	*/
	exports.textFormatTypesZodSchema = zod_1$5.z.enum([
		"markdown",
		"plain",
		"xml"
	]);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/textHighlight.js
var require_textHighlight = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.textHighlightZodSchema = void 0;
	const zod_1$4 = __require("zod");
	/**
	* Zod schema for validating TextHighlight objects.
	*/
	exports.textHighlightZodSchema = zod_1$4.z.object({
		text: zod_1$4.z.string().min(1),
		occurrence: zod_1$4.z.number()
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/exceptionHelper.js
var require_exceptionHelper = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ExceptionHelper = void 0;
	/**
	* Helper class for generating exceptions with error codes.
	*/
	var ExceptionHelper = class ExceptionHelper {
		/**
		* Generates a typed exception with error code and help link.
		* The message format is: [CODE] - [message] - [helplink]
		* @param ErrorType The constructor of the error type to create
		* @param errorDefinition The error definition containing code, description, and optional help link
		* @param innerException Optional inner exception
		* @param params Optional parameters object for message formatting with key-value pairs
		* @returns A new exception instance with error code and help link, typed as AgentError
		*/
		static generateException(ErrorType, errorDefinition, innerException, params) {
			var _a;
			let description = errorDefinition.description;
			if (params) Object.keys(params).forEach((key) => {
				description = description.replace(`{${key}}`, params[key]);
			});
			const helplink = ((_a = errorDefinition.helplink) !== null && _a !== void 0 ? _a : ExceptionHelper.DEFAULT_HELPLINK).replace("{errorCode}", errorDefinition.code.toString());
			const exception = new ErrorType(`[${errorDefinition.code}] - ${description} - ${helplink}`);
			exception.code = errorDefinition.code;
			exception.helpLink = helplink;
			if (innerException) exception.innerException = innerException;
			return exception;
		}
	};
	exports.ExceptionHelper = ExceptionHelper;
	/**
	* Default help link template for error codes.
	* The {errorCode} token will be replaced with the actual error code.
	*/
	ExceptionHelper.DEFAULT_HELPLINK = "https://aka.ms/M365AgentsErrorCodesJS/#{errorCode}";
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/errorHelper.js
var require_errorHelper$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.Errors = void 0;
	/**
	* Error definitions for the Activity system.
	* This contains localized error codes for the Activity subsystem of the AgentSDK.
	*
	* Each error definition includes an error code (starting from -110000), a description, and a help link
	* pointing to an AKA link to get help for the given error.
	*
	* Usage example:
	* ```
	* throw ExceptionHelper.generateException(
	*   Error,
	*   Errors.InvalidActivityTypeUndefined
	* );
	* ```
	*/
	exports.Errors = {
		InvalidActivityTypeUndefined: {
			code: -11e4,
			description: "Invalid ActivityType: undefined"
		},
		InvalidActivityTypeNull: {
			code: -110001,
			description: "Invalid ActivityType: null"
		},
		InvalidActivityTypeEmptyString: {
			code: -110002,
			description: "Invalid ActivityType: empty string"
		},
		InvalidChannelIdFormat: {
			code: -110003,
			description: "Invalid channelId {channelId}. Found subChannel but no main channel."
		},
		PrimaryChannelNotSet: {
			code: -110004,
			description: "Primary channel must be set before setting subChannel"
		},
		ActivityRecipientUndefined: {
			code: -110005,
			description: "Activity Recipient undefined"
		},
		ActivityConversationUndefined: {
			code: -110006,
			description: "Activity Conversation undefined"
		},
		ActivityChannelIdUndefined: {
			code: -110007,
			description: "Activity ChannelId undefined"
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/activity.js
var require_activity = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.Activity = exports.activityZodSchema = void 0;
	const uuid_1$2 = __require("uuid");
	const zod_1$3 = __require("zod");
	const semanticAction_1 = require_semanticAction();
	const suggestedActions_1 = require_suggestedActions();
	const activityEventNames_1 = require_activityEventNames();
	const activityImportance_1 = require_activityImportance();
	const activityTypes_1 = require_activityTypes();
	const attachment_1 = require_attachment();
	const attachmentLayoutTypes_1 = require_attachmentLayoutTypes();
	const productInfo_1 = require_productInfo();
	const channelAccount_1 = require_channelAccount();
	const channels_1 = require_channels();
	const conversationAccount_1 = require_conversationAccount();
	const conversationReference_1 = require_conversationReference();
	const endOfConversationCodes_1 = require_endOfConversationCodes();
	const deliveryModes_1 = require_deliveryModes();
	const entity_1 = require_entity();
	const inputHints_1 = require_inputHints();
	const messageReaction_1 = require_messageReaction();
	const textFormatTypes_1 = require_textFormatTypes();
	const textHighlight_1 = require_textHighlight();
	const roleTypes_1 = require_roleTypes();
	const exceptionHelper_1 = require_exceptionHelper();
	const errorHelper_1 = require_errorHelper$1();
	/**
	* Zod schema for validating an Activity object.
	*/
	exports.activityZodSchema = zod_1$3.z.object({
		type: zod_1$3.z.union([activityTypes_1.activityTypesZodSchema, zod_1$3.z.string().min(1)]),
		text: zod_1$3.z.string().optional(),
		id: zod_1$3.z.string().min(1).optional(),
		channelId: zod_1$3.z.string().min(1).optional(),
		from: channelAccount_1.channelAccountZodSchema.optional(),
		timestamp: zod_1$3.z.union([zod_1$3.z.date(), zod_1$3.z.string().min(1).transform((s) => new Date(s))]).optional(),
		localTimestamp: zod_1$3.z.union([zod_1$3.z.date(), zod_1$3.z.string().min(1).transform((s) => new Date(s))]).optional(),
		localTimezone: zod_1$3.z.string().min(1).optional(),
		callerId: zod_1$3.z.string().min(1).optional(),
		serviceUrl: zod_1$3.z.string().min(1).optional(),
		conversation: conversationAccount_1.conversationAccountZodSchema.optional(),
		recipient: channelAccount_1.channelAccountZodSchema.optional(),
		textFormat: zod_1$3.z.union([textFormatTypes_1.textFormatTypesZodSchema, zod_1$3.z.string().min(1)]).optional(),
		attachmentLayout: zod_1$3.z.union([attachmentLayoutTypes_1.attachmentLayoutTypesZodSchema, zod_1$3.z.string().min(1)]).optional(),
		membersAdded: zod_1$3.z.array(channelAccount_1.channelAccountZodSchema).optional(),
		membersRemoved: zod_1$3.z.array(channelAccount_1.channelAccountZodSchema).optional(),
		reactionsAdded: zod_1$3.z.array(messageReaction_1.messageReactionZodSchema).optional(),
		reactionsRemoved: zod_1$3.z.array(messageReaction_1.messageReactionZodSchema).optional(),
		topicName: zod_1$3.z.string().min(1).optional(),
		historyDisclosed: zod_1$3.z.boolean().optional(),
		locale: zod_1$3.z.string().min(1).optional(),
		speak: zod_1$3.z.string().min(1).optional(),
		inputHint: zod_1$3.z.union([inputHints_1.inputHintsZodSchema, zod_1$3.z.string().min(1)]).optional(),
		summary: zod_1$3.z.string().min(1).optional(),
		suggestedActions: suggestedActions_1.suggestedActionsZodSchema.optional(),
		attachments: zod_1$3.z.array(attachment_1.attachmentZodSchema).optional(),
		entities: zod_1$3.z.array(entity_1.entityZodSchema.passthrough()).optional(),
		channelData: zod_1$3.z.any().optional(),
		action: zod_1$3.z.string().min(1).optional(),
		replyToId: zod_1$3.z.string().min(1).optional(),
		label: zod_1$3.z.string().min(1).optional(),
		valueType: zod_1$3.z.string().min(1).optional(),
		value: zod_1$3.z.unknown().optional(),
		name: zod_1$3.z.union([activityEventNames_1.activityEventNamesZodSchema, zod_1$3.z.string().min(1)]).optional(),
		relatesTo: conversationReference_1.conversationReferenceZodSchema.optional(),
		code: zod_1$3.z.union([endOfConversationCodes_1.endOfConversationCodesZodSchema, zod_1$3.z.string().min(1)]).optional(),
		expiration: zod_1$3.z.union([zod_1$3.z.date(), zod_1$3.z.string().min(1).transform((s) => new Date(s))]).optional(),
		importance: zod_1$3.z.union([activityImportance_1.activityImportanceZodSchema, zod_1$3.z.string().min(1)]).optional(),
		deliveryMode: zod_1$3.z.union([deliveryModes_1.deliveryModesZodSchema, zod_1$3.z.string().min(1)]).optional(),
		listenFor: zod_1$3.z.array(zod_1$3.z.string().min(1)).optional(),
		textHighlights: zod_1$3.z.array(textHighlight_1.textHighlightZodSchema).optional(),
		semanticAction: semanticAction_1.semanticActionZodSchema.optional()
	});
	exports.Activity = class Activity {
		/**
		* Creates a new Activity instance.
		* @param t The type of the activity.
		* @throws Will throw an error if the activity type is invalid.
		*/
		constructor(t) {
			if (t === void 0) throw exceptionHelper_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.InvalidActivityTypeUndefined);
			if (t === null) throw exceptionHelper_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.InvalidActivityTypeNull);
			if (typeof t === "string" && t.length === 0) throw exceptionHelper_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.InvalidActivityTypeEmptyString);
			this.type = t;
		}
		/**
		* Creates an Activity instance from a JSON string.
		* @param json The JSON string representing the activity.
		* @returns The created Activity instance.
		*/
		static fromJson(json) {
			return this.fromObject(JSON.parse(json));
		}
		/**
		* Creates an Activity instance from an object.
		* @param o The object representing the activity.
		* @returns The created Activity instance.
		*/
		static fromObject(o) {
			const parsedActivity = exports.activityZodSchema.passthrough().parse(o);
			const activity = new Activity(parsedActivity.type);
			Object.assign(activity, parsedActivity);
			return activity;
		}
		/**
		* Return the combined channel:subChannel value like agent:email
		*/
		get channelId() {
			var _a;
			return (_a = this._channelId) === null || _a === void 0 ? void 0 : _a.concat(this.channelIdSubChannel ? `:${this.channelIdSubChannel}` : "");
		}
		/**
		* Given a composite channelId like agent:email, return the channel and subChannel.
		* @param value
		* @returns [channel, subChannel]
		*/
		static parseChannelId(value) {
			let channel;
			let subChannel;
			if (value && value.indexOf(":") !== -1) {
				channel = value.substring(0, value.indexOf(":"));
				subChannel = value.substring(value.indexOf(":") + 1);
			} else channel = value;
			return [channel, subChannel];
		}
		/**
		* Sets the channel ID for the activity - if a subChannel is provided, will create the necessary ProductInfo entity
		* @param value The channel ID value.
		*/
		set channelId(value) {
			const [channel, subChannel] = Activity.parseChannelId(value);
			if (value && !channel) throw exceptionHelper_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.InvalidChannelIdFormat, void 0, { channelId: value });
			this._channelId = channel;
			if (subChannel) (0, productInfo_1.addProductInfoToActivity)(this, subChannel);
			else (0, productInfo_1.clearProductInfoFromActivity)(this);
		}
		/**
		* Sets the primary channel ID for the activity.
		*/
		set channelIdChannel(value) {
			this._channelId = value;
		}
		/**
		* Returns the primary channel ID for the activity.
		*/
		get channelIdChannel() {
			return this._channelId;
		}
		/**
		* Returns the sub-channel ID for the activity.
		*/
		get channelIdSubChannel() {
			var _a, _b;
			return (_b = (_a = this.entities) === null || _a === void 0 ? void 0 : _a.find((e) => e.type === "ProductInfo")) === null || _b === void 0 ? void 0 : _b.id;
		}
		/**
		* Sets the sub-channel ID for the activity.
		*/
		set channelIdSubChannel(value) {
			if (!this._channelId) throw exceptionHelper_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.PrimaryChannelNotSet);
			this.channelId = `${this._channelId}${value ? `:${value}` : ""}`;
		}
		/**
		* Creates a continuation activity from a conversation reference.
		* @param reference The conversation reference.
		* @returns The created continuation activity.
		*/
		static getContinuationActivity(reference) {
			var _a;
			const continuationActivityObj = {
				type: activityTypes_1.ActivityTypes.Event,
				name: activityEventNames_1.ActivityEventNames.ContinueConversation,
				id: (_a = reference.activityId) !== null && _a !== void 0 ? _a : (0, uuid_1$2.v4)(),
				channelId: reference.channelId,
				locale: reference.locale,
				serviceUrl: reference.serviceUrl,
				conversation: reference.conversation,
				recipient: reference.agent,
				from: reference.user,
				relatesTo: reference
			};
			return Activity.fromObject(continuationActivityObj);
		}
		/**
		* Gets the appropriate reply-to ID for the activity.
		* @returns The reply-to ID, or undefined if not applicable.
		*/
		getAppropriateReplyToId() {
			if (this.type !== activityTypes_1.ActivityTypes.ConversationUpdate || this.channelId !== channels_1.Channels.Directline && this.channelId !== channels_1.Channels.Webchat) return this.id;
		}
		/**
		* Gets the conversation reference for the activity.
		* @returns The conversation reference.
		* @throws Will throw an error if required properties are undefined.
		*/
		getConversationReference() {
			if (this.recipient === null || this.recipient === void 0) throw exceptionHelper_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ActivityRecipientUndefined);
			if (this.conversation === null || this.conversation === void 0) throw exceptionHelper_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ActivityConversationUndefined);
			if (this.channelId === null || this.channelId === void 0) throw exceptionHelper_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ActivityChannelIdUndefined);
			return {
				activityId: this.getAppropriateReplyToId(),
				user: this.from,
				agent: this.recipient,
				conversation: this.conversation,
				channelId: this.channelId,
				locale: this.locale,
				serviceUrl: this.serviceUrl
			};
		}
		/**
		* Applies a conversation reference to the activity.
		* @param reference The conversation reference.
		* @param isIncoming Whether the activity is incoming.
		* @returns The updated activity.
		*/
		applyConversationReference(reference, isIncoming = false) {
			var _a, _b, _c;
			this.channelId = reference.channelId;
			(_a = this.locale) !== null && _a !== void 0 || (this.locale = reference.locale);
			this.serviceUrl = reference.serviceUrl;
			this.conversation = reference.conversation;
			if (isIncoming) {
				this.from = reference.user;
				this.recipient = (_b = reference.agent) !== null && _b !== void 0 ? _b : void 0;
				if (reference.activityId) this.id = reference.activityId;
			} else {
				this.from = (_c = reference.agent) !== null && _c !== void 0 ? _c : void 0;
				this.recipient = reference.user;
				if (reference.activityId) this.replyToId = reference.activityId;
			}
			return this;
		}
		clone() {
			const activityCopy = JSON.parse(JSON.stringify(this));
			for (const key in activityCopy) if (typeof activityCopy[key] === "string" && !isNaN(Date.parse(activityCopy[key]))) activityCopy[key] = new Date(activityCopy[key]);
			Object.setPrototypeOf(activityCopy, Activity.prototype);
			return activityCopy;
		}
		/**
		* Gets the mentions in the activity.
		* @param activity The activity.
		* @returns The list of mentions.
		*/
		getMentions(activity) {
			const result = [];
			if (activity.entities !== void 0) {
				for (let i = 0; i < activity.entities.length; i++) if (activity.entities[i].type.toLowerCase() === "mention") result.push(activity.entities[i]);
			}
			return result;
		}
		/**
		* Normalizes mentions in the activity by removing mention tags and optionally removing recipient mention.
		* @param removeMention Whether to remove the recipient mention from the activity.
		*/
		normalizeMentions(removeMention = false) {
			var _a, _b;
			if (this.type === activityTypes_1.ActivityTypes.Message) {
				if (removeMention) {
					this.removeRecipientMention();
					if (this.entities !== void 0 && ((_a = this.recipient) === null || _a === void 0 ? void 0 : _a.id)) this.entities = this.entities.filter((entity) => {
						var _a;
						if (entity.type.toLowerCase() === "mention") return entity.mentioned.id !== ((_a = this.recipient) === null || _a === void 0 ? void 0 : _a.id);
						return true;
					});
				}
				if (this.text) this.text = Activity.removeAt(this.text);
				if (this.entities !== void 0) {
					const mentions = this.getMentions(this);
					for (const mention of mentions) if (mention.text) mention.text = (_b = Activity.removeAt(mention.text)) === null || _b === void 0 ? void 0 : _b.trim();
				}
			}
		}
		/**
		* Removes <at> </at> tags from the specified text.
		* @param text The text to process.
		* @returns The text with <at> </at> tags removed.
		*/
		static removeAt(text) {
			if (!text) return text;
			let foundTag;
			do {
				foundTag = false;
				const iAtStart = text.toLowerCase().indexOf("<at");
				if (iAtStart >= 0) {
					const iAtEnd = text.indexOf(">", iAtStart);
					if (iAtEnd > 0) {
						const iAtClose = text.toLowerCase().indexOf("</at>", iAtEnd);
						if (iAtClose > 0) {
							let followingText = text.substring(iAtClose + 5);
							if (followingText.length > 0 && !/\s/.test(followingText[0])) followingText = ` ${followingText}`;
							text = text.substring(0, iAtClose) + followingText;
							const tagContent = text.substring(iAtEnd + 1, iAtClose);
							let prefixText = text.substring(0, iAtStart);
							if (prefixText.length > 0 && !/\s$/.test(prefixText)) prefixText += " ";
							text = prefixText + tagContent + followingText;
							foundTag = true;
						}
					}
				}
			} while (foundTag);
			return text;
		}
		/**
		* Removes the mention text for a given ID.
		* @param id The ID of the mention to remove.
		* @returns The updated text.
		*/
		removeMentionText(id) {
			const mentionsFiltered = this.getMentions(this).filter((mention) => mention.mentioned.id === id);
			if (mentionsFiltered.length > 0 && this.text) this.text = this.text.replace(mentionsFiltered[0].text, "").trim();
			return this.text || "";
		}
		/**
		* Removes the recipient mention from the activity text.
		* @returns The updated text.
		*/
		removeRecipientMention() {
			if (this.recipient != null && this.recipient.id) return this.removeMentionText(this.recipient.id);
			return "";
		}
		/**
		* Gets the conversation reference for a reply.
		* @param replyId The ID of the reply.
		* @returns The conversation reference.
		*/
		getReplyConversationReference(replyId) {
			const reference = this.getConversationReference();
			reference.activityId = replyId;
			return reference;
		}
		/**
		* Converts the activity to a JSON string.
		* @param replacer A function that transforms the results.
		* @param space Adds indentation, white space, and line break characters to the return-value JSON text.
		* @returns The JSON string representation of the activity.
		*/
		toJsonString(replacer, space) {
			const copy = { ...this };
			copy.channelId = copy._channelId;
			delete copy._channelId;
			return JSON.stringify(copy, replacer, space);
		}
		/**
		* Does this activity represent an agentic request?
		* @returns True if agentic
		*/
		isAgenticRequest() {
			if (!this.recipient || !this.recipient.role) return false;
			return this.recipient.role.toLowerCase() === roleTypes_1.RoleTypes.AgenticUser.toLowerCase() || this.recipient.role.toLowerCase() === roleTypes_1.RoleTypes.AgenticIdentity.toLowerCase();
		}
		/**
		* Retrieves the tenant ID associated with the agentic recipient of the activity, if available; otherwise, returns the tenant ID from the conversation.
		* @returns The tenant ID of the agentic recipient if present; otherwise, the tenant ID from the conversation. Returns undefined if neither is available.
		*/
		getAgenticTenantId() {
			var _a, _b, _c;
			return (_b = (_a = this.recipient) === null || _a === void 0 ? void 0 : _a.tenantId) !== null && _b !== void 0 ? _b : (_c = this.conversation) === null || _c === void 0 ? void 0 : _c.tenantId;
		}
		/**
		* Gets the agent instance ID from the context if its agentic
		* @returns agent instance id as string
		*/
		getAgenticInstanceId() {
			var _a;
			if (this.isAgenticRequest()) return (_a = this.recipient) === null || _a === void 0 ? void 0 : _a.agenticAppId;
		}
		/**
		* Gets the agentic user (UPN) from the context if it's an agentic request.
		*/
		getAgenticUser() {
			var _a;
			if (this.isAgenticRequest()) return (_a = this.recipient) === null || _a === void 0 ? void 0 : _a.agenticUserId;
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/activityTreatments.js
var require_activityTreatments = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ActivityTreatments = void 0;
	/**
	* Enum representing treatment types for the activity.
	*/
	var ActivityTreatments;
	(function(ActivityTreatments) {
		/**
		* Indicates that only the recipient should be able to see the message even if the activity
		* is being sent to a group of people.
		*/
		ActivityTreatments["Targeted"] = "targeted";
	})(ActivityTreatments || (exports.ActivityTreatments = ActivityTreatments = {}));
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-activity@1.3.1/node_modules/@microsoft/agents-activity/dist/src/index.js
var require_src$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$15) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$15, p)) __createBinding(exports$15, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ActivityErrors = exports.ExceptionHelper = exports.Logger = exports.debug = exports.ActivityTreatments = exports.TextFormatTypes = exports.MessageReactionTypes = exports.InputHints = exports.DeliveryModes = exports.ActivityTypes = exports.ActivityImportance = exports.ActivityEventNames = exports.activityZodSchema = exports.Activity = exports.RoleTypes = exports.MembershipTypes = exports.MembershipSourceTypes = exports.EndOfConversationCodes = exports.Channels = exports.AttachmentLayoutTypes = exports.SemanticActionStateTypes = exports.ActionTypes = void 0;
	/**
	* Export statements for various modules.
	*/
	var actionTypes_1 = require_actionTypes();
	Object.defineProperty(exports, "ActionTypes", {
		enumerable: true,
		get: function() {
			return actionTypes_1.ActionTypes;
		}
	});
	var semanticActionStateTypes_1 = require_semanticActionStateTypes();
	Object.defineProperty(exports, "SemanticActionStateTypes", {
		enumerable: true,
		get: function() {
			return semanticActionStateTypes_1.SemanticActionStateTypes;
		}
	});
	var attachmentLayoutTypes_1 = require_attachmentLayoutTypes();
	Object.defineProperty(exports, "AttachmentLayoutTypes", {
		enumerable: true,
		get: function() {
			return attachmentLayoutTypes_1.AttachmentLayoutTypes;
		}
	});
	var channels_1 = require_channels();
	Object.defineProperty(exports, "Channels", {
		enumerable: true,
		get: function() {
			return channels_1.Channels;
		}
	});
	var endOfConversationCodes_1 = require_endOfConversationCodes();
	Object.defineProperty(exports, "EndOfConversationCodes", {
		enumerable: true,
		get: function() {
			return endOfConversationCodes_1.EndOfConversationCodes;
		}
	});
	var membershipSourceTypes_1 = require_membershipSourceTypes();
	Object.defineProperty(exports, "MembershipSourceTypes", {
		enumerable: true,
		get: function() {
			return membershipSourceTypes_1.MembershipSourceTypes;
		}
	});
	var membershipTypes_1 = require_membershipTypes();
	Object.defineProperty(exports, "MembershipTypes", {
		enumerable: true,
		get: function() {
			return membershipTypes_1.MembershipTypes;
		}
	});
	var roleTypes_1 = require_roleTypes();
	Object.defineProperty(exports, "RoleTypes", {
		enumerable: true,
		get: function() {
			return roleTypes_1.RoleTypes;
		}
	});
	__exportStar(require_AIEntity(), exports);
	__exportStar(require_adaptiveCardInvokeAction(), exports);
	var activity_1 = require_activity();
	Object.defineProperty(exports, "Activity", {
		enumerable: true,
		get: function() {
			return activity_1.Activity;
		}
	});
	Object.defineProperty(exports, "activityZodSchema", {
		enumerable: true,
		get: function() {
			return activity_1.activityZodSchema;
		}
	});
	var activityEventNames_1 = require_activityEventNames();
	Object.defineProperty(exports, "ActivityEventNames", {
		enumerable: true,
		get: function() {
			return activityEventNames_1.ActivityEventNames;
		}
	});
	var activityImportance_1 = require_activityImportance();
	Object.defineProperty(exports, "ActivityImportance", {
		enumerable: true,
		get: function() {
			return activityImportance_1.ActivityImportance;
		}
	});
	var activityTypes_1 = require_activityTypes();
	Object.defineProperty(exports, "ActivityTypes", {
		enumerable: true,
		get: function() {
			return activityTypes_1.ActivityTypes;
		}
	});
	var deliveryModes_1 = require_deliveryModes();
	Object.defineProperty(exports, "DeliveryModes", {
		enumerable: true,
		get: function() {
			return deliveryModes_1.DeliveryModes;
		}
	});
	var inputHints_1 = require_inputHints();
	Object.defineProperty(exports, "InputHints", {
		enumerable: true,
		get: function() {
			return inputHints_1.InputHints;
		}
	});
	var messageReactionTypes_1 = require_messageReactionTypes();
	Object.defineProperty(exports, "MessageReactionTypes", {
		enumerable: true,
		get: function() {
			return messageReactionTypes_1.MessageReactionTypes;
		}
	});
	var textFormatTypes_1 = require_textFormatTypes();
	Object.defineProperty(exports, "TextFormatTypes", {
		enumerable: true,
		get: function() {
			return textFormatTypes_1.TextFormatTypes;
		}
	});
	var activityTreatments_1 = require_activityTreatments();
	Object.defineProperty(exports, "ActivityTreatments", {
		enumerable: true,
		get: function() {
			return activityTreatments_1.ActivityTreatments;
		}
	});
	var logger_1 = require_logger();
	Object.defineProperty(exports, "debug", {
		enumerable: true,
		get: function() {
			return logger_1.debug;
		}
	});
	Object.defineProperty(exports, "Logger", {
		enumerable: true,
		get: function() {
			return logger_1.Logger;
		}
	});
	var exceptionHelper_1 = require_exceptionHelper();
	Object.defineProperty(exports, "ExceptionHelper", {
		enumerable: true,
		get: function() {
			return exceptionHelper_1.ExceptionHelper;
		}
	});
	var errorHelper_1 = require_errorHelper$1();
	Object.defineProperty(exports, "ActivityErrors", {
		enumerable: true,
		get: function() {
			return errorHelper_1.Errors;
		}
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/msalConnectionManager.js
var require_msalConnectionManager = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MsalConnectionManager = void 0;
	const agents_activity_1 = require_src$2();
	const msalTokenProvider_1 = require_msalTokenProvider();
	var MsalConnectionManager = class MsalConnectionManager {
		constructor(connectionsConfigurations = /* @__PURE__ */ new Map(), connectionsMap = [], configuration = {}) {
			this._connections = /* @__PURE__ */ new Map();
			this._connectionsMap = connectionsMap.length > 0 ? connectionsMap : configuration.connectionsMap || [];
			this._serviceConnectionConfiguration = {};
			const providedConnections = connectionsConfigurations.size > 0 ? connectionsConfigurations : configuration.connections || /* @__PURE__ */ new Map();
			for (const [name, config] of providedConnections) {
				this._connections.set(name, new msalTokenProvider_1.MsalTokenProvider(config));
				if (name === MsalConnectionManager.DEFAULT_CONNECTION) this._serviceConnectionConfiguration = config;
			}
		}
		/**
		* Get the OAuth connection for the agent.
		* @param connectionName The name of the connection.
		* @returns The OAuth connection for the agent.
		*/
		getConnection(connectionName) {
			const conn = this._connections.get(connectionName);
			if (!conn) throw new Error(`Connection not found: ${connectionName}`);
			return this.applyConnectionDefaults(conn);
		}
		/**
		* Get the default OAuth connection for the agent.
		* @returns The default OAuth connection for the agent.
		*/
		getDefaultConnection() {
			if (this._connections.size === 0) throw new Error("No connections found for this Agent in the Connections Configuration.");
			for (const item of this._connectionsMap) if (item.serviceUrl === "*" && !item.audience) return this.getConnection(item.connection);
			const conn = this._connections.values().next().value;
			return this.applyConnectionDefaults(conn);
		}
		/**
		* Finds a connection based on a map.
		*
		* @param identity - The identity.  Usually TurnContext.identity.
		* @param serviceUrl The service URL.
		* @returns The TokenProvider for the connection.
		*
		* @remarks
		* Example environment variables:
		* connectionsMap__0__connection=seviceConnection
		* connectionsMap__0__serviceUrl=http://*..botframework.com/*
		* connectionsMap__0__audience=optional
		* connectionsMap__1__connection=agentic
		* connectionsMap__1__serviceUrl=agentic
		*
		* ServiceUrl is:  A regex to match with, or "*" for any serviceUrl value.
		* Connection is: A name in the 'Connections' list.
		*/
		getTokenProvider(identity, serviceUrl) {
			if (!identity) throw new Error("Identity is required to get the token provider.");
			let audience;
			if (Array.isArray(identity === null || identity === void 0 ? void 0 : identity.aud)) audience = identity.aud[0];
			else audience = identity.aud;
			if (!audience || !serviceUrl) throw new Error("Audience and Service URL are required to get the token provider.");
			if (this._connectionsMap.length === 0) return this.getDefaultConnection();
			for (const item of this._connectionsMap) {
				let audienceMatch = true;
				if (item.audience && audience) audienceMatch = item.audience === audience;
				if (audienceMatch) {
					if (item.serviceUrl === "*" || !item.serviceUrl) return this.getConnection(item.connection);
					if (new RegExp(item.serviceUrl, "i").test(serviceUrl)) return this.getConnection(item.connection);
				}
			}
			throw new Error(`No connection found for audience: ${audience} and serviceUrl: ${serviceUrl}`);
		}
		/**
		* Finds a connection based on an activity's blueprint.
		* @param identity - The identity.  Usually TurnContext.identity.
		* @param activity The activity.
		* @returns The TokenProvider for the connection.
		*/
		getTokenProviderFromActivity(identity, activity) {
			var _a, _b, _c, _d;
			let connection = this.getTokenProvider(identity, activity.serviceUrl || "");
			if (connection && (((_a = activity.recipient) === null || _a === void 0 ? void 0 : _a.role) === agents_activity_1.RoleTypes.AgenticIdentity || ((_b = activity.recipient) === null || _b === void 0 ? void 0 : _b.role) === agents_activity_1.RoleTypes.AgenticUser)) {
				if (((_c = connection.connectionSettings) === null || _c === void 0 ? void 0 : _c.altBlueprintConnectionName) && connection.connectionSettings.altBlueprintConnectionName.trim() !== "") connection = this.getConnection((_d = connection.connectionSettings) === null || _d === void 0 ? void 0 : _d.altBlueprintConnectionName);
			}
			return connection;
		}
		/**
		* Get the default connection configuration for the agent.
		* @returns The default connection configuration for the agent.
		*/
		getDefaultConnectionConfiguration() {
			return this._serviceConnectionConfiguration;
		}
		applyConnectionDefaults(conn) {
			var _a, _b;
			var _c, _d;
			if (conn.connectionSettings) {
				(_a = (_c = conn.connectionSettings).authority) !== null && _a !== void 0 || (_c.authority = "https://login.microsoftonline.com");
				(_b = (_d = conn.connectionSettings).issuers) !== null && _b !== void 0 || (_d.issuers = [
					"https://api.botframework.com",
					`https://sts.windows.net/${conn.connectionSettings.tenantId}/`,
					`${conn.connectionSettings.authority}/${conn.connectionSettings.tenantId}/v2.0`
				]);
			}
			return conn;
		}
	};
	exports.MsalConnectionManager = MsalConnectionManager;
	MsalConnectionManager.DEFAULT_CONNECTION = "serviceConnection";
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/index.js
var require_auth$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$14) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$14, p)) __createBinding(exports$14, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_authConfiguration(), exports);
	__exportStar(require_authConstants(), exports);
	__exportStar(require_authProvider(), exports);
	__exportStar(require_msalTokenProvider(), exports);
	__exportStar(require_request$1(), exports);
	__exportStar(require_msalTokenCredential(), exports);
	__exportStar(require_msalConnectionManager(), exports);
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/digest.js
var require_digest = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$17 = __require("crypto");
	const digest = (algorithm, data) => (0, crypto_1$17.createHash)(algorithm).update(data).digest();
	exports.default = digest;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/buffer_utils.js
var require_buffer_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.concatKdf = exports.lengthAndInput = exports.uint32be = exports.uint64be = exports.p2s = exports.concat = exports.decoder = exports.encoder = void 0;
	const digest_js_1 = require_digest();
	exports.encoder = new TextEncoder();
	exports.decoder = new TextDecoder();
	const MAX_INT32 = 2 ** 32;
	function concat(...buffers) {
		const size = buffers.reduce((acc, { length }) => acc + length, 0);
		const buf = new Uint8Array(size);
		let i = 0;
		buffers.forEach((buffer) => {
			buf.set(buffer, i);
			i += buffer.length;
		});
		return buf;
	}
	exports.concat = concat;
	function p2s(alg, p2sInput) {
		return concat(exports.encoder.encode(alg), new Uint8Array([0]), p2sInput);
	}
	exports.p2s = p2s;
	function writeUInt32BE(buf, value, offset) {
		if (value < 0 || value >= MAX_INT32) throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
		buf.set([
			value >>> 24,
			value >>> 16,
			value >>> 8,
			value & 255
		], offset);
	}
	function uint64be(value) {
		const high = Math.floor(value / MAX_INT32);
		const low = value % MAX_INT32;
		const buf = new Uint8Array(8);
		writeUInt32BE(buf, high, 0);
		writeUInt32BE(buf, low, 4);
		return buf;
	}
	exports.uint64be = uint64be;
	function uint32be(value) {
		const buf = new Uint8Array(4);
		writeUInt32BE(buf, value);
		return buf;
	}
	exports.uint32be = uint32be;
	function lengthAndInput(input) {
		return concat(uint32be(input.length), input);
	}
	exports.lengthAndInput = lengthAndInput;
	async function concatKdf(secret, bits, value) {
		const iterations = Math.ceil((bits >> 3) / 32);
		const res = new Uint8Array(iterations * 32);
		for (let iter = 0; iter < iterations; iter++) {
			const buf = new Uint8Array(4 + secret.length + value.length);
			buf.set(uint32be(iter + 1));
			buf.set(secret, 4);
			buf.set(value, 4 + secret.length);
			res.set(await (0, digest_js_1.default)("sha256", buf), iter * 32);
		}
		return res.slice(0, bits >> 3);
	}
	exports.concatKdf = concatKdf;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/base64url.js
var require_base64url$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0;
	const buffer_1$5 = __require("buffer");
	const buffer_utils_js_1 = require_buffer_utils();
	function normalize(input) {
		let encoded = input;
		if (encoded instanceof Uint8Array) encoded = buffer_utils_js_1.decoder.decode(encoded);
		return encoded;
	}
	if (buffer_1$5.Buffer.isEncoding("base64url")) exports.encode = (input) => buffer_1$5.Buffer.from(input).toString("base64url");
	else exports.encode = (input) => buffer_1$5.Buffer.from(input).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
	const decodeBase64 = (input) => buffer_1$5.Buffer.from(input, "base64");
	exports.decodeBase64 = decodeBase64;
	const encodeBase64 = (input) => buffer_1$5.Buffer.from(input).toString("base64");
	exports.encodeBase64 = encodeBase64;
	const decode = (input) => buffer_1$5.Buffer.from(normalize(input), "base64");
	exports.decode = decode;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/util/errors.js
var require_errors$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.JWSSignatureVerificationFailed = exports.JWKSTimeout = exports.JWKSMultipleMatchingKeys = exports.JWKSNoMatchingKey = exports.JWKSInvalid = exports.JWKInvalid = exports.JWTInvalid = exports.JWSInvalid = exports.JWEInvalid = exports.JWEDecompressionFailed = exports.JWEDecryptionFailed = exports.JOSENotSupported = exports.JOSEAlgNotAllowed = exports.JWTExpired = exports.JWTClaimValidationFailed = exports.JOSEError = void 0;
	var JOSEError = class extends Error {
		static get code() {
			return "ERR_JOSE_GENERIC";
		}
		constructor(message) {
			var _a;
			super(message);
			this.code = "ERR_JOSE_GENERIC";
			this.name = this.constructor.name;
			(_a = Error.captureStackTrace) === null || _a === void 0 || _a.call(Error, this, this.constructor);
		}
	};
	exports.JOSEError = JOSEError;
	var JWTClaimValidationFailed = class extends JOSEError {
		static get code() {
			return "ERR_JWT_CLAIM_VALIDATION_FAILED";
		}
		constructor(message, claim = "unspecified", reason = "unspecified") {
			super(message);
			this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
			this.claim = claim;
			this.reason = reason;
		}
	};
	exports.JWTClaimValidationFailed = JWTClaimValidationFailed;
	var JWTExpired = class extends JOSEError {
		static get code() {
			return "ERR_JWT_EXPIRED";
		}
		constructor(message, claim = "unspecified", reason = "unspecified") {
			super(message);
			this.code = "ERR_JWT_EXPIRED";
			this.claim = claim;
			this.reason = reason;
		}
	};
	exports.JWTExpired = JWTExpired;
	var JOSEAlgNotAllowed = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JOSE_ALG_NOT_ALLOWED";
		}
		static get code() {
			return "ERR_JOSE_ALG_NOT_ALLOWED";
		}
	};
	exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed;
	var JOSENotSupported = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JOSE_NOT_SUPPORTED";
		}
		static get code() {
			return "ERR_JOSE_NOT_SUPPORTED";
		}
	};
	exports.JOSENotSupported = JOSENotSupported;
	var JWEDecryptionFailed = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWE_DECRYPTION_FAILED";
			this.message = "decryption operation failed";
		}
		static get code() {
			return "ERR_JWE_DECRYPTION_FAILED";
		}
	};
	exports.JWEDecryptionFailed = JWEDecryptionFailed;
	var JWEDecompressionFailed = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWE_DECOMPRESSION_FAILED";
			this.message = "decompression operation failed";
		}
		static get code() {
			return "ERR_JWE_DECOMPRESSION_FAILED";
		}
	};
	exports.JWEDecompressionFailed = JWEDecompressionFailed;
	var JWEInvalid = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWE_INVALID";
		}
		static get code() {
			return "ERR_JWE_INVALID";
		}
	};
	exports.JWEInvalid = JWEInvalid;
	var JWSInvalid = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWS_INVALID";
		}
		static get code() {
			return "ERR_JWS_INVALID";
		}
	};
	exports.JWSInvalid = JWSInvalid;
	var JWTInvalid = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWT_INVALID";
		}
		static get code() {
			return "ERR_JWT_INVALID";
		}
	};
	exports.JWTInvalid = JWTInvalid;
	var JWKInvalid = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWK_INVALID";
		}
		static get code() {
			return "ERR_JWK_INVALID";
		}
	};
	exports.JWKInvalid = JWKInvalid;
	var JWKSInvalid = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWKS_INVALID";
		}
		static get code() {
			return "ERR_JWKS_INVALID";
		}
	};
	exports.JWKSInvalid = JWKSInvalid;
	var JWKSNoMatchingKey = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWKS_NO_MATCHING_KEY";
			this.message = "no applicable key found in the JSON Web Key Set";
		}
		static get code() {
			return "ERR_JWKS_NO_MATCHING_KEY";
		}
	};
	exports.JWKSNoMatchingKey = JWKSNoMatchingKey;
	var JWKSMultipleMatchingKeys = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
			this.message = "multiple matching keys found in the JSON Web Key Set";
		}
		static get code() {
			return "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
		}
	};
	exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys;
	var JWKSTimeout = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWKS_TIMEOUT";
			this.message = "request timed out";
		}
		static get code() {
			return "ERR_JWKS_TIMEOUT";
		}
	};
	exports.JWKSTimeout = JWKSTimeout;
	var JWSSignatureVerificationFailed = class extends JOSEError {
		constructor() {
			super(...arguments);
			this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
			this.message = "signature verification failed";
		}
		static get code() {
			return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
		}
	};
	exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/random.js
var require_random = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.default = void 0;
	var crypto_1$16 = __require("crypto");
	Object.defineProperty(exports, "default", {
		enumerable: true,
		get: function() {
			return crypto_1$16.randomFillSync;
		}
	});
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/iv.js
var require_iv = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.bitLength = void 0;
	const errors_js_1 = require_errors$1();
	const random_js_1 = require_random();
	function bitLength(alg) {
		switch (alg) {
			case "A128GCM":
			case "A128GCMKW":
			case "A192GCM":
			case "A192GCMKW":
			case "A256GCM":
			case "A256GCMKW": return 96;
			case "A128CBC-HS256":
			case "A192CBC-HS384":
			case "A256CBC-HS512": return 128;
			default: throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
		}
	}
	exports.bitLength = bitLength;
	exports.default = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3));
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/check_iv_length.js
var require_check_iv_length = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const errors_js_1 = require_errors$1();
	const iv_js_1 = require_iv();
	const checkIvLength = (enc, iv) => {
		if (iv.length << 3 !== (0, iv_js_1.bitLength)(enc)) throw new errors_js_1.JWEInvalid("Invalid Initialization Vector length");
	};
	exports.default = checkIvLength;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/is_key_object.js
var require_is_key_object = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$15 = __require("crypto");
	const util$1 = __require("util");
	exports.default = util$1.types.isKeyObject ? (obj) => util$1.types.isKeyObject(obj) : (obj) => obj != null && obj instanceof crypto_1$15.KeyObject;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/check_cek_length.js
var require_check_cek_length = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const errors_js_1 = require_errors$1();
	const is_key_object_js_1 = require_is_key_object();
	const checkCekLength = (enc, cek) => {
		let expected;
		switch (enc) {
			case "A128CBC-HS256":
			case "A192CBC-HS384":
			case "A256CBC-HS512":
				expected = parseInt(enc.slice(-3), 10);
				break;
			case "A128GCM":
			case "A192GCM":
			case "A256GCM":
				expected = parseInt(enc.slice(1, 4), 10);
				break;
			default: throw new errors_js_1.JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`);
		}
		if (cek instanceof Uint8Array) {
			const actual = cek.byteLength << 3;
			if (actual !== expected) throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
			return;
		}
		if ((0, is_key_object_js_1.default)(cek) && cek.type === "secret") {
			const actual = cek.symmetricKeySize << 3;
			if (actual !== expected) throw new errors_js_1.JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
			return;
		}
		throw new TypeError("Invalid Content Encryption Key type");
	};
	exports.default = checkCekLength;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/timing_safe_equal.js
var require_timing_safe_equal = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.default = __require("crypto").timingSafeEqual;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/cbc_tag.js
var require_cbc_tag = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$14 = __require("crypto");
	const buffer_utils_js_1 = require_buffer_utils();
	function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) {
		const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3));
		const hmac = (0, crypto_1$14.createHmac)(`sha${macSize}`, macKey);
		hmac.update(macData);
		return hmac.digest().slice(0, keySize >> 3);
	}
	exports.default = cbcTag;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/webcrypto.js
var require_webcrypto = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.isCryptoKey = void 0;
	const crypto$2 = __require("crypto");
	const util = __require("util");
	exports.default = crypto$2.webcrypto;
	exports.isCryptoKey = util.types.isCryptoKey ? (key) => util.types.isCryptoKey(key) : (key) => false;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/crypto_key.js
var require_crypto_key = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.checkEncCryptoKey = exports.checkSigCryptoKey = void 0;
	function unusable(name, prop = "algorithm.name") {
		return /* @__PURE__ */ new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
	}
	function isAlgorithm(algorithm, name) {
		return algorithm.name === name;
	}
	function getHashLength(hash) {
		return parseInt(hash.name.slice(4), 10);
	}
	function getNamedCurve(alg) {
		switch (alg) {
			case "ES256": return "P-256";
			case "ES384": return "P-384";
			case "ES512": return "P-521";
			default: throw new Error("unreachable");
		}
	}
	function checkUsage(key, usages) {
		if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {
			let msg = "CryptoKey does not support this operation, its usages must include ";
			if (usages.length > 2) {
				const last = usages.pop();
				msg += `one of ${usages.join(", ")}, or ${last}.`;
			} else if (usages.length === 2) msg += `one of ${usages[0]} or ${usages[1]}.`;
			else msg += `${usages[0]}.`;
			throw new TypeError(msg);
		}
	}
	function checkSigCryptoKey(key, alg, ...usages) {
		switch (alg) {
			case "HS256":
			case "HS384":
			case "HS512": {
				if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
				const expected = parseInt(alg.slice(2), 10);
				if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
				break;
			}
			case "RS256":
			case "RS384":
			case "RS512": {
				if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
				const expected = parseInt(alg.slice(2), 10);
				if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
				break;
			}
			case "PS256":
			case "PS384":
			case "PS512": {
				if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
				const expected = parseInt(alg.slice(2), 10);
				if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
				break;
			}
			case "EdDSA":
				if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") throw unusable("Ed25519 or Ed448");
				break;
			case "ES256":
			case "ES384":
			case "ES512": {
				if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
				const expected = getNamedCurve(alg);
				if (key.algorithm.namedCurve !== expected) throw unusable(expected, "algorithm.namedCurve");
				break;
			}
			default: throw new TypeError("CryptoKey does not support this operation");
		}
		checkUsage(key, usages);
	}
	exports.checkSigCryptoKey = checkSigCryptoKey;
	function checkEncCryptoKey(key, alg, ...usages) {
		switch (alg) {
			case "A128GCM":
			case "A192GCM":
			case "A256GCM": {
				if (!isAlgorithm(key.algorithm, "AES-GCM")) throw unusable("AES-GCM");
				const expected = parseInt(alg.slice(1, 4), 10);
				if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length");
				break;
			}
			case "A128KW":
			case "A192KW":
			case "A256KW": {
				if (!isAlgorithm(key.algorithm, "AES-KW")) throw unusable("AES-KW");
				const expected = parseInt(alg.slice(1, 4), 10);
				if (key.algorithm.length !== expected) throw unusable(expected, "algorithm.length");
				break;
			}
			case "ECDH":
				switch (key.algorithm.name) {
					case "ECDH":
					case "X25519":
					case "X448": break;
					default: throw unusable("ECDH, X25519, or X448");
				}
				break;
			case "PBES2-HS256+A128KW":
			case "PBES2-HS384+A192KW":
			case "PBES2-HS512+A256KW":
				if (!isAlgorithm(key.algorithm, "PBKDF2")) throw unusable("PBKDF2");
				break;
			case "RSA-OAEP":
			case "RSA-OAEP-256":
			case "RSA-OAEP-384":
			case "RSA-OAEP-512": {
				if (!isAlgorithm(key.algorithm, "RSA-OAEP")) throw unusable("RSA-OAEP");
				const expected = parseInt(alg.slice(9), 10) || 1;
				if (getHashLength(key.algorithm.hash) !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
				break;
			}
			default: throw new TypeError("CryptoKey does not support this operation");
		}
		checkUsage(key, usages);
	}
	exports.checkEncCryptoKey = checkEncCryptoKey;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/invalid_key_input.js
var require_invalid_key_input = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.withAlg = void 0;
	function message(msg, actual, ...types) {
		if (types.length > 2) {
			const last = types.pop();
			msg += `one of type ${types.join(", ")}, or ${last}.`;
		} else if (types.length === 2) msg += `one of type ${types[0]} or ${types[1]}.`;
		else msg += `of type ${types[0]}.`;
		if (actual == null) msg += ` Received ${actual}`;
		else if (typeof actual === "function" && actual.name) msg += ` Received function ${actual.name}`;
		else if (typeof actual === "object" && actual != null) {
			if (actual.constructor && actual.constructor.name) msg += ` Received an instance of ${actual.constructor.name}`;
		}
		return msg;
	}
	exports.default = (actual, ...types) => {
		return message("Key must be ", actual, ...types);
	};
	function withAlg(alg, actual, ...types) {
		return message(`Key for the ${alg} algorithm must be `, actual, ...types);
	}
	exports.withAlg = withAlg;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/ciphers.js
var require_ciphers = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$13 = __require("crypto");
	let ciphers;
	exports.default = (algorithm) => {
		ciphers || (ciphers = new Set((0, crypto_1$13.getCiphers)()));
		return ciphers.has(algorithm);
	};
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/is_key_like.js
var require_is_key_like = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.types = void 0;
	const webcrypto_js_1 = require_webcrypto();
	const is_key_object_js_1 = require_is_key_object();
	exports.default = (key) => (0, is_key_object_js_1.default)(key) || (0, webcrypto_js_1.isCryptoKey)(key);
	const types = ["KeyObject"];
	exports.types = types;
	if (globalThis.CryptoKey || (webcrypto_js_1.default === null || webcrypto_js_1.default === void 0 ? void 0 : webcrypto_js_1.default.CryptoKey)) types.push("CryptoKey");
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/decrypt.js
var require_decrypt$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$12 = __require("crypto");
	const check_iv_length_js_1 = require_check_iv_length();
	const check_cek_length_js_1 = require_check_cek_length();
	const buffer_utils_js_1 = require_buffer_utils();
	const errors_js_1 = require_errors$1();
	const timing_safe_equal_js_1 = require_timing_safe_equal();
	const cbc_tag_js_1 = require_cbc_tag();
	const webcrypto_js_1 = require_webcrypto();
	const crypto_key_js_1 = require_crypto_key();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const ciphers_js_1 = require_ciphers();
	const is_key_like_js_1 = require_is_key_like();
	function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
		const keySize = parseInt(enc.slice(1, 4), 10);
		if ((0, is_key_object_js_1.default)(cek)) cek = cek.export();
		const encKey = cek.subarray(keySize >> 3);
		const macKey = cek.subarray(0, keySize >> 3);
		const macSize = parseInt(enc.slice(-3), 10);
		const algorithm = `aes-${keySize}-cbc`;
		if (!(0, ciphers_js_1.default)(algorithm)) throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
		const expectedTag = (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize);
		let macCheckPassed;
		try {
			macCheckPassed = (0, timing_safe_equal_js_1.default)(tag, expectedTag);
		} catch {}
		if (!macCheckPassed) throw new errors_js_1.JWEDecryptionFailed();
		let plaintext;
		try {
			const decipher = (0, crypto_1$12.createDecipheriv)(algorithm, encKey, iv);
			plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final());
		} catch {}
		if (!plaintext) throw new errors_js_1.JWEDecryptionFailed();
		return plaintext;
	}
	function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
		const algorithm = `aes-${parseInt(enc.slice(1, 4), 10)}-gcm`;
		if (!(0, ciphers_js_1.default)(algorithm)) throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
		try {
			const decipher = (0, crypto_1$12.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 });
			decipher.setAuthTag(tag);
			if (aad.byteLength) decipher.setAAD(aad, { plaintextLength: ciphertext.length });
			const plaintext = decipher.update(ciphertext);
			decipher.final();
			return plaintext;
		} catch {
			throw new errors_js_1.JWEDecryptionFailed();
		}
	}
	const decrypt = (enc, cek, ciphertext, iv, tag, aad) => {
		let key;
		if ((0, webcrypto_js_1.isCryptoKey)(cek)) {
			(0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, "decrypt");
			key = crypto_1$12.KeyObject.from(cek);
		} else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) key = cek;
		else throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, "Uint8Array"));
		(0, check_cek_length_js_1.default)(enc, key);
		(0, check_iv_length_js_1.default)(enc, iv);
		switch (enc) {
			case "A128CBC-HS256":
			case "A192CBC-HS384":
			case "A256CBC-HS512": return cbcDecrypt(enc, key, ciphertext, iv, tag, aad);
			case "A128GCM":
			case "A192GCM":
			case "A256GCM": return gcmDecrypt(enc, key, ciphertext, iv, tag, aad);
			default: throw new errors_js_1.JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
		}
	};
	exports.default = decrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/zlib.js
var require_zlib = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.deflate = exports.inflate = void 0;
	const util_1$5 = __require("util");
	const zlib_1 = __require("zlib");
	const errors_js_1 = require_errors$1();
	const inflateRaw = (0, util_1$5.promisify)(zlib_1.inflateRaw);
	const deflateRaw = (0, util_1$5.promisify)(zlib_1.deflateRaw);
	const inflate = (input) => inflateRaw(input, { maxOutputLength: 25e4 }).catch(() => {
		throw new errors_js_1.JWEDecompressionFailed();
	});
	exports.inflate = inflate;
	const deflate = (input) => deflateRaw(input);
	exports.deflate = deflate;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/is_disjoint.js
var require_is_disjoint = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const isDisjoint = (...headers) => {
		const sources = headers.filter(Boolean);
		if (sources.length === 0 || sources.length === 1) return true;
		let acc;
		for (const header of sources) {
			const parameters = Object.keys(header);
			if (!acc || acc.size === 0) {
				acc = new Set(parameters);
				continue;
			}
			for (const parameter of parameters) {
				if (acc.has(parameter)) return false;
				acc.add(parameter);
			}
		}
		return true;
	};
	exports.default = isDisjoint;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/is_object.js
var require_is_object = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	function isObjectLike(value) {
		return typeof value === "object" && value !== null;
	}
	function isObject(input) {
		if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") return false;
		if (Object.getPrototypeOf(input) === null) return true;
		let proto = input;
		while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
		return Object.getPrototypeOf(input) === proto;
	}
	exports.default = isObject;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/aeskw.js
var require_aeskw = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.unwrap = exports.wrap = void 0;
	const buffer_1$4 = __require("buffer");
	const crypto_1$11 = __require("crypto");
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const webcrypto_js_1 = require_webcrypto();
	const crypto_key_js_1 = require_crypto_key();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const ciphers_js_1 = require_ciphers();
	const is_key_like_js_1 = require_is_key_like();
	function checkKeySize(key, alg) {
		if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) throw new TypeError(`Invalid key size for alg: ${alg}`);
	}
	function ensureKeyObject(key, alg, usage) {
		if ((0, is_key_object_js_1.default)(key)) return key;
		if (key instanceof Uint8Array) return (0, crypto_1$11.createSecretKey)(key);
		if ((0, webcrypto_js_1.isCryptoKey)(key)) {
			(0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage);
			return crypto_1$11.KeyObject.from(key);
		}
		throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, "Uint8Array"));
	}
	const wrap = (alg, key, cek) => {
		const algorithm = `aes${parseInt(alg.slice(1, 4), 10)}-wrap`;
		if (!(0, ciphers_js_1.default)(algorithm)) throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
		const keyObject = ensureKeyObject(key, alg, "wrapKey");
		checkKeySize(keyObject, alg);
		const cipher = (0, crypto_1$11.createCipheriv)(algorithm, keyObject, buffer_1$4.Buffer.alloc(8, 166));
		return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final());
	};
	exports.wrap = wrap;
	const unwrap = (alg, key, encryptedKey) => {
		const algorithm = `aes${parseInt(alg.slice(1, 4), 10)}-wrap`;
		if (!(0, ciphers_js_1.default)(algorithm)) throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
		const keyObject = ensureKeyObject(key, alg, "unwrapKey");
		checkKeySize(keyObject, alg);
		const cipher = (0, crypto_1$11.createDecipheriv)(algorithm, keyObject, buffer_1$4.Buffer.alloc(8, 166));
		return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final());
	};
	exports.unwrap = unwrap;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/get_named_curve.js
var require_get_named_curve = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.setCurve = exports.weakMap = void 0;
	const buffer_1$3 = __require("buffer");
	const crypto_1$10 = __require("crypto");
	const errors_js_1 = require_errors$1();
	const webcrypto_js_1 = require_webcrypto();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const is_key_like_js_1 = require_is_key_like();
	const p256 = buffer_1$3.Buffer.from([
		42,
		134,
		72,
		206,
		61,
		3,
		1,
		7
	]);
	const p384 = buffer_1$3.Buffer.from([
		43,
		129,
		4,
		0,
		34
	]);
	const p521 = buffer_1$3.Buffer.from([
		43,
		129,
		4,
		0,
		35
	]);
	const secp256k1 = buffer_1$3.Buffer.from([
		43,
		129,
		4,
		0,
		10
	]);
	exports.weakMap = /* @__PURE__ */ new WeakMap();
	const namedCurveToJOSE = (namedCurve) => {
		switch (namedCurve) {
			case "prime256v1": return "P-256";
			case "secp384r1": return "P-384";
			case "secp521r1": return "P-521";
			case "secp256k1": return "secp256k1";
			default: throw new errors_js_1.JOSENotSupported("Unsupported key curve for this operation");
		}
	};
	const getNamedCurve = (kee, raw) => {
		var _a;
		let key;
		if ((0, webcrypto_js_1.isCryptoKey)(kee)) key = crypto_1$10.KeyObject.from(kee);
		else if ((0, is_key_object_js_1.default)(kee)) key = kee;
		else throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types));
		if (key.type === "secret") throw new TypeError("only \"private\" or \"public\" type keys can be used for this operation");
		switch (key.asymmetricKeyType) {
			case "ed25519":
			case "ed448": return `Ed${key.asymmetricKeyType.slice(2)}`;
			case "x25519":
			case "x448": return `X${key.asymmetricKeyType.slice(1)}`;
			case "ec": {
				if (exports.weakMap.has(key)) return exports.weakMap.get(key);
				let namedCurve = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.namedCurve;
				if (!namedCurve && key.type === "private") namedCurve = getNamedCurve((0, crypto_1$10.createPublicKey)(key), true);
				else if (!namedCurve) {
					const buf = key.export({
						format: "der",
						type: "spki"
					});
					const i = buf[1] < 128 ? 14 : 15;
					const len = buf[i];
					const curveOid = buf.slice(i + 1, i + 1 + len);
					if (curveOid.equals(p256)) namedCurve = "prime256v1";
					else if (curveOid.equals(p384)) namedCurve = "secp384r1";
					else if (curveOid.equals(p521)) namedCurve = "secp521r1";
					else if (curveOid.equals(secp256k1)) namedCurve = "secp256k1";
					else throw new errors_js_1.JOSENotSupported("Unsupported key curve for this operation");
				}
				if (raw) return namedCurve;
				const curve = namedCurveToJOSE(namedCurve);
				exports.weakMap.set(key, curve);
				return curve;
			}
			default: throw new TypeError("Invalid asymmetric key type for this operation");
		}
	};
	function setCurve(keyObject, curve) {
		exports.weakMap.set(keyObject, curve);
	}
	exports.setCurve = setCurve;
	exports.default = getNamedCurve;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/ecdhes.js
var require_ecdhes = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ecdhAllowed = exports.generateEpk = exports.deriveKey = void 0;
	const crypto_1$9 = __require("crypto");
	const util_1$4 = __require("util");
	const get_named_curve_js_1 = require_get_named_curve();
	const buffer_utils_js_1 = require_buffer_utils();
	const errors_js_1 = require_errors$1();
	const webcrypto_js_1 = require_webcrypto();
	const crypto_key_js_1 = require_crypto_key();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const is_key_like_js_1 = require_is_key_like();
	const generateKeyPair = (0, util_1$4.promisify)(crypto_1$9.generateKeyPair);
	async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
		let publicKey;
		if ((0, webcrypto_js_1.isCryptoKey)(publicKee)) {
			(0, crypto_key_js_1.checkEncCryptoKey)(publicKee, "ECDH");
			publicKey = crypto_1$9.KeyObject.from(publicKee);
		} else if ((0, is_key_object_js_1.default)(publicKee)) publicKey = publicKee;
		else throw new TypeError((0, invalid_key_input_js_1.default)(publicKee, ...is_key_like_js_1.types));
		let privateKey;
		if ((0, webcrypto_js_1.isCryptoKey)(privateKee)) {
			(0, crypto_key_js_1.checkEncCryptoKey)(privateKee, "ECDH", "deriveBits");
			privateKey = crypto_1$9.KeyObject.from(privateKee);
		} else if ((0, is_key_object_js_1.default)(privateKee)) privateKey = privateKee;
		else throw new TypeError((0, invalid_key_input_js_1.default)(privateKee, ...is_key_like_js_1.types));
		const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength));
		const sharedSecret = (0, crypto_1$9.diffieHellman)({
			privateKey,
			publicKey
		});
		return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value);
	}
	exports.deriveKey = deriveKey;
	async function generateEpk(kee) {
		let key;
		if ((0, webcrypto_js_1.isCryptoKey)(kee)) key = crypto_1$9.KeyObject.from(kee);
		else if ((0, is_key_object_js_1.default)(kee)) key = kee;
		else throw new TypeError((0, invalid_key_input_js_1.default)(kee, ...is_key_like_js_1.types));
		switch (key.asymmetricKeyType) {
			case "x25519": return generateKeyPair("x25519");
			case "x448": return generateKeyPair("x448");
			case "ec": return generateKeyPair("ec", { namedCurve: (0, get_named_curve_js_1.default)(key) });
			default: throw new errors_js_1.JOSENotSupported("Invalid or unsupported EPK");
		}
	}
	exports.generateEpk = generateEpk;
	const ecdhAllowed = (key) => [
		"P-256",
		"P-384",
		"P-521",
		"X25519",
		"X448"
	].includes((0, get_named_curve_js_1.default)(key));
	exports.ecdhAllowed = ecdhAllowed;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/check_p2s.js
var require_check_p2s = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const errors_js_1 = require_errors$1();
	function checkP2s(p2s) {
		if (!(p2s instanceof Uint8Array) || p2s.length < 8) throw new errors_js_1.JWEInvalid("PBES2 Salt Input must be 8 or more octets");
	}
	exports.default = checkP2s;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/pbes2kw.js
var require_pbes2kw = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.decrypt = exports.encrypt = void 0;
	const util_1$3 = __require("util");
	const crypto_1$8 = __require("crypto");
	const random_js_1 = require_random();
	const buffer_utils_js_1 = require_buffer_utils();
	const base64url_js_1 = require_base64url$1();
	const aeskw_js_1 = require_aeskw();
	const check_p2s_js_1 = require_check_p2s();
	const webcrypto_js_1 = require_webcrypto();
	const crypto_key_js_1 = require_crypto_key();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const is_key_like_js_1 = require_is_key_like();
	const pbkdf2 = (0, util_1$3.promisify)(crypto_1$8.pbkdf2);
	function getPassword(key, alg) {
		if ((0, is_key_object_js_1.default)(key)) return key.export();
		if (key instanceof Uint8Array) return key;
		if ((0, webcrypto_js_1.isCryptoKey)(key)) {
			(0, crypto_key_js_1.checkEncCryptoKey)(key, alg, "deriveBits", "deriveKey");
			return crypto_1$8.KeyObject.from(key).export();
		}
		throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, "Uint8Array"));
	}
	const encrypt = async (alg, key, cek, p2c = 2048, p2s = (0, random_js_1.default)(new Uint8Array(16))) => {
		(0, check_p2s_js_1.default)(p2s);
		const salt = (0, buffer_utils_js_1.p2s)(alg, p2s);
		const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
		const derivedKey = await pbkdf2(getPassword(key, alg), salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
		return {
			encryptedKey: await (0, aeskw_js_1.wrap)(alg.slice(-6), derivedKey, cek),
			p2c,
			p2s: (0, base64url_js_1.encode)(p2s)
		};
	};
	exports.encrypt = encrypt;
	const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {
		(0, check_p2s_js_1.default)(p2s);
		const salt = (0, buffer_utils_js_1.p2s)(alg, p2s);
		const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
		const derivedKey = await pbkdf2(getPassword(key, alg), salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
		return (0, aeskw_js_1.unwrap)(alg.slice(-6), derivedKey, encryptedKey);
	};
	exports.decrypt = decrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/check_modulus_length.js
var require_check_modulus_length = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.setModulusLength = exports.weakMap = void 0;
	exports.weakMap = /* @__PURE__ */ new WeakMap();
	const getLength = (buf, index) => {
		let len = buf.readUInt8(1);
		if ((len & 128) === 0) {
			if (index === 0) return len;
			return getLength(buf.subarray(2 + len), index - 1);
		}
		const num = len & 127;
		len = 0;
		for (let i = 0; i < num; i++) {
			len <<= 8;
			const j = buf.readUInt8(2 + i);
			len |= j;
		}
		if (index === 0) return len;
		return getLength(buf.subarray(2 + len), index - 1);
	};
	const getLengthOfSeqIndex = (sequence, index) => {
		const len = sequence.readUInt8(1);
		if ((len & 128) === 0) return getLength(sequence.subarray(2), index);
		const num = len & 127;
		return getLength(sequence.subarray(2 + num), index);
	};
	const getModulusLength = (key) => {
		var _a, _b;
		if (exports.weakMap.has(key)) return exports.weakMap.get(key);
		const modulusLength = (_b = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.modulusLength) !== null && _b !== void 0 ? _b : getLengthOfSeqIndex(key.export({
			format: "der",
			type: "pkcs1"
		}), key.type === "private" ? 1 : 0) - 1 << 3;
		exports.weakMap.set(key, modulusLength);
		return modulusLength;
	};
	const setModulusLength = (keyObject, modulusLength) => {
		exports.weakMap.set(keyObject, modulusLength);
	};
	exports.setModulusLength = setModulusLength;
	exports.default = (key, alg) => {
		if (getModulusLength(key) < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
	};
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/rsaes.js
var require_rsaes = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.decrypt = exports.encrypt = void 0;
	const crypto_1$7 = __require("crypto");
	const check_modulus_length_js_1 = require_check_modulus_length();
	const webcrypto_js_1 = require_webcrypto();
	const crypto_key_js_1 = require_crypto_key();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const is_key_like_js_1 = require_is_key_like();
	const checkKey = (key, alg) => {
		if (key.asymmetricKeyType !== "rsa") throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");
		(0, check_modulus_length_js_1.default)(key, alg);
	};
	const resolvePadding = (alg) => {
		switch (alg) {
			case "RSA-OAEP":
			case "RSA-OAEP-256":
			case "RSA-OAEP-384":
			case "RSA-OAEP-512": return crypto_1$7.constants.RSA_PKCS1_OAEP_PADDING;
			case "RSA1_5": return crypto_1$7.constants.RSA_PKCS1_PADDING;
			default: return;
		}
	};
	const resolveOaepHash = (alg) => {
		switch (alg) {
			case "RSA-OAEP": return "sha1";
			case "RSA-OAEP-256": return "sha256";
			case "RSA-OAEP-384": return "sha384";
			case "RSA-OAEP-512": return "sha512";
			default: return;
		}
	};
	function ensureKeyObject(key, alg, ...usages) {
		if ((0, is_key_object_js_1.default)(key)) return key;
		if ((0, webcrypto_js_1.isCryptoKey)(key)) {
			(0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages);
			return crypto_1$7.KeyObject.from(key);
		}
		throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
	}
	const encrypt = (alg, key, cek) => {
		const padding = resolvePadding(alg);
		const oaepHash = resolveOaepHash(alg);
		const keyObject = ensureKeyObject(key, alg, "wrapKey", "encrypt");
		checkKey(keyObject, alg);
		return (0, crypto_1$7.publicEncrypt)({
			key: keyObject,
			oaepHash,
			padding
		}, cek);
	};
	exports.encrypt = encrypt;
	const decrypt = (alg, key, encryptedKey) => {
		const padding = resolvePadding(alg);
		const oaepHash = resolveOaepHash(alg);
		const keyObject = ensureKeyObject(key, alg, "unwrapKey", "decrypt");
		checkKey(keyObject, alg);
		return (0, crypto_1$7.privateDecrypt)({
			key: keyObject,
			oaepHash,
			padding
		}, encryptedKey);
	};
	exports.decrypt = decrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/cek.js
var require_cek = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.bitLength = void 0;
	const errors_js_1 = require_errors$1();
	const random_js_1 = require_random();
	function bitLength(alg) {
		switch (alg) {
			case "A128GCM": return 128;
			case "A192GCM": return 192;
			case "A256GCM":
			case "A128CBC-HS256": return 256;
			case "A192CBC-HS384": return 384;
			case "A256CBC-HS512": return 512;
			default: throw new errors_js_1.JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
		}
	}
	exports.bitLength = bitLength;
	exports.default = (alg) => (0, random_js_1.default)(new Uint8Array(bitLength(alg) >> 3));
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/asn1.js
var require_asn1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.fromX509 = exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0;
	const crypto_1$6 = __require("crypto");
	const buffer_1$2 = __require("buffer");
	const webcrypto_js_1 = require_webcrypto();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const is_key_like_js_1 = require_is_key_like();
	const genericExport = (keyType, keyFormat, key) => {
		let keyObject;
		if ((0, webcrypto_js_1.isCryptoKey)(key)) {
			if (!key.extractable) throw new TypeError("CryptoKey is not extractable");
			keyObject = crypto_1$6.KeyObject.from(key);
		} else if ((0, is_key_object_js_1.default)(key)) keyObject = key;
		else throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
		if (keyObject.type !== keyType) throw new TypeError(`key is not a ${keyType} key`);
		return keyObject.export({
			format: "pem",
			type: keyFormat
		});
	};
	const toSPKI = (key) => {
		return genericExport("public", "spki", key);
	};
	exports.toSPKI = toSPKI;
	const toPKCS8 = (key) => {
		return genericExport("private", "pkcs8", key);
	};
	exports.toPKCS8 = toPKCS8;
	const fromPKCS8 = (pem) => (0, crypto_1$6.createPrivateKey)({
		key: buffer_1$2.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ""), "base64"),
		type: "pkcs8",
		format: "der"
	});
	exports.fromPKCS8 = fromPKCS8;
	const fromSPKI = (pem) => (0, crypto_1$6.createPublicKey)({
		key: buffer_1$2.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ""), "base64"),
		type: "spki",
		format: "der"
	});
	exports.fromSPKI = fromSPKI;
	const fromX509 = (pem) => (0, crypto_1$6.createPublicKey)({
		key: pem,
		type: "spki",
		format: "pem"
	});
	exports.fromX509 = fromX509;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/asn1_sequence_encoder.js
var require_asn1_sequence_encoder = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const buffer_1$1 = __require("buffer");
	const errors_js_1 = require_errors$1();
	const tagInteger = 2;
	const tagBitStr = 3;
	const tagOctStr = 4;
	const tagSequence = 48;
	const bZero = buffer_1$1.Buffer.from([0]);
	const bTagInteger = buffer_1$1.Buffer.from([tagInteger]);
	const bTagBitStr = buffer_1$1.Buffer.from([tagBitStr]);
	const bTagSequence = buffer_1$1.Buffer.from([tagSequence]);
	const bTagOctStr = buffer_1$1.Buffer.from([tagOctStr]);
	const encodeLength = (len) => {
		if (len < 128) return buffer_1$1.Buffer.from([len]);
		const buffer = buffer_1$1.Buffer.alloc(5);
		buffer.writeUInt32BE(len, 1);
		let offset = 1;
		while (buffer[offset] === 0) offset++;
		buffer[offset - 1] = 128 | 5 - offset;
		return buffer.slice(offset - 1);
	};
	const oids = new Map([
		["P-256", buffer_1$1.Buffer.from("06 08 2A 86 48 CE 3D 03 01 07".replace(/ /g, ""), "hex")],
		["secp256k1", buffer_1$1.Buffer.from("06 05 2B 81 04 00 0A".replace(/ /g, ""), "hex")],
		["P-384", buffer_1$1.Buffer.from("06 05 2B 81 04 00 22".replace(/ /g, ""), "hex")],
		["P-521", buffer_1$1.Buffer.from("06 05 2B 81 04 00 23".replace(/ /g, ""), "hex")],
		["ecPublicKey", buffer_1$1.Buffer.from("06 07 2A 86 48 CE 3D 02 01".replace(/ /g, ""), "hex")],
		["X25519", buffer_1$1.Buffer.from("06 03 2B 65 6E".replace(/ /g, ""), "hex")],
		["X448", buffer_1$1.Buffer.from("06 03 2B 65 6F".replace(/ /g, ""), "hex")],
		["Ed25519", buffer_1$1.Buffer.from("06 03 2B 65 70".replace(/ /g, ""), "hex")],
		["Ed448", buffer_1$1.Buffer.from("06 03 2B 65 71".replace(/ /g, ""), "hex")]
	]);
	var DumbAsn1Encoder = class {
		constructor() {
			this.length = 0;
			this.elements = [];
		}
		oidFor(oid) {
			const bOid = oids.get(oid);
			if (!bOid) throw new errors_js_1.JOSENotSupported("Invalid or unsupported OID");
			this.elements.push(bOid);
			this.length += bOid.length;
		}
		zero() {
			this.elements.push(bTagInteger, buffer_1$1.Buffer.from([1]), bZero);
			this.length += 3;
		}
		one() {
			this.elements.push(bTagInteger, buffer_1$1.Buffer.from([1]), buffer_1$1.Buffer.from([1]));
			this.length += 3;
		}
		unsignedInteger(integer) {
			if (integer[0] & 128) {
				const len = encodeLength(integer.length + 1);
				this.elements.push(bTagInteger, len, bZero, integer);
				this.length += 2 + len.length + integer.length;
			} else {
				let i = 0;
				while (integer[i] === 0 && (integer[i + 1] & 128) === 0) i++;
				const len = encodeLength(integer.length - i);
				this.elements.push(bTagInteger, encodeLength(integer.length - i), integer.slice(i));
				this.length += 1 + len.length + integer.length - i;
			}
		}
		octStr(octStr) {
			const len = encodeLength(octStr.length);
			this.elements.push(bTagOctStr, encodeLength(octStr.length), octStr);
			this.length += 1 + len.length + octStr.length;
		}
		bitStr(bitS) {
			const len = encodeLength(bitS.length + 1);
			this.elements.push(bTagBitStr, encodeLength(bitS.length + 1), bZero, bitS);
			this.length += 1 + len.length + bitS.length + 1;
		}
		add(seq) {
			this.elements.push(seq);
			this.length += seq.length;
		}
		end(tag = bTagSequence) {
			const len = encodeLength(this.length);
			return buffer_1$1.Buffer.concat([
				tag,
				len,
				...this.elements
			], 1 + len.length + this.length);
		}
	};
	exports.default = DumbAsn1Encoder;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/flags.js
var require_flags = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.jwkImport = exports.jwkExport = exports.rsaPssParams = exports.oneShotCallback = void 0;
	const [major, minor] = process.versions.node.split(".").map((str) => parseInt(str, 10));
	exports.oneShotCallback = major >= 16 || major === 15 && minor >= 13;
	exports.rsaPssParams = !("electron" in process.versions) && (major >= 17 || major === 16 && minor >= 9);
	exports.jwkExport = major >= 16 || major === 15 && minor >= 9;
	exports.jwkImport = major >= 16 || major === 15 && minor >= 12;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/jwk_to_key.js
var require_jwk_to_key = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const buffer_1 = __require("buffer");
	const crypto_1$5 = __require("crypto");
	const base64url_js_1 = require_base64url$1();
	const errors_js_1 = require_errors$1();
	const get_named_curve_js_1 = require_get_named_curve();
	const check_modulus_length_js_1 = require_check_modulus_length();
	const asn1_sequence_encoder_js_1 = require_asn1_sequence_encoder();
	const flags_js_1 = require_flags();
	const parse = (jwk) => {
		if (flags_js_1.jwkImport && jwk.kty !== "oct") return jwk.d ? (0, crypto_1$5.createPrivateKey)({
			format: "jwk",
			key: jwk
		}) : (0, crypto_1$5.createPublicKey)({
			format: "jwk",
			key: jwk
		});
		switch (jwk.kty) {
			case "oct": return (0, crypto_1$5.createSecretKey)((0, base64url_js_1.decode)(jwk.k));
			case "RSA": {
				const enc = new asn1_sequence_encoder_js_1.default();
				const isPrivate = jwk.d !== void 0;
				const modulus = buffer_1.Buffer.from(jwk.n, "base64");
				const exponent = buffer_1.Buffer.from(jwk.e, "base64");
				if (isPrivate) {
					enc.zero();
					enc.unsignedInteger(modulus);
					enc.unsignedInteger(exponent);
					enc.unsignedInteger(buffer_1.Buffer.from(jwk.d, "base64"));
					enc.unsignedInteger(buffer_1.Buffer.from(jwk.p, "base64"));
					enc.unsignedInteger(buffer_1.Buffer.from(jwk.q, "base64"));
					enc.unsignedInteger(buffer_1.Buffer.from(jwk.dp, "base64"));
					enc.unsignedInteger(buffer_1.Buffer.from(jwk.dq, "base64"));
					enc.unsignedInteger(buffer_1.Buffer.from(jwk.qi, "base64"));
				} else {
					enc.unsignedInteger(modulus);
					enc.unsignedInteger(exponent);
				}
				const createInput = {
					key: enc.end(),
					format: "der",
					type: "pkcs1"
				};
				const keyObject = isPrivate ? (0, crypto_1$5.createPrivateKey)(createInput) : (0, crypto_1$5.createPublicKey)(createInput);
				(0, check_modulus_length_js_1.setModulusLength)(keyObject, modulus.length << 3);
				return keyObject;
			}
			case "EC": {
				const enc = new asn1_sequence_encoder_js_1.default();
				const isPrivate = jwk.d !== void 0;
				const pub = buffer_1.Buffer.concat([
					buffer_1.Buffer.alloc(1, 4),
					buffer_1.Buffer.from(jwk.x, "base64"),
					buffer_1.Buffer.from(jwk.y, "base64")
				]);
				if (isPrivate) {
					enc.zero();
					const enc$1 = new asn1_sequence_encoder_js_1.default();
					enc$1.oidFor("ecPublicKey");
					enc$1.oidFor(jwk.crv);
					enc.add(enc$1.end());
					const enc$2 = new asn1_sequence_encoder_js_1.default();
					enc$2.one();
					enc$2.octStr(buffer_1.Buffer.from(jwk.d, "base64"));
					const enc$3 = new asn1_sequence_encoder_js_1.default();
					enc$3.bitStr(pub);
					const f2 = enc$3.end(buffer_1.Buffer.from([161]));
					enc$2.add(f2);
					const f = enc$2.end();
					const enc$4 = new asn1_sequence_encoder_js_1.default();
					enc$4.add(f);
					const f3 = enc$4.end(buffer_1.Buffer.from([4]));
					enc.add(f3);
					const der = enc.end();
					const keyObject = (0, crypto_1$5.createPrivateKey)({
						key: der,
						format: "der",
						type: "pkcs8"
					});
					(0, get_named_curve_js_1.setCurve)(keyObject, jwk.crv);
					return keyObject;
				}
				const enc$1 = new asn1_sequence_encoder_js_1.default();
				enc$1.oidFor("ecPublicKey");
				enc$1.oidFor(jwk.crv);
				enc.add(enc$1.end());
				enc.bitStr(pub);
				const der = enc.end();
				const keyObject = (0, crypto_1$5.createPublicKey)({
					key: der,
					format: "der",
					type: "spki"
				});
				(0, get_named_curve_js_1.setCurve)(keyObject, jwk.crv);
				return keyObject;
			}
			case "OKP": {
				const enc = new asn1_sequence_encoder_js_1.default();
				if (jwk.d !== void 0) {
					enc.zero();
					const enc$1 = new asn1_sequence_encoder_js_1.default();
					enc$1.oidFor(jwk.crv);
					enc.add(enc$1.end());
					const enc$2 = new asn1_sequence_encoder_js_1.default();
					enc$2.octStr(buffer_1.Buffer.from(jwk.d, "base64"));
					const f = enc$2.end(buffer_1.Buffer.from([4]));
					enc.add(f);
					const der = enc.end();
					return (0, crypto_1$5.createPrivateKey)({
						key: der,
						format: "der",
						type: "pkcs8"
					});
				}
				const enc$1 = new asn1_sequence_encoder_js_1.default();
				enc$1.oidFor(jwk.crv);
				enc.add(enc$1.end());
				enc.bitStr(buffer_1.Buffer.from(jwk.x, "base64"));
				const der = enc.end();
				return (0, crypto_1$5.createPublicKey)({
					key: der,
					format: "der",
					type: "spki"
				});
			}
			default: throw new errors_js_1.JOSENotSupported("Invalid or unsupported JWK \"kty\" (Key Type) Parameter value");
		}
	};
	exports.default = parse;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/key/import.js
var require_import = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.importJWK = exports.importPKCS8 = exports.importX509 = exports.importSPKI = void 0;
	const base64url_js_1 = require_base64url$1();
	const asn1_js_1 = require_asn1();
	const jwk_to_key_js_1 = require_jwk_to_key();
	const errors_js_1 = require_errors$1();
	const is_object_js_1 = require_is_object();
	async function importSPKI(spki, alg, options) {
		if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) throw new TypeError("\"spki\" must be SPKI formatted string");
		return (0, asn1_js_1.fromSPKI)(spki, alg, options);
	}
	exports.importSPKI = importSPKI;
	async function importX509(x509, alg, options) {
		if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) throw new TypeError("\"x509\" must be X.509 formatted string");
		return (0, asn1_js_1.fromX509)(x509, alg, options);
	}
	exports.importX509 = importX509;
	async function importPKCS8(pkcs8, alg, options) {
		if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) throw new TypeError("\"pkcs8\" must be PKCS#8 formatted string");
		return (0, asn1_js_1.fromPKCS8)(pkcs8, alg, options);
	}
	exports.importPKCS8 = importPKCS8;
	async function importJWK(jwk, alg, octAsKeyObject) {
		var _a;
		if (!(0, is_object_js_1.default)(jwk)) throw new TypeError("JWK must be an object");
		alg || (alg = jwk.alg);
		switch (jwk.kty) {
			case "oct":
				if (typeof jwk.k !== "string" || !jwk.k) throw new TypeError("missing \"k\" (Key Value) Parameter value");
				octAsKeyObject !== null && octAsKeyObject !== void 0 || (octAsKeyObject = jwk.ext !== true);
				if (octAsKeyObject) return (0, jwk_to_key_js_1.default)({
					...jwk,
					alg,
					ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false
				});
				return (0, base64url_js_1.decode)(jwk.k);
			case "RSA": if (jwk.oth !== void 0) throw new errors_js_1.JOSENotSupported("RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported");
			case "EC":
			case "OKP": return (0, jwk_to_key_js_1.default)({
				...jwk,
				alg
			});
			default: throw new errors_js_1.JOSENotSupported("Unsupported \"kty\" (Key Type) Parameter value");
		}
	}
	exports.importJWK = importJWK;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/check_key_type.js
var require_check_key_type = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const invalid_key_input_js_1 = require_invalid_key_input();
	const is_key_like_js_1 = require_is_key_like();
	const symmetricTypeCheck = (alg, key) => {
		if (key instanceof Uint8Array) return;
		if (!(0, is_key_like_js_1.default)(key)) throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types, "Uint8Array"));
		if (key.type !== "secret") throw new TypeError(`${is_key_like_js_1.types.join(" or ")} instances for symmetric algorithms must be of type "secret"`);
	};
	const asymmetricTypeCheck = (alg, key, usage) => {
		if (!(0, is_key_like_js_1.default)(key)) throw new TypeError((0, invalid_key_input_js_1.withAlg)(alg, key, ...is_key_like_js_1.types));
		if (key.type === "secret") throw new TypeError(`${is_key_like_js_1.types.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);
		if (usage === "sign" && key.type === "public") throw new TypeError(`${is_key_like_js_1.types.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);
		if (usage === "decrypt" && key.type === "public") throw new TypeError(`${is_key_like_js_1.types.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);
		if (key.algorithm && usage === "verify" && key.type === "private") throw new TypeError(`${is_key_like_js_1.types.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);
		if (key.algorithm && usage === "encrypt" && key.type === "private") throw new TypeError(`${is_key_like_js_1.types.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`);
	};
	const checkKeyType = (alg, key, usage) => {
		if (alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg)) symmetricTypeCheck(alg, key);
		else asymmetricTypeCheck(alg, key, usage);
	};
	exports.default = checkKeyType;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/encrypt.js
var require_encrypt$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$4 = __require("crypto");
	const check_iv_length_js_1 = require_check_iv_length();
	const check_cek_length_js_1 = require_check_cek_length();
	const buffer_utils_js_1 = require_buffer_utils();
	const cbc_tag_js_1 = require_cbc_tag();
	const webcrypto_js_1 = require_webcrypto();
	const crypto_key_js_1 = require_crypto_key();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const errors_js_1 = require_errors$1();
	const ciphers_js_1 = require_ciphers();
	const is_key_like_js_1 = require_is_key_like();
	function cbcEncrypt(enc, plaintext, cek, iv, aad) {
		const keySize = parseInt(enc.slice(1, 4), 10);
		if ((0, is_key_object_js_1.default)(cek)) cek = cek.export();
		const encKey = cek.subarray(keySize >> 3);
		const macKey = cek.subarray(0, keySize >> 3);
		const algorithm = `aes-${keySize}-cbc`;
		if (!(0, ciphers_js_1.default)(algorithm)) throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
		const cipher = (0, crypto_1$4.createCipheriv)(algorithm, encKey, iv);
		const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final());
		const macSize = parseInt(enc.slice(-3), 10);
		return {
			ciphertext,
			tag: (0, cbc_tag_js_1.default)(aad, iv, ciphertext, macSize, macKey, keySize)
		};
	}
	function gcmEncrypt(enc, plaintext, cek, iv, aad) {
		const algorithm = `aes-${parseInt(enc.slice(1, 4), 10)}-gcm`;
		if (!(0, ciphers_js_1.default)(algorithm)) throw new errors_js_1.JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
		const cipher = (0, crypto_1$4.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 });
		if (aad.byteLength) cipher.setAAD(aad, { plaintextLength: plaintext.length });
		const ciphertext = cipher.update(plaintext);
		cipher.final();
		return {
			ciphertext,
			tag: cipher.getAuthTag()
		};
	}
	const encrypt = (enc, plaintext, cek, iv, aad) => {
		let key;
		if ((0, webcrypto_js_1.isCryptoKey)(cek)) {
			(0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, "encrypt");
			key = crypto_1$4.KeyObject.from(cek);
		} else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) key = cek;
		else throw new TypeError((0, invalid_key_input_js_1.default)(cek, ...is_key_like_js_1.types, "Uint8Array"));
		(0, check_cek_length_js_1.default)(enc, key);
		(0, check_iv_length_js_1.default)(enc, iv);
		switch (enc) {
			case "A128CBC-HS256":
			case "A192CBC-HS384":
			case "A256CBC-HS512": return cbcEncrypt(enc, plaintext, key, iv, aad);
			case "A128GCM":
			case "A192GCM":
			case "A256GCM": return gcmEncrypt(enc, plaintext, key, iv, aad);
			default: throw new errors_js_1.JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
		}
	};
	exports.default = encrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/aesgcmkw.js
var require_aesgcmkw = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.unwrap = exports.wrap = void 0;
	const encrypt_js_1 = require_encrypt$4();
	const decrypt_js_1 = require_decrypt$4();
	const iv_js_1 = require_iv();
	const base64url_js_1 = require_base64url$1();
	async function wrap(alg, key, cek, iv) {
		const jweAlgorithm = alg.slice(0, 7);
		iv || (iv = (0, iv_js_1.default)(jweAlgorithm));
		const { ciphertext: encryptedKey, tag } = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0));
		return {
			encryptedKey,
			iv: (0, base64url_js_1.encode)(iv),
			tag: (0, base64url_js_1.encode)(tag)
		};
	}
	exports.wrap = wrap;
	async function unwrap(alg, key, encryptedKey, iv, tag) {
		const jweAlgorithm = alg.slice(0, 7);
		return (0, decrypt_js_1.default)(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0));
	}
	exports.unwrap = unwrap;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/decrypt_key_management.js
var require_decrypt_key_management = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const aeskw_js_1 = require_aeskw();
	const ECDH = require_ecdhes();
	const pbes2kw_js_1 = require_pbes2kw();
	const rsaes_js_1 = require_rsaes();
	const base64url_js_1 = require_base64url$1();
	const errors_js_1 = require_errors$1();
	const cek_js_1 = require_cek();
	const import_js_1 = require_import();
	const check_key_type_js_1 = require_check_key_type();
	const is_object_js_1 = require_is_object();
	const aesgcmkw_js_1 = require_aesgcmkw();
	async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
		(0, check_key_type_js_1.default)(alg, key, "decrypt");
		switch (alg) {
			case "dir":
				if (encryptedKey !== void 0) throw new errors_js_1.JWEInvalid("Encountered unexpected JWE Encrypted Key");
				return key;
			case "ECDH-ES": if (encryptedKey !== void 0) throw new errors_js_1.JWEInvalid("Encountered unexpected JWE Encrypted Key");
			case "ECDH-ES+A128KW":
			case "ECDH-ES+A192KW":
			case "ECDH-ES+A256KW": {
				if (!(0, is_object_js_1.default)(joseHeader.epk)) throw new errors_js_1.JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
				if (!ECDH.ecdhAllowed(key)) throw new errors_js_1.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
				const epk = await (0, import_js_1.importJWK)(joseHeader.epk, alg);
				let partyUInfo;
				let partyVInfo;
				if (joseHeader.apu !== void 0) {
					if (typeof joseHeader.apu !== "string") throw new errors_js_1.JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
					try {
						partyUInfo = (0, base64url_js_1.decode)(joseHeader.apu);
					} catch {
						throw new errors_js_1.JWEInvalid("Failed to base64url decode the apu");
					}
				}
				if (joseHeader.apv !== void 0) {
					if (typeof joseHeader.apv !== "string") throw new errors_js_1.JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
					try {
						partyVInfo = (0, base64url_js_1.decode)(joseHeader.apv);
					} catch {
						throw new errors_js_1.JWEInvalid("Failed to base64url decode the apv");
					}
				}
				const sharedSecret = await ECDH.deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? (0, cek_js_1.bitLength)(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
				if (alg === "ECDH-ES") return sharedSecret;
				if (encryptedKey === void 0) throw new errors_js_1.JWEInvalid("JWE Encrypted Key missing");
				return (0, aeskw_js_1.unwrap)(alg.slice(-6), sharedSecret, encryptedKey);
			}
			case "RSA1_5":
			case "RSA-OAEP":
			case "RSA-OAEP-256":
			case "RSA-OAEP-384":
			case "RSA-OAEP-512":
				if (encryptedKey === void 0) throw new errors_js_1.JWEInvalid("JWE Encrypted Key missing");
				return (0, rsaes_js_1.decrypt)(alg, key, encryptedKey);
			case "PBES2-HS256+A128KW":
			case "PBES2-HS384+A192KW":
			case "PBES2-HS512+A256KW": {
				if (encryptedKey === void 0) throw new errors_js_1.JWEInvalid("JWE Encrypted Key missing");
				if (typeof joseHeader.p2c !== "number") throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
				const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 1e4;
				if (joseHeader.p2c > p2cLimit) throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
				if (typeof joseHeader.p2s !== "string") throw new errors_js_1.JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
				let p2s;
				try {
					p2s = (0, base64url_js_1.decode)(joseHeader.p2s);
				} catch {
					throw new errors_js_1.JWEInvalid("Failed to base64url decode the p2s");
				}
				return (0, pbes2kw_js_1.decrypt)(alg, key, encryptedKey, joseHeader.p2c, p2s);
			}
			case "A128KW":
			case "A192KW":
			case "A256KW":
				if (encryptedKey === void 0) throw new errors_js_1.JWEInvalid("JWE Encrypted Key missing");
				return (0, aeskw_js_1.unwrap)(alg, key, encryptedKey);
			case "A128GCMKW":
			case "A192GCMKW":
			case "A256GCMKW": {
				if (encryptedKey === void 0) throw new errors_js_1.JWEInvalid("JWE Encrypted Key missing");
				if (typeof joseHeader.iv !== "string") throw new errors_js_1.JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
				if (typeof joseHeader.tag !== "string") throw new errors_js_1.JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
				let iv;
				try {
					iv = (0, base64url_js_1.decode)(joseHeader.iv);
				} catch {
					throw new errors_js_1.JWEInvalid("Failed to base64url decode the iv");
				}
				let tag;
				try {
					tag = (0, base64url_js_1.decode)(joseHeader.tag);
				} catch {
					throw new errors_js_1.JWEInvalid("Failed to base64url decode the tag");
				}
				return (0, aesgcmkw_js_1.unwrap)(alg, key, encryptedKey, iv, tag);
			}
			default: throw new errors_js_1.JOSENotSupported("Invalid or unsupported \"alg\" (JWE Algorithm) header value");
		}
	}
	exports.default = decryptKeyManagement;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/validate_crit.js
var require_validate_crit = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const errors_js_1 = require_errors$1();
	function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
		if (joseHeader.crit !== void 0 && protectedHeader.crit === void 0) throw new Err("\"crit\" (Critical) Header Parameter MUST be integrity protected");
		if (!protectedHeader || protectedHeader.crit === void 0) return /* @__PURE__ */ new Set();
		if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) throw new Err("\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present");
		let recognized;
		if (recognizedOption !== void 0) recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
		else recognized = recognizedDefault;
		for (const parameter of protectedHeader.crit) {
			if (!recognized.has(parameter)) throw new errors_js_1.JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
			if (joseHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
			else if (recognized.get(parameter) && protectedHeader[parameter] === void 0) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
		}
		return new Set(protectedHeader.crit);
	}
	exports.default = validateCrit;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/validate_algorithms.js
var require_validate_algorithms = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const validateAlgorithms = (option, algorithms) => {
		if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) throw new TypeError(`"${option}" option must be an array of strings`);
		if (!algorithms) return;
		return new Set(algorithms);
	};
	exports.default = validateAlgorithms;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js
var require_decrypt$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.flattenedDecrypt = void 0;
	const base64url_js_1 = require_base64url$1();
	const decrypt_js_1 = require_decrypt$4();
	const zlib_js_1 = require_zlib();
	const errors_js_1 = require_errors$1();
	const is_disjoint_js_1 = require_is_disjoint();
	const is_object_js_1 = require_is_object();
	const decrypt_key_management_js_1 = require_decrypt_key_management();
	const buffer_utils_js_1 = require_buffer_utils();
	const cek_js_1 = require_cek();
	const validate_crit_js_1 = require_validate_crit();
	const validate_algorithms_js_1 = require_validate_algorithms();
	async function flattenedDecrypt(jwe, key, options) {
		var _a;
		if (!(0, is_object_js_1.default)(jwe)) throw new errors_js_1.JWEInvalid("Flattened JWE must be an object");
		if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) throw new errors_js_1.JWEInvalid("JOSE Header missing");
		if (typeof jwe.iv !== "string") throw new errors_js_1.JWEInvalid("JWE Initialization Vector missing or incorrect type");
		if (typeof jwe.ciphertext !== "string") throw new errors_js_1.JWEInvalid("JWE Ciphertext missing or incorrect type");
		if (typeof jwe.tag !== "string") throw new errors_js_1.JWEInvalid("JWE Authentication Tag missing or incorrect type");
		if (jwe.protected !== void 0 && typeof jwe.protected !== "string") throw new errors_js_1.JWEInvalid("JWE Protected Header incorrect type");
		if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") throw new errors_js_1.JWEInvalid("JWE Encrypted Key incorrect type");
		if (jwe.aad !== void 0 && typeof jwe.aad !== "string") throw new errors_js_1.JWEInvalid("JWE AAD incorrect type");
		if (jwe.header !== void 0 && !(0, is_object_js_1.default)(jwe.header)) throw new errors_js_1.JWEInvalid("JWE Shared Unprotected Header incorrect type");
		if (jwe.unprotected !== void 0 && !(0, is_object_js_1.default)(jwe.unprotected)) throw new errors_js_1.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
		let parsedProt;
		if (jwe.protected) try {
			const protectedHeader = (0, base64url_js_1.decode)(jwe.protected);
			parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader));
		} catch {
			throw new errors_js_1.JWEInvalid("JWE Protected Header is invalid");
		}
		if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) throw new errors_js_1.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
		const joseHeader = {
			...parsedProt,
			...jwe.header,
			...jwe.unprotected
		};
		(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, /* @__PURE__ */ new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
		if (joseHeader.zip !== void 0) {
			if (!parsedProt || !parsedProt.zip) throw new errors_js_1.JWEInvalid("JWE \"zip\" (Compression Algorithm) Header MUST be integrity protected");
			if (joseHeader.zip !== "DEF") throw new errors_js_1.JOSENotSupported("Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value");
		}
		const { alg, enc } = joseHeader;
		if (typeof alg !== "string" || !alg) throw new errors_js_1.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
		if (typeof enc !== "string" || !enc) throw new errors_js_1.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
		const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)("keyManagementAlgorithms", options.keyManagementAlgorithms);
		const contentEncryptionAlgorithms = options && (0, validate_algorithms_js_1.default)("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
		if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) throw new errors_js_1.JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter not allowed");
		if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) throw new errors_js_1.JOSEAlgNotAllowed("\"enc\" (Encryption Algorithm) Header Parameter not allowed");
		let encryptedKey;
		if (jwe.encrypted_key !== void 0) try {
			encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key);
		} catch {
			throw new errors_js_1.JWEInvalid("Failed to base64url decode the encrypted_key");
		}
		let resolvedKey = false;
		if (typeof key === "function") {
			key = await key(parsedProt, jwe);
			resolvedKey = true;
		}
		let cek;
		try {
			cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options);
		} catch (err) {
			if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) throw err;
			cek = (0, cek_js_1.default)(enc);
		}
		let iv;
		let tag;
		try {
			iv = (0, base64url_js_1.decode)(jwe.iv);
		} catch {
			throw new errors_js_1.JWEInvalid("Failed to base64url decode the iv");
		}
		try {
			tag = (0, base64url_js_1.decode)(jwe.tag);
		} catch {
			throw new errors_js_1.JWEInvalid("Failed to base64url decode the tag");
		}
		const protectedHeader = buffer_utils_js_1.encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : "");
		let additionalData;
		if (jwe.aad !== void 0) additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode("."), buffer_utils_js_1.encoder.encode(jwe.aad));
		else additionalData = protectedHeader;
		let ciphertext;
		try {
			ciphertext = (0, base64url_js_1.decode)(jwe.ciphertext);
		} catch {
			throw new errors_js_1.JWEInvalid("Failed to base64url decode the ciphertext");
		}
		let plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData);
		if (joseHeader.zip === "DEF") plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || zlib_js_1.inflate)(plaintext);
		const result = { plaintext };
		if (jwe.protected !== void 0) result.protectedHeader = parsedProt;
		if (jwe.aad !== void 0) try {
			result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad);
		} catch {
			throw new errors_js_1.JWEInvalid("Failed to base64url decode the aad");
		}
		if (jwe.unprotected !== void 0) result.sharedUnprotectedHeader = jwe.unprotected;
		if (jwe.header !== void 0) result.unprotectedHeader = jwe.header;
		if (resolvedKey) return {
			...result,
			key
		};
		return result;
	}
	exports.flattenedDecrypt = flattenedDecrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js
var require_decrypt$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.compactDecrypt = void 0;
	const decrypt_js_1 = require_decrypt$3();
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	async function compactDecrypt(jwe, key, options) {
		if (jwe instanceof Uint8Array) jwe = buffer_utils_js_1.decoder.decode(jwe);
		if (typeof jwe !== "string") throw new errors_js_1.JWEInvalid("Compact JWE must be a string or Uint8Array");
		const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length } = jwe.split(".");
		if (length !== 5) throw new errors_js_1.JWEInvalid("Invalid Compact JWE");
		const decrypted = await (0, decrypt_js_1.flattenedDecrypt)({
			ciphertext,
			iv: iv || void 0,
			protected: protectedHeader || void 0,
			tag: tag || void 0,
			encrypted_key: encryptedKey || void 0
		}, key, options);
		const result = {
			plaintext: decrypted.plaintext,
			protectedHeader: decrypted.protectedHeader
		};
		if (typeof key === "function") return {
			...result,
			key: decrypted.key
		};
		return result;
	}
	exports.compactDecrypt = compactDecrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwe/general/decrypt.js
var require_decrypt$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.generalDecrypt = void 0;
	const decrypt_js_1 = require_decrypt$3();
	const errors_js_1 = require_errors$1();
	const is_object_js_1 = require_is_object();
	async function generalDecrypt(jwe, key, options) {
		if (!(0, is_object_js_1.default)(jwe)) throw new errors_js_1.JWEInvalid("General JWE must be an object");
		if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) throw new errors_js_1.JWEInvalid("JWE Recipients missing or incorrect type");
		if (!jwe.recipients.length) throw new errors_js_1.JWEInvalid("JWE Recipients has no members");
		for (const recipient of jwe.recipients) try {
			return await (0, decrypt_js_1.flattenedDecrypt)({
				aad: jwe.aad,
				ciphertext: jwe.ciphertext,
				encrypted_key: recipient.encrypted_key,
				header: recipient.header,
				iv: jwe.iv,
				protected: jwe.protected,
				tag: jwe.tag,
				unprotected: jwe.unprotected
			}, key, options);
		} catch {}
		throw new errors_js_1.JWEDecryptionFailed();
	}
	exports.generalDecrypt = generalDecrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/asn1_sequence_decoder.js
var require_asn1_sequence_decoder = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const tagInteger = 2;
	const tagSequence = 48;
	var Asn1SequenceDecoder = class {
		constructor(buffer) {
			if (buffer[0] !== tagSequence) throw new TypeError();
			this.buffer = buffer;
			this.offset = 1;
			if (this.decodeLength() !== buffer.length - this.offset) throw new TypeError();
		}
		decodeLength() {
			let length = this.buffer[this.offset++];
			if (length & 128) {
				const nBytes = length & -129;
				length = 0;
				for (let i = 0; i < nBytes; i++) length = length << 8 | this.buffer[this.offset + i];
				this.offset += nBytes;
			}
			return length;
		}
		unsignedInteger() {
			if (this.buffer[this.offset++] !== tagInteger) throw new TypeError();
			let length = this.decodeLength();
			if (this.buffer[this.offset] === 0) {
				this.offset++;
				length--;
			}
			const result = this.buffer.slice(this.offset, this.offset + length);
			this.offset += length;
			return result;
		}
		end() {
			if (this.offset !== this.buffer.length) throw new TypeError();
		}
	};
	exports.default = Asn1SequenceDecoder;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/key_to_jwk.js
var require_key_to_jwk = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$3 = __require("crypto");
	const base64url_js_1 = require_base64url$1();
	const asn1_sequence_decoder_js_1 = require_asn1_sequence_decoder();
	const errors_js_1 = require_errors$1();
	const get_named_curve_js_1 = require_get_named_curve();
	const webcrypto_js_1 = require_webcrypto();
	const is_key_object_js_1 = require_is_key_object();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const is_key_like_js_1 = require_is_key_like();
	const flags_js_1 = require_flags();
	const keyToJWK = (key) => {
		let keyObject;
		if ((0, webcrypto_js_1.isCryptoKey)(key)) {
			if (!key.extractable) throw new TypeError("CryptoKey is not extractable");
			keyObject = crypto_1$3.KeyObject.from(key);
		} else if ((0, is_key_object_js_1.default)(key)) keyObject = key;
		else if (key instanceof Uint8Array) return {
			kty: "oct",
			k: (0, base64url_js_1.encode)(key)
		};
		else throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, "Uint8Array"));
		if (flags_js_1.jwkExport) {
			if (keyObject.type !== "secret" && ![
				"rsa",
				"ec",
				"ed25519",
				"x25519",
				"ed448",
				"x448"
			].includes(keyObject.asymmetricKeyType)) throw new errors_js_1.JOSENotSupported("Unsupported key asymmetricKeyType");
			return keyObject.export({ format: "jwk" });
		}
		switch (keyObject.type) {
			case "secret": return {
				kty: "oct",
				k: (0, base64url_js_1.encode)(keyObject.export())
			};
			case "private":
			case "public": switch (keyObject.asymmetricKeyType) {
				case "rsa": {
					const der = keyObject.export({
						format: "der",
						type: "pkcs1"
					});
					const dec = new asn1_sequence_decoder_js_1.default(der);
					if (keyObject.type === "private") dec.unsignedInteger();
					const n = (0, base64url_js_1.encode)(dec.unsignedInteger());
					const e = (0, base64url_js_1.encode)(dec.unsignedInteger());
					let jwk;
					if (keyObject.type === "private") jwk = {
						d: (0, base64url_js_1.encode)(dec.unsignedInteger()),
						p: (0, base64url_js_1.encode)(dec.unsignedInteger()),
						q: (0, base64url_js_1.encode)(dec.unsignedInteger()),
						dp: (0, base64url_js_1.encode)(dec.unsignedInteger()),
						dq: (0, base64url_js_1.encode)(dec.unsignedInteger()),
						qi: (0, base64url_js_1.encode)(dec.unsignedInteger())
					};
					dec.end();
					return {
						kty: "RSA",
						n,
						e,
						...jwk
					};
				}
				case "ec": {
					const crv = (0, get_named_curve_js_1.default)(keyObject);
					let len;
					let offset;
					let correction;
					switch (crv) {
						case "secp256k1":
							len = 64;
							offset = 33;
							correction = -1;
							break;
						case "P-256":
							len = 64;
							offset = 36;
							correction = -1;
							break;
						case "P-384":
							len = 96;
							offset = 35;
							correction = -3;
							break;
						case "P-521":
							len = 132;
							offset = 35;
							correction = -3;
							break;
						default: throw new errors_js_1.JOSENotSupported("Unsupported curve");
					}
					if (keyObject.type === "public") {
						const der = keyObject.export({
							type: "spki",
							format: "der"
						});
						return {
							kty: "EC",
							crv,
							x: (0, base64url_js_1.encode)(der.subarray(-len, -len / 2)),
							y: (0, base64url_js_1.encode)(der.subarray(-len / 2))
						};
					}
					const der = keyObject.export({
						type: "pkcs8",
						format: "der"
					});
					if (der.length < 100) offset += correction;
					return {
						...keyToJWK((0, crypto_1$3.createPublicKey)(keyObject)),
						d: (0, base64url_js_1.encode)(der.subarray(offset, offset + len / 2))
					};
				}
				case "ed25519":
				case "x25519": {
					const crv = (0, get_named_curve_js_1.default)(keyObject);
					if (keyObject.type === "public") {
						const der = keyObject.export({
							type: "spki",
							format: "der"
						});
						return {
							kty: "OKP",
							crv,
							x: (0, base64url_js_1.encode)(der.subarray(-32))
						};
					}
					const der = keyObject.export({
						type: "pkcs8",
						format: "der"
					});
					return {
						...keyToJWK((0, crypto_1$3.createPublicKey)(keyObject)),
						d: (0, base64url_js_1.encode)(der.subarray(-32))
					};
				}
				case "ed448":
				case "x448": {
					const crv = (0, get_named_curve_js_1.default)(keyObject);
					if (keyObject.type === "public") {
						const der = keyObject.export({
							type: "spki",
							format: "der"
						});
						return {
							kty: "OKP",
							crv,
							x: (0, base64url_js_1.encode)(der.subarray(crv === "Ed448" ? -57 : -56))
						};
					}
					const der = keyObject.export({
						type: "pkcs8",
						format: "der"
					});
					return {
						...keyToJWK((0, crypto_1$3.createPublicKey)(keyObject)),
						d: (0, base64url_js_1.encode)(der.subarray(crv === "Ed448" ? -57 : -56))
					};
				}
				default: throw new errors_js_1.JOSENotSupported("Unsupported key asymmetricKeyType");
			}
			default: throw new errors_js_1.JOSENotSupported("Unsupported key type");
		}
	};
	exports.default = keyToJWK;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/key/export.js
var require_export = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.exportJWK = exports.exportPKCS8 = exports.exportSPKI = void 0;
	const asn1_js_1 = require_asn1();
	const asn1_js_2 = require_asn1();
	const key_to_jwk_js_1 = require_key_to_jwk();
	async function exportSPKI(key) {
		return (0, asn1_js_1.toSPKI)(key);
	}
	exports.exportSPKI = exportSPKI;
	async function exportPKCS8(key) {
		return (0, asn1_js_2.toPKCS8)(key);
	}
	exports.exportPKCS8 = exportPKCS8;
	async function exportJWK(key) {
		return (0, key_to_jwk_js_1.default)(key);
	}
	exports.exportJWK = exportJWK;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/encrypt_key_management.js
var require_encrypt_key_management = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const aeskw_js_1 = require_aeskw();
	const ECDH = require_ecdhes();
	const pbes2kw_js_1 = require_pbes2kw();
	const rsaes_js_1 = require_rsaes();
	const base64url_js_1 = require_base64url$1();
	const cek_js_1 = require_cek();
	const errors_js_1 = require_errors$1();
	const export_js_1 = require_export();
	const check_key_type_js_1 = require_check_key_type();
	const aesgcmkw_js_1 = require_aesgcmkw();
	async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
		let encryptedKey;
		let parameters;
		let cek;
		(0, check_key_type_js_1.default)(alg, key, "encrypt");
		switch (alg) {
			case "dir":
				cek = key;
				break;
			case "ECDH-ES":
			case "ECDH-ES+A128KW":
			case "ECDH-ES+A192KW":
			case "ECDH-ES+A256KW": {
				if (!ECDH.ecdhAllowed(key)) throw new errors_js_1.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
				const { apu, apv } = providedParameters;
				let { epk: ephemeralKey } = providedParameters;
				ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey);
				const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey);
				const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
				parameters = { epk: {
					x,
					crv,
					kty
				} };
				if (kty === "EC") parameters.epk.y = y;
				if (apu) parameters.apu = (0, base64url_js_1.encode)(apu);
				if (apv) parameters.apv = (0, base64url_js_1.encode)(apv);
				if (alg === "ECDH-ES") {
					cek = sharedSecret;
					break;
				}
				cek = providedCek || (0, cek_js_1.default)(enc);
				const kwAlg = alg.slice(-6);
				encryptedKey = await (0, aeskw_js_1.wrap)(kwAlg, sharedSecret, cek);
				break;
			}
			case "RSA1_5":
			case "RSA-OAEP":
			case "RSA-OAEP-256":
			case "RSA-OAEP-384":
			case "RSA-OAEP-512":
				cek = providedCek || (0, cek_js_1.default)(enc);
				encryptedKey = await (0, rsaes_js_1.encrypt)(alg, key, cek);
				break;
			case "PBES2-HS256+A128KW":
			case "PBES2-HS384+A192KW":
			case "PBES2-HS512+A256KW": {
				cek = providedCek || (0, cek_js_1.default)(enc);
				const { p2c, p2s } = providedParameters;
				({encryptedKey, ...parameters} = await (0, pbes2kw_js_1.encrypt)(alg, key, cek, p2c, p2s));
				break;
			}
			case "A128KW":
			case "A192KW":
			case "A256KW":
				cek = providedCek || (0, cek_js_1.default)(enc);
				encryptedKey = await (0, aeskw_js_1.wrap)(alg, key, cek);
				break;
			case "A128GCMKW":
			case "A192GCMKW":
			case "A256GCMKW": {
				cek = providedCek || (0, cek_js_1.default)(enc);
				const { iv } = providedParameters;
				({encryptedKey, ...parameters} = await (0, aesgcmkw_js_1.wrap)(alg, key, cek, iv));
				break;
			}
			default: throw new errors_js_1.JOSENotSupported("Invalid or unsupported \"alg\" (JWE Algorithm) header value");
		}
		return {
			cek,
			encryptedKey,
			parameters
		};
	}
	exports.default = encryptKeyManagement;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwe/flattened/encrypt.js
var require_encrypt$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.FlattenedEncrypt = exports.unprotected = void 0;
	const base64url_js_1 = require_base64url$1();
	const encrypt_js_1 = require_encrypt$4();
	const zlib_js_1 = require_zlib();
	const iv_js_1 = require_iv();
	const encrypt_key_management_js_1 = require_encrypt_key_management();
	const errors_js_1 = require_errors$1();
	const is_disjoint_js_1 = require_is_disjoint();
	const buffer_utils_js_1 = require_buffer_utils();
	const validate_crit_js_1 = require_validate_crit();
	exports.unprotected = Symbol();
	var FlattenedEncrypt = class {
		constructor(plaintext) {
			if (!(plaintext instanceof Uint8Array)) throw new TypeError("plaintext must be an instance of Uint8Array");
			this._plaintext = plaintext;
		}
		setKeyManagementParameters(parameters) {
			if (this._keyManagementParameters) throw new TypeError("setKeyManagementParameters can only be called once");
			this._keyManagementParameters = parameters;
			return this;
		}
		setProtectedHeader(protectedHeader) {
			if (this._protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
			this._protectedHeader = protectedHeader;
			return this;
		}
		setSharedUnprotectedHeader(sharedUnprotectedHeader) {
			if (this._sharedUnprotectedHeader) throw new TypeError("setSharedUnprotectedHeader can only be called once");
			this._sharedUnprotectedHeader = sharedUnprotectedHeader;
			return this;
		}
		setUnprotectedHeader(unprotectedHeader) {
			if (this._unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
			this._unprotectedHeader = unprotectedHeader;
			return this;
		}
		setAdditionalAuthenticatedData(aad) {
			this._aad = aad;
			return this;
		}
		setContentEncryptionKey(cek) {
			if (this._cek) throw new TypeError("setContentEncryptionKey can only be called once");
			this._cek = cek;
			return this;
		}
		setInitializationVector(iv) {
			if (this._iv) throw new TypeError("setInitializationVector can only be called once");
			this._iv = iv;
			return this;
		}
		async encrypt(key, options) {
			if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) throw new errors_js_1.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
			if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) throw new errors_js_1.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
			const joseHeader = {
				...this._protectedHeader,
				...this._unprotectedHeader,
				...this._sharedUnprotectedHeader
			};
			(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, /* @__PURE__ */ new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
			if (joseHeader.zip !== void 0) {
				if (!this._protectedHeader || !this._protectedHeader.zip) throw new errors_js_1.JWEInvalid("JWE \"zip\" (Compression Algorithm) Header MUST be integrity protected");
				if (joseHeader.zip !== "DEF") throw new errors_js_1.JOSENotSupported("Unsupported JWE \"zip\" (Compression Algorithm) Header Parameter value");
			}
			const { alg, enc } = joseHeader;
			if (typeof alg !== "string" || !alg) throw new errors_js_1.JWEInvalid("JWE \"alg\" (Algorithm) Header Parameter missing or invalid");
			if (typeof enc !== "string" || !enc) throw new errors_js_1.JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid");
			let encryptedKey;
			if (alg === "dir") {
				if (this._cek) throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption");
			} else if (alg === "ECDH-ES") {
				if (this._cek) throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");
			}
			let cek;
			{
				let parameters;
				({cek, encryptedKey, parameters} = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters));
				if (parameters) if (options && exports.unprotected in options) if (!this._unprotectedHeader) this.setUnprotectedHeader(parameters);
				else this._unprotectedHeader = {
					...this._unprotectedHeader,
					...parameters
				};
				else if (!this._protectedHeader) this.setProtectedHeader(parameters);
				else this._protectedHeader = {
					...this._protectedHeader,
					...parameters
				};
			}
			this._iv || (this._iv = (0, iv_js_1.default)(enc));
			let additionalData;
			let protectedHeader;
			let aadMember;
			if (this._protectedHeader) protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader)));
			else protectedHeader = buffer_utils_js_1.encoder.encode("");
			if (this._aad) {
				aadMember = (0, base64url_js_1.encode)(this._aad);
				additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode("."), buffer_utils_js_1.encoder.encode(aadMember));
			} else additionalData = protectedHeader;
			let ciphertext;
			let tag;
			if (joseHeader.zip === "DEF") {
				const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || zlib_js_1.deflate)(this._plaintext);
				({ciphertext, tag} = await (0, encrypt_js_1.default)(enc, deflated, cek, this._iv, additionalData));
			} else ({ciphertext, tag} = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData));
			const jwe = {
				ciphertext: (0, base64url_js_1.encode)(ciphertext),
				iv: (0, base64url_js_1.encode)(this._iv),
				tag: (0, base64url_js_1.encode)(tag)
			};
			if (encryptedKey) jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);
			if (aadMember) jwe.aad = aadMember;
			if (this._protectedHeader) jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader);
			if (this._sharedUnprotectedHeader) jwe.unprotected = this._sharedUnprotectedHeader;
			if (this._unprotectedHeader) jwe.header = this._unprotectedHeader;
			return jwe;
		}
	};
	exports.FlattenedEncrypt = FlattenedEncrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwe/general/encrypt.js
var require_encrypt$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.GeneralEncrypt = void 0;
	const encrypt_js_1 = require_encrypt$3();
	const errors_js_1 = require_errors$1();
	const cek_js_1 = require_cek();
	const is_disjoint_js_1 = require_is_disjoint();
	const encrypt_key_management_js_1 = require_encrypt_key_management();
	const base64url_js_1 = require_base64url$1();
	const validate_crit_js_1 = require_validate_crit();
	var IndividualRecipient = class {
		constructor(enc, key, options) {
			this.parent = enc;
			this.key = key;
			this.options = options;
		}
		setUnprotectedHeader(unprotectedHeader) {
			if (this.unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
			this.unprotectedHeader = unprotectedHeader;
			return this;
		}
		addRecipient(...args) {
			return this.parent.addRecipient(...args);
		}
		encrypt(...args) {
			return this.parent.encrypt(...args);
		}
		done() {
			return this.parent;
		}
	};
	var GeneralEncrypt = class {
		constructor(plaintext) {
			this._recipients = [];
			this._plaintext = plaintext;
		}
		addRecipient(key, options) {
			const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit });
			this._recipients.push(recipient);
			return recipient;
		}
		setProtectedHeader(protectedHeader) {
			if (this._protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
			this._protectedHeader = protectedHeader;
			return this;
		}
		setSharedUnprotectedHeader(sharedUnprotectedHeader) {
			if (this._unprotectedHeader) throw new TypeError("setSharedUnprotectedHeader can only be called once");
			this._unprotectedHeader = sharedUnprotectedHeader;
			return this;
		}
		setAdditionalAuthenticatedData(aad) {
			this._aad = aad;
			return this;
		}
		async encrypt(options) {
			var _a, _b, _c;
			if (!this._recipients.length) throw new errors_js_1.JWEInvalid("at least one recipient must be added");
			options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw };
			if (this._recipients.length === 1) {
				const [recipient] = this._recipients;
				const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, {
					...recipient.options,
					...options
				});
				let jwe = {
					ciphertext: flattened.ciphertext,
					iv: flattened.iv,
					recipients: [{}],
					tag: flattened.tag
				};
				if (flattened.aad) jwe.aad = flattened.aad;
				if (flattened.protected) jwe.protected = flattened.protected;
				if (flattened.unprotected) jwe.unprotected = flattened.unprotected;
				if (flattened.encrypted_key) jwe.recipients[0].encrypted_key = flattened.encrypted_key;
				if (flattened.header) jwe.recipients[0].header = flattened.header;
				return jwe;
			}
			let enc;
			for (let i = 0; i < this._recipients.length; i++) {
				const recipient = this._recipients[i];
				if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) throw new errors_js_1.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
				const joseHeader = {
					...this._protectedHeader,
					...this._unprotectedHeader,
					...recipient.unprotectedHeader
				};
				const { alg } = joseHeader;
				if (typeof alg !== "string" || !alg) throw new errors_js_1.JWEInvalid("JWE \"alg\" (Algorithm) Header Parameter missing or invalid");
				if (alg === "dir" || alg === "ECDH-ES") throw new errors_js_1.JWEInvalid("\"dir\" and \"ECDH-ES\" alg may only be used with a single recipient");
				if (typeof joseHeader.enc !== "string" || !joseHeader.enc) throw new errors_js_1.JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid");
				if (!enc) enc = joseHeader.enc;
				else if (enc !== joseHeader.enc) throw new errors_js_1.JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter must be the same for all recipients");
				(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this._protectedHeader, joseHeader);
				if (joseHeader.zip !== void 0) {
					if (!this._protectedHeader || !this._protectedHeader.zip) throw new errors_js_1.JWEInvalid("JWE \"zip\" (Compression Algorithm) Header MUST be integrity protected");
				}
			}
			const cek = (0, cek_js_1.default)(enc);
			let jwe = {
				ciphertext: "",
				iv: "",
				recipients: [],
				tag: ""
			};
			for (let i = 0; i < this._recipients.length; i++) {
				const recipient = this._recipients[i];
				const target = {};
				jwe.recipients.push(target);
				const p2c = {
					...this._protectedHeader,
					...this._unprotectedHeader,
					...recipient.unprotectedHeader
				}.alg.startsWith("PBES2") ? 2048 + i : void 0;
				if (i === 0) {
					const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(cek).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters({ p2c }).encrypt(recipient.key, {
						...recipient.options,
						...options,
						[encrypt_js_1.unprotected]: true
					});
					jwe.ciphertext = flattened.ciphertext;
					jwe.iv = flattened.iv;
					jwe.tag = flattened.tag;
					if (flattened.aad) jwe.aad = flattened.aad;
					if (flattened.protected) jwe.protected = flattened.protected;
					if (flattened.unprotected) jwe.unprotected = flattened.unprotected;
					target.encrypted_key = flattened.encrypted_key;
					if (flattened.header) target.header = flattened.header;
					continue;
				}
				const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) || ((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) || ((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.alg), enc, recipient.key, cek, { p2c });
				target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);
				if (recipient.unprotectedHeader || parameters) target.header = {
					...recipient.unprotectedHeader,
					...parameters
				};
			}
			return jwe;
		}
	};
	exports.GeneralEncrypt = GeneralEncrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/dsa_digest.js
var require_dsa_digest = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const errors_js_1 = require_errors$1();
	function dsaDigest(alg) {
		switch (alg) {
			case "PS256":
			case "RS256":
			case "ES256":
			case "ES256K": return "sha256";
			case "PS384":
			case "RS384":
			case "ES384": return "sha384";
			case "PS512":
			case "RS512":
			case "ES512": return "sha512";
			case "EdDSA": return;
			default: throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
		}
	}
	exports.default = dsaDigest;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/node_key.js
var require_node_key = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$2 = __require("crypto");
	const get_named_curve_js_1 = require_get_named_curve();
	const errors_js_1 = require_errors$1();
	const check_modulus_length_js_1 = require_check_modulus_length();
	const flags_js_1 = require_flags();
	const PSS = {
		padding: crypto_1$2.constants.RSA_PKCS1_PSS_PADDING,
		saltLength: crypto_1$2.constants.RSA_PSS_SALTLEN_DIGEST
	};
	const ecCurveAlgMap = new Map([
		["ES256", "P-256"],
		["ES256K", "secp256k1"],
		["ES384", "P-384"],
		["ES512", "P-521"]
	]);
	function keyForCrypto(alg, key) {
		switch (alg) {
			case "EdDSA":
				if (!["ed25519", "ed448"].includes(key.asymmetricKeyType)) throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");
				return key;
			case "RS256":
			case "RS384":
			case "RS512":
				if (key.asymmetricKeyType !== "rsa") throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");
				(0, check_modulus_length_js_1.default)(key, alg);
				return key;
			case flags_js_1.rsaPssParams && "PS256":
			case flags_js_1.rsaPssParams && "PS384":
			case flags_js_1.rsaPssParams && "PS512":
				if (key.asymmetricKeyType === "rsa-pss") {
					const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;
					const length = parseInt(alg.slice(-3), 10);
					if (hashAlgorithm !== void 0 && (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`);
					if (saltLength !== void 0 && saltLength > length >> 3) throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`);
				} else if (key.asymmetricKeyType !== "rsa") throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");
				(0, check_modulus_length_js_1.default)(key, alg);
				return {
					key,
					...PSS
				};
			case !flags_js_1.rsaPssParams && "PS256":
			case !flags_js_1.rsaPssParams && "PS384":
			case !flags_js_1.rsaPssParams && "PS512":
				if (key.asymmetricKeyType !== "rsa") throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");
				(0, check_modulus_length_js_1.default)(key, alg);
				return {
					key,
					...PSS
				};
			case "ES256":
			case "ES256K":
			case "ES384":
			case "ES512": {
				if (key.asymmetricKeyType !== "ec") throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");
				const actual = (0, get_named_curve_js_1.default)(key);
				const expected = ecCurveAlgMap.get(alg);
				if (actual !== expected) throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`);
				return {
					dsaEncoding: "ieee-p1363",
					key
				};
			}
			default: throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
		}
	}
	exports.default = keyForCrypto;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/hmac_digest.js
var require_hmac_digest = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const errors_js_1 = require_errors$1();
	function hmacDigest(alg) {
		switch (alg) {
			case "HS256": return "sha256";
			case "HS384": return "sha384";
			case "HS512": return "sha512";
			default: throw new errors_js_1.JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
		}
	}
	exports.default = hmacDigest;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/get_sign_verify_key.js
var require_get_sign_verify_key = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto_1$1 = __require("crypto");
	const webcrypto_js_1 = require_webcrypto();
	const crypto_key_js_1 = require_crypto_key();
	const invalid_key_input_js_1 = require_invalid_key_input();
	const is_key_like_js_1 = require_is_key_like();
	function getSignVerifyKey(alg, key, usage) {
		if (key instanceof Uint8Array) {
			if (!alg.startsWith("HS")) throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));
			return (0, crypto_1$1.createSecretKey)(key);
		}
		if (key instanceof crypto_1$1.KeyObject) return key;
		if ((0, webcrypto_js_1.isCryptoKey)(key)) {
			(0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage);
			return crypto_1$1.KeyObject.from(key);
		}
		throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, "Uint8Array"));
	}
	exports.default = getSignVerifyKey;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/sign.js
var require_sign$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto$1 = __require("crypto");
	const util_1$2 = __require("util");
	const dsa_digest_js_1 = require_dsa_digest();
	const hmac_digest_js_1 = require_hmac_digest();
	const node_key_js_1 = require_node_key();
	const get_sign_verify_key_js_1 = require_get_sign_verify_key();
	let oneShotSign;
	if (crypto$1.sign.length > 3) oneShotSign = (0, util_1$2.promisify)(crypto$1.sign);
	else oneShotSign = crypto$1.sign;
	const sign = async (alg, key, data) => {
		const keyObject = (0, get_sign_verify_key_js_1.default)(alg, key, "sign");
		if (alg.startsWith("HS")) {
			const hmac = crypto$1.createHmac((0, hmac_digest_js_1.default)(alg), keyObject);
			hmac.update(data);
			return hmac.digest();
		}
		return oneShotSign((0, dsa_digest_js_1.default)(alg), data, (0, node_key_js_1.default)(alg, keyObject));
	};
	exports.default = sign;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/verify.js
var require_verify$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const crypto = __require("crypto");
	const util_1$1 = __require("util");
	const dsa_digest_js_1 = require_dsa_digest();
	const node_key_js_1 = require_node_key();
	const sign_js_1 = require_sign$4();
	const get_sign_verify_key_js_1 = require_get_sign_verify_key();
	const flags_js_1 = require_flags();
	let oneShotVerify;
	if (crypto.verify.length > 4 && flags_js_1.oneShotCallback) oneShotVerify = (0, util_1$1.promisify)(crypto.verify);
	else oneShotVerify = crypto.verify;
	const verify = async (alg, key, signature, data) => {
		const keyObject = (0, get_sign_verify_key_js_1.default)(alg, key, "verify");
		if (alg.startsWith("HS")) {
			const expected = await (0, sign_js_1.default)(alg, keyObject, data);
			const actual = signature;
			try {
				return crypto.timingSafeEqual(actual, expected);
			} catch {
				return false;
			}
		}
		const algorithm = (0, dsa_digest_js_1.default)(alg);
		const keyInput = (0, node_key_js_1.default)(alg, keyObject);
		try {
			return await oneShotVerify(algorithm, data, keyInput, signature);
		} catch {
			return false;
		}
	};
	exports.default = verify;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jws/flattened/verify.js
var require_verify$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.flattenedVerify = void 0;
	const base64url_js_1 = require_base64url$1();
	const verify_js_1 = require_verify$4();
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const is_disjoint_js_1 = require_is_disjoint();
	const is_object_js_1 = require_is_object();
	const check_key_type_js_1 = require_check_key_type();
	const validate_crit_js_1 = require_validate_crit();
	const validate_algorithms_js_1 = require_validate_algorithms();
	async function flattenedVerify(jws, key, options) {
		var _a;
		if (!(0, is_object_js_1.default)(jws)) throw new errors_js_1.JWSInvalid("Flattened JWS must be an object");
		if (jws.protected === void 0 && jws.header === void 0) throw new errors_js_1.JWSInvalid("Flattened JWS must have either of the \"protected\" or \"header\" members");
		if (jws.protected !== void 0 && typeof jws.protected !== "string") throw new errors_js_1.JWSInvalid("JWS Protected Header incorrect type");
		if (jws.payload === void 0) throw new errors_js_1.JWSInvalid("JWS Payload missing");
		if (typeof jws.signature !== "string") throw new errors_js_1.JWSInvalid("JWS Signature missing or incorrect type");
		if (jws.header !== void 0 && !(0, is_object_js_1.default)(jws.header)) throw new errors_js_1.JWSInvalid("JWS Unprotected Header incorrect type");
		let parsedProt = {};
		if (jws.protected) try {
			const protectedHeader = (0, base64url_js_1.decode)(jws.protected);
			parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader));
		} catch {
			throw new errors_js_1.JWSInvalid("JWS Protected Header is invalid");
		}
		if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) throw new errors_js_1.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
		const joseHeader = {
			...parsedProt,
			...jws.header
		};
		const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([["b64", true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
		let b64 = true;
		if (extensions.has("b64")) {
			b64 = parsedProt.b64;
			if (typeof b64 !== "boolean") throw new errors_js_1.JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
		}
		const { alg } = joseHeader;
		if (typeof alg !== "string" || !alg) throw new errors_js_1.JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
		const algorithms = options && (0, validate_algorithms_js_1.default)("algorithms", options.algorithms);
		if (algorithms && !algorithms.has(alg)) throw new errors_js_1.JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter not allowed");
		if (b64) {
			if (typeof jws.payload !== "string") throw new errors_js_1.JWSInvalid("JWS Payload must be a string");
		} else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) throw new errors_js_1.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
		let resolvedKey = false;
		if (typeof key === "function") {
			key = await key(parsedProt, jws);
			resolvedKey = true;
		}
		(0, check_key_type_js_1.default)(alg, key, "verify");
		const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ""), buffer_utils_js_1.encoder.encode("."), typeof jws.payload === "string" ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload);
		let signature;
		try {
			signature = (0, base64url_js_1.decode)(jws.signature);
		} catch {
			throw new errors_js_1.JWSInvalid("Failed to base64url decode the signature");
		}
		if (!await (0, verify_js_1.default)(alg, key, signature, data)) throw new errors_js_1.JWSSignatureVerificationFailed();
		let payload;
		if (b64) try {
			payload = (0, base64url_js_1.decode)(jws.payload);
		} catch {
			throw new errors_js_1.JWSInvalid("Failed to base64url decode the payload");
		}
		else if (typeof jws.payload === "string") payload = buffer_utils_js_1.encoder.encode(jws.payload);
		else payload = jws.payload;
		const result = { payload };
		if (jws.protected !== void 0) result.protectedHeader = parsedProt;
		if (jws.header !== void 0) result.unprotectedHeader = jws.header;
		if (resolvedKey) return {
			...result,
			key
		};
		return result;
	}
	exports.flattenedVerify = flattenedVerify;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jws/compact/verify.js
var require_verify$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.compactVerify = void 0;
	const verify_js_1 = require_verify$3();
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	async function compactVerify(jws, key, options) {
		if (jws instanceof Uint8Array) jws = buffer_utils_js_1.decoder.decode(jws);
		if (typeof jws !== "string") throw new errors_js_1.JWSInvalid("Compact JWS must be a string or Uint8Array");
		const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
		if (length !== 3) throw new errors_js_1.JWSInvalid("Invalid Compact JWS");
		const verified = await (0, verify_js_1.flattenedVerify)({
			payload,
			protected: protectedHeader,
			signature
		}, key, options);
		const result = {
			payload: verified.payload,
			protectedHeader: verified.protectedHeader
		};
		if (typeof key === "function") return {
			...result,
			key: verified.key
		};
		return result;
	}
	exports.compactVerify = compactVerify;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jws/general/verify.js
var require_verify$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.generalVerify = void 0;
	const verify_js_1 = require_verify$3();
	const errors_js_1 = require_errors$1();
	const is_object_js_1 = require_is_object();
	async function generalVerify(jws, key, options) {
		if (!(0, is_object_js_1.default)(jws)) throw new errors_js_1.JWSInvalid("General JWS must be an object");
		if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) throw new errors_js_1.JWSInvalid("JWS Signatures missing or incorrect type");
		for (const signature of jws.signatures) try {
			return await (0, verify_js_1.flattenedVerify)({
				header: signature.header,
				payload: jws.payload,
				protected: signature.protected,
				signature: signature.signature
			}, key, options);
		} catch {}
		throw new errors_js_1.JWSSignatureVerificationFailed();
	}
	exports.generalVerify = generalVerify;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/epoch.js
var require_epoch = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.default = (date) => Math.floor(date.getTime() / 1e3);
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/secs.js
var require_secs = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const minute = 60;
	const hour = minute * 60;
	const day = hour * 24;
	const week = day * 7;
	const year = day * 365.25;
	const REGEX = /^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i;
	exports.default = (str) => {
		const matched = REGEX.exec(str);
		if (!matched) throw new TypeError("Invalid time period format");
		const value = parseFloat(matched[1]);
		switch (matched[2].toLowerCase()) {
			case "sec":
			case "secs":
			case "second":
			case "seconds":
			case "s": return Math.round(value);
			case "minute":
			case "minutes":
			case "min":
			case "mins":
			case "m": return Math.round(value * minute);
			case "hour":
			case "hours":
			case "hr":
			case "hrs":
			case "h": return Math.round(value * hour);
			case "day":
			case "days":
			case "d": return Math.round(value * day);
			case "week":
			case "weeks":
			case "w": return Math.round(value * week);
			default: return Math.round(value * year);
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/lib/jwt_claims_set.js
var require_jwt_claims_set = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const epoch_js_1 = require_epoch();
	const secs_js_1 = require_secs();
	const is_object_js_1 = require_is_object();
	const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, "");
	const checkAudiencePresence = (audPayload, audOption) => {
		if (typeof audPayload === "string") return audOption.includes(audPayload);
		if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
		return false;
	};
	exports.default = (protectedHeader, encodedPayload, options = {}) => {
		const { typ } = options;
		if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new errors_js_1.JWTClaimValidationFailed("unexpected \"typ\" JWT header value", "typ", "check_failed");
		let payload;
		try {
			payload = JSON.parse(buffer_utils_js_1.decoder.decode(encodedPayload));
		} catch {}
		if (!(0, is_object_js_1.default)(payload)) throw new errors_js_1.JWTInvalid("JWT Claims Set must be a top-level JSON object");
		const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
		if (maxTokenAge !== void 0) requiredClaims.push("iat");
		if (audience !== void 0) requiredClaims.push("aud");
		if (subject !== void 0) requiredClaims.push("sub");
		if (issuer !== void 0) requiredClaims.push("iss");
		for (const claim of new Set(requiredClaims.reverse())) if (!(claim in payload)) throw new errors_js_1.JWTClaimValidationFailed(`missing required "${claim}" claim`, claim, "missing");
		if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) throw new errors_js_1.JWTClaimValidationFailed("unexpected \"iss\" claim value", "iss", "check_failed");
		if (subject && payload.sub !== subject) throw new errors_js_1.JWTClaimValidationFailed("unexpected \"sub\" claim value", "sub", "check_failed");
		if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) throw new errors_js_1.JWTClaimValidationFailed("unexpected \"aud\" claim value", "aud", "check_failed");
		let tolerance;
		switch (typeof options.clockTolerance) {
			case "string":
				tolerance = (0, secs_js_1.default)(options.clockTolerance);
				break;
			case "number":
				tolerance = options.clockTolerance;
				break;
			case "undefined":
				tolerance = 0;
				break;
			default: throw new TypeError("Invalid clockTolerance option type");
		}
		const { currentDate } = options;
		const now = (0, epoch_js_1.default)(currentDate || /* @__PURE__ */ new Date());
		if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") throw new errors_js_1.JWTClaimValidationFailed("\"iat\" claim must be a number", "iat", "invalid");
		if (payload.nbf !== void 0) {
			if (typeof payload.nbf !== "number") throw new errors_js_1.JWTClaimValidationFailed("\"nbf\" claim must be a number", "nbf", "invalid");
			if (payload.nbf > now + tolerance) throw new errors_js_1.JWTClaimValidationFailed("\"nbf\" claim timestamp check failed", "nbf", "check_failed");
		}
		if (payload.exp !== void 0) {
			if (typeof payload.exp !== "number") throw new errors_js_1.JWTClaimValidationFailed("\"exp\" claim must be a number", "exp", "invalid");
			if (payload.exp <= now - tolerance) throw new errors_js_1.JWTExpired("\"exp\" claim timestamp check failed", "exp", "check_failed");
		}
		if (maxTokenAge) {
			const age = now - payload.iat;
			const max = typeof maxTokenAge === "number" ? maxTokenAge : (0, secs_js_1.default)(maxTokenAge);
			if (age - tolerance > max) throw new errors_js_1.JWTExpired("\"iat\" claim timestamp check failed (too far in the past)", "iat", "check_failed");
			if (age < 0 - tolerance) throw new errors_js_1.JWTClaimValidationFailed("\"iat\" claim timestamp check failed (it should be in the past)", "iat", "check_failed");
		}
		return payload;
	};
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwt/verify.js
var require_verify = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.jwtVerify = void 0;
	const verify_js_1 = require_verify$2();
	const jwt_claims_set_js_1 = require_jwt_claims_set();
	const errors_js_1 = require_errors$1();
	async function jwtVerify(jwt, key, options) {
		var _a;
		const verified = await (0, verify_js_1.compactVerify)(jwt, key, options);
		if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes("b64")) && verified.protectedHeader.b64 === false) throw new errors_js_1.JWTInvalid("JWTs MUST NOT use unencoded payload");
		const result = {
			payload: (0, jwt_claims_set_js_1.default)(verified.protectedHeader, verified.payload, options),
			protectedHeader: verified.protectedHeader
		};
		if (typeof key === "function") return {
			...result,
			key: verified.key
		};
		return result;
	}
	exports.jwtVerify = jwtVerify;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwt/decrypt.js
var require_decrypt = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.jwtDecrypt = void 0;
	const decrypt_js_1 = require_decrypt$2();
	const jwt_claims_set_js_1 = require_jwt_claims_set();
	const errors_js_1 = require_errors$1();
	async function jwtDecrypt(jwt, key, options) {
		const decrypted = await (0, decrypt_js_1.compactDecrypt)(jwt, key, options);
		const payload = (0, jwt_claims_set_js_1.default)(decrypted.protectedHeader, decrypted.plaintext, options);
		const { protectedHeader } = decrypted;
		if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) throw new errors_js_1.JWTClaimValidationFailed("replicated \"iss\" claim header parameter mismatch", "iss", "mismatch");
		if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) throw new errors_js_1.JWTClaimValidationFailed("replicated \"sub\" claim header parameter mismatch", "sub", "mismatch");
		if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) throw new errors_js_1.JWTClaimValidationFailed("replicated \"aud\" claim header parameter mismatch", "aud", "mismatch");
		const result = {
			payload,
			protectedHeader
		};
		if (typeof key === "function") return {
			...result,
			key: decrypted.key
		};
		return result;
	}
	exports.jwtDecrypt = jwtDecrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwe/compact/encrypt.js
var require_encrypt$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.CompactEncrypt = void 0;
	const encrypt_js_1 = require_encrypt$3();
	var CompactEncrypt = class {
		constructor(plaintext) {
			this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext);
		}
		setContentEncryptionKey(cek) {
			this._flattened.setContentEncryptionKey(cek);
			return this;
		}
		setInitializationVector(iv) {
			this._flattened.setInitializationVector(iv);
			return this;
		}
		setProtectedHeader(protectedHeader) {
			this._flattened.setProtectedHeader(protectedHeader);
			return this;
		}
		setKeyManagementParameters(parameters) {
			this._flattened.setKeyManagementParameters(parameters);
			return this;
		}
		async encrypt(key, options) {
			const jwe = await this._flattened.encrypt(key, options);
			return [
				jwe.protected,
				jwe.encrypted_key,
				jwe.iv,
				jwe.ciphertext,
				jwe.tag
			].join(".");
		}
	};
	exports.CompactEncrypt = CompactEncrypt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jws/flattened/sign.js
var require_sign$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.FlattenedSign = void 0;
	const base64url_js_1 = require_base64url$1();
	const sign_js_1 = require_sign$4();
	const is_disjoint_js_1 = require_is_disjoint();
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const check_key_type_js_1 = require_check_key_type();
	const validate_crit_js_1 = require_validate_crit();
	var FlattenedSign = class {
		constructor(payload) {
			if (!(payload instanceof Uint8Array)) throw new TypeError("payload must be an instance of Uint8Array");
			this._payload = payload;
		}
		setProtectedHeader(protectedHeader) {
			if (this._protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
			this._protectedHeader = protectedHeader;
			return this;
		}
		setUnprotectedHeader(unprotectedHeader) {
			if (this._unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
			this._unprotectedHeader = unprotectedHeader;
			return this;
		}
		async sign(key, options) {
			if (!this._protectedHeader && !this._unprotectedHeader) throw new errors_js_1.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
			if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader)) throw new errors_js_1.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
			const joseHeader = {
				...this._protectedHeader,
				...this._unprotectedHeader
			};
			const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([["b64", true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
			let b64 = true;
			if (extensions.has("b64")) {
				b64 = this._protectedHeader.b64;
				if (typeof b64 !== "boolean") throw new errors_js_1.JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
			}
			const { alg } = joseHeader;
			if (typeof alg !== "string" || !alg) throw new errors_js_1.JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
			(0, check_key_type_js_1.default)(alg, key, "sign");
			let payload = this._payload;
			if (b64) payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload));
			let protectedHeader;
			if (this._protectedHeader) protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader)));
			else protectedHeader = buffer_utils_js_1.encoder.encode("");
			const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode("."), payload);
			const signature = await (0, sign_js_1.default)(alg, key, data);
			const jws = {
				signature: (0, base64url_js_1.encode)(signature),
				payload: ""
			};
			if (b64) jws.payload = buffer_utils_js_1.decoder.decode(payload);
			if (this._unprotectedHeader) jws.header = this._unprotectedHeader;
			if (this._protectedHeader) jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader);
			return jws;
		}
	};
	exports.FlattenedSign = FlattenedSign;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jws/compact/sign.js
var require_sign$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.CompactSign = void 0;
	const sign_js_1 = require_sign$3();
	var CompactSign = class {
		constructor(payload) {
			this._flattened = new sign_js_1.FlattenedSign(payload);
		}
		setProtectedHeader(protectedHeader) {
			this._flattened.setProtectedHeader(protectedHeader);
			return this;
		}
		async sign(key, options) {
			const jws = await this._flattened.sign(key, options);
			if (jws.payload === void 0) throw new TypeError("use the flattened module for creating JWS with b64: false");
			return `${jws.protected}.${jws.payload}.${jws.signature}`;
		}
	};
	exports.CompactSign = CompactSign;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jws/general/sign.js
var require_sign$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.GeneralSign = void 0;
	const sign_js_1 = require_sign$3();
	const errors_js_1 = require_errors$1();
	var IndividualSignature = class {
		constructor(sig, key, options) {
			this.parent = sig;
			this.key = key;
			this.options = options;
		}
		setProtectedHeader(protectedHeader) {
			if (this.protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
			this.protectedHeader = protectedHeader;
			return this;
		}
		setUnprotectedHeader(unprotectedHeader) {
			if (this.unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
			this.unprotectedHeader = unprotectedHeader;
			return this;
		}
		addSignature(...args) {
			return this.parent.addSignature(...args);
		}
		sign(...args) {
			return this.parent.sign(...args);
		}
		done() {
			return this.parent;
		}
	};
	var GeneralSign = class {
		constructor(payload) {
			this._signatures = [];
			this._payload = payload;
		}
		addSignature(key, options) {
			const signature = new IndividualSignature(this, key, options);
			this._signatures.push(signature);
			return signature;
		}
		async sign() {
			if (!this._signatures.length) throw new errors_js_1.JWSInvalid("at least one signature must be added");
			const jws = {
				signatures: [],
				payload: ""
			};
			for (let i = 0; i < this._signatures.length; i++) {
				const signature = this._signatures[i];
				const flattened = new sign_js_1.FlattenedSign(this._payload);
				flattened.setProtectedHeader(signature.protectedHeader);
				flattened.setUnprotectedHeader(signature.unprotectedHeader);
				const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
				if (i === 0) jws.payload = payload;
				else if (jws.payload !== payload) throw new errors_js_1.JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");
				jws.signatures.push(rest);
			}
			return jws;
		}
	};
	exports.GeneralSign = GeneralSign;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwt/produce.js
var require_produce = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ProduceJWT = void 0;
	const epoch_js_1 = require_epoch();
	const is_object_js_1 = require_is_object();
	const secs_js_1 = require_secs();
	var ProduceJWT = class {
		constructor(payload) {
			if (!(0, is_object_js_1.default)(payload)) throw new TypeError("JWT Claims Set MUST be an object");
			this._payload = payload;
		}
		setIssuer(issuer) {
			this._payload = {
				...this._payload,
				iss: issuer
			};
			return this;
		}
		setSubject(subject) {
			this._payload = {
				...this._payload,
				sub: subject
			};
			return this;
		}
		setAudience(audience) {
			this._payload = {
				...this._payload,
				aud: audience
			};
			return this;
		}
		setJti(jwtId) {
			this._payload = {
				...this._payload,
				jti: jwtId
			};
			return this;
		}
		setNotBefore(input) {
			if (typeof input === "number") this._payload = {
				...this._payload,
				nbf: input
			};
			else this._payload = {
				...this._payload,
				nbf: (0, epoch_js_1.default)(/* @__PURE__ */ new Date()) + (0, secs_js_1.default)(input)
			};
			return this;
		}
		setExpirationTime(input) {
			if (typeof input === "number") this._payload = {
				...this._payload,
				exp: input
			};
			else this._payload = {
				...this._payload,
				exp: (0, epoch_js_1.default)(/* @__PURE__ */ new Date()) + (0, secs_js_1.default)(input)
			};
			return this;
		}
		setIssuedAt(input) {
			if (typeof input === "undefined") this._payload = {
				...this._payload,
				iat: (0, epoch_js_1.default)(/* @__PURE__ */ new Date())
			};
			else this._payload = {
				...this._payload,
				iat: input
			};
			return this;
		}
	};
	exports.ProduceJWT = ProduceJWT;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwt/sign.js
var require_sign = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.SignJWT = void 0;
	const sign_js_1 = require_sign$2();
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const produce_js_1 = require_produce();
	var SignJWT = class extends produce_js_1.ProduceJWT {
		setProtectedHeader(protectedHeader) {
			this._protectedHeader = protectedHeader;
			return this;
		}
		async sign(key, options) {
			var _a;
			const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload)));
			sig.setProtectedHeader(this._protectedHeader);
			if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) throw new errors_js_1.JWTInvalid("JWTs MUST NOT use unencoded payload");
			return sig.sign(key, options);
		}
	};
	exports.SignJWT = SignJWT;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwt/encrypt.js
var require_encrypt = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.EncryptJWT = void 0;
	const encrypt_js_1 = require_encrypt$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const produce_js_1 = require_produce();
	var EncryptJWT = class extends produce_js_1.ProduceJWT {
		setProtectedHeader(protectedHeader) {
			if (this._protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
			this._protectedHeader = protectedHeader;
			return this;
		}
		setKeyManagementParameters(parameters) {
			if (this._keyManagementParameters) throw new TypeError("setKeyManagementParameters can only be called once");
			this._keyManagementParameters = parameters;
			return this;
		}
		setContentEncryptionKey(cek) {
			if (this._cek) throw new TypeError("setContentEncryptionKey can only be called once");
			this._cek = cek;
			return this;
		}
		setInitializationVector(iv) {
			if (this._iv) throw new TypeError("setInitializationVector can only be called once");
			this._iv = iv;
			return this;
		}
		replicateIssuerAsHeader() {
			this._replicateIssuerAsHeader = true;
			return this;
		}
		replicateSubjectAsHeader() {
			this._replicateSubjectAsHeader = true;
			return this;
		}
		replicateAudienceAsHeader() {
			this._replicateAudienceAsHeader = true;
			return this;
		}
		async encrypt(key, options) {
			const enc = new encrypt_js_1.CompactEncrypt(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload)));
			if (this._replicateIssuerAsHeader) this._protectedHeader = {
				...this._protectedHeader,
				iss: this._payload.iss
			};
			if (this._replicateSubjectAsHeader) this._protectedHeader = {
				...this._protectedHeader,
				sub: this._payload.sub
			};
			if (this._replicateAudienceAsHeader) this._protectedHeader = {
				...this._protectedHeader,
				aud: this._payload.aud
			};
			enc.setProtectedHeader(this._protectedHeader);
			if (this._iv) enc.setInitializationVector(this._iv);
			if (this._cek) enc.setContentEncryptionKey(this._cek);
			if (this._keyManagementParameters) enc.setKeyManagementParameters(this._keyManagementParameters);
			return enc.encrypt(key, options);
		}
	};
	exports.EncryptJWT = EncryptJWT;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwk/thumbprint.js
var require_thumbprint = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = void 0;
	const digest_js_1 = require_digest();
	const base64url_js_1 = require_base64url$1();
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const is_object_js_1 = require_is_object();
	const check = (value, description) => {
		if (typeof value !== "string" || !value) throw new errors_js_1.JWKInvalid(`${description} missing or invalid`);
	};
	async function calculateJwkThumbprint(jwk, digestAlgorithm) {
		if (!(0, is_object_js_1.default)(jwk)) throw new TypeError("JWK must be an object");
		digestAlgorithm !== null && digestAlgorithm !== void 0 || (digestAlgorithm = "sha256");
		if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") throw new TypeError("digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"");
		let components;
		switch (jwk.kty) {
			case "EC":
				check(jwk.crv, "\"crv\" (Curve) Parameter");
				check(jwk.x, "\"x\" (X Coordinate) Parameter");
				check(jwk.y, "\"y\" (Y Coordinate) Parameter");
				components = {
					crv: jwk.crv,
					kty: jwk.kty,
					x: jwk.x,
					y: jwk.y
				};
				break;
			case "OKP":
				check(jwk.crv, "\"crv\" (Subtype of Key Pair) Parameter");
				check(jwk.x, "\"x\" (Public Key) Parameter");
				components = {
					crv: jwk.crv,
					kty: jwk.kty,
					x: jwk.x
				};
				break;
			case "RSA":
				check(jwk.e, "\"e\" (Exponent) Parameter");
				check(jwk.n, "\"n\" (Modulus) Parameter");
				components = {
					e: jwk.e,
					kty: jwk.kty,
					n: jwk.n
				};
				break;
			case "oct":
				check(jwk.k, "\"k\" (Key Value) Parameter");
				components = {
					k: jwk.k,
					kty: jwk.kty
				};
				break;
			default: throw new errors_js_1.JOSENotSupported("\"kty\" (Key Type) Parameter missing or unsupported");
		}
		const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components));
		return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data));
	}
	exports.calculateJwkThumbprint = calculateJwkThumbprint;
	async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
		digestAlgorithm !== null && digestAlgorithm !== void 0 || (digestAlgorithm = "sha256");
		const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
		return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
	}
	exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwk/embedded.js
var require_embedded = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.EmbeddedJWK = void 0;
	const import_js_1 = require_import();
	const is_object_js_1 = require_is_object();
	const errors_js_1 = require_errors$1();
	async function EmbeddedJWK(protectedHeader, token) {
		const joseHeader = {
			...protectedHeader,
			...token === null || token === void 0 ? void 0 : token.header
		};
		if (!(0, is_object_js_1.default)(joseHeader.jwk)) throw new errors_js_1.JWSInvalid("\"jwk\" (JSON Web Key) Header Parameter must be a JSON object");
		const key = await (0, import_js_1.importJWK)({
			...joseHeader.jwk,
			ext: true
		}, joseHeader.alg, true);
		if (key instanceof Uint8Array || key.type !== "public") throw new errors_js_1.JWSInvalid("\"jwk\" (JSON Web Key) Header Parameter must be a public key");
		return key;
	}
	exports.EmbeddedJWK = EmbeddedJWK;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwks/local.js
var require_local = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.createLocalJWKSet = exports.LocalJWKSet = exports.isJWKSLike = void 0;
	const import_js_1 = require_import();
	const errors_js_1 = require_errors$1();
	const is_object_js_1 = require_is_object();
	function getKtyFromAlg(alg) {
		switch (typeof alg === "string" && alg.slice(0, 2)) {
			case "RS":
			case "PS": return "RSA";
			case "ES": return "EC";
			case "Ed": return "OKP";
			default: throw new errors_js_1.JOSENotSupported("Unsupported \"alg\" value for a JSON Web Key Set");
		}
	}
	function isJWKSLike(jwks) {
		return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
	}
	exports.isJWKSLike = isJWKSLike;
	function isJWKLike(key) {
		return (0, is_object_js_1.default)(key);
	}
	function clone(obj) {
		if (typeof structuredClone === "function") return structuredClone(obj);
		return JSON.parse(JSON.stringify(obj));
	}
	var LocalJWKSet = class {
		constructor(jwks) {
			this._cached = /* @__PURE__ */ new WeakMap();
			if (!isJWKSLike(jwks)) throw new errors_js_1.JWKSInvalid("JSON Web Key Set malformed");
			this._jwks = clone(jwks);
		}
		async getKey(protectedHeader, token) {
			const { alg, kid } = {
				...protectedHeader,
				...token === null || token === void 0 ? void 0 : token.header
			};
			const kty = getKtyFromAlg(alg);
			const candidates = this._jwks.keys.filter((jwk) => {
				let candidate = kty === jwk.kty;
				if (candidate && typeof kid === "string") candidate = kid === jwk.kid;
				if (candidate && typeof jwk.alg === "string") candidate = alg === jwk.alg;
				if (candidate && typeof jwk.use === "string") candidate = jwk.use === "sig";
				if (candidate && Array.isArray(jwk.key_ops)) candidate = jwk.key_ops.includes("verify");
				if (candidate && alg === "EdDSA") candidate = jwk.crv === "Ed25519" || jwk.crv === "Ed448";
				if (candidate) switch (alg) {
					case "ES256":
						candidate = jwk.crv === "P-256";
						break;
					case "ES256K":
						candidate = jwk.crv === "secp256k1";
						break;
					case "ES384":
						candidate = jwk.crv === "P-384";
						break;
					case "ES512":
						candidate = jwk.crv === "P-521";
						break;
				}
				return candidate;
			});
			const { 0: jwk, length } = candidates;
			if (length === 0) throw new errors_js_1.JWKSNoMatchingKey();
			else if (length !== 1) {
				const error = new errors_js_1.JWKSMultipleMatchingKeys();
				const { _cached } = this;
				error[Symbol.asyncIterator] = async function* () {
					for (const jwk of candidates) try {
						yield await importWithAlgCache(_cached, jwk, alg);
					} catch {
						continue;
					}
				};
				throw error;
			}
			return importWithAlgCache(this._cached, jwk, alg);
		}
	};
	exports.LocalJWKSet = LocalJWKSet;
	async function importWithAlgCache(cache, jwk, alg) {
		const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
		if (cached[alg] === void 0) {
			const key = await (0, import_js_1.importJWK)({
				...jwk,
				ext: true
			}, alg);
			if (key instanceof Uint8Array || key.type !== "public") throw new errors_js_1.JWKSInvalid("JSON Web Key Set members must be public keys");
			cached[alg] = key;
		}
		return cached[alg];
	}
	function createLocalJWKSet(jwks) {
		const set = new LocalJWKSet(jwks);
		return async function(protectedHeader, token) {
			return set.getKey(protectedHeader, token);
		};
	}
	exports.createLocalJWKSet = createLocalJWKSet;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/fetch_jwks.js
var require_fetch_jwks = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	const http$1 = __require("http");
	const https$1 = __require("https");
	const events_1$2 = __require("events");
	const errors_js_1 = require_errors$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const fetchJwks = async (url, timeout, options) => {
		let get;
		switch (url.protocol) {
			case "https:":
				get = https$1.get;
				break;
			case "http:":
				get = http$1.get;
				break;
			default: throw new TypeError("Unsupported URL protocol.");
		}
		const { agent, headers } = options;
		const req = get(url.href, {
			agent,
			timeout,
			headers
		});
		const [response] = await Promise.race([(0, events_1$2.once)(req, "response"), (0, events_1$2.once)(req, "timeout")]);
		if (!response) {
			req.destroy();
			throw new errors_js_1.JWKSTimeout();
		}
		if (response.statusCode !== 200) throw new errors_js_1.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
		const parts = [];
		for await (const part of response) parts.push(part);
		try {
			return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts)));
		} catch {
			throw new errors_js_1.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
		}
	};
	exports.default = fetchJwks;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwks/remote.js
var require_remote = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.createRemoteJWKSet = void 0;
	const fetch_jwks_js_1 = require_fetch_jwks();
	const errors_js_1 = require_errors$1();
	const local_js_1 = require_local();
	function isCloudflareWorkers() {
		return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
	}
	var RemoteJWKSet = class extends local_js_1.LocalJWKSet {
		constructor(url, options) {
			super({ keys: [] });
			this._jwks = void 0;
			if (!(url instanceof URL)) throw new TypeError("url must be an instance of URL");
			this._url = new URL(url.href);
			this._options = {
				agent: options === null || options === void 0 ? void 0 : options.agent,
				headers: options === null || options === void 0 ? void 0 : options.headers
			};
			this._timeoutDuration = typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === "number" ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5e3;
			this._cooldownDuration = typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === "number" ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 3e4;
			this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === "number" ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 6e5;
		}
		coolingDown() {
			return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false;
		}
		fresh() {
			return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false;
		}
		async getKey(protectedHeader, token) {
			if (!this._jwks || !this.fresh()) await this.reload();
			try {
				return await super.getKey(protectedHeader, token);
			} catch (err) {
				if (err instanceof errors_js_1.JWKSNoMatchingKey) {
					if (this.coolingDown() === false) {
						await this.reload();
						return super.getKey(protectedHeader, token);
					}
				}
				throw err;
			}
		}
		async reload() {
			if (this._pendingFetch && isCloudflareWorkers()) this._pendingFetch = void 0;
			this._pendingFetch || (this._pendingFetch = (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options).then((json) => {
				if (!(0, local_js_1.isJWKSLike)(json)) throw new errors_js_1.JWKSInvalid("JSON Web Key Set malformed");
				this._jwks = { keys: json.keys };
				this._jwksTimestamp = Date.now();
				this._pendingFetch = void 0;
			}).catch((err) => {
				this._pendingFetch = void 0;
				throw err;
			}));
			await this._pendingFetch;
		}
	};
	function createRemoteJWKSet(url, options) {
		const set = new RemoteJWKSet(url, options);
		return async function(protectedHeader, token) {
			return set.getKey(protectedHeader, token);
		};
	}
	exports.createRemoteJWKSet = createRemoteJWKSet;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/jwt/unsecured.js
var require_unsecured = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.UnsecuredJWT = void 0;
	const base64url = require_base64url$1();
	const buffer_utils_js_1 = require_buffer_utils();
	const errors_js_1 = require_errors$1();
	const jwt_claims_set_js_1 = require_jwt_claims_set();
	const produce_js_1 = require_produce();
	var UnsecuredJWT = class extends produce_js_1.ProduceJWT {
		encode() {
			return `${base64url.encode(JSON.stringify({ alg: "none" }))}.${base64url.encode(JSON.stringify(this._payload))}.`;
		}
		static decode(jwt, options) {
			if (typeof jwt !== "string") throw new errors_js_1.JWTInvalid("Unsecured JWT must be a string");
			const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split(".");
			if (length !== 3 || signature !== "") throw new errors_js_1.JWTInvalid("Invalid Unsecured JWT");
			let header;
			try {
				header = JSON.parse(buffer_utils_js_1.decoder.decode(base64url.decode(encodedHeader)));
				if (header.alg !== "none") throw new Error();
			} catch {
				throw new errors_js_1.JWTInvalid("Invalid Unsecured JWT");
			}
			return {
				payload: (0, jwt_claims_set_js_1.default)(header, base64url.decode(encodedPayload), options),
				header
			};
		}
	};
	exports.UnsecuredJWT = UnsecuredJWT;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/util/base64url.js
var require_base64url = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.decode = exports.encode = void 0;
	const base64url = require_base64url$1();
	exports.encode = base64url.encode;
	exports.decode = base64url.decode;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/util/decode_protected_header.js
var require_decode_protected_header = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.decodeProtectedHeader = void 0;
	const base64url_js_1 = require_base64url();
	const buffer_utils_js_1 = require_buffer_utils();
	const is_object_js_1 = require_is_object();
	function decodeProtectedHeader(token) {
		let protectedB64u;
		if (typeof token === "string") {
			const parts = token.split(".");
			if (parts.length === 3 || parts.length === 5) [protectedB64u] = parts;
		} else if (typeof token === "object" && token) if ("protected" in token) protectedB64u = token.protected;
		else throw new TypeError("Token does not contain a Protected Header");
		try {
			if (typeof protectedB64u !== "string" || !protectedB64u) throw new Error();
			const result = JSON.parse(buffer_utils_js_1.decoder.decode((0, base64url_js_1.decode)(protectedB64u)));
			if (!(0, is_object_js_1.default)(result)) throw new Error();
			return result;
		} catch {
			throw new TypeError("Invalid Token or Protected Header formatting");
		}
	}
	exports.decodeProtectedHeader = decodeProtectedHeader;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/util/decode_jwt.js
var require_decode_jwt = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.decodeJwt = void 0;
	const base64url_js_1 = require_base64url();
	const buffer_utils_js_1 = require_buffer_utils();
	const is_object_js_1 = require_is_object();
	const errors_js_1 = require_errors$1();
	function decodeJwt(jwt) {
		if (typeof jwt !== "string") throw new errors_js_1.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
		const { 1: payload, length } = jwt.split(".");
		if (length === 5) throw new errors_js_1.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
		if (length !== 3) throw new errors_js_1.JWTInvalid("Invalid JWT");
		if (!payload) throw new errors_js_1.JWTInvalid("JWTs must contain a payload");
		let decoded;
		try {
			decoded = (0, base64url_js_1.decode)(payload);
		} catch {
			throw new errors_js_1.JWTInvalid("Failed to base64url decode the payload");
		}
		let result;
		try {
			result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded));
		} catch {
			throw new errors_js_1.JWTInvalid("Failed to parse the decoded payload as JSON");
		}
		if (!(0, is_object_js_1.default)(result)) throw new errors_js_1.JWTInvalid("Invalid JWT Claims Set");
		return result;
	}
	exports.decodeJwt = decodeJwt;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/generate.js
var require_generate = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.generateKeyPair = exports.generateSecret = void 0;
	const crypto_1 = __require("crypto");
	const util_1 = __require("util");
	const random_js_1 = require_random();
	const check_modulus_length_js_1 = require_check_modulus_length();
	const errors_js_1 = require_errors$1();
	const generate = (0, util_1.promisify)(crypto_1.generateKeyPair);
	async function generateSecret(alg, options) {
		let length;
		switch (alg) {
			case "HS256":
			case "HS384":
			case "HS512":
			case "A128CBC-HS256":
			case "A192CBC-HS384":
			case "A256CBC-HS512":
				length = parseInt(alg.slice(-3), 10);
				break;
			case "A128KW":
			case "A192KW":
			case "A256KW":
			case "A128GCMKW":
			case "A192GCMKW":
			case "A256GCMKW":
			case "A128GCM":
			case "A192GCM":
			case "A256GCM":
				length = parseInt(alg.slice(1, 4), 10);
				break;
			default: throw new errors_js_1.JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
		}
		return (0, crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3)));
	}
	exports.generateSecret = generateSecret;
	async function generateKeyPair(alg, options) {
		var _a, _b;
		switch (alg) {
			case "RS256":
			case "RS384":
			case "RS512":
			case "PS256":
			case "PS384":
			case "PS512":
			case "RSA-OAEP":
			case "RSA-OAEP-256":
			case "RSA-OAEP-384":
			case "RSA-OAEP-512":
			case "RSA1_5": {
				const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048;
				if (typeof modulusLength !== "number" || modulusLength < 2048) throw new errors_js_1.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
				const keypair = await generate("rsa", {
					modulusLength,
					publicExponent: 65537
				});
				(0, check_modulus_length_js_1.setModulusLength)(keypair.privateKey, modulusLength);
				(0, check_modulus_length_js_1.setModulusLength)(keypair.publicKey, modulusLength);
				return keypair;
			}
			case "ES256": return generate("ec", { namedCurve: "P-256" });
			case "ES256K": return generate("ec", { namedCurve: "secp256k1" });
			case "ES384": return generate("ec", { namedCurve: "P-384" });
			case "ES512": return generate("ec", { namedCurve: "P-521" });
			case "EdDSA": switch (options === null || options === void 0 ? void 0 : options.crv) {
				case void 0:
				case "Ed25519": return generate("ed25519");
				case "Ed448": return generate("ed448");
				default: throw new errors_js_1.JOSENotSupported("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448");
			}
			case "ECDH-ES":
			case "ECDH-ES+A128KW":
			case "ECDH-ES+A192KW":
			case "ECDH-ES+A256KW":
				const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : "P-256";
				switch (crv) {
					case void 0:
					case "P-256":
					case "P-384":
					case "P-521": return generate("ec", { namedCurve: crv });
					case "X25519": return generate("x25519");
					case "X448": return generate("x448");
					default: throw new errors_js_1.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448");
				}
			default: throw new errors_js_1.JOSENotSupported("Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value");
		}
	}
	exports.generateKeyPair = generateKeyPair;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/key/generate_key_pair.js
var require_generate_key_pair = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.generateKeyPair = void 0;
	const generate_js_1 = require_generate();
	async function generateKeyPair(alg, options) {
		return (0, generate_js_1.generateKeyPair)(alg, options);
	}
	exports.generateKeyPair = generateKeyPair;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/key/generate_secret.js
var require_generate_secret = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.generateSecret = void 0;
	const generate_js_1 = require_generate();
	async function generateSecret(alg, options) {
		return (0, generate_js_1.generateSecret)(alg, options);
	}
	exports.generateSecret = generateSecret;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/runtime/runtime.js
var require_runtime$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.default = "node:crypto";
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/util/runtime.js
var require_runtime = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.default = require_runtime$1().default;
}));
//#endregion
//#region node_modules/.pnpm/jose@4.15.9/node_modules/jose/dist/node/cjs/index.js
var require_cjs = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.cryptoRuntime = exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0;
	var decrypt_js_1 = require_decrypt$2();
	Object.defineProperty(exports, "compactDecrypt", {
		enumerable: true,
		get: function() {
			return decrypt_js_1.compactDecrypt;
		}
	});
	var decrypt_js_2 = require_decrypt$3();
	Object.defineProperty(exports, "flattenedDecrypt", {
		enumerable: true,
		get: function() {
			return decrypt_js_2.flattenedDecrypt;
		}
	});
	var decrypt_js_3 = require_decrypt$1();
	Object.defineProperty(exports, "generalDecrypt", {
		enumerable: true,
		get: function() {
			return decrypt_js_3.generalDecrypt;
		}
	});
	var encrypt_js_1 = require_encrypt$2();
	Object.defineProperty(exports, "GeneralEncrypt", {
		enumerable: true,
		get: function() {
			return encrypt_js_1.GeneralEncrypt;
		}
	});
	var verify_js_1 = require_verify$2();
	Object.defineProperty(exports, "compactVerify", {
		enumerable: true,
		get: function() {
			return verify_js_1.compactVerify;
		}
	});
	var verify_js_2 = require_verify$3();
	Object.defineProperty(exports, "flattenedVerify", {
		enumerable: true,
		get: function() {
			return verify_js_2.flattenedVerify;
		}
	});
	var verify_js_3 = require_verify$1();
	Object.defineProperty(exports, "generalVerify", {
		enumerable: true,
		get: function() {
			return verify_js_3.generalVerify;
		}
	});
	var verify_js_4 = require_verify();
	Object.defineProperty(exports, "jwtVerify", {
		enumerable: true,
		get: function() {
			return verify_js_4.jwtVerify;
		}
	});
	var decrypt_js_4 = require_decrypt();
	Object.defineProperty(exports, "jwtDecrypt", {
		enumerable: true,
		get: function() {
			return decrypt_js_4.jwtDecrypt;
		}
	});
	var encrypt_js_2 = require_encrypt$1();
	Object.defineProperty(exports, "CompactEncrypt", {
		enumerable: true,
		get: function() {
			return encrypt_js_2.CompactEncrypt;
		}
	});
	var encrypt_js_3 = require_encrypt$3();
	Object.defineProperty(exports, "FlattenedEncrypt", {
		enumerable: true,
		get: function() {
			return encrypt_js_3.FlattenedEncrypt;
		}
	});
	var sign_js_1 = require_sign$2();
	Object.defineProperty(exports, "CompactSign", {
		enumerable: true,
		get: function() {
			return sign_js_1.CompactSign;
		}
	});
	var sign_js_2 = require_sign$3();
	Object.defineProperty(exports, "FlattenedSign", {
		enumerable: true,
		get: function() {
			return sign_js_2.FlattenedSign;
		}
	});
	var sign_js_3 = require_sign$1();
	Object.defineProperty(exports, "GeneralSign", {
		enumerable: true,
		get: function() {
			return sign_js_3.GeneralSign;
		}
	});
	var sign_js_4 = require_sign();
	Object.defineProperty(exports, "SignJWT", {
		enumerable: true,
		get: function() {
			return sign_js_4.SignJWT;
		}
	});
	var encrypt_js_4 = require_encrypt();
	Object.defineProperty(exports, "EncryptJWT", {
		enumerable: true,
		get: function() {
			return encrypt_js_4.EncryptJWT;
		}
	});
	var thumbprint_js_1 = require_thumbprint();
	Object.defineProperty(exports, "calculateJwkThumbprint", {
		enumerable: true,
		get: function() {
			return thumbprint_js_1.calculateJwkThumbprint;
		}
	});
	Object.defineProperty(exports, "calculateJwkThumbprintUri", {
		enumerable: true,
		get: function() {
			return thumbprint_js_1.calculateJwkThumbprintUri;
		}
	});
	var embedded_js_1 = require_embedded();
	Object.defineProperty(exports, "EmbeddedJWK", {
		enumerable: true,
		get: function() {
			return embedded_js_1.EmbeddedJWK;
		}
	});
	var local_js_1 = require_local();
	Object.defineProperty(exports, "createLocalJWKSet", {
		enumerable: true,
		get: function() {
			return local_js_1.createLocalJWKSet;
		}
	});
	var remote_js_1 = require_remote();
	Object.defineProperty(exports, "createRemoteJWKSet", {
		enumerable: true,
		get: function() {
			return remote_js_1.createRemoteJWKSet;
		}
	});
	var unsecured_js_1 = require_unsecured();
	Object.defineProperty(exports, "UnsecuredJWT", {
		enumerable: true,
		get: function() {
			return unsecured_js_1.UnsecuredJWT;
		}
	});
	var export_js_1 = require_export();
	Object.defineProperty(exports, "exportPKCS8", {
		enumerable: true,
		get: function() {
			return export_js_1.exportPKCS8;
		}
	});
	Object.defineProperty(exports, "exportSPKI", {
		enumerable: true,
		get: function() {
			return export_js_1.exportSPKI;
		}
	});
	Object.defineProperty(exports, "exportJWK", {
		enumerable: true,
		get: function() {
			return export_js_1.exportJWK;
		}
	});
	var import_js_1 = require_import();
	Object.defineProperty(exports, "importSPKI", {
		enumerable: true,
		get: function() {
			return import_js_1.importSPKI;
		}
	});
	Object.defineProperty(exports, "importPKCS8", {
		enumerable: true,
		get: function() {
			return import_js_1.importPKCS8;
		}
	});
	Object.defineProperty(exports, "importX509", {
		enumerable: true,
		get: function() {
			return import_js_1.importX509;
		}
	});
	Object.defineProperty(exports, "importJWK", {
		enumerable: true,
		get: function() {
			return import_js_1.importJWK;
		}
	});
	var decode_protected_header_js_1 = require_decode_protected_header();
	Object.defineProperty(exports, "decodeProtectedHeader", {
		enumerable: true,
		get: function() {
			return decode_protected_header_js_1.decodeProtectedHeader;
		}
	});
	var decode_jwt_js_1 = require_decode_jwt();
	Object.defineProperty(exports, "decodeJwt", {
		enumerable: true,
		get: function() {
			return decode_jwt_js_1.decodeJwt;
		}
	});
	exports.errors = require_errors$1();
	var generate_key_pair_js_1 = require_generate_key_pair();
	Object.defineProperty(exports, "generateKeyPair", {
		enumerable: true,
		get: function() {
			return generate_key_pair_js_1.generateKeyPair;
		}
	});
	var generate_secret_js_1 = require_generate_secret();
	Object.defineProperty(exports, "generateSecret", {
		enumerable: true,
		get: function() {
			return generate_secret_js_1.generateSecret;
		}
	});
	exports.base64url = require_base64url();
	var runtime_js_1 = require_runtime();
	Object.defineProperty(exports, "cryptoRuntime", {
		enumerable: true,
		get: function() {
			return runtime_js_1.default;
		}
	});
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/errors/JwksError.js
var require_JwksError = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	function JwksError(message) {
		Error.call(this, message);
		Error.captureStackTrace(this, this.constructor);
		this.name = "JwksError";
		this.message = message;
	}
	JwksError.prototype = Object.create(Error.prototype);
	JwksError.prototype.constructor = JwksError;
	module.exports = JwksError;
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/utils.js
var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const jose = require_cjs();
	const JwksError = require_JwksError();
	function resolveAlg(jwk) {
		if (jwk.alg) return jwk.alg;
		if (jwk.kty === "RSA") return "RS256";
		if (jwk.kty === "EC") switch (jwk.crv) {
			case "P-256": return "ES256";
			case "secp256k1": return "ES256K";
			case "P-384": return "ES384";
			case "P-521": return "ES512";
		}
		if (jwk.kty === "OKP") switch (jwk.crv) {
			case "Ed25519":
			case "Ed448": return "EdDSA";
		}
		throw new JwksError("Unsupported JWK");
	}
	async function retrieveSigningKeys(jwks) {
		const results = [];
		jwks = jwks.filter(({ use }) => use === "sig" || use === void 0).filter(({ kty }) => kty === "RSA" || kty === "EC" || kty === "OKP");
		for (const jwk of jwks) try {
			const key = await jose.importJWK({
				...jwk,
				ext: true
			}, resolveAlg(jwk));
			if (key.type !== "public") continue;
			let getSpki;
			switch (key[Symbol.toStringTag]) {
				case "CryptoKey": {
					const spki = await jose.exportSPKI(key);
					getSpki = () => spki;
					break;
				}
				default: getSpki = () => key.export({
					format: "pem",
					type: "spki"
				});
			}
			results.push({
				get publicKey() {
					return getSpki();
				},
				get rsaPublicKey() {
					return getSpki();
				},
				getPublicKey() {
					return getSpki();
				},
				...typeof jwk.kid === "string" && jwk.kid ? { kid: jwk.kid } : void 0,
				...typeof jwk.alg === "string" && jwk.alg ? { alg: jwk.alg } : void 0
			});
		} catch (err) {
			continue;
		}
		return results;
	}
	module.exports = { retrieveSigningKeys };
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/errors/ArgumentError.js
var require_ArgumentError = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	function ArgumentError(message) {
		Error.call(this, message);
		Error.captureStackTrace(this, this.constructor);
		this.name = "ArgumentError";
		this.message = message;
	}
	ArgumentError.prototype = Object.create(Error.prototype);
	ArgumentError.prototype.constructor = ArgumentError;
	module.exports = ArgumentError;
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/wrappers/request.js
var require_request = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const http = __require("http");
	const https = __require("https");
	const ArgumentError = require_ArgumentError();
	module.exports.default = (options) => {
		if (options.fetcher) return options.fetcher(options.uri);
		return new Promise((resolve, reject) => {
			let url;
			try {
				url = new URL(options.uri);
			} catch (err) {
				throw new ArgumentError("Invalid JWKS URI: The provided URI is not a valid URL.");
			}
			const { hostname, port, protocol, pathname, search } = url;
			const requestOptions = {
				hostname,
				path: pathname + search,
				port,
				method: "GET",
				...options.headers && { headers: { ...options.headers } },
				...options.timeout && { timeout: options.timeout },
				...options.agent && { agent: options.agent }
			};
			const httpRequest = (protocol === "https:" ? https : http).request(requestOptions, (res) => {
				let rawData = "";
				res.setEncoding("utf8");
				res.on("data", (chunk) => {
					rawData += chunk;
				});
				res.on("end", () => {
					if (res.statusCode < 200 || res.statusCode >= 300) reject({ errorMsg: res.body && (res.body.message || res.body) || res.statusMessage || `Http Error ${res.statusCode}` });
					else try {
						resolve(rawData && JSON.parse(rawData));
					} catch (error) {
						reject(error);
					}
				});
			});
			httpRequest.on("timeout", () => httpRequest.destroy()).on("error", (e) => reject(e)).end();
		});
	};
}));
//#endregion
//#region node_modules/.pnpm/yallist@4.0.0/node_modules/yallist/iterator.js
var require_iterator = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = function(Yallist) {
		Yallist.prototype[Symbol.iterator] = function* () {
			for (let walker = this.head; walker; walker = walker.next) yield walker.value;
		};
	};
}));
//#endregion
//#region node_modules/.pnpm/yallist@4.0.0/node_modules/yallist/yallist.js
var require_yallist = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = Yallist;
	Yallist.Node = Node;
	Yallist.create = Yallist;
	function Yallist(list) {
		var self = this;
		if (!(self instanceof Yallist)) self = new Yallist();
		self.tail = null;
		self.head = null;
		self.length = 0;
		if (list && typeof list.forEach === "function") list.forEach(function(item) {
			self.push(item);
		});
		else if (arguments.length > 0) for (var i = 0, l = arguments.length; i < l; i++) self.push(arguments[i]);
		return self;
	}
	Yallist.prototype.removeNode = function(node) {
		if (node.list !== this) throw new Error("removing node which does not belong to this list");
		var next = node.next;
		var prev = node.prev;
		if (next) next.prev = prev;
		if (prev) prev.next = next;
		if (node === this.head) this.head = next;
		if (node === this.tail) this.tail = prev;
		node.list.length--;
		node.next = null;
		node.prev = null;
		node.list = null;
		return next;
	};
	Yallist.prototype.unshiftNode = function(node) {
		if (node === this.head) return;
		if (node.list) node.list.removeNode(node);
		var head = this.head;
		node.list = this;
		node.next = head;
		if (head) head.prev = node;
		this.head = node;
		if (!this.tail) this.tail = node;
		this.length++;
	};
	Yallist.prototype.pushNode = function(node) {
		if (node === this.tail) return;
		if (node.list) node.list.removeNode(node);
		var tail = this.tail;
		node.list = this;
		node.prev = tail;
		if (tail) tail.next = node;
		this.tail = node;
		if (!this.head) this.head = node;
		this.length++;
	};
	Yallist.prototype.push = function() {
		for (var i = 0, l = arguments.length; i < l; i++) push(this, arguments[i]);
		return this.length;
	};
	Yallist.prototype.unshift = function() {
		for (var i = 0, l = arguments.length; i < l; i++) unshift(this, arguments[i]);
		return this.length;
	};
	Yallist.prototype.pop = function() {
		if (!this.tail) return;
		var res = this.tail.value;
		this.tail = this.tail.prev;
		if (this.tail) this.tail.next = null;
		else this.head = null;
		this.length--;
		return res;
	};
	Yallist.prototype.shift = function() {
		if (!this.head) return;
		var res = this.head.value;
		this.head = this.head.next;
		if (this.head) this.head.prev = null;
		else this.tail = null;
		this.length--;
		return res;
	};
	Yallist.prototype.forEach = function(fn, thisp) {
		thisp = thisp || this;
		for (var walker = this.head, i = 0; walker !== null; i++) {
			fn.call(thisp, walker.value, i, this);
			walker = walker.next;
		}
	};
	Yallist.prototype.forEachReverse = function(fn, thisp) {
		thisp = thisp || this;
		for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
			fn.call(thisp, walker.value, i, this);
			walker = walker.prev;
		}
	};
	Yallist.prototype.get = function(n) {
		for (var i = 0, walker = this.head; walker !== null && i < n; i++) walker = walker.next;
		if (i === n && walker !== null) return walker.value;
	};
	Yallist.prototype.getReverse = function(n) {
		for (var i = 0, walker = this.tail; walker !== null && i < n; i++) walker = walker.prev;
		if (i === n && walker !== null) return walker.value;
	};
	Yallist.prototype.map = function(fn, thisp) {
		thisp = thisp || this;
		var res = new Yallist();
		for (var walker = this.head; walker !== null;) {
			res.push(fn.call(thisp, walker.value, this));
			walker = walker.next;
		}
		return res;
	};
	Yallist.prototype.mapReverse = function(fn, thisp) {
		thisp = thisp || this;
		var res = new Yallist();
		for (var walker = this.tail; walker !== null;) {
			res.push(fn.call(thisp, walker.value, this));
			walker = walker.prev;
		}
		return res;
	};
	Yallist.prototype.reduce = function(fn, initial) {
		var acc;
		var walker = this.head;
		if (arguments.length > 1) acc = initial;
		else if (this.head) {
			walker = this.head.next;
			acc = this.head.value;
		} else throw new TypeError("Reduce of empty list with no initial value");
		for (var i = 0; walker !== null; i++) {
			acc = fn(acc, walker.value, i);
			walker = walker.next;
		}
		return acc;
	};
	Yallist.prototype.reduceReverse = function(fn, initial) {
		var acc;
		var walker = this.tail;
		if (arguments.length > 1) acc = initial;
		else if (this.tail) {
			walker = this.tail.prev;
			acc = this.tail.value;
		} else throw new TypeError("Reduce of empty list with no initial value");
		for (var i = this.length - 1; walker !== null; i--) {
			acc = fn(acc, walker.value, i);
			walker = walker.prev;
		}
		return acc;
	};
	Yallist.prototype.toArray = function() {
		var arr = new Array(this.length);
		for (var i = 0, walker = this.head; walker !== null; i++) {
			arr[i] = walker.value;
			walker = walker.next;
		}
		return arr;
	};
	Yallist.prototype.toArrayReverse = function() {
		var arr = new Array(this.length);
		for (var i = 0, walker = this.tail; walker !== null; i++) {
			arr[i] = walker.value;
			walker = walker.prev;
		}
		return arr;
	};
	Yallist.prototype.slice = function(from, to) {
		to = to || this.length;
		if (to < 0) to += this.length;
		from = from || 0;
		if (from < 0) from += this.length;
		var ret = new Yallist();
		if (to < from || to < 0) return ret;
		if (from < 0) from = 0;
		if (to > this.length) to = this.length;
		for (var i = 0, walker = this.head; walker !== null && i < from; i++) walker = walker.next;
		for (; walker !== null && i < to; i++, walker = walker.next) ret.push(walker.value);
		return ret;
	};
	Yallist.prototype.sliceReverse = function(from, to) {
		to = to || this.length;
		if (to < 0) to += this.length;
		from = from || 0;
		if (from < 0) from += this.length;
		var ret = new Yallist();
		if (to < from || to < 0) return ret;
		if (from < 0) from = 0;
		if (to > this.length) to = this.length;
		for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) walker = walker.prev;
		for (; walker !== null && i > from; i--, walker = walker.prev) ret.push(walker.value);
		return ret;
	};
	Yallist.prototype.splice = function(start, deleteCount, ...nodes) {
		if (start > this.length) start = this.length - 1;
		if (start < 0) start = this.length + start;
		for (var i = 0, walker = this.head; walker !== null && i < start; i++) walker = walker.next;
		var ret = [];
		for (var i = 0; walker && i < deleteCount; i++) {
			ret.push(walker.value);
			walker = this.removeNode(walker);
		}
		if (walker === null) walker = this.tail;
		if (walker !== this.head && walker !== this.tail) walker = walker.prev;
		for (var i = 0; i < nodes.length; i++) walker = insert(this, walker, nodes[i]);
		return ret;
	};
	Yallist.prototype.reverse = function() {
		var head = this.head;
		var tail = this.tail;
		for (var walker = head; walker !== null; walker = walker.prev) {
			var p = walker.prev;
			walker.prev = walker.next;
			walker.next = p;
		}
		this.head = tail;
		this.tail = head;
		return this;
	};
	function insert(self, node, value) {
		var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self);
		if (inserted.next === null) self.tail = inserted;
		if (inserted.prev === null) self.head = inserted;
		self.length++;
		return inserted;
	}
	function push(self, item) {
		self.tail = new Node(item, self.tail, null, self);
		if (!self.head) self.head = self.tail;
		self.length++;
	}
	function unshift(self, item) {
		self.head = new Node(item, null, self.head, self);
		if (!self.tail) self.tail = self.head;
		self.length++;
	}
	function Node(value, prev, next, list) {
		if (!(this instanceof Node)) return new Node(value, prev, next, list);
		this.list = list;
		this.value = value;
		if (prev) {
			prev.next = this;
			this.prev = prev;
		} else this.prev = null;
		if (next) {
			next.prev = this;
			this.next = next;
		} else this.next = null;
	}
	try {
		require_iterator()(Yallist);
	} catch (er) {}
}));
//#endregion
//#region node_modules/.pnpm/lru-cache@6.0.0/node_modules/lru-cache/index.js
var require_lru_cache = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const Yallist = require_yallist();
	const MAX = Symbol("max");
	const LENGTH = Symbol("length");
	const LENGTH_CALCULATOR = Symbol("lengthCalculator");
	const ALLOW_STALE = Symbol("allowStale");
	const MAX_AGE = Symbol("maxAge");
	const DISPOSE = Symbol("dispose");
	const NO_DISPOSE_ON_SET = Symbol("noDisposeOnSet");
	const LRU_LIST = Symbol("lruList");
	const CACHE = Symbol("cache");
	const UPDATE_AGE_ON_GET = Symbol("updateAgeOnGet");
	const naiveLength = () => 1;
	var LRUCache = class {
		constructor(options) {
			if (typeof options === "number") options = { max: options };
			if (!options) options = {};
			if (options.max && (typeof options.max !== "number" || options.max < 0)) throw new TypeError("max must be a non-negative number");
			this[MAX] = options.max || Infinity;
			const lc = options.length || naiveLength;
			this[LENGTH_CALCULATOR] = typeof lc !== "function" ? naiveLength : lc;
			this[ALLOW_STALE] = options.stale || false;
			if (options.maxAge && typeof options.maxAge !== "number") throw new TypeError("maxAge must be a number");
			this[MAX_AGE] = options.maxAge || 0;
			this[DISPOSE] = options.dispose;
			this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
			this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;
			this.reset();
		}
		set max(mL) {
			if (typeof mL !== "number" || mL < 0) throw new TypeError("max must be a non-negative number");
			this[MAX] = mL || Infinity;
			trim(this);
		}
		get max() {
			return this[MAX];
		}
		set allowStale(allowStale) {
			this[ALLOW_STALE] = !!allowStale;
		}
		get allowStale() {
			return this[ALLOW_STALE];
		}
		set maxAge(mA) {
			if (typeof mA !== "number") throw new TypeError("maxAge must be a non-negative number");
			this[MAX_AGE] = mA;
			trim(this);
		}
		get maxAge() {
			return this[MAX_AGE];
		}
		set lengthCalculator(lC) {
			if (typeof lC !== "function") lC = naiveLength;
			if (lC !== this[LENGTH_CALCULATOR]) {
				this[LENGTH_CALCULATOR] = lC;
				this[LENGTH] = 0;
				this[LRU_LIST].forEach((hit) => {
					hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
					this[LENGTH] += hit.length;
				});
			}
			trim(this);
		}
		get lengthCalculator() {
			return this[LENGTH_CALCULATOR];
		}
		get length() {
			return this[LENGTH];
		}
		get itemCount() {
			return this[LRU_LIST].length;
		}
		rforEach(fn, thisp) {
			thisp = thisp || this;
			for (let walker = this[LRU_LIST].tail; walker !== null;) {
				const prev = walker.prev;
				forEachStep(this, fn, walker, thisp);
				walker = prev;
			}
		}
		forEach(fn, thisp) {
			thisp = thisp || this;
			for (let walker = this[LRU_LIST].head; walker !== null;) {
				const next = walker.next;
				forEachStep(this, fn, walker, thisp);
				walker = next;
			}
		}
		keys() {
			return this[LRU_LIST].toArray().map((k) => k.key);
		}
		values() {
			return this[LRU_LIST].toArray().map((k) => k.value);
		}
		reset() {
			if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) this[LRU_LIST].forEach((hit) => this[DISPOSE](hit.key, hit.value));
			this[CACHE] = /* @__PURE__ */ new Map();
			this[LRU_LIST] = new Yallist();
			this[LENGTH] = 0;
		}
		dump() {
			return this[LRU_LIST].map((hit) => isStale(this, hit) ? false : {
				k: hit.key,
				v: hit.value,
				e: hit.now + (hit.maxAge || 0)
			}).toArray().filter((h) => h);
		}
		dumpLru() {
			return this[LRU_LIST];
		}
		set(key, value, maxAge) {
			maxAge = maxAge || this[MAX_AGE];
			if (maxAge && typeof maxAge !== "number") throw new TypeError("maxAge must be a number");
			const now = maxAge ? Date.now() : 0;
			const len = this[LENGTH_CALCULATOR](value, key);
			if (this[CACHE].has(key)) {
				if (len > this[MAX]) {
					del(this, this[CACHE].get(key));
					return false;
				}
				const item = this[CACHE].get(key).value;
				if (this[DISPOSE]) {
					if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value);
				}
				item.now = now;
				item.maxAge = maxAge;
				item.value = value;
				this[LENGTH] += len - item.length;
				item.length = len;
				this.get(key);
				trim(this);
				return true;
			}
			const hit = new Entry(key, value, len, now, maxAge);
			if (hit.length > this[MAX]) {
				if (this[DISPOSE]) this[DISPOSE](key, value);
				return false;
			}
			this[LENGTH] += hit.length;
			this[LRU_LIST].unshift(hit);
			this[CACHE].set(key, this[LRU_LIST].head);
			trim(this);
			return true;
		}
		has(key) {
			if (!this[CACHE].has(key)) return false;
			const hit = this[CACHE].get(key).value;
			return !isStale(this, hit);
		}
		get(key) {
			return get(this, key, true);
		}
		peek(key) {
			return get(this, key, false);
		}
		pop() {
			const node = this[LRU_LIST].tail;
			if (!node) return null;
			del(this, node);
			return node.value;
		}
		del(key) {
			del(this, this[CACHE].get(key));
		}
		load(arr) {
			this.reset();
			const now = Date.now();
			for (let l = arr.length - 1; l >= 0; l--) {
				const hit = arr[l];
				const expiresAt = hit.e || 0;
				if (expiresAt === 0) this.set(hit.k, hit.v);
				else {
					const maxAge = expiresAt - now;
					if (maxAge > 0) this.set(hit.k, hit.v, maxAge);
				}
			}
		}
		prune() {
			this[CACHE].forEach((value, key) => get(this, key, false));
		}
	};
	const get = (self, key, doUse) => {
		const node = self[CACHE].get(key);
		if (node) {
			const hit = node.value;
			if (isStale(self, hit)) {
				del(self, node);
				if (!self[ALLOW_STALE]) return void 0;
			} else if (doUse) {
				if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now();
				self[LRU_LIST].unshiftNode(node);
			}
			return hit.value;
		}
	};
	const isStale = (self, hit) => {
		if (!hit || !hit.maxAge && !self[MAX_AGE]) return false;
		const diff = Date.now() - hit.now;
		return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && diff > self[MAX_AGE];
	};
	const trim = (self) => {
		if (self[LENGTH] > self[MAX]) for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
			const prev = walker.prev;
			del(self, walker);
			walker = prev;
		}
	};
	const del = (self, node) => {
		if (node) {
			const hit = node.value;
			if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value);
			self[LENGTH] -= hit.length;
			self[CACHE].delete(hit.key);
			self[LRU_LIST].removeNode(node);
		}
	};
	var Entry = class {
		constructor(key, value, length, now, maxAge) {
			this.key = key;
			this.value = value;
			this.length = length;
			this.now = now;
			this.maxAge = maxAge || 0;
		}
	};
	const forEachStep = (self, fn, node, thisp) => {
		let hit = node.value;
		if (isStale(self, hit)) {
			del(self, node);
			if (!self[ALLOW_STALE]) hit = void 0;
		}
		if (hit) fn.call(thisp, hit.value, hit.key, self);
	};
	module.exports = LRUCache;
}));
//#endregion
//#region node_modules/.pnpm/lodash.clonedeep@4.5.0/node_modules/lodash.clonedeep/index.js
var require_lodash_clonedeep = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* lodash (Custom Build) <https://lodash.com/>
	* Build: `lodash modularize exports="npm" -o ./`
	* Copyright jQuery Foundation and other contributors <https://jquery.org/>
	* Released under MIT license <https://lodash.com/license>
	* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
	* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
	*/
	/** Used as the size to enable large array optimizations. */
	var LARGE_ARRAY_SIZE = 200;
	/** Used to stand-in for `undefined` hash values. */
	var HASH_UNDEFINED = "__lodash_hash_undefined__";
	/** Used as references for various `Number` constants. */
	var MAX_SAFE_INTEGER = 9007199254740991;
	/** `Object#toString` result references. */
	var argsTag = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", promiseTag = "[object Promise]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", weakMapTag = "[object WeakMap]";
	var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]";
	/**
	* Used to match `RegExp`
	* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
	*/
	var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
	/** Used to match `RegExp` flags from their coerced string values. */
	var reFlags = /\w*$/;
	/** Used to detect host constructors (Safari). */
	var reIsHostCtor = /^\[object .+?Constructor\]$/;
	/** Used to detect unsigned integer values. */
	var reIsUint = /^(?:0|[1-9]\d*)$/;
	/** Used to identify `toStringTag` values supported by `_.clone`. */
	var cloneableTags = {};
	cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
	cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false;
	/** Detect free variable `global` from Node.js. */
	var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
	/** Detect free variable `self`. */
	var freeSelf = typeof self == "object" && self && self.Object === Object && self;
	/** Used as a reference to the global object. */
	var root = freeGlobal || freeSelf || Function("return this")();
	/** Detect free variable `exports`. */
	var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
	/** Detect free variable `module`. */
	var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module;
	/** Detect the popular CommonJS extension `module.exports`. */
	var moduleExports = freeModule && freeModule.exports === freeExports;
	/**
	* Adds the key-value `pair` to `map`.
	*
	* @private
	* @param {Object} map The map to modify.
	* @param {Array} pair The key-value pair to add.
	* @returns {Object} Returns `map`.
	*/
	function addMapEntry(map, pair) {
		map.set(pair[0], pair[1]);
		return map;
	}
	/**
	* Adds `value` to `set`.
	*
	* @private
	* @param {Object} set The set to modify.
	* @param {*} value The value to add.
	* @returns {Object} Returns `set`.
	*/
	function addSetEntry(set, value) {
		set.add(value);
		return set;
	}
	/**
	* A specialized version of `_.forEach` for arrays without support for
	* iteratee shorthands.
	*
	* @private
	* @param {Array} [array] The array to iterate over.
	* @param {Function} iteratee The function invoked per iteration.
	* @returns {Array} Returns `array`.
	*/
	function arrayEach(array, iteratee) {
		var index = -1, length = array ? array.length : 0;
		while (++index < length) if (iteratee(array[index], index, array) === false) break;
		return array;
	}
	/**
	* Appends the elements of `values` to `array`.
	*
	* @private
	* @param {Array} array The array to modify.
	* @param {Array} values The values to append.
	* @returns {Array} Returns `array`.
	*/
	function arrayPush(array, values) {
		var index = -1, length = values.length, offset = array.length;
		while (++index < length) array[offset + index] = values[index];
		return array;
	}
	/**
	* A specialized version of `_.reduce` for arrays without support for
	* iteratee shorthands.
	*
	* @private
	* @param {Array} [array] The array to iterate over.
	* @param {Function} iteratee The function invoked per iteration.
	* @param {*} [accumulator] The initial value.
	* @param {boolean} [initAccum] Specify using the first element of `array` as
	*  the initial value.
	* @returns {*} Returns the accumulated value.
	*/
	function arrayReduce(array, iteratee, accumulator, initAccum) {
		var index = -1, length = array ? array.length : 0;
		if (initAccum && length) accumulator = array[++index];
		while (++index < length) accumulator = iteratee(accumulator, array[index], index, array);
		return accumulator;
	}
	/**
	* The base implementation of `_.times` without support for iteratee shorthands
	* or max array length checks.
	*
	* @private
	* @param {number} n The number of times to invoke `iteratee`.
	* @param {Function} iteratee The function invoked per iteration.
	* @returns {Array} Returns the array of results.
	*/
	function baseTimes(n, iteratee) {
		var index = -1, result = Array(n);
		while (++index < n) result[index] = iteratee(index);
		return result;
	}
	/**
	* Gets the value at `key` of `object`.
	*
	* @private
	* @param {Object} [object] The object to query.
	* @param {string} key The key of the property to get.
	* @returns {*} Returns the property value.
	*/
	function getValue(object, key) {
		return object == null ? void 0 : object[key];
	}
	/**
	* Checks if `value` is a host object in IE < 9.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
	*/
	function isHostObject(value) {
		var result = false;
		if (value != null && typeof value.toString != "function") try {
			result = !!(value + "");
		} catch (e) {}
		return result;
	}
	/**
	* Converts `map` to its key-value pairs.
	*
	* @private
	* @param {Object} map The map to convert.
	* @returns {Array} Returns the key-value pairs.
	*/
	function mapToArray(map) {
		var index = -1, result = Array(map.size);
		map.forEach(function(value, key) {
			result[++index] = [key, value];
		});
		return result;
	}
	/**
	* Creates a unary function that invokes `func` with its argument transformed.
	*
	* @private
	* @param {Function} func The function to wrap.
	* @param {Function} transform The argument transform.
	* @returns {Function} Returns the new function.
	*/
	function overArg(func, transform) {
		return function(arg) {
			return func(transform(arg));
		};
	}
	/**
	* Converts `set` to an array of its values.
	*
	* @private
	* @param {Object} set The set to convert.
	* @returns {Array} Returns the values.
	*/
	function setToArray(set) {
		var index = -1, result = Array(set.size);
		set.forEach(function(value) {
			result[++index] = value;
		});
		return result;
	}
	/** Used for built-in method references. */
	var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype;
	/** Used to detect overreaching core-js shims. */
	var coreJsData = root["__core-js_shared__"];
	/** Used to detect methods masquerading as native. */
	var maskSrcKey = function() {
		var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
		return uid ? "Symbol(src)_1." + uid : "";
	}();
	/** Used to resolve the decompiled source of functions. */
	var funcToString = funcProto.toString;
	/** Used to check objects for own properties. */
	var hasOwnProperty = objectProto.hasOwnProperty;
	/**
	* Used to resolve the
	* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	* of values.
	*/
	var objectToString = objectProto.toString;
	/** Used to detect if a method is native. */
	var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
	/** Built-in value references. */
	var Buffer = moduleExports ? root.Buffer : void 0, Symbol = root.Symbol, Uint8Array = root.Uint8Array, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice;
	var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : void 0, nativeKeys = overArg(Object.keys, Object);
	var DataView = getNative(root, "DataView"), Map = getNative(root, "Map"), Promise = getNative(root, "Promise"), Set = getNative(root, "Set"), WeakMap = getNative(root, "WeakMap"), nativeCreate = getNative(Object, "create");
	/** Used to detect maps, sets, and weakmaps. */
	var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap);
	/** Used to convert symbols to primitives and strings. */
	var symbolProto = Symbol ? Symbol.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
	/**
	* Creates a hash object.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function Hash(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the hash.
	*
	* @private
	* @name clear
	* @memberOf Hash
	*/
	function hashClear() {
		this.__data__ = nativeCreate ? nativeCreate(null) : {};
	}
	/**
	* Removes `key` and its value from the hash.
	*
	* @private
	* @name delete
	* @memberOf Hash
	* @param {Object} hash The hash to modify.
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function hashDelete(key) {
		return this.has(key) && delete this.__data__[key];
	}
	/**
	* Gets the hash value for `key`.
	*
	* @private
	* @name get
	* @memberOf Hash
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function hashGet(key) {
		var data = this.__data__;
		if (nativeCreate) {
			var result = data[key];
			return result === HASH_UNDEFINED ? void 0 : result;
		}
		return hasOwnProperty.call(data, key) ? data[key] : void 0;
	}
	/**
	* Checks if a hash value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf Hash
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function hashHas(key) {
		var data = this.__data__;
		return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key);
	}
	/**
	* Sets the hash `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf Hash
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the hash instance.
	*/
	function hashSet(key, value) {
		var data = this.__data__;
		data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
		return this;
	}
	Hash.prototype.clear = hashClear;
	Hash.prototype["delete"] = hashDelete;
	Hash.prototype.get = hashGet;
	Hash.prototype.has = hashHas;
	Hash.prototype.set = hashSet;
	/**
	* Creates an list cache object.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function ListCache(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the list cache.
	*
	* @private
	* @name clear
	* @memberOf ListCache
	*/
	function listCacheClear() {
		this.__data__ = [];
	}
	/**
	* Removes `key` and its value from the list cache.
	*
	* @private
	* @name delete
	* @memberOf ListCache
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function listCacheDelete(key) {
		var data = this.__data__, index = assocIndexOf(data, key);
		if (index < 0) return false;
		if (index == data.length - 1) data.pop();
		else splice.call(data, index, 1);
		return true;
	}
	/**
	* Gets the list cache value for `key`.
	*
	* @private
	* @name get
	* @memberOf ListCache
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function listCacheGet(key) {
		var data = this.__data__, index = assocIndexOf(data, key);
		return index < 0 ? void 0 : data[index][1];
	}
	/**
	* Checks if a list cache value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf ListCache
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function listCacheHas(key) {
		return assocIndexOf(this.__data__, key) > -1;
	}
	/**
	* Sets the list cache `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf ListCache
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the list cache instance.
	*/
	function listCacheSet(key, value) {
		var data = this.__data__, index = assocIndexOf(data, key);
		if (index < 0) data.push([key, value]);
		else data[index][1] = value;
		return this;
	}
	ListCache.prototype.clear = listCacheClear;
	ListCache.prototype["delete"] = listCacheDelete;
	ListCache.prototype.get = listCacheGet;
	ListCache.prototype.has = listCacheHas;
	ListCache.prototype.set = listCacheSet;
	/**
	* Creates a map cache object to store key-value pairs.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function MapCache(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the map.
	*
	* @private
	* @name clear
	* @memberOf MapCache
	*/
	function mapCacheClear() {
		this.__data__ = {
			"hash": new Hash(),
			"map": new (Map || ListCache)(),
			"string": new Hash()
		};
	}
	/**
	* Removes `key` and its value from the map.
	*
	* @private
	* @name delete
	* @memberOf MapCache
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function mapCacheDelete(key) {
		return getMapData(this, key)["delete"](key);
	}
	/**
	* Gets the map value for `key`.
	*
	* @private
	* @name get
	* @memberOf MapCache
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function mapCacheGet(key) {
		return getMapData(this, key).get(key);
	}
	/**
	* Checks if a map value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf MapCache
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function mapCacheHas(key) {
		return getMapData(this, key).has(key);
	}
	/**
	* Sets the map `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf MapCache
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the map cache instance.
	*/
	function mapCacheSet(key, value) {
		getMapData(this, key).set(key, value);
		return this;
	}
	MapCache.prototype.clear = mapCacheClear;
	MapCache.prototype["delete"] = mapCacheDelete;
	MapCache.prototype.get = mapCacheGet;
	MapCache.prototype.has = mapCacheHas;
	MapCache.prototype.set = mapCacheSet;
	/**
	* Creates a stack cache object to store key-value pairs.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function Stack(entries) {
		this.__data__ = new ListCache(entries);
	}
	/**
	* Removes all key-value entries from the stack.
	*
	* @private
	* @name clear
	* @memberOf Stack
	*/
	function stackClear() {
		this.__data__ = new ListCache();
	}
	/**
	* Removes `key` and its value from the stack.
	*
	* @private
	* @name delete
	* @memberOf Stack
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function stackDelete(key) {
		return this.__data__["delete"](key);
	}
	/**
	* Gets the stack value for `key`.
	*
	* @private
	* @name get
	* @memberOf Stack
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function stackGet(key) {
		return this.__data__.get(key);
	}
	/**
	* Checks if a stack value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf Stack
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function stackHas(key) {
		return this.__data__.has(key);
	}
	/**
	* Sets the stack `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf Stack
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the stack cache instance.
	*/
	function stackSet(key, value) {
		var cache = this.__data__;
		if (cache instanceof ListCache) {
			var pairs = cache.__data__;
			if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
				pairs.push([key, value]);
				return this;
			}
			cache = this.__data__ = new MapCache(pairs);
		}
		cache.set(key, value);
		return this;
	}
	Stack.prototype.clear = stackClear;
	Stack.prototype["delete"] = stackDelete;
	Stack.prototype.get = stackGet;
	Stack.prototype.has = stackHas;
	Stack.prototype.set = stackSet;
	/**
	* Creates an array of the enumerable property names of the array-like `value`.
	*
	* @private
	* @param {*} value The value to query.
	* @param {boolean} inherited Specify returning inherited property names.
	* @returns {Array} Returns the array of property names.
	*/
	function arrayLikeKeys(value, inherited) {
		var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
		var length = result.length, skipIndexes = !!length;
		for (var key in value) if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) result.push(key);
		return result;
	}
	/**
	* Assigns `value` to `key` of `object` if the existing value is not equivalent
	* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
	* for equality comparisons.
	*
	* @private
	* @param {Object} object The object to modify.
	* @param {string} key The key of the property to assign.
	* @param {*} value The value to assign.
	*/
	function assignValue(object, key, value) {
		var objValue = object[key];
		if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === void 0 && !(key in object)) object[key] = value;
	}
	/**
	* Gets the index at which the `key` is found in `array` of key-value pairs.
	*
	* @private
	* @param {Array} array The array to inspect.
	* @param {*} key The key to search for.
	* @returns {number} Returns the index of the matched value, else `-1`.
	*/
	function assocIndexOf(array, key) {
		var length = array.length;
		while (length--) if (eq(array[length][0], key)) return length;
		return -1;
	}
	/**
	* The base implementation of `_.assign` without support for multiple sources
	* or `customizer` functions.
	*
	* @private
	* @param {Object} object The destination object.
	* @param {Object} source The source object.
	* @returns {Object} Returns `object`.
	*/
	function baseAssign(object, source) {
		return object && copyObject(source, keys(source), object);
	}
	/**
	* The base implementation of `_.clone` and `_.cloneDeep` which tracks
	* traversed objects.
	*
	* @private
	* @param {*} value The value to clone.
	* @param {boolean} [isDeep] Specify a deep clone.
	* @param {boolean} [isFull] Specify a clone including symbols.
	* @param {Function} [customizer] The function to customize cloning.
	* @param {string} [key] The key of `value`.
	* @param {Object} [object] The parent object of `value`.
	* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
	* @returns {*} Returns the cloned value.
	*/
	function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
		var result;
		if (customizer) result = object ? customizer(value, key, object, stack) : customizer(value);
		if (result !== void 0) return result;
		if (!isObject(value)) return value;
		var isArr = isArray(value);
		if (isArr) {
			result = initCloneArray(value);
			if (!isDeep) return copyArray(value, result);
		} else {
			var tag = getTag(value), isFunc = tag == funcTag || tag == genTag;
			if (isBuffer(value)) return cloneBuffer(value, isDeep);
			if (tag == objectTag || tag == argsTag || isFunc && !object) {
				if (isHostObject(value)) return object ? value : {};
				result = initCloneObject(isFunc ? {} : value);
				if (!isDeep) return copySymbols(value, baseAssign(result, value));
			} else {
				if (!cloneableTags[tag]) return object ? value : {};
				result = initCloneByTag(value, tag, baseClone, isDeep);
			}
		}
		stack || (stack = new Stack());
		var stacked = stack.get(value);
		if (stacked) return stacked;
		stack.set(value, result);
		if (!isArr) var props = isFull ? getAllKeys(value) : keys(value);
		arrayEach(props || value, function(subValue, key) {
			if (props) {
				key = subValue;
				subValue = value[key];
			}
			assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
		});
		return result;
	}
	/**
	* The base implementation of `_.create` without support for assigning
	* properties to the created object.
	*
	* @private
	* @param {Object} prototype The object to inherit from.
	* @returns {Object} Returns the new object.
	*/
	function baseCreate(proto) {
		return isObject(proto) ? objectCreate(proto) : {};
	}
	/**
	* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
	* `keysFunc` and `symbolsFunc` to get the enumerable property names and
	* symbols of `object`.
	*
	* @private
	* @param {Object} object The object to query.
	* @param {Function} keysFunc The function to get the keys of `object`.
	* @param {Function} symbolsFunc The function to get the symbols of `object`.
	* @returns {Array} Returns the array of property names and symbols.
	*/
	function baseGetAllKeys(object, keysFunc, symbolsFunc) {
		var result = keysFunc(object);
		return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
	}
	/**
	* The base implementation of `getTag`.
	*
	* @private
	* @param {*} value The value to query.
	* @returns {string} Returns the `toStringTag`.
	*/
	function baseGetTag(value) {
		return objectToString.call(value);
	}
	/**
	* The base implementation of `_.isNative` without bad shim checks.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a native function,
	*  else `false`.
	*/
	function baseIsNative(value) {
		if (!isObject(value) || isMasked(value)) return false;
		return (isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor).test(toSource(value));
	}
	/**
	* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
	*
	* @private
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of property names.
	*/
	function baseKeys(object) {
		if (!isPrototype(object)) return nativeKeys(object);
		var result = [];
		for (var key in Object(object)) if (hasOwnProperty.call(object, key) && key != "constructor") result.push(key);
		return result;
	}
	/**
	* Creates a clone of  `buffer`.
	*
	* @private
	* @param {Buffer} buffer The buffer to clone.
	* @param {boolean} [isDeep] Specify a deep clone.
	* @returns {Buffer} Returns the cloned buffer.
	*/
	function cloneBuffer(buffer, isDeep) {
		if (isDeep) return buffer.slice();
		var result = new buffer.constructor(buffer.length);
		buffer.copy(result);
		return result;
	}
	/**
	* Creates a clone of `arrayBuffer`.
	*
	* @private
	* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
	* @returns {ArrayBuffer} Returns the cloned array buffer.
	*/
	function cloneArrayBuffer(arrayBuffer) {
		var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
		new Uint8Array(result).set(new Uint8Array(arrayBuffer));
		return result;
	}
	/**
	* Creates a clone of `dataView`.
	*
	* @private
	* @param {Object} dataView The data view to clone.
	* @param {boolean} [isDeep] Specify a deep clone.
	* @returns {Object} Returns the cloned data view.
	*/
	function cloneDataView(dataView, isDeep) {
		var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
		return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
	}
	/**
	* Creates a clone of `map`.
	*
	* @private
	* @param {Object} map The map to clone.
	* @param {Function} cloneFunc The function to clone values.
	* @param {boolean} [isDeep] Specify a deep clone.
	* @returns {Object} Returns the cloned map.
	*/
	function cloneMap(map, isDeep, cloneFunc) {
		return arrayReduce(isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map), addMapEntry, new map.constructor());
	}
	/**
	* Creates a clone of `regexp`.
	*
	* @private
	* @param {Object} regexp The regexp to clone.
	* @returns {Object} Returns the cloned regexp.
	*/
	function cloneRegExp(regexp) {
		var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
		result.lastIndex = regexp.lastIndex;
		return result;
	}
	/**
	* Creates a clone of `set`.
	*
	* @private
	* @param {Object} set The set to clone.
	* @param {Function} cloneFunc The function to clone values.
	* @param {boolean} [isDeep] Specify a deep clone.
	* @returns {Object} Returns the cloned set.
	*/
	function cloneSet(set, isDeep, cloneFunc) {
		return arrayReduce(isDeep ? cloneFunc(setToArray(set), true) : setToArray(set), addSetEntry, new set.constructor());
	}
	/**
	* Creates a clone of the `symbol` object.
	*
	* @private
	* @param {Object} symbol The symbol object to clone.
	* @returns {Object} Returns the cloned symbol object.
	*/
	function cloneSymbol(symbol) {
		return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
	}
	/**
	* Creates a clone of `typedArray`.
	*
	* @private
	* @param {Object} typedArray The typed array to clone.
	* @param {boolean} [isDeep] Specify a deep clone.
	* @returns {Object} Returns the cloned typed array.
	*/
	function cloneTypedArray(typedArray, isDeep) {
		var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
		return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
	}
	/**
	* Copies the values of `source` to `array`.
	*
	* @private
	* @param {Array} source The array to copy values from.
	* @param {Array} [array=[]] The array to copy values to.
	* @returns {Array} Returns `array`.
	*/
	function copyArray(source, array) {
		var index = -1, length = source.length;
		array || (array = Array(length));
		while (++index < length) array[index] = source[index];
		return array;
	}
	/**
	* Copies properties of `source` to `object`.
	*
	* @private
	* @param {Object} source The object to copy properties from.
	* @param {Array} props The property identifiers to copy.
	* @param {Object} [object={}] The object to copy properties to.
	* @param {Function} [customizer] The function to customize copied values.
	* @returns {Object} Returns `object`.
	*/
	function copyObject(source, props, object, customizer) {
		object || (object = {});
		var index = -1, length = props.length;
		while (++index < length) {
			var key = props[index];
			var newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
			assignValue(object, key, newValue === void 0 ? source[key] : newValue);
		}
		return object;
	}
	/**
	* Copies own symbol properties of `source` to `object`.
	*
	* @private
	* @param {Object} source The object to copy symbols from.
	* @param {Object} [object={}] The object to copy symbols to.
	* @returns {Object} Returns `object`.
	*/
	function copySymbols(source, object) {
		return copyObject(source, getSymbols(source), object);
	}
	/**
	* Creates an array of own enumerable property names and symbols of `object`.
	*
	* @private
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of property names and symbols.
	*/
	function getAllKeys(object) {
		return baseGetAllKeys(object, keys, getSymbols);
	}
	/**
	* Gets the data for `map`.
	*
	* @private
	* @param {Object} map The map to query.
	* @param {string} key The reference key.
	* @returns {*} Returns the map data.
	*/
	function getMapData(map, key) {
		var data = map.__data__;
		return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
	}
	/**
	* Gets the native function at `key` of `object`.
	*
	* @private
	* @param {Object} object The object to query.
	* @param {string} key The key of the method to get.
	* @returns {*} Returns the function if it's native, else `undefined`.
	*/
	function getNative(object, key) {
		var value = getValue(object, key);
		return baseIsNative(value) ? value : void 0;
	}
	/**
	* Creates an array of the own enumerable symbol properties of `object`.
	*
	* @private
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of symbols.
	*/
	var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
	/**
	* Gets the `toStringTag` of `value`.
	*
	* @private
	* @param {*} value The value to query.
	* @returns {string} Returns the `toStringTag`.
	*/
	var getTag = baseGetTag;
	if (DataView && getTag(new DataView(/* @__PURE__ */ new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) getTag = function(value) {
		var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : void 0;
		if (ctorString) switch (ctorString) {
			case dataViewCtorString: return dataViewTag;
			case mapCtorString: return mapTag;
			case promiseCtorString: return promiseTag;
			case setCtorString: return setTag;
			case weakMapCtorString: return weakMapTag;
		}
		return result;
	};
	/**
	* Initializes an array clone.
	*
	* @private
	* @param {Array} array The array to clone.
	* @returns {Array} Returns the initialized clone.
	*/
	function initCloneArray(array) {
		var length = array.length, result = array.constructor(length);
		if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) {
			result.index = array.index;
			result.input = array.input;
		}
		return result;
	}
	/**
	* Initializes an object clone.
	*
	* @private
	* @param {Object} object The object to clone.
	* @returns {Object} Returns the initialized clone.
	*/
	function initCloneObject(object) {
		return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
	}
	/**
	* Initializes an object clone based on its `toStringTag`.
	*
	* **Note:** This function only supports cloning values with tags of
	* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
	*
	* @private
	* @param {Object} object The object to clone.
	* @param {string} tag The `toStringTag` of the object to clone.
	* @param {Function} cloneFunc The function to clone values.
	* @param {boolean} [isDeep] Specify a deep clone.
	* @returns {Object} Returns the initialized clone.
	*/
	function initCloneByTag(object, tag, cloneFunc, isDeep) {
		var Ctor = object.constructor;
		switch (tag) {
			case arrayBufferTag: return cloneArrayBuffer(object);
			case boolTag:
			case dateTag: return new Ctor(+object);
			case dataViewTag: return cloneDataView(object, isDeep);
			case float32Tag:
			case float64Tag:
			case int8Tag:
			case int16Tag:
			case int32Tag:
			case uint8Tag:
			case uint8ClampedTag:
			case uint16Tag:
			case uint32Tag: return cloneTypedArray(object, isDeep);
			case mapTag: return cloneMap(object, isDeep, cloneFunc);
			case numberTag:
			case stringTag: return new Ctor(object);
			case regexpTag: return cloneRegExp(object);
			case setTag: return cloneSet(object, isDeep, cloneFunc);
			case symbolTag: return cloneSymbol(object);
		}
	}
	/**
	* Checks if `value` is a valid array-like index.
	*
	* @private
	* @param {*} value The value to check.
	* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
	* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
	*/
	function isIndex(value, length) {
		length = length == null ? MAX_SAFE_INTEGER : length;
		return !!length && (typeof value == "number" || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
	}
	/**
	* Checks if `value` is suitable for use as unique object key.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
	*/
	function isKeyable(value) {
		var type = typeof value;
		return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
	}
	/**
	* Checks if `func` has its source masked.
	*
	* @private
	* @param {Function} func The function to check.
	* @returns {boolean} Returns `true` if `func` is masked, else `false`.
	*/
	function isMasked(func) {
		return !!maskSrcKey && maskSrcKey in func;
	}
	/**
	* Checks if `value` is likely a prototype object.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
	*/
	function isPrototype(value) {
		var Ctor = value && value.constructor;
		return value === (typeof Ctor == "function" && Ctor.prototype || objectProto);
	}
	/**
	* Converts `func` to its source code.
	*
	* @private
	* @param {Function} func The function to process.
	* @returns {string} Returns the source code.
	*/
	function toSource(func) {
		if (func != null) {
			try {
				return funcToString.call(func);
			} catch (e) {}
			try {
				return func + "";
			} catch (e) {}
		}
		return "";
	}
	/**
	* This method is like `_.clone` except that it recursively clones `value`.
	*
	* @static
	* @memberOf _
	* @since 1.0.0
	* @category Lang
	* @param {*} value The value to recursively clone.
	* @returns {*} Returns the deep cloned value.
	* @see _.clone
	* @example
	*
	* var objects = [{ 'a': 1 }, { 'b': 2 }];
	*
	* var deep = _.cloneDeep(objects);
	* console.log(deep[0] === objects[0]);
	* // => false
	*/
	function cloneDeep(value) {
		return baseClone(value, true, true);
	}
	/**
	* Performs a
	* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
	* comparison between two values to determine if they are equivalent.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to compare.
	* @param {*} other The other value to compare.
	* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
	* @example
	*
	* var object = { 'a': 1 };
	* var other = { 'a': 1 };
	*
	* _.eq(object, object);
	* // => true
	*
	* _.eq(object, other);
	* // => false
	*
	* _.eq('a', 'a');
	* // => true
	*
	* _.eq('a', Object('a'));
	* // => false
	*
	* _.eq(NaN, NaN);
	* // => true
	*/
	function eq(value, other) {
		return value === other || value !== value && other !== other;
	}
	/**
	* Checks if `value` is likely an `arguments` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an `arguments` object,
	*  else `false`.
	* @example
	*
	* _.isArguments(function() { return arguments; }());
	* // => true
	*
	* _.isArguments([1, 2, 3]);
	* // => false
	*/
	function isArguments(value) {
		return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag);
	}
	/**
	* Checks if `value` is classified as an `Array` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an array, else `false`.
	* @example
	*
	* _.isArray([1, 2, 3]);
	* // => true
	*
	* _.isArray(document.body.children);
	* // => false
	*
	* _.isArray('abc');
	* // => false
	*
	* _.isArray(_.noop);
	* // => false
	*/
	var isArray = Array.isArray;
	/**
	* Checks if `value` is array-like. A value is considered array-like if it's
	* not a function and has a `value.length` that's an integer greater than or
	* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
	* @example
	*
	* _.isArrayLike([1, 2, 3]);
	* // => true
	*
	* _.isArrayLike(document.body.children);
	* // => true
	*
	* _.isArrayLike('abc');
	* // => true
	*
	* _.isArrayLike(_.noop);
	* // => false
	*/
	function isArrayLike(value) {
		return value != null && isLength(value.length) && !isFunction(value);
	}
	/**
	* This method is like `_.isArrayLike` except that it also checks if `value`
	* is an object.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an array-like object,
	*  else `false`.
	* @example
	*
	* _.isArrayLikeObject([1, 2, 3]);
	* // => true
	*
	* _.isArrayLikeObject(document.body.children);
	* // => true
	*
	* _.isArrayLikeObject('abc');
	* // => false
	*
	* _.isArrayLikeObject(_.noop);
	* // => false
	*/
	function isArrayLikeObject(value) {
		return isObjectLike(value) && isArrayLike(value);
	}
	/**
	* Checks if `value` is a buffer.
	*
	* @static
	* @memberOf _
	* @since 4.3.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
	* @example
	*
	* _.isBuffer(new Buffer(2));
	* // => true
	*
	* _.isBuffer(new Uint8Array(2));
	* // => false
	*/
	var isBuffer = nativeIsBuffer || stubFalse;
	/**
	* Checks if `value` is classified as a `Function` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a function, else `false`.
	* @example
	*
	* _.isFunction(_);
	* // => true
	*
	* _.isFunction(/abc/);
	* // => false
	*/
	function isFunction(value) {
		var tag = isObject(value) ? objectToString.call(value) : "";
		return tag == funcTag || tag == genTag;
	}
	/**
	* Checks if `value` is a valid array-like length.
	*
	* **Note:** This method is loosely based on
	* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
	* @example
	*
	* _.isLength(3);
	* // => true
	*
	* _.isLength(Number.MIN_VALUE);
	* // => false
	*
	* _.isLength(Infinity);
	* // => false
	*
	* _.isLength('3');
	* // => false
	*/
	function isLength(value) {
		return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
	}
	/**
	* Checks if `value` is the
	* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
	* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an object, else `false`.
	* @example
	*
	* _.isObject({});
	* // => true
	*
	* _.isObject([1, 2, 3]);
	* // => true
	*
	* _.isObject(_.noop);
	* // => true
	*
	* _.isObject(null);
	* // => false
	*/
	function isObject(value) {
		var type = typeof value;
		return !!value && (type == "object" || type == "function");
	}
	/**
	* Checks if `value` is object-like. A value is object-like if it's not `null`
	* and has a `typeof` result of "object".
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
	* @example
	*
	* _.isObjectLike({});
	* // => true
	*
	* _.isObjectLike([1, 2, 3]);
	* // => true
	*
	* _.isObjectLike(_.noop);
	* // => false
	*
	* _.isObjectLike(null);
	* // => false
	*/
	function isObjectLike(value) {
		return !!value && typeof value == "object";
	}
	/**
	* Creates an array of the own enumerable property names of `object`.
	*
	* **Note:** Non-object values are coerced to objects. See the
	* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
	* for more details.
	*
	* @static
	* @since 0.1.0
	* @memberOf _
	* @category Object
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of property names.
	* @example
	*
	* function Foo() {
	*   this.a = 1;
	*   this.b = 2;
	* }
	*
	* Foo.prototype.c = 3;
	*
	* _.keys(new Foo);
	* // => ['a', 'b'] (iteration order is not guaranteed)
	*
	* _.keys('hi');
	* // => ['0', '1']
	*/
	function keys(object) {
		return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
	}
	/**
	* This method returns a new empty array.
	*
	* @static
	* @memberOf _
	* @since 4.13.0
	* @category Util
	* @returns {Array} Returns the new empty array.
	* @example
	*
	* var arrays = _.times(2, _.stubArray);
	*
	* console.log(arrays);
	* // => [[], []]
	*
	* console.log(arrays[0] === arrays[1]);
	* // => false
	*/
	function stubArray() {
		return [];
	}
	/**
	* This method returns `false`.
	*
	* @static
	* @memberOf _
	* @since 4.13.0
	* @category Util
	* @returns {boolean} Returns `false`.
	* @example
	*
	* _.times(2, _.stubFalse);
	* // => [false, false]
	*/
	function stubFalse() {
		return false;
	}
	module.exports = cloneDeep;
}));
//#endregion
//#region node_modules/.pnpm/lru-memoizer@2.3.0/node_modules/lru-memoizer/lib/freeze.js
var require_freeze = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.deepFreeze = void 0;
	function deepFreeze(o) {
		if (o) {
			Object.freeze(o);
			Object.getOwnPropertyNames(o).forEach(function(prop) {
				if (o.hasOwnProperty(prop) && o[prop] !== null && (typeof o[prop] === "object" || typeof o[prop] === "function") && o[prop].constructor !== Buffer && !Object.isFrozen(o[prop])) deepFreeze(o[prop]);
			});
		}
		return o;
	}
	exports.deepFreeze = deepFreeze;
}));
//#endregion
//#region node_modules/.pnpm/lru-memoizer@2.3.0/node_modules/lru-memoizer/lib/sync.js
var require_sync = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __read = exports && exports.__read || function(o, n) {
		var m = typeof Symbol === "function" && o[Symbol.iterator];
		if (!m) return o;
		var i = m.call(o), r, ar = [], e;
		try {
			while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
		} catch (error) {
			e = { error };
		} finally {
			try {
				if (r && !r.done && (m = i["return"])) m.call(i);
			} finally {
				if (e) throw e.error;
			}
		}
		return ar;
	};
	var __spread = exports && exports.__spread || function() {
		for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
		return ar;
	};
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.syncMemoizer = void 0;
	var lru_cache_1 = __importDefault(require_lru_cache());
	var events_1$1 = __require("events");
	var lodash_clonedeep_1 = __importDefault(require_lodash_clonedeep());
	var freeze_1 = require_freeze();
	function syncMemoizer(options) {
		var cache = new lru_cache_1.default(options);
		var load = options.load;
		var hash = options.hash;
		var bypass = options.bypass;
		var itemMaxAge = options.itemMaxAge;
		var freeze = options.freeze;
		var clone = options.clone;
		var emitter = new events_1$1.EventEmitter();
		var defaultResult = Object.assign({
			del,
			reset: function() {
				return cache.reset();
			},
			keys: cache.keys.bind(cache),
			on: emitter.on.bind(emitter),
			once: emitter.once.bind(emitter)
		}, options);
		if (options.disable) return Object.assign(load, defaultResult);
		function del() {
			var key = hash.apply(void 0, __spread(arguments));
			cache.del(key);
		}
		function emit(event) {
			var parameters = [];
			for (var _i = 1; _i < arguments.length; _i++) parameters[_i - 1] = arguments[_i];
			emitter.emit.apply(emitter, __spread([event], parameters));
		}
		function isPromise(result) {
			return result && result.then && typeof result.then === "function";
		}
		function processResult(result) {
			var res = result;
			if (clone) if (isPromise(res)) res = res.then(lodash_clonedeep_1.default);
			else res = lodash_clonedeep_1.default(res);
			if (freeze) if (isPromise(res)) res = res.then(freeze_1.deepFreeze);
			else freeze_1.deepFreeze(res);
			return res;
		}
		var result = function() {
			var args = [];
			for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
			if (bypass && bypass.apply(void 0, __spread(args))) {
				emit.apply(void 0, __spread(["miss"], args));
				return load.apply(void 0, __spread(args));
			}
			var key = hash.apply(void 0, __spread(args));
			var fromCache = cache.get(key);
			if (fromCache) {
				emit.apply(void 0, __spread(["hit"], args));
				return processResult(fromCache);
			}
			emit.apply(void 0, __spread(["miss"], args));
			var result = load.apply(void 0, __spread(args));
			if (itemMaxAge) cache.set(key, result, itemMaxAge.apply(void 0, __spread(args.concat([result]))));
			else cache.set(key, result);
			return processResult(result);
		};
		return Object.assign(result, defaultResult);
	}
	exports.syncMemoizer = syncMemoizer;
}));
//#endregion
//#region node_modules/.pnpm/lru-memoizer@2.3.0/node_modules/lru-memoizer/lib/async.js
var require_async = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __read = exports && exports.__read || function(o, n) {
		var m = typeof Symbol === "function" && o[Symbol.iterator];
		if (!m) return o;
		var i = m.call(o), r, ar = [], e;
		try {
			while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
		} catch (error) {
			e = { error };
		} finally {
			try {
				if (r && !r.done && (m = i["return"])) m.call(i);
			} finally {
				if (e) throw e.error;
			}
		}
		return ar;
	};
	var __spread = exports && exports.__spread || function() {
		for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
		return ar;
	};
	var __values = exports && exports.__values || function(o) {
		var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
		if (m) return m.call(o);
		if (o && typeof o.length === "number") return { next: function() {
			if (o && i >= o.length) o = void 0;
			return {
				value: o && o[i++],
				done: !o
			};
		} };
		throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
	};
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.asyncMemoizer = void 0;
	var lru_cache_1 = __importDefault(require_lru_cache());
	var events_1 = __require("events");
	var lodash_clonedeep_1 = __importDefault(require_lodash_clonedeep());
	var freeze_1 = require_freeze();
	var sync_1 = require_sync();
	function asyncMemoizer(options) {
		var cache = new lru_cache_1.default(options);
		var load = options.load;
		var hash = options.hash;
		var bypass = options.bypass;
		var itemMaxAge = options.itemMaxAge;
		var freeze = options.freeze;
		var clone = options.clone;
		var queueMaxAge = options.queueMaxAge || 1e3;
		var loading = /* @__PURE__ */ new Map();
		var emitter = new events_1.EventEmitter();
		var memoizerMethods = Object.assign({
			del,
			reset: function() {
				return cache.reset();
			},
			keys: cache.keys.bind(cache),
			on: emitter.on.bind(emitter),
			once: emitter.once.bind(emitter)
		}, options);
		if (options.disable) return Object.assign(load, memoizerMethods);
		function del() {
			var args = [];
			for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
			var key = hash.apply(void 0, __spread(args));
			cache.del(key);
		}
		function add(key, parameters, result) {
			if (freeze) result.forEach(freeze_1.deepFreeze);
			if (itemMaxAge) cache.set(key, result, itemMaxAge.apply(void 0, __spread(parameters.concat(result))));
			else cache.set(key, result);
		}
		function runCallbacks(callbacks, args) {
			var e_1, _a;
			try {
				for (var callbacks_1 = __values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {
					var callback = callbacks_1_1.value;
					if (clone) setImmediate.apply(void 0, __spread([callback], args.map(lodash_clonedeep_1.default)));
					else setImmediate.apply(void 0, __spread([callback], args));
				}
			} catch (e_1_1) {
				e_1 = { error: e_1_1 };
			} finally {
				try {
					if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1);
				} finally {
					if (e_1) throw e_1.error;
				}
			}
		}
		function emit(event) {
			var parameters = [];
			for (var _i = 1; _i < arguments.length; _i++) parameters[_i - 1] = arguments[_i];
			emitter.emit.apply(emitter, __spread([event], parameters));
		}
		function memoizedFunction() {
			var args = [];
			for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
			var parameters = args.slice(0, -1);
			var callback = args.slice(-1).pop();
			var key;
			if (bypass && bypass.apply(void 0, __spread(parameters))) {
				emit.apply(void 0, __spread(["miss"], parameters));
				return load.apply(void 0, __spread(args));
			}
			if (parameters.length === 0 && !hash) key = "_";
			else key = hash.apply(void 0, __spread(parameters));
			var fromCache = cache.get(key);
			if (fromCache) {
				emit.apply(void 0, __spread(["hit"], parameters));
				return runCallbacks([callback], [null].concat(fromCache));
			}
			var pendingLoad = loading.get(key);
			if (pendingLoad && pendingLoad.expiresAt > Date.now()) {
				pendingLoad.queue.push(callback);
				emit.apply(void 0, __spread(["queue"], parameters));
				return;
			}
			emit.apply(void 0, __spread(["miss"], parameters));
			var started = Date.now();
			var queue = [callback];
			loading.set(key, {
				queue,
				expiresAt: started + queueMaxAge
			});
			var loadHandler = function() {
				var args = [];
				for (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];
				if (!args[0]) add(key, parameters, args.slice(1));
				loading.delete(key);
				emit.apply(void 0, __spread(["loaded", Date.now() - started], parameters));
				runCallbacks(queue, args);
			};
			load.apply(void 0, __spread(parameters, [loadHandler]));
		}
		return Object.assign(memoizedFunction, memoizerMethods);
	}
	exports.asyncMemoizer = asyncMemoizer;
	asyncMemoizer.sync = sync_1.syncMemoizer;
}));
//#endregion
//#region node_modules/.pnpm/lru-memoizer@2.3.0/node_modules/lru-memoizer/lib/index.js
var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = require_async().asyncMemoizer;
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/wrappers/cache.js
var require_cache = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const logger = require_src$3()("jwks");
	const memoizer = require_lib();
	const { promisify, callbackify: callbackify$1 } = __require("util");
	function cacheWrapper(client, { cacheMaxEntries = 5, cacheMaxAge = 6e5 }) {
		logger(`Configured caching of signing keys. Max: ${cacheMaxEntries} / Age: ${cacheMaxAge}`);
		return promisify(memoizer({
			hash: (kid) => kid,
			load: callbackify$1(client.getSigningKey.bind(client)),
			maxAge: cacheMaxAge,
			max: cacheMaxEntries
		}));
	}
	module.exports.default = cacheWrapper;
}));
//#endregion
//#region node_modules/.pnpm/limiter@1.1.5/node_modules/limiter/lib/tokenBucket.js
var require_tokenBucket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* A hierarchical token bucket for rate limiting. See
	* http://en.wikipedia.org/wiki/Token_bucket for more information.
	* @author John Hurliman <jhurliman@cull.tv>
	*
	* @param {Number} bucketSize Maximum number of tokens to hold in the bucket.
	*  Also known as the burst rate.
	* @param {Number} tokensPerInterval Number of tokens to drip into the bucket
	*  over the course of one interval.
	* @param {String|Number} interval The interval length in milliseconds, or as
	*  one of the following strings: 'second', 'minute', 'hour', day'.
	* @param {TokenBucket} parentBucket Optional. A token bucket that will act as
	*  the parent of this bucket.
	*/
	var TokenBucket = function(bucketSize, tokensPerInterval, interval, parentBucket) {
		this.bucketSize = bucketSize;
		this.tokensPerInterval = tokensPerInterval;
		if (typeof interval === "string") switch (interval) {
			case "sec":
			case "second":
				this.interval = 1e3;
				break;
			case "min":
			case "minute":
				this.interval = 1e3 * 60;
				break;
			case "hr":
			case "hour":
				this.interval = 1e3 * 60 * 60;
				break;
			case "day":
				this.interval = 1e3 * 60 * 60 * 24;
				break;
			default: throw new Error("Invaid interval " + interval);
		}
		else this.interval = interval;
		this.parentBucket = parentBucket;
		this.content = 0;
		this.lastDrip = +/* @__PURE__ */ new Date();
	};
	TokenBucket.prototype = {
		bucketSize: 1,
		tokensPerInterval: 1,
		interval: 1e3,
		parentBucket: null,
		content: 0,
		lastDrip: 0,
		removeTokens: function(count, callback) {
			var self = this;
			if (!this.bucketSize) {
				process.nextTick(callback.bind(null, null, count, Number.POSITIVE_INFINITY));
				return true;
			}
			if (count > this.bucketSize) {
				process.nextTick(callback.bind(null, "Requested tokens " + count + " exceeds bucket size " + this.bucketSize, null));
				return false;
			}
			this.drip();
			if (count > this.content) return comeBackLater();
			if (this.parentBucket) return this.parentBucket.removeTokens(count, function(err, remainingTokens) {
				if (err) return callback(err, null);
				if (count > self.content) return comeBackLater();
				self.content -= count;
				callback(null, Math.min(remainingTokens, self.content));
			});
			else {
				this.content -= count;
				process.nextTick(callback.bind(null, null, this.content));
				return true;
			}
			function comeBackLater() {
				var waitInterval = Math.ceil((count - self.content) * (self.interval / self.tokensPerInterval));
				setTimeout(function() {
					self.removeTokens(count, callback);
				}, waitInterval);
				return false;
			}
		},
		tryRemoveTokens: function(count) {
			if (!this.bucketSize) return true;
			if (count > this.bucketSize) return false;
			this.drip();
			if (count > this.content) return false;
			if (this.parentBucket && !this.parentBucket.tryRemoveTokens(count)) return false;
			this.content -= count;
			return true;
		},
		drip: function() {
			if (!this.tokensPerInterval) {
				this.content = this.bucketSize;
				return;
			}
			var now = +/* @__PURE__ */ new Date();
			var deltaMS = Math.max(now - this.lastDrip, 0);
			this.lastDrip = now;
			var dripAmount = deltaMS * (this.tokensPerInterval / this.interval);
			this.content = Math.min(this.content + dripAmount, this.bucketSize);
		}
	};
	module.exports = TokenBucket;
}));
//#endregion
//#region node_modules/.pnpm/limiter@1.1.5/node_modules/limiter/lib/clock.js
var require_clock = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var getMilliseconds = function() {
		if (typeof process !== "undefined" && process.hrtime) {
			var hrtime = process.hrtime();
			var seconds = hrtime[0];
			var nanoseconds = hrtime[1];
			return seconds * 1e3 + Math.floor(nanoseconds / 1e6);
		}
		return (/* @__PURE__ */ new Date()).getTime();
	};
	module.exports = getMilliseconds;
}));
//#endregion
//#region node_modules/.pnpm/limiter@1.1.5/node_modules/limiter/lib/rateLimiter.js
var require_rateLimiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var TokenBucket = require_tokenBucket();
	var getMilliseconds = require_clock();
	/**
	* A generic rate limiter. Underneath the hood, this uses a token bucket plus
	* an additional check to limit how many tokens we can remove each interval.
	* @author John Hurliman <jhurliman@jhurliman.org>
	*
	* @param {Number} tokensPerInterval Maximum number of tokens that can be
	*  removed at any given moment and over the course of one interval.
	* @param {String|Number} interval The interval length in milliseconds, or as
	*  one of the following strings: 'second', 'minute', 'hour', day'.
	* @param {Boolean} fireImmediately Optional. Whether or not the callback
	*  will fire immediately when rate limiting is in effect (default is false).
	*/
	var RateLimiter = function(tokensPerInterval, interval, fireImmediately) {
		this.tokenBucket = new TokenBucket(tokensPerInterval, tokensPerInterval, interval, null);
		this.tokenBucket.content = tokensPerInterval;
		this.curIntervalStart = getMilliseconds();
		this.tokensThisInterval = 0;
		this.fireImmediately = fireImmediately;
	};
	RateLimiter.prototype = {
		tokenBucket: null,
		curIntervalStart: 0,
		tokensThisInterval: 0,
		fireImmediately: false,
		removeTokens: function(count, callback) {
			if (count > this.tokenBucket.bucketSize) {
				process.nextTick(callback.bind(null, "Requested tokens " + count + " exceeds maximum tokens per interval " + this.tokenBucket.bucketSize, null));
				return false;
			}
			var self = this;
			var now = getMilliseconds();
			if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {
				this.curIntervalStart = now;
				this.tokensThisInterval = 0;
			}
			if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {
				if (this.fireImmediately) process.nextTick(callback.bind(null, null, -1));
				else {
					var waitInterval = Math.ceil(this.curIntervalStart + this.tokenBucket.interval - now);
					setTimeout(function() {
						self.tokenBucket.removeTokens(count, afterTokensRemoved);
					}, waitInterval);
				}
				return false;
			}
			return this.tokenBucket.removeTokens(count, afterTokensRemoved);
			function afterTokensRemoved(err, tokensRemaining) {
				if (err) return callback(err, null);
				self.tokensThisInterval += count;
				callback(null, tokensRemaining);
			}
		},
		tryRemoveTokens: function(count) {
			if (count > this.tokenBucket.bucketSize) return false;
			var now = getMilliseconds();
			if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {
				this.curIntervalStart = now;
				this.tokensThisInterval = 0;
			}
			if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) return false;
			var removed = this.tokenBucket.tryRemoveTokens(count);
			if (removed) this.tokensThisInterval += count;
			return removed;
		},
		getTokensRemaining: function() {
			this.tokenBucket.drip();
			return this.tokenBucket.content;
		}
	};
	module.exports = RateLimiter;
}));
//#endregion
//#region node_modules/.pnpm/limiter@1.1.5/node_modules/limiter/index.js
var require_limiter = /* @__PURE__ */ __commonJSMin(((exports) => {
	exports.RateLimiter = require_rateLimiter();
	exports.TokenBucket = require_tokenBucket();
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/errors/JwksRateLimitError.js
var require_JwksRateLimitError = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	function JwksRateLimitError(message) {
		Error.call(this, message);
		Error.captureStackTrace(this, this.constructor);
		this.name = "JwksRateLimitError";
		this.message = message;
	}
	JwksRateLimitError.prototype = Object.create(Error.prototype);
	JwksRateLimitError.prototype.constructor = JwksRateLimitError;
	module.exports = JwksRateLimitError;
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/wrappers/rateLimit.js
var require_rateLimit = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const logger = require_src$3()("jwks");
	const { RateLimiter } = require_limiter();
	const JwksRateLimitError = require_JwksRateLimitError();
	function rateLimitWrapper(client, { jwksRequestsPerMinute = 10 }) {
		const getSigningKey = client.getSigningKey.bind(client);
		const limiter = new RateLimiter(jwksRequestsPerMinute, "minute", true);
		logger(`Configured rate limiting to JWKS endpoint at ${jwksRequestsPerMinute}/minute`);
		return async (kid) => await new Promise((resolve, reject) => {
			limiter.removeTokens(1, async (err, remaining) => {
				if (err) reject(err);
				logger("Requests to the JWKS endpoint available for the next minute:", remaining);
				if (remaining < 0) {
					logger("Too many requests to the JWKS endpoint");
					reject(new JwksRateLimitError("Too many requests to the JWKS endpoint"));
				} else try {
					resolve(await getSigningKey(kid));
				} catch (error) {
					reject(error);
				}
			});
		});
	}
	module.exports.default = rateLimitWrapper;
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/wrappers/interceptor.js
var require_interceptor = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const retrieveSigningKeys = require_utils().retrieveSigningKeys;
	/**
	* Uses getKeysInterceptor to allow users to retrieve keys from a file,
	* external cache, or provided object before falling back to the jwksUri endpoint
	*/
	function getKeysInterceptor(client, { getKeysInterceptor }) {
		const getSigningKey = client.getSigningKey.bind(client);
		return async (kid) => {
			const keys = await getKeysInterceptor();
			let signingKeys;
			if (keys && keys.length) signingKeys = await retrieveSigningKeys(keys);
			if (signingKeys && signingKeys.length) {
				const key = signingKeys.find((k) => !kid || k.kid === kid);
				if (key) return key;
			}
			return getSigningKey(kid);
		};
	}
	module.exports.default = getKeysInterceptor;
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/wrappers/callbackSupport.js
var require_callbackSupport = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { callbackify } = __require("util");
	const callbackSupport = (client) => {
		const getSigningKey = client.getSigningKey.bind(client);
		return (kid, cb) => {
			if (cb) return callbackify(getSigningKey)(kid, cb);
			return getSigningKey(kid);
		};
	};
	module.exports.default = callbackSupport;
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/wrappers/index.js
var require_wrappers = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		request: require_request().default,
		cacheSigningKey: require_cache().default,
		rateLimitSigningKey: require_rateLimit().default,
		getKeysInterceptor: require_interceptor().default,
		callbackSupport: require_callbackSupport().default
	};
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/errors/SigningKeyNotFoundError.js
var require_SigningKeyNotFoundError = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	function SigningKeyNotFoundError(message) {
		Error.call(this, message);
		Error.captureStackTrace(this, this.constructor);
		this.name = "SigningKeyNotFoundError";
		this.message = message;
	}
	SigningKeyNotFoundError.prototype = Object.create(Error.prototype);
	SigningKeyNotFoundError.prototype.constructor = SigningKeyNotFoundError;
	module.exports = SigningKeyNotFoundError;
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/JwksClient.js
var require_JwksClient = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const logger = require_src$3()("jwks");
	const { retrieveSigningKeys } = require_utils();
	const { request, cacheSigningKey, rateLimitSigningKey, getKeysInterceptor, callbackSupport } = require_wrappers();
	const JwksError = require_JwksError();
	const SigningKeyNotFoundError = require_SigningKeyNotFoundError();
	var JwksClient = class {
		constructor(options) {
			this.options = {
				rateLimit: false,
				cache: true,
				timeout: 3e4,
				...options
			};
			if (this.options.getKeysInterceptor) this.getSigningKey = getKeysInterceptor(this, options);
			if (this.options.rateLimit) this.getSigningKey = rateLimitSigningKey(this, options);
			if (this.options.cache) this.getSigningKey = cacheSigningKey(this, options);
			this.getSigningKey = callbackSupport(this, options);
		}
		async getKeys() {
			logger(`Fetching keys from '${this.options.jwksUri}'`);
			try {
				const res = await request({
					uri: this.options.jwksUri,
					headers: this.options.requestHeaders,
					agent: this.options.requestAgent,
					timeout: this.options.timeout,
					fetcher: this.options.fetcher
				});
				logger("Keys:", res.keys);
				return res.keys;
			} catch (err) {
				const { errorMsg } = err;
				logger("Failure:", errorMsg || err);
				throw errorMsg ? new JwksError(errorMsg) : err;
			}
		}
		async getSigningKeys() {
			const keys = await this.getKeys();
			if (!keys || !keys.length) throw new JwksError("The JWKS endpoint did not contain any keys");
			const signingKeys = await retrieveSigningKeys(keys);
			if (!signingKeys.length) throw new JwksError("The JWKS endpoint did not contain any signing keys");
			logger("Signing Keys:", signingKeys);
			return signingKeys;
		}
		async getSigningKey(kid) {
			logger(`Fetching signing key for '${kid}'`);
			const keys = await this.getSigningKeys();
			const kidDefined = kid !== void 0 && kid !== null;
			if (!kidDefined && keys.length > 1) {
				logger("No KID specified and JWKS endpoint returned more than 1 key");
				throw new SigningKeyNotFoundError("No KID specified and JWKS endpoint returned more than 1 key");
			}
			const key = keys.find((k) => !kidDefined || k.kid === kid);
			if (key) return key;
			else {
				logger(`Unable to find a signing key that matches '${kid}'`);
				throw new SigningKeyNotFoundError(`Unable to find a signing key that matches '${kid}'`);
			}
		}
	};
	module.exports = { JwksClient };
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/errors/index.js
var require_errors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		ArgumentError: require_ArgumentError(),
		JwksError: require_JwksError(),
		JwksRateLimitError: require_JwksRateLimitError(),
		SigningKeyNotFoundError: require_SigningKeyNotFoundError()
	};
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/integrations/config.js
var require_config = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = [
		"RS256",
		"RS384",
		"RS512",
		"PS256",
		"PS384",
		"PS512",
		"ES256",
		"ES256K",
		"ES384",
		"ES512",
		"EdDSA"
	];
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/integrations/hapi.js
var require_hapi = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { ArgumentError } = require_errors();
	const { JwksClient } = require_JwksClient();
	const supportedAlg = require_config();
	const handleSigningKeyError = (err, cb) => {
		if (err && err.name === "SigningKeyNotFoundError") return cb(err, null, null);
		if (err) return cb(err, null, null);
	};
	/**
	* Call hapiJwt2Key as a Promise
	* @param {object} options 
	* @returns {Promise}
	*/
	module.exports.hapiJwt2KeyAsync = (options) => {
		const secretProvider = module.exports.hapiJwt2Key(options);
		return function(decoded) {
			return new Promise((resolve, reject) => {
				const cb = (err, key) => {
					!key || err ? reject(err) : resolve({ key });
				};
				secretProvider(decoded, cb);
			});
		};
	};
	module.exports.hapiJwt2Key = function(options) {
		if (options === null || options === void 0) throw new ArgumentError("An options object must be provided when initializing hapiJwt2Key");
		const client = new JwksClient(options);
		const onError = options.handleSigningKeyError || handleSigningKeyError;
		return function secretProvider(decoded, cb) {
			if (!decoded || !decoded.header) return cb(/* @__PURE__ */ new Error("Cannot find a signing certificate if there is no header"), null, null);
			if (!supportedAlg.includes(decoded.header.alg)) return cb(/* @__PURE__ */ new Error("Unsupported algorithm " + decoded.header.alg + " supplied."), null, null);
			client.getSigningKey(decoded.header.kid).then((key) => {
				return cb(null, key.publicKey || key.rsaPublicKey, key);
			}).catch((err) => {
				return onError(err, (newError) => cb(newError, null, null));
			});
		};
	};
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/integrations/express.js
var require_express = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { ArgumentError } = require_errors();
	const { JwksClient } = require_JwksClient();
	const supportedAlg = require_config();
	const handleSigningKeyError = (err, cb) => {
		if (err && err.name === "SigningKeyNotFoundError") return cb(null);
		if (err) return cb(err);
	};
	module.exports.expressJwtSecret = function(options) {
		if (options === null || options === void 0) throw new ArgumentError("An options object must be provided when initializing expressJwtSecret");
		const client = new JwksClient(options);
		const onError = options.handleSigningKeyError || handleSigningKeyError;
		const expressJwt7Provider = async (req, token) => {
			if (!token) return;
			const header = token.header;
			if (!header || !supportedAlg.includes(header.alg)) return;
			try {
				const key = await client.getSigningKey(header.kid);
				return key.publicKey || key.rsaPublicKey;
			} catch (err) {
				return new Promise((resolve, reject) => {
					onError(err, (newError) => {
						if (!newError) return resolve();
						reject(newError);
					});
				});
			}
		};
		return function secretProvider(req, header, payload, cb) {
			if (arguments.length === 4) {
				expressJwt7Provider(req, { header }).then((key) => {
					setImmediate(cb, null, key);
				}).catch((err) => {
					setImmediate(cb, err);
				});
				return;
			}
			return expressJwt7Provider(req, arguments[1]);
		};
	};
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/integrations/koa.js
var require_koa = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { ArgumentError } = require_errors();
	const { JwksClient } = require_JwksClient();
	const supportedAlg = require_config();
	module.exports.koaJwtSecret = function(options = {}) {
		if (!options.jwksUri) throw new ArgumentError("No JWKS provided. Please provide a jwksUri");
		const client = new JwksClient(options);
		return function secretProvider({ alg, kid } = {}) {
			return new Promise((resolve, reject) => {
				if (!supportedAlg.includes(alg)) return reject(/* @__PURE__ */ new Error("Missing / invalid token algorithm"));
				client.getSigningKey(kid).then((key) => {
					resolve(key.publicKey || key.rsaPublicKey);
				}).catch((err) => {
					if (options.handleSigningKeyError) return options.handleSigningKeyError(err).then(reject);
					return reject(err);
				});
			});
		};
	};
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/integrations/passport.js
var require_passport = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const jose = require_cjs();
	const { ArgumentError } = require_errors();
	const { JwksClient } = require_JwksClient();
	const supportedAlg = require_config();
	const handleSigningKeyError = (err, cb) => {
		if (err && err.name === "SigningKeyNotFoundError") return cb(null);
		if (err) return cb(err);
	};
	module.exports.passportJwtSecret = function(options) {
		if (options === null || options === void 0) throw new ArgumentError("An options object must be provided when initializing passportJwtSecret");
		if (!options.jwksUri) throw new ArgumentError("No JWKS provided. Please provide a jwksUri");
		const client = new JwksClient(options);
		const onError = options.handleSigningKeyError || handleSigningKeyError;
		return function secretProvider(req, rawJwtToken, cb) {
			let decoded;
			try {
				decoded = {
					payload: jose.decodeJwt(rawJwtToken),
					header: jose.decodeProtectedHeader(rawJwtToken)
				};
			} catch (err) {
				decoded = null;
			}
			if (!decoded || !supportedAlg.includes(decoded.header.alg)) return cb(null, null);
			client.getSigningKey(decoded.header.kid).then((key) => {
				cb(null, key.publicKey || key.rsaPublicKey);
			}).catch((err) => {
				onError(err, (newError) => cb(newError, null));
			});
		};
	};
}));
//#endregion
//#region node_modules/.pnpm/jwks-rsa@3.2.2/node_modules/jwks-rsa/src/index.js
var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { JwksClient } = require_JwksClient();
	const errors = require_errors();
	const { hapiJwt2Key, hapiJwt2KeyAsync } = require_hapi();
	const { expressJwtSecret } = require_express();
	const { koaJwtSecret } = require_koa();
	const { passportJwtSecret } = require_passport();
	module.exports = (options) => {
		return new JwksClient(options);
	};
	module.exports.JwksClient = JwksClient;
	module.exports.ArgumentError = errors.ArgumentError;
	module.exports.JwksError = errors.JwksError;
	module.exports.JwksRateLimitError = errors.JwksRateLimitError;
	module.exports.SigningKeyNotFoundError = errors.SigningKeyNotFoundError;
	module.exports.expressJwtSecret = expressJwtSecret;
	module.exports.hapiJwt2Key = hapiJwt2Key;
	module.exports.hapiJwt2KeyAsync = hapiJwt2KeyAsync;
	module.exports.koaJwtSecret = koaJwtSecret;
	module.exports.passportJwtSecret = passportJwtSecret;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/auth/jwt-middleware.js
var require_jwt_middleware = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.authorizeJWT = void 0;
	const jwks_rsa_1 = __importDefault(require_src$1());
	const jsonwebtoken_1 = __importDefault(require_jsonwebtoken());
	const logger = (0, require_logger().debug)("agents:jwt-middleware");
	/**
	* Verifies the JWT token.
	* @param raw The raw JWT token.
	* @param config The authentication configuration.
	* @returns A promise that resolves to the JWT payload.
	*/
	const verifyToken = async (raw, config) => {
		const payload = jsonwebtoken_1.default.decode(raw);
		logger.debug("jwt.decode ", JSON.stringify(payload));
		if (!payload) throw new Error("invalid token");
		const audience = payload.aud;
		const matchingEntry = config.connections && config.connections.size > 0 ? [...config.connections.entries()].find(([_, configuration]) => configuration.clientId === audience) : void 0;
		if (!matchingEntry) {
			const err = /* @__PURE__ */ new Error("Audience mismatch");
			logger.error(err.message, audience);
			throw err;
		}
		const [key, authConfig] = matchingEntry;
		logger.debug(`Audience found at key: ${key}`);
		const jwksUri = payload.iss === "https://api.botframework.com" ? "https://login.botframework.com/v1/.well-known/keys" : `${authConfig.authority}/${authConfig.tenantId}/discovery/v2.0/keys`;
		logger.debug(`fetching keys from ${jwksUri}`);
		const jwksClient = (0, jwks_rsa_1.default)({ jwksUri });
		const getKey = (header, callback) => {
			jwksClient.getSigningKey(header.kid, (err, key) => {
				if (err) {
					logger.error("jwksClient.getSigningKey ", JSON.stringify(err));
					logger.error(JSON.stringify(err));
					callback(err, void 0);
					return;
				}
				callback(null, key === null || key === void 0 ? void 0 : key.getPublicKey());
			});
		};
		const verifyOptions = {
			audience: [authConfig.clientId, "https://api.botframework.com"],
			ignoreExpiration: false,
			algorithms: ["RS256"],
			clockTolerance: 300
		};
		return await new Promise((resolve, reject) => {
			jsonwebtoken_1.default.verify(raw, getKey, verifyOptions, (err, user) => {
				if (err) {
					logger.error("jwt.verify ", JSON.stringify(err));
					reject(err);
					return;
				}
				resolve(user);
			});
		});
	};
	/**
	* Middleware to authorize JWT tokens.
	* @param authConfig The authentication configuration.
	* @returns An Express middleware function.
	*/
	const authorizeJWT = (authConfig) => {
		return async function(req, res, next) {
			let failed = false;
			logger.debug("authorizing jwt");
			if (req.method !== "POST" && req.method !== "GET") {
				failed = true;
				logger.warn("Method not allowed", req.method);
				res.status(405).send({ "jwt-auth-error": "Method not allowed" });
			} else {
				const authHeader = req.headers.authorization;
				if (authHeader) {
					const token = authHeader.split(" ")[1];
					try {
						const user = await verifyToken(token, authConfig);
						logger.debug("token verified for ", user);
						req.user = user;
					} catch (err) {
						failed = true;
						logger.error(err);
						res.status(401).send({ "jwt-auth-error": err.message });
					}
				} else if (!authConfig.clientId && false);
				else {
					failed = true;
					logger.error("authorization header not found");
					res.status(401).send({ "jwt-auth-error": "authorization header not found" });
				}
			}
			if (!failed) next();
		};
	};
	exports.authorizeJWT = authorizeJWT;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/errorHelper.js
var require_errorHelper = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.Errors = void 0;
	exports.Errors = {
		MissingTurnContext: {
			code: -12e4,
			description: "Missing TurnContext parameter"
		},
		TurnContextMissingActivity: {
			code: -120010,
			description: "TurnContext does not include an activity"
		},
		ActivityMissingType: {
			code: -120020,
			description: "Activity is missing its type"
		},
		InvalidActivityObject: {
			code: -120030,
			description: "Invalid activity object"
		},
		ActivityRequired: {
			code: -120040,
			description: "Activity is required."
		},
		ActivityParameterRequired: {
			code: -120050,
			description: "activity parameter required"
		},
		EmptyActivitiesArray: {
			code: -120060,
			description: "Expecting one or more activities, but the array was empty."
		},
		ActivitiesParameterRequired: {
			code: -120070,
			description: "activities parameter required"
		},
		CannotSetRespondedToFalse: {
			code: -120080,
			description: "TurnContext: cannot set 'responded' to a value of 'false'."
		},
		ContextParameterRequired: {
			code: -120090,
			description: "context parameter required"
		},
		ChannelIdRequired: {
			code: -120100,
			description: "channelId is required."
		},
		ConversationIdRequired: {
			code: -120110,
			description: "conversationId is required."
		},
		InvalidConversationReference: {
			code: -120120,
			description: "Invalid conversation reference object"
		},
		ContinueConversationInvalidReference: {
			code: -120130,
			description: "continueConversation: Invalid conversation reference object"
		},
		ContextRequired: {
			code: -120140,
			description: "context is required"
		},
		UserIdAndConversationIdRequired: {
			code: -120150,
			description: "userId and conversationId are required"
		},
		ConversationIdAndActivityIdRequired: {
			code: -120160,
			description: "conversationId and activityId are required"
		},
		ServiceUrlRequired: {
			code: -120170,
			description: "serviceUrl must be a non-empty string"
		},
		ConversationParametersRequired: {
			code: -120180,
			description: "conversationParameters must be defined"
		},
		MissingActivityChannelId: {
			code: -120190,
			description: "missing activity.channelId"
		},
		MissingActivityFromId: {
			code: -120200,
			description: "missing activity.from.id"
		},
		MissingActivityConversationId: {
			code: -120210,
			description: "missing activity.conversation.id"
		},
		MissingContextActivityChannelId: {
			code: -120220,
			description: "missing context.activity.channelId"
		},
		ChannelIdAndFromIdRequired: {
			code: -120230,
			description: "Both 'activity.channelId' and 'activity.from.id' are required for this operation."
		},
		ChannelIdAndFromIdRequiredForSignout: {
			code: -120240,
			description: "Both 'activity.channelId' and 'activity.from.id' are required to perform signout."
		},
		AttachmentDataRequired: {
			code: -120250,
			description: "attachmentData is required"
		},
		AttachmentIdRequired: {
			code: -120260,
			description: "attachmentId is required"
		},
		ViewIdRequired: {
			code: -120270,
			description: "viewId is required"
		},
		HeadersRequired: {
			code: -120280,
			description: "Headers must be provided."
		},
		RequestBodyParameterRequired: {
			code: -120290,
			description: "request.body parameter required"
		},
		ConnectionNotFoundInEnvironment: {
			code: -120300,
			description: "Connection \"{connectionName}\" not found in environment."
		},
		NoDefaultConnectionFound: {
			code: -120310,
			description: "No default connection found in environment connections."
		},
		ClientIdRequiredInProduction: {
			code: -120320,
			description: "ClientId required in production"
		},
		ClientIdNotFoundForConnection: {
			code: -120330,
			description: "ClientId not found for connection: {connectionName}"
		},
		CannotCreateConnectorClientForAgenticUser: {
			code: -120340,
			description: "Could not create connector client for agentic user"
		},
		ConnectionNotFound: {
			code: -120350,
			description: "Connection not found: {connectionName}"
		},
		NoConnectionsFoundInConfiguration: {
			code: -120360,
			description: "No connections found for this Agent in the Connections Configuration."
		},
		ConnectionsOptionNotAvailable: {
			code: -120370,
			description: "The 'connections' option is not available in the app options. Ensure that the app is properly configured."
		},
		ConnectionSettingsRequired: {
			code: -120380,
			description: "Connection settings must be provided for this operation."
		},
		IdentityRequiredForTokenProvider: {
			code: -120390,
			description: "Identity is required to get the token provider."
		},
		AudienceAndServiceUrlRequiredForTokenProvider: {
			code: -120400,
			description: "Audience and Service URL are required to get the token provider."
		},
		NoConnectionForAudienceAndServiceUrl: {
			code: -120410,
			description: "No connection found for audience: {audience} and serviceUrl: {serviceUrl}"
		},
		InvalidToken: {
			code: -120420,
			description: "invalid token"
		},
		InvalidExchangeTokenParameters: {
			code: -120430,
			description: "Invalid parameters for exchangeToken method."
		},
		InvalidAuthConfig: {
			code: -120440,
			description: "Invalid authConfig."
		},
		FailedToAcquireToken: {
			code: -120450,
			description: "Failed to acquire token"
		},
		FailedToAcquireInstanceToken: {
			code: -120460,
			description: "Failed to acquire instance token"
		},
		UserTokenClientNotAvailable: {
			code: -120470,
			description: "The 'userTokenClient' is not available in the adapter. Ensure that the adapter supports user token operations."
		},
		TokenNotExchangeableForOBO: {
			code: -120480,
			description: "The current token is not exchangeable for an on-behalf-of flow. Ensure the token audience starts with 'api://'."
		},
		ConnectionNameOrEnvVariableRequired: {
			code: -120490,
			description: "The 'name' property or '{handlerId}_connectionName' env variable is required to initialize the handler."
		},
		FailedToSignOut: {
			code: -120500,
			description: "Failed to sign out"
		},
		FailedToSignIn: {
			code: -120510,
			description: "Failed to sign in"
		},
		AtLeastOneScopeRequired: {
			code: -120520,
			description: "At least one scope must be specified for the Agentic authorization handler."
		},
		AuthorizationOptionNotAvailable: {
			code: -120530,
			description: "The Application.authorization property is unavailable because no authorization options were configured."
		},
		AuthHandlerNotFound: {
			code: -120540,
			description: "Cannot find auth handler with ID '{handlerId}'. Ensure it is configured in the agent application options."
		},
		AuthHandlersNotFound: {
			code: -120550,
			description: "Cannot find auth handlers with ID(s): {handlerIds}"
		},
		NoAuthHandlersConfigured: {
			code: -120560,
			description: "The AgentApplication.authorization does not have any auth handlers"
		},
		UnsupportedAuthHandlerType: {
			code: -120570,
			description: "Unsupported authorization handler type: {handlerType}"
		},
		UnexpectedRegistrationStatus: {
			code: -120580,
			description: "Unexpected registration status: {status}"
		},
		StorageRequiredForAuthorization: {
			code: -120590,
			description: "Storage is required for Authorization. Ensure that a storage provider is configured in the app options."
		},
		MissingAgentClientConfig: {
			code: -120600,
			description: "Missing agent client config for agent {agentName}"
		},
		AgentNameRequired: {
			code: -120610,
			description: "Agent name is required"
		},
		FailedToPostActivityToAgent: {
			code: -120620,
			description: "Failed to post activity to agent: {statusText}"
		},
		LogicParameterRequired: {
			code: -120630,
			description: "logic must be defined"
		},
		StorageETagConflict: {
			code: -120700,
			description: "Storage: error writing \"{key}\" due to eTag conflict."
		},
		StorageOptionNotAvailable: {
			code: -120710,
			description: "The 'storage' option is not available in the app options. Ensure that the app is properly configured."
		},
		StateNotLoaded: {
			code: -120720,
			description: "State not loaded. Call load() before accessing state properties."
		},
		InvalidStateScope: {
			code: -120730,
			description: "Invalid state scope: {scope}"
		},
		LongRunningMessagesPropertyUnavailable: {
			code: -120850,
			description: "The Application.longRunningMessages property is unavailable because no adapter was configured in the app."
		},
		TranscriptLoggerPropertyUnavailable: {
			code: -120860,
			description: "The Application.transcriptLogger property is unavailable because no adapter was configured in the app."
		},
		TranscriptLoggerInstanceRequired: {
			code: -120870,
			description: "TranscriptLoggerMiddleware requires a TranscriptLogger instance."
		},
		ExtensionAlreadyRegistered: {
			code: -120880,
			description: "Extension already registered"
		},
		InvalidMiddlewarePluginType: {
			code: -120890,
			description: "MiddlewareSet.use(): invalid plugin type being added."
		},
		StreamAlreadyEnded: {
			code: -120900,
			description: "The stream has already ended."
		},
		UnexpectedActionExecute: {
			code: -120950,
			description: "Unexpected AdaptiveCards.actionExecute() triggered for activity type: {activityType}"
		},
		UnexpectedActionSubmit: {
			code: -120960,
			description: "Unexpected AdaptiveCards.actionSubmit() triggered for activity type: {activityType}"
		},
		UnexpectedSearchAction: {
			code: -120970,
			description: "Unexpected AdaptiveCards.search() triggered for activity type: {activityType}"
		},
		InvalidActionValue: {
			code: -120980,
			description: "Invalid action value: {error}"
		},
		UnknownErrorType: {
			code: -120990,
			description: "Unknown error type: {errorMessage}"
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/statusCodes.js
var require_statusCodes = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.StatusCodes = void 0;
	/**
	* HTTP status codes enumeration for agent hosting responses.
	*
	* This enum provides a comprehensive set of HTTP status codes commonly used
	* in agent hosting scenarios, including success, redirection, client error,
	* and server error status codes.
	*/
	var StatusCodes;
	(function(StatusCodes) {
		/**
		* The request has succeeded.
		* Standard response for successful HTTP requests.
		*/
		StatusCodes[StatusCodes["OK"] = 200] = "OK";
		/**
		* The request has been fulfilled and resulted in a new resource being created.
		* Typically returned when a new agent, conversation, or resource is successfully created.
		*/
		StatusCodes[StatusCodes["CREATED"] = 201] = "CREATED";
		/**
		* Indicates multiple options for the resource that the client may follow.
		* Used when there are multiple possible responses or resource locations available.
		*/
		StatusCodes[StatusCodes["MULTIPLE_CHOICES"] = 300] = "MULTIPLE_CHOICES";
		/**
		* The server cannot or will not process the request due to a client error.
		* Returned when the request contains invalid syntax, malformed parameters,
		* or violates agent hosting protocol requirements.
		*/
		StatusCodes[StatusCodes["BAD_REQUEST"] = 400] = "BAD_REQUEST";
		/**
		* The request requires user authentication.
		* Indicates that the client must authenticate itself to get the requested response.
		* Common in agent scenarios requiring valid authentication tokens or credentials.
		*/
		StatusCodes[StatusCodes["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
		/**
		* The requested resource could not be found.
		* Returned when the specified agent, conversation, or endpoint does not exist
		* or is not accessible with the current permissions.
		*/
		StatusCodes[StatusCodes["NOT_FOUND"] = 404] = "NOT_FOUND";
		/**
		* The request method is not allowed for the requested resource.
		* Indicates that the HTTP method used is not supported for the specific
		* agent endpoint or resource being accessed.
		*/
		StatusCodes[StatusCodes["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
		/**
		* The request could not be completed due to a conflict with the current state of the resource.
		* Common when attempting to create duplicate resources or when agent state
		* conflicts prevent the operation from completing.
		*/
		StatusCodes[StatusCodes["CONFLICT"] = 409] = "CONFLICT";
		/**
		* The server does not meet one of the preconditions specified by the client.
		* Returned when conditional requests fail, such as when required headers
		* or agent capabilities are not present or valid.
		*/
		StatusCodes[StatusCodes["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
		/**
		* The client should switch to a different protocol.
		* Used to indicate that the agent hosting service requires a protocol upgrade
		* or different communication method to fulfill the request.
		*/
		StatusCodes[StatusCodes["UPGRADE_REQUIRED"] = 426] = "UPGRADE_REQUIRED";
		/**
		* The server encountered an unexpected condition that prevented it from fulfilling the request.
		* Generic error message when an unexpected agent hosting error occurs
		* and no more specific message is suitable.
		*/
		StatusCodes[StatusCodes["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
		/**
		* The server does not support the functionality required to fulfill the request.
		* Returned when the agent hosting service does not implement the requested
		* feature or capability.
		*/
		StatusCodes[StatusCodes["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
		/**
		* The server received an invalid response from the upstream server.
		* Common when agent hosting services depend on external services
		* that return invalid or malformed responses.
		*/
		StatusCodes[StatusCodes["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
	})(StatusCodes || (exports.StatusCodes = StatusCodes = {}));
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/invokeException.js
var require_invokeException = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.InvokeException = void 0;
	/**
	* Represents an exception that occurs during an invoke operation.
	*/
	var InvokeException = class extends Error {
		/**
		* Creates a new instance of InvokeException.
		* @param status The status code of the exception.
		* @param response The optional response body.
		*/
		constructor(status, response) {
			super();
			this.status = status;
			this.response = response;
			this.name = "InvokeException";
		}
		/**
		* Creates an invoke response from the exception.
		* @returns The invoke response.
		*/
		createInvokeResponse() {
			return {
				status: this.status,
				body: this.response
			};
		}
	};
	exports.InvokeException = InvokeException;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/tokenResponseEventName.js
var require_tokenResponseEventName = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.tokenResponseEventName = void 0;
	/**
	* The event name used for token response activities.
	*/
	exports.tokenResponseEventName = "tokens/response";
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/activityHandler.js
var require_activityHandler = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ActivityHandler = exports.INVOKE_RESPONSE_KEY = void 0;
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	const logger_1 = require_logger();
	const agents_activity_1 = require_src$2();
	const errorHelper_1 = require_errorHelper();
	const statusCodes_1 = require_statusCodes();
	const invokeException_1 = require_invokeException();
	const tokenResponseEventName_1 = require_tokenResponseEventName();
	/** Symbol key for invoke response */
	exports.INVOKE_RESPONSE_KEY = Symbol("invokeResponse");
	const logger = (0, logger_1.debug)("agents:activity-handler");
	/**
	* Handles incoming activities from channels and dispatches them to the appropriate handlers.
	*
	* @remarks
	* This class is provided to simplify the migration from Bot Framework SDK v4 to the Agents Hosting framework.
	*
	* The ActivityHandler serves as the central hub for processing incoming activities in conversational AI applications.
	* It provides a comprehensive framework for handling various activity types including messages, conversation updates,
	* message reactions, typing indicators, installation updates, and invoke operations such as adaptive cards and search.
	*
	* ## Key Features:
	* - **Activity Routing**: Automatically routes activities to appropriate handlers based on activity type
	* - **Handler Registration**: Provides fluent API methods (onMessage, onConversationUpdate, etc.) for registering event handlers
	* - **Invoke Support**: Built-in handling for adaptive card actions and search invoke operations
	* - **Error Handling**: Robust error handling with proper HTTP status codes for invoke operations
	* - **Extensibility**: Designed for inheritance to allow custom behavior and specialized handlers
	*
	* ## Usage:
	* ```typescript
	* const handler = new ActivityHandler()
	*   .onMessage(async (context, next) => {
	*     await context.sendActivity('Hello!');
	*     await next();
	*   })
	*   .onMembersAdded(async (context, next) => {
	*     // Welcome new members
	*     await next();
	*   });
	* ```
	*
	* Developers can extend this class to implement domain-specific logic, override default behaviors,
	* or add support for custom activity types and invoke operations.
	*/
	var ActivityHandler = class {
		constructor() {
			/**
			* Collection of handlers registered for different activity types
			* @protected
			*/
			this.handlers = {};
		}
		/**
		* Registers a handler for the Turn activity type.
		* This is called for all activities regardless of type.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onTurn(handler) {
			return this.on("Turn", handler);
		}
		/**
		* Registers a handler for the MembersAdded activity type.
		* This is called when new members are added to the conversation.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onMembersAdded(handler) {
			return this.on("MembersAdded", handler);
		}
		/**
		* Registers a handler for the MembersRemoved activity type.
		* This is called when members are removed from the conversation.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onMembersRemoved(handler) {
			return this.on("MembersRemoved", handler);
		}
		/**
		* Registers a handler for the Message activity type.
		* This is called when a message is received from the user.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onMessage(handler) {
			return this.on("Message", handler);
		}
		/**
		* Registers a handler for the MessageUpdate activity type.
		* This is called when a message is updated.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onMessageUpdate(handler) {
			return this.on("MessageUpdate", handler);
		}
		/**
		* Registers a handler for the MessageDelete activity type.
		* This is called when a message is deleted.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onMessageDelete(handler) {
			return this.on("MessageDelete", handler);
		}
		/**
		* Registers a handler for the ConversationUpdate activity type.
		* This is called when the conversation is updated, such as when members are added or removed.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onConversationUpdate(handler) {
			return this.on("ConversationUpdate", handler);
		}
		/**
		* Registers a handler for the MessageReaction activity type.
		* This is called when reactions are added or removed from messages.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onMessageReaction(handler) {
			return this.on("MessageReaction", handler);
		}
		/**
		* Registers a handler for the ReactionsAdded activity type.
		* This is called when reactions are added to messages.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onReactionsAdded(handler) {
			return this.on("ReactionsAdded", handler);
		}
		/**
		* Registers a handler for the ReactionsRemoved activity type.
		* This is called when reactions are removed from messages.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onReactionsRemoved(handler) {
			return this.on("ReactionsRemoved", handler);
		}
		/**
		* Registers a handler for the Typing activity type.
		* This is called when a typing indicator is received.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onTyping(handler) {
			return this.on("Typing", handler);
		}
		/**
		* Registers a handler for the InstallationUpdate activity type.
		* This is called when an agent is installed or uninstalled.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onInstallationUpdate(handler) {
			return this.on("InstallationUpdate", handler);
		}
		/**
		* Registers a handler for the InstallationUpdateAdd activity type.
		* This is called when an agent is installed or upgraded.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onInstallationUpdateAdd(handler) {
			return this.on("InstallationUpdateAdd", handler);
		}
		/**
		* Registers a handler for the InstallationUpdateRemove activity type.
		* This is called when an agent is uninstalled or downgraded.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onInstallationUpdateRemove(handler) {
			return this.on("InstallationUpdateRemove", handler);
		}
		/**
		* Registers a handler for the EndOfConversation activity type.
		* This is called when the conversation ends.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onEndOfConversation(handler) {
			return this.on("EndOfConversation", handler);
		}
		/**
		* Registers a handler for the SignInInvoke activity type.
		* This is called when a sign-in is requested.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onSignInInvoke(handler) {
			return this.on("SignInInvoke", handler);
		}
		/**
		* Registers a handler for unrecognized activity types.
		* This is called when an activity type is not recognized.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onUnrecognizedActivityType(handler) {
			return this.on("UnrecognizedActivityType", handler);
		}
		/**
		* Registers an activity event handler for the _dialog_ event, emitted as the last event for an incoming activity.
		* This handler is called after all other handlers have been processed.
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		*/
		onDialog(handler) {
			return this.on("Default", handler);
		}
		/**
		* Runs the activity handler pipeline.
		* This method is called to process an incoming activity through the registered handlers.
		* @param context - The turn context for the current turn of conversation
		* @throws Error if context is missing, activity is missing, or activity type is missing
		*/
		async run(context) {
			if (!context) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.MissingTurnContext);
			if (!context.activity) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.TurnContextMissingActivity);
			if (!context.activity.type) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ActivityMissingType);
			await this.handle(context, "Turn", async () => {
				await this.onTurnActivity(context);
			});
		}
		/**
		* Handles the Turn activity.
		* This method is called for every activity type and dispatches to the appropriate handler.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onTurnActivity(context) {
			switch (context.activity.type) {
				case agents_activity_1.ActivityTypes.Message:
					await this.onMessageActivity(context);
					break;
				case agents_activity_1.ActivityTypes.MessageUpdate:
					await this.onMessageUpdateActivity(context);
					break;
				case agents_activity_1.ActivityTypes.MessageDelete:
					await this.onMessageDeleteActivity(context);
					break;
				case agents_activity_1.ActivityTypes.ConversationUpdate:
					await this.onConversationUpdateActivity(context);
					break;
				case agents_activity_1.ActivityTypes.Invoke: {
					const invokeResponse = await this.onInvokeActivity(context);
					if (invokeResponse && !context.turnState.get(exports.INVOKE_RESPONSE_KEY)) {
						const activity = agents_activity_1.Activity.fromObject({
							value: invokeResponse,
							type: "invokeResponse"
						});
						await context.sendActivity(activity);
					}
					break;
				}
				case agents_activity_1.ActivityTypes.MessageReaction:
					await this.onMessageReactionActivity(context);
					break;
				case agents_activity_1.ActivityTypes.Typing:
					await this.onTypingActivity(context);
					break;
				case agents_activity_1.ActivityTypes.InstallationUpdate:
					await this.onInstallationUpdateActivity(context);
					break;
				case agents_activity_1.ActivityTypes.EndOfConversation:
					await this.onEndOfConversationActivity(context);
					break;
				default:
					await this.onUnrecognizedActivity(context);
					break;
			}
		}
		/**
		* Handles the Message activity.
		* This method processes incoming message activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onMessageActivity(context) {
			await this.handle(context, "Message", this.defaultNextEvent(context));
		}
		/**
		* Handles the MessageUpdate activity.
		* This method processes message update activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onMessageUpdateActivity(context) {
			await this.handle(context, "MessageUpdate", async () => {
				await this.dispatchMessageUpdateActivity(context);
			});
		}
		/**
		* Handles the MessageDelete activity.
		* This method processes message deletion activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onMessageDeleteActivity(context) {
			await this.handle(context, "MessageDelete", async () => {
				await this.dispatchMessageDeleteActivity(context);
			});
		}
		/**
		* Handles the ConversationUpdate activity.
		* This method processes conversation update activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onConversationUpdateActivity(context) {
			await this.handle(context, "ConversationUpdate", async () => {
				await this.dispatchConversationUpdateActivity(context);
			});
		}
		/**
		* Handles the SignInInvoke activity.
		* This method processes sign-in invoke activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onSigninInvokeActivity(context) {
			await this.handle(context, "SignInInvoke", this.defaultNextEvent(context));
		}
		/**
		* Handles the Invoke activity.
		* This method processes various invoke activities based on their name.
		* @param context - The turn context for the current turn of conversation
		* @returns An invoke response object with status and body
		* @protected
		*/
		async onInvokeActivity(context) {
			try {
				switch (context.activity.name) {
					case "application/search": {
						const invokeValue = this.getSearchInvokeValue(context.activity);
						const response = await this.onSearchInvoke(context, invokeValue);
						return {
							status: response.statusCode,
							body: response
						};
					}
					case "adaptiveCard/action": {
						const invokeValue = this.getAdaptiveCardInvokeValue(context.activity);
						const response = await this.onAdaptiveCardInvoke(context, invokeValue);
						return {
							status: response.statusCode,
							body: response
						};
					}
					case "signin/verifyState":
					case "signin/tokenExchange":
						await this.onSigninInvokeActivity(context);
						return { status: statusCodes_1.StatusCodes.OK };
					default: throw new invokeException_1.InvokeException(statusCodes_1.StatusCodes.NOT_IMPLEMENTED);
				}
			} catch (err) {
				if (err.message === "NotImplemented") return { status: statusCodes_1.StatusCodes.NOT_IMPLEMENTED };
				if (err instanceof invokeException_1.InvokeException) return err.createInvokeResponse();
				throw err;
			} finally {
				this.defaultNextEvent(context)();
			}
		}
		/**
		* Handles the AdaptiveCardInvoke activity.
		* This method processes adaptive card invoke activities.
		* @param _context - The turn context for the current turn of conversation
		* @param _invokeValue - The adaptive card invoke value
		* @returns A promise that resolves to an adaptive card invoke response
		* @protected
		*/
		async onAdaptiveCardInvoke(_context, _invokeValue) {
			return await Promise.reject(new invokeException_1.InvokeException(statusCodes_1.StatusCodes.NOT_IMPLEMENTED));
		}
		/**
		* Handles the SearchInvoke activity.
		* This method processes search invoke activities.
		* @param _context - The turn context for the current turn of conversation
		* @param _invokeValue - The search invoke value
		* @returns A promise that resolves to a search invoke response
		* @protected
		*/
		async onSearchInvoke(_context, _invokeValue) {
			return await Promise.reject(new invokeException_1.InvokeException(statusCodes_1.StatusCodes.NOT_IMPLEMENTED));
		}
		/**
		* Retrieves the SearchInvoke value from the activity.
		* This method extracts and validates the search invoke value from an activity.
		* @param activity - The activity to extract the search invoke value from
		* @returns The validated search invoke value
		* @private
		*/
		getSearchInvokeValue(activity) {
			const value = activity.value;
			if (!value) {
				const response = this.createAdaptiveCardInvokeErrorResponse(statusCodes_1.StatusCodes.BAD_REQUEST, "BadRequest", "Missing value property for search");
				throw new invokeException_1.InvokeException(statusCodes_1.StatusCodes.BAD_REQUEST, response);
			}
			if (!value.kind) if (activity.channelId === agents_activity_1.Channels.Msteams) value.kind = "search";
			else {
				const response = this.createAdaptiveCardInvokeErrorResponse(statusCodes_1.StatusCodes.BAD_REQUEST, "BadRequest", "Missing kind property for search.");
				throw new invokeException_1.InvokeException(statusCodes_1.StatusCodes.BAD_REQUEST, response);
			}
			if (!value.queryText) {
				const response = this.createAdaptiveCardInvokeErrorResponse(statusCodes_1.StatusCodes.BAD_REQUEST, "BadRequest", "Missing queryText for search.");
				throw new invokeException_1.InvokeException(statusCodes_1.StatusCodes.BAD_REQUEST, response);
			}
			return value;
		}
		/**
		* Retrieves the AdaptiveCardInvoke value from the activity.
		* This method extracts and validates the adaptive card invoke value from an activity.
		* @param activity - The activity to extract the adaptive card invoke value from
		* @returns The validated adaptive card invoke value
		* @private
		*/
		getAdaptiveCardInvokeValue(activity) {
			const value = activity.value;
			if (!value) {
				const response = this.createAdaptiveCardInvokeErrorResponse(statusCodes_1.StatusCodes.BAD_REQUEST, "BadRequest", "Missing value property");
				throw new invokeException_1.InvokeException(statusCodes_1.StatusCodes.BAD_REQUEST, response);
			}
			if (value.action.type !== "Action.Execute") {
				const response = this.createAdaptiveCardInvokeErrorResponse(statusCodes_1.StatusCodes.BAD_REQUEST, "NotSupported", `The action '${value.action.type}' is not supported.`);
				throw new invokeException_1.InvokeException(statusCodes_1.StatusCodes.BAD_REQUEST, response);
			}
			const { action, authentication, state } = value;
			const { data, id: actionId, type, verb } = action !== null && action !== void 0 ? action : {};
			const { connectionName, id: authenticationId, token } = authentication !== null && authentication !== void 0 ? authentication : {};
			return {
				action: {
					data,
					id: actionId,
					type,
					verb
				},
				authentication: {
					connectionName,
					id: authenticationId,
					token
				},
				state
			};
		}
		/**
		* Creates an error response for AdaptiveCardInvoke.
		* This method creates an error response for adaptive card invoke activities.
		* @param statusCode - The HTTP status code for the response
		* @param code - The error code
		* @param message - The error message
		* @returns An adaptive card invoke error response
		* @private
		*/
		createAdaptiveCardInvokeErrorResponse(statusCode, code, message) {
			return {
				statusCode,
				type: "application/vnd.microsoft.error",
				value: {
					code,
					message
				}
			};
		}
		/**
		* Handles the MessageReaction activity.
		* This method processes message reaction activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onMessageReactionActivity(context) {
			await this.handle(context, "MessageReaction", async () => {
				await this.dispatchMessageReactionActivity(context);
			});
		}
		/**
		* Handles the EndOfConversation activity.
		* This method processes end of conversation activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onEndOfConversationActivity(context) {
			await this.handle(context, "EndOfConversation", this.defaultNextEvent(context));
		}
		/**
		* Handles the Typing activity.
		* This method processes typing indicator activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onTypingActivity(context) {
			await this.handle(context, "Typing", this.defaultNextEvent(context));
		}
		/**
		* Handles the InstallationUpdate activity.
		* This method processes installation update activities.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onInstallationUpdateActivity(context) {
			switch (context.activity.action) {
				case "add":
				case "add-upgrade":
					await this.handle(context, "InstallationUpdateAdd", this.defaultNextEvent(context));
					return;
				case "remove":
				case "remove-upgrade": await this.handle(context, "InstallationUpdateRemove", this.defaultNextEvent(context));
			}
		}
		/**
		* Handles unrecognized activity types.
		* This method processes activities with unrecognized types.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async onUnrecognizedActivity(context) {
			await this.handle(context, "UnrecognizedActivityType", this.defaultNextEvent(context));
		}
		/**
		* Dispatches the ConversationUpdate activity.
		* This method dispatches conversation update activities to the appropriate handlers.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async dispatchConversationUpdateActivity(context) {
			if (context.activity.membersAdded != null && context.activity.membersAdded.length > 0) await this.handle(context, "MembersAdded", this.defaultNextEvent(context));
			else if (context.activity.membersRemoved != null && context.activity.membersRemoved.length > 0) await this.handle(context, "MembersRemoved", this.defaultNextEvent(context));
			else await this.defaultNextEvent(context)();
		}
		/**
		* Dispatches the MessageReaction activity.
		* This method dispatches message reaction activities to the appropriate handlers.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async dispatchMessageReactionActivity(context) {
			var _a, _b;
			if (context.activity.reactionsAdded != null || context.activity.reactionsRemoved != null) {
				if ((_a = context.activity.reactionsAdded) === null || _a === void 0 ? void 0 : _a.length) await this.handle(context, "ReactionsAdded", this.defaultNextEvent(context));
				if ((_b = context.activity.reactionsRemoved) === null || _b === void 0 ? void 0 : _b.length) await this.handle(context, "ReactionsRemoved", this.defaultNextEvent(context));
			} else await this.defaultNextEvent(context)();
		}
		/**
		* Dispatches the MessageUpdate activity.
		* This method dispatches message update activities to the appropriate handlers.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async dispatchMessageUpdateActivity(context) {
			await this.defaultNextEvent(context)();
		}
		/**
		* Dispatches the MessageDelete activity.
		* This method dispatches message delete activities to the appropriate handlers.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async dispatchMessageDeleteActivity(context) {
			await this.defaultNextEvent(context)();
		}
		/**
		* Returns the default next event handler.
		* This method creates a function that calls the default handler.
		* @param context - The turn context for the current turn of conversation
		* @returns A function that calls the default handler
		* @protected
		*/
		defaultNextEvent(context) {
			const defaultHandler = async () => {
				await this.handle(context, "Default", async () => {});
			};
			return defaultHandler;
		}
		/**
		* Registers a handler for a specific activity type.
		* This method adds a handler to the list of handlers for a specific activity type.
		* @param type - The activity type to register the handler for
		* @param handler - The handler to register
		* @returns The current instance for method chaining
		* @protected
		*/
		on(type, handler) {
			if (!this.handlers[type]) this.handlers[type] = [handler];
			else this.handlers[type].push(handler);
			return this;
		}
		/**
		* Executes the handlers for a specific activity type.
		* This method calls each registered handler for the specified activity type.
		* @param context - The turn context for the current turn of conversation
		* @param type - The activity type to handle
		* @param onNext - The function to call when all handlers have been executed
		* @returns The value returned by the last handler
		* @protected
		*/
		async handle(context, type, onNext) {
			let returnValue = null;
			async function runHandler(index) {
				if (index < handlers.length) {
					const val = await handlers[index](context, async () => await runHandler(index + 1));
					if (typeof val !== "undefined" && returnValue === null) returnValue = val;
				} else {
					const val = await onNext();
					if (typeof val !== "undefined") returnValue = val;
				}
			}
			logger.info(`${type} handler called`);
			const handlers = this.handlers[type] || [];
			await runHandler(0);
			return returnValue;
		}
		/**
		* Creates an InvokeResponse object.
		* This static method creates an invoke response with the specified body.
		* @param body - The body of the response
		* @returns An invoke response object with status and body
		* @protected
		*/
		static createInvokeResponse(body) {
			return {
				status: 200,
				body
			};
		}
		/**
		* Dispatches the Event activity.
		* This method dispatches event activities to the appropriate handlers.
		* @param context - The turn context for the current turn of conversation
		* @protected
		*/
		async dispatchEventActivity(context) {
			if (context.activity.name === tokenResponseEventName_1.tokenResponseEventName) await this.handle(context, "TokenResponseEvent", this.defaultNextEvent(context));
			else await this.defaultNextEvent(context)();
		}
	};
	exports.ActivityHandler = ActivityHandler;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/turnContextStateCollection.js
var require_turnContextStateCollection = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.TurnContextStateCollection = void 0;
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	const TURN_STATE_SCOPE_CACHE = Symbol("turnStateScopeCache");
	/**
	* A collection for managing state within a turn context.
	*/
	var TurnContextStateCollection = class extends Map {
		get(key) {
			return super.get(key);
		}
		/**
		* Pushes a value onto the stack for the specified key.
		* @param key The key of the element to push.
		* @param value The value to push onto the stack.
		*/
		push(key, value) {
			var _a;
			const current = this.get(key);
			const cache = this.get(TURN_STATE_SCOPE_CACHE) || /* @__PURE__ */ new Map();
			if (cache.has(key)) (_a = cache.get(key)) === null || _a === void 0 || _a.push(current);
			else cache.set(key, [current]);
			if (value === void 0) value = current;
			this.set(key, value);
			this.set(TURN_STATE_SCOPE_CACHE, cache);
		}
		/**
		* Pops a value from the stack for the specified key.
		* @param key The key of the element to pop.
		* @returns The value that was popped from the stack.
		*/
		pop(key) {
			var _a;
			const current = this.get(key);
			let previous;
			const cache = this.get(TURN_STATE_SCOPE_CACHE) || /* @__PURE__ */ new Map();
			if (cache.has(key)) previous = (_a = cache.get(key)) === null || _a === void 0 ? void 0 : _a.pop();
			this.set(key, previous);
			this.set(TURN_STATE_SCOPE_CACHE, cache);
			return current;
		}
	};
	exports.TurnContextStateCollection = TurnContextStateCollection;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/streaming/citationUtil.js
var require_citationUtil = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.CitationUtil = void 0;
	/**
	* Utility functions for manipulating text and citations.
	*/
	var CitationUtil = class {
		/**
		*
		* Clips the text to a maximum length in case it exceeds the limit.
		* @param {string} text The text to clip.
		* @param {number} maxLength The maximum length of the text to return, cutting off the last whole word.
		* @returns {string} The modified text
		*/
		static snippet(text, maxLength) {
			if (text.length <= maxLength) return text;
			let snippet = text.slice(0, maxLength);
			snippet = snippet.slice(0, Math.min(snippet.length, snippet.lastIndexOf(" ")));
			snippet += "...";
			return snippet;
		}
		/**
		* Convert citation tags `[doc(s)n]` to `[n]` where n is a number.
		* @param {string} text The text to format.
		* @returns {string} The formatted text.
		*/
		static formatCitationsResponse(text) {
			return text.replace(/\[docs?(\d+)\]/gi, "[$1]");
		}
		/**
		* Get the citations used in the text. This will remove any citations that are included in the citations array from the response but not referenced in the text.
		* @param {string} text - The text to search for citation references, i.e. [1], [2], etc.
		* @param {ClientCitation[]} citations - The list of citations to search for.
		* @returns {ClientCitation[] | undefined} The list of citations used in the text.
		*/
		static getUsedCitations(text, citations) {
			const matches = text.match(/\[(\d+)\]/gi);
			if (!matches) return;
			const filteredMatches = /* @__PURE__ */ new Set();
			matches.forEach((match) => {
				if (filteredMatches.has(match)) return;
				filteredMatches.add(match);
			});
			const usedCitations = [];
			filteredMatches.forEach((match) => {
				const found = citations.find((citation) => `[${citation.position}]` === match);
				if (found) usedCitations.push(found);
			});
			return usedCitations;
		}
	};
	exports.CitationUtil = CitationUtil;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/streaming/streamingResponse.js
var require_streamingResponse = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.StreamingResponse = exports.StreamingResponseResult = void 0;
	const agents_activity_1 = require_src$2();
	const citationUtil_1 = require_citationUtil();
	const logger = (0, require_logger().debug)("agents:streamingResponse");
	/**
	* Results for streaming response operations.
	*/
	var StreamingResponseResult;
	(function(StreamingResponseResult) {
		/**
		* The operation was successful.
		*/
		StreamingResponseResult["Success"] = "success";
		/**
		* The stream has already ended.
		*/
		StreamingResponseResult["AlreadyEnded"] = "alreadyEnded";
		/**
		* The user canceled the streaming response.
		*/
		StreamingResponseResult["UserCanceled"] = "userCanceled";
		/**
		* An error occurred during the streaming response.
		*/
		StreamingResponseResult["Error"] = "error";
	})(StreamingResponseResult || (exports.StreamingResponseResult = StreamingResponseResult = {}));
	/**
	* A helper class for streaming responses to the client.
	*
	* @remarks
	* This class is used to send a series of updates to the client in a single response. The expected
	* sequence of calls is:
	*
	* `queueInformativeUpdate()`, `queueTextChunk()`, `queueTextChunk()`, ..., `endStream()`.
	*
	* Once `endStream()` is called, the stream is considered ended and no further updates can be sent.
	*/
	var StreamingResponse = class {
		/**
		* Creates a new StreamingResponse instance.
		*
		* @param {TurnContext} context - Context for the current turn of conversation with the user.
		* @returns {TurnContext} - The context for the current turn of conversation with the user.
		*/
		constructor(context) {
			this._nextSequence = 1;
			this._message = "";
			this._ended = false;
			this._delayInMs = 250;
			this._isStreamingChannel = true;
			this._canceled = false;
			this._userCanceled = false;
			this._queue = [];
			this._chunkQueued = false;
			this._enableFeedbackLoop = false;
			this._enableGeneratedByAILabel = false;
			this._citations = [];
			this._context = context;
			this.loadDefaults(context.activity);
		}
		/**
		* Gets the stream ID of the current response.
		*
		* @returns {string | undefined} - The stream ID of the current response.
		*
		* @remarks
		* Assigned after the initial update is sent.
		*/
		get streamId() {
			return this._streamId;
		}
		/**
		* Gets the citations of the current response.
		*/
		get citations() {
			return this._citations;
		}
		/**
		* Gets the number of updates sent for the stream.
		*
		* @returns {number} - The number of updates sent for the stream.
		*/
		get updatesSent() {
			return this._nextSequence - 1;
		}
		/**
		* Gets the delay in milliseconds between chunks.
		* @remarks
		* Teams default: 1000 ms
		* Web Chat / Direct Line default: 500 ms
		* Other channels: 250 ms
		*/
		get delayInMs() {
			return this._delayInMs;
		}
		/**
		* Gets whether the channel supports streaming.
		*/
		get isStreamingChannel() {
			return this._isStreamingChannel;
		}
		/**
		* Queues an informative update to be sent to the client.
		*
		* @param {string} text Text of the update to send.
		*/
		queueInformativeUpdate(text) {
			if (!this.isStreamingChannel || !text.trim() || this._canceled) return;
			if (this._ended) throw new Error("The stream has already ended.");
			this.queueActivity(() => agents_activity_1.Activity.fromObject({
				type: "typing",
				text,
				entities: [{
					type: "streaminfo",
					streamType: "informative",
					streamSequence: this._nextSequence++
				}]
			}));
		}
		/**
		* Queues a chunk of partial message text to be sent to the client
		*
		* @param {string} text Partial text of the message to send.
		* @param {Citation[]} citations Citations to be included in the message.
		*
		* @remarks
		* The text we be sent as quickly as possible to the client. Chunks may be combined before
		* delivery to the client.
		*
		*/
		queueTextChunk(text, citations) {
			if (!text.trim() || this._canceled) return;
			if (this._ended) throw new Error("The stream has already ended.");
			this._message += text;
			this._message = citationUtil_1.CitationUtil.formatCitationsResponse(this._message);
			if (!this.isStreamingChannel) return;
			this.queueNextChunk();
		}
		/**
		* Ends the stream by sending the final message to the client.
		*
		* @returns {Promise<StreamingResponseResult>} - StreamingResponseResult with the result of the streaming response.
		*/
		async endStream() {
			if (this._ended) return StreamingResponseResult.AlreadyEnded;
			if (this._canceled) return this._userCanceled ? StreamingResponseResult.UserCanceled : StreamingResponseResult.Error;
			this._ended = true;
			if (!this.isStreamingChannel) {
				await this.sendActivity(this.createFinalMessage());
				return StreamingResponseResult.Success;
			}
			this.queueNextChunk();
			await this.waitForQueue();
			return StreamingResponseResult.Success;
		}
		/**
		* Resets the streaming response to its initial state.
		* If the stream is still running, this will wait for completion.
		*/
		async reset() {
			await this.waitForQueue();
			this._queueSync = void 0;
			this._queue = [];
			this._chunkQueued = false;
			this._ended = false;
			this._canceled = false;
			this._userCanceled = false;
			this._message = "";
			this._nextSequence = 1;
			this._streamId = void 0;
		}
		/**
		* Set Activity that will be (optionally) used for the final streaming message.
		*/
		setFinalMessage(activity) {
			this._finalMessage = activity;
		}
		/**
		* Sets the attachments to attach to the final chunk.
		*
		* @param attachments List of attachments.
		*/
		setAttachments(attachments) {
			this._attachments = attachments;
		}
		/**
		* Sets the sensitivity label to attach to the final chunk.
		*
		* @param sensitivityLabel The sensitivty label.
		*/
		setSensitivityLabel(sensitivityLabel) {
			this._sensitivityLabel = sensitivityLabel;
		}
		/**
		* Sets the citations for the full message.
		*
		* @param {Citation[]} citations Citations to be included in the message.
		*/
		setCitations(citations) {
			if (citations.length > 0) {
				if (!this._citations) this._citations = [];
				let currPos = this._citations.length;
				for (const citation of citations) {
					const clientCitation = {
						"@type": "Claim",
						position: currPos + 1,
						appearance: {
							"@type": "DigitalDocument",
							name: citation.title || `Document #${currPos + 1}`,
							abstract: citationUtil_1.CitationUtil.snippet(citation.content, 477),
							url: citation.url
						}
					};
					currPos++;
					this._citations.push(clientCitation);
				}
			}
		}
		/**
		* Sets the Feedback Loop in Teams that allows a user to
		* give thumbs up or down to a response.
		* Default is `false`.
		*
		* @param enableFeedbackLoop If true, the feedback loop is enabled.
		*/
		setFeedbackLoop(enableFeedbackLoop) {
			this._enableFeedbackLoop = enableFeedbackLoop;
		}
		/**
		* Sets the type of UI to use for the feedback loop.
		*
		* @param feedbackLoopType The type of the feedback loop.
		*/
		setFeedbackLoopType(feedbackLoopType) {
			this._feedbackLoopType = feedbackLoopType;
		}
		/**
		* Sets the the Generated by AI label in Teams
		* Default is `false`.
		*
		* @param enableGeneratedByAILabel If true, the label is added.
		*/
		setGeneratedByAILabel(enableGeneratedByAILabel) {
			this._enableGeneratedByAILabel = enableGeneratedByAILabel;
		}
		/**
		* Sets the delay in milliseconds between chunks.
		* @param delayInMs The delay in milliseconds.
		*/
		setDelayInMs(delayInMs) {
			this._delayInMs = delayInMs;
		}
		/**
		* Returns the most recently streamed message.
		*
		* @returns The streamed message.
		*/
		getMessage() {
			return this._message;
		}
		/**
		* Waits for the outgoing activity queue to be empty.
		*
		* @returns {Promise<void>} - A promise representing the async operation.
		*/
		waitForQueue() {
			return this._queueSync || Promise.resolve();
		}
		/**
		* Queues the next chunk of text to be sent to the client.
		*
		* @private
		*/
		queueNextChunk() {
			if (this._chunkQueued) return;
			this._chunkQueued = true;
			this.queueActivity(() => {
				this._chunkQueued = false;
				if (this._ended) return this.createFinalMessage();
				else return agents_activity_1.Activity.fromObject({
					type: "typing",
					text: this._message,
					entities: [{
						type: "streaminfo",
						streamType: "streaming",
						streamSequence: this._nextSequence++
					}]
				});
			});
		}
		/**
		* Queues an activity to be sent to the client.
		*/
		queueActivity(factory) {
			var _a;
			this._queue.push(factory);
			(_a = this._queueSync) !== null && _a !== void 0 || (this._queueSync = this.drainQueue());
		}
		/**
		* Sends any queued activities to the client until the queue is empty.
		*
		* @returns {Promise<void>} - A promise that will be resolved once the queue is empty.
		* @private
		*/
		async drainQueue() {
			try {
				logger.debug(`Draining queue with ${this._queue.length} activities.`);
				while (this._queue.length > 0) {
					const activity = this._queue.shift()();
					await this.sendActivity(activity);
				}
			} catch (err) {
				logger.error(`Error occurred when draining activity queue: "${JSON.stringify(err)}".`);
			} finally {
				this._queueSync = void 0;
			}
		}
		/**
		* Creates the final message to be sent at the end of the stream.
		*/
		createFinalMessage() {
			var _a, _b;
			const activity = (_a = this._finalMessage) !== null && _a !== void 0 ? _a : new agents_activity_1.Activity("message");
			activity.type = "message";
			if (!this._finalMessage) activity.text = this._message || "end of stream response";
			(_b = activity.entities) !== null && _b !== void 0 || (activity.entities = []);
			activity.attachments = this._attachments;
			this._nextSequence++;
			if (this.isStreamingChannel) activity.entities.push({
				type: "streaminfo",
				streamType: "final",
				streamSequence: this._nextSequence
			});
			return activity;
		}
		/**
		* Sends an activity to the client and saves the stream ID returned.
		*
		* @param {Activity} activity - The activity to send.
		* @returns {Promise<void>} - A promise representing the async operation.
		* @private
		*/
		async sendActivity(activity) {
			var _a, _b;
			if (this._streamId) {
				activity.id = this._streamId;
				if (!activity.entities) activity.entities = [];
				if (!activity.entities[0]) activity.entities[0] = {};
				activity.entities[0].streamId = this._streamId;
			}
			if (this._citations && this._citations.length > 0 && !this._ended) {
				const currCitations = (_a = citationUtil_1.CitationUtil.getUsedCitations(this._message, this._citations)) !== null && _a !== void 0 ? _a : void 0;
				activity.entities.push({
					type: "https://schema.org/Message",
					"@type": "Message",
					"@context": "https://schema.org",
					"@id": "",
					citation: currCitations
				});
			}
			if (this._ended) {
				activity.channelData = {
					feedbackLoopEnabled: (_b = this._enableFeedbackLoop) !== null && _b !== void 0 ? _b : false,
					...this._feedbackLoopType ? { type: this._feedbackLoopType } : {}
				};
				if (this._enableGeneratedByAILabel) (0, agents_activity_1.addAIToActivity)(activity, this._citations, this._sensitivityLabel);
			}
			try {
				const response = await this._context.sendActivity(activity);
				if (!this._streamId) this._streamId = response === null || response === void 0 ? void 0 : response.id;
				await new Promise((resolve) => setTimeout(resolve, this.delayInMs));
			} catch (error) {
				const { message } = error;
				this._canceled = true;
				this._queueSync = void 0;
				this._queue = [];
				if (message.includes("ContentStreamNotAllowed")) {
					logger.warn("Streaming content is not allowed by the client side.", { originalError: message });
					this._userCanceled = true;
				} else if (message.includes("BadArgument") && message.toLowerCase().includes("streaming api is not enabled")) {
					logger.warn("Interaction does not support streaming. Defaulting to non-streaming response.", { originalError: message });
					this._canceled = false;
					this._isStreamingChannel = false;
				}
			}
		}
		/**
		* Loads default values for the streaming response.
		*/
		loadDefaults(activity) {
			if (!activity) return;
			if (activity.deliveryMode === agents_activity_1.DeliveryModes.ExpectReplies) this._isStreamingChannel = false;
			else if (agents_activity_1.Channels.Msteams === activity.channelId) if (activity.isAgenticRequest()) this._isStreamingChannel = false;
			else {
				this._isStreamingChannel = true;
				this._delayInMs = 1e3;
			}
			else if (agents_activity_1.Channels.Webchat === activity.channelId || agents_activity_1.Channels.Directline === activity.channelId) {
				this._isStreamingChannel = true;
				this._delayInMs = 500;
			} else this._isStreamingChannel = false;
		}
	};
	exports.StreamingResponse = StreamingResponse;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/turnContext.js
var require_turnContext = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.TurnContext = exports.AgentCallbackHandlerKey = void 0;
	/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */
	const activityHandler_1 = require_activityHandler();
	const agents_activity_1 = require_src$2();
	const turnContextStateCollection_1 = require_turnContextStateCollection();
	const streamingResponse_1 = require_streamingResponse();
	/**
	* Key for the agent callback handler in TurnState collection.
	*/
	exports.AgentCallbackHandlerKey = "agentCallbackHandler";
	exports.TurnContext = class TurnContext {
		constructor(adapterOrContext, request, identity) {
			this._respondedRef = { responded: false };
			this._turnState = new turnContextStateCollection_1.TurnContextStateCollection();
			this._onSendActivities = [];
			this._onUpdateActivity = [];
			this._onDeleteActivity = [];
			this._turn = "turn";
			this._locale = "locale";
			/**
			* A list of reply activities that are buffered until the end of the turn.
			*
			* This is primarily used with the 'expectReplies' delivery mode where all
			* activities during a turn are collected and returned as a single response.
			*/
			this.bufferedReplyActivities = [];
			if (adapterOrContext instanceof TurnContext) adapterOrContext.copyTo(this);
			else {
				this._adapter = adapterOrContext;
				this._activity = request;
				this._identity = identity;
			}
			this._streamingResponse = new streamingResponse_1.StreamingResponse(this);
		}
		/**
		* Sends a trace activity for debugging purposes.
		*
		* @param name The name/category of the trace
		* @param value The value/data to include in the trace
		* @param valueType Optional type name for the value
		* @param label Optional descriptive label for the trace
		* @returns A promise that resolves to the resource response or undefined
		*
		* @remarks
		* Trace activities are typically used for debugging and are only visible in
		* channels that support them, like the Bot Framework Emulator.
		*/
		async sendTraceActivity(name, value, valueType, label) {
			const traceActivity = {
				type: agents_activity_1.ActivityTypes.Trace,
				timestamp: (/* @__PURE__ */ new Date()).toISOString(),
				name,
				value,
				valueType,
				label
			};
			return await this.sendActivity(traceActivity);
		}
		/**
		* Sends an activity to the sender of the incoming activity.
		*
		* @param activityOrText The activity to send or a string for a simple message
		* @param speak Optional text to be spoken by the agent
		* @param inputHint Optional input hint to indicate if the agent is expecting input
		* @returns A promise that resolves to the resource response or undefined
		*
		* @remarks
		* This is the primary method used to respond to the user. It automatically
		* addresses the response to the correct conversation and recipient using
		* information from the incoming activity.
		*/
		async sendActivity(activityOrText, speak, inputHint) {
			let activity;
			if (typeof activityOrText === "string") {
				activity = {
					type: agents_activity_1.ActivityTypes.Message,
					text: activityOrText,
					inputHint: inputHint || agents_activity_1.InputHints.AcceptingInput
				};
				if (speak) activity.speak = speak;
			} else activity = activityOrText;
			return (await this.sendActivities([activity]) || [])[0];
		}
		/**
		* Sends multiple activities to the sender of the incoming activity.
		*
		* @param activities The array of activities to send
		* @returns A promise that resolves to an array of resource responses
		*
		* @remarks
		* This method applies conversation references to each activity and
		* emits them through the middleware chain before sending them to
		* the adapter.
		*/
		async sendActivities(activities) {
			let sentNonTraceActivity = false;
			const ref = this.activity.getConversationReference();
			const output = activities.map((activity) => {
				const result = agents_activity_1.Activity.fromObject(activity).applyConversationReference(ref);
				if (!result.type) result.type = agents_activity_1.ActivityTypes.Message;
				if (result.type === agents_activity_1.ActivityTypes.InvokeResponse) this.turnState.set(activityHandler_1.INVOKE_RESPONSE_KEY, result);
				if (result.type !== agents_activity_1.ActivityTypes.Trace) sentNonTraceActivity = true;
				if (result.id) delete result.id;
				return result;
			});
			return await this.emit(this._onSendActivities, output, async () => {
				if (this.activity.deliveryMode === agents_activity_1.DeliveryModes.ExpectReplies) {
					const responses = [];
					output.forEach((a) => {
						this.bufferedReplyActivities.push(a);
						if (a.type === agents_activity_1.ActivityTypes.InvokeResponse) this.turnState.set(activityHandler_1.INVOKE_RESPONSE_KEY, a);
						responses.push({ id: "" });
					});
					if (sentNonTraceActivity) this.responded = true;
					return responses;
				} else {
					const responses = await this.adapter.sendActivities(this, output);
					for (let index = 0; index < (responses === null || responses === void 0 ? void 0 : responses.length); index++) {
						const activity = output[index];
						activity.id = responses[index].id;
					}
					if (sentNonTraceActivity) this.responded = true;
					return responses;
				}
			});
		}
		/**
		* Updates an existing activity in the conversation.
		*
		* @param activity The activity to update with its ID specified
		* @returns A promise that resolves when the activity has been updated
		*
		* @remarks
		* This can be used to edit previously sent activities, for example to
		* update the content of an adaptive card or change a message.
		*/
		async updateActivity(activity) {
			const newActivity = agents_activity_1.Activity.fromObject(activity);
			const ref = this.activity.getConversationReference();
			const a = newActivity.applyConversationReference(ref);
			return await this.emit(this._onUpdateActivity, a, async () => await this.adapter.updateActivity(this, a).then(() => {}));
		}
		/**
		* Deletes an activity from the conversation.
		*
		* @param idOrReference The ID of the activity to delete or a conversation reference
		* @returns A promise that resolves when the activity has been deleted
		*/
		async deleteActivity(idOrReference) {
			let reference;
			if (typeof idOrReference === "string") {
				reference = this.activity.getConversationReference();
				reference.activityId = idOrReference;
			} else reference = idOrReference;
			return await this.emit(this._onDeleteActivity, reference, async () => await this.adapter.deleteActivity(this, reference));
		}
		/**
		* @deprecated This function will not be supported in future versions.  Use TurnContext.turnState.get<ConnectorClient>(CloudAdapter.ConnectorClientKey).
		* Uploads an attachment to the conversation.
		*
		* @param conversationId The ID of the conversation
		* @param attachmentData The attachment data to upload
		* @returns A promise that resolves to the resource response
		*/
		async uploadAttachment(conversationId, attachmentData) {
			return await this.adapter.uploadAttachment(this, conversationId, attachmentData);
		}
		/**
		* @deprecated This function will not be supported in future versions.  Use TurnContext.turnState.get<ConnectorClient>(CloudAdapter.ConnectorClientKey).
		* Gets information about an attachment.
		*
		* @param attachmentId The ID of the attachment
		* @returns A promise that resolves to the attachment information
		*/
		async getAttachmentInfo(attachmentId) {
			return await this.adapter.getAttachmentInfo(this, attachmentId);
		}
		/**
		* @deprecated This function will not be supported in future versions.  Use TurnContext.turnState.get<ConnectorClient>(CloudAdapter.ConnectorClientKey).
		* Gets the content of an attachment.
		*
		* @param attachmentId The ID of the attachment
		* @param viewId The view to get
		* @returns A promise that resolves to a readable stream of the attachment content
		*/
		async getAttachment(attachmentId, viewId) {
			return await this.adapter.getAttachment(this, attachmentId, viewId);
		}
		/**
		* Registers a handler for intercepting and processing activities being sent.
		*
		* @param handler The handler to register
		* @returns The current TurnContext instance for chaining
		*
		* @remarks
		* This method follows a middleware pattern, allowing multiple handlers to
		* be chained together. Handlers can modify activities or inject new ones.
		*/
		onSendActivities(handler) {
			this._onSendActivities.push(handler);
			return this;
		}
		/**
		* Registers a handler for intercepting activity updates.
		*
		* @param handler The handler to register
		* @returns The current TurnContext instance for chaining
		*/
		onUpdateActivity(handler) {
			this._onUpdateActivity.push(handler);
			return this;
		}
		/**
		* Registers a handler for intercepting activity deletions.
		*
		* @param handler The handler to register
		* @returns The current TurnContext instance for chaining
		*/
		onDeleteActivity(handler) {
			this._onDeleteActivity.push(handler);
			return this;
		}
		/**
		* Copies the properties of this TurnContext to another TurnContext.
		*
		* Used internally when cloning contexts.
		*
		* @param context The context to copy to
		* @protected
		*/
		copyTo(context) {
			[
				"_adapter",
				"_activity",
				"_respondedRef",
				"_services",
				"_onSendActivities",
				"_onUpdateActivity",
				"_onDeleteActivity"
			].forEach((prop) => context[prop] = this[prop]);
		}
		/**
		* Gets the adapter that created this context.
		*
		* @remarks
		* The adapter is responsible for sending and receiving activities
		* to and from the user's channel.
		*/
		get adapter() {
			return this._adapter;
		}
		/**
		* Gets the incoming activity that started this turn.
		*
		* @remarks
		* This is the activity that was received from the user or channel
		* and triggered the creation of this context.
		*/
		get activity() {
			return this._activity;
		}
		get identity() {
			return this._identity;
		}
		/**
		* Gets or sets whether the turn has sent a response to the user.
		*
		* @remarks
		* This is used to track whether the agent has responded to the user's
		* activity. Once set to true, it cannot be set back to false.
		*/
		get responded() {
			return this._respondedRef.responded;
		}
		set responded(value) {
			if (!value) throw new Error("TurnContext: cannot set 'responded' to a value of 'false'.");
			this._respondedRef.responded = true;
		}
		/**
		* Gets or sets the locale for the turn.
		*
		* @remarks
		* The locale affects language-dependent operations like
		* formatting dates or numbers.
		*/
		get locale() {
			const turnObj = this._turnState.get(this._turn);
			if (turnObj && typeof turnObj[this._locale] === "string") return turnObj[this._locale];
		}
		set locale(value) {
			let turnObj = this._turnState.get(this._turn);
			if (turnObj) turnObj[this._locale] = value;
			else {
				turnObj = { [this._locale]: value };
				this._turnState.set(this._turn, turnObj);
			}
		}
		/**
		* Gets the turn state collection for storing data during the turn.
		*
		* @remarks
		* The turn state collection provides a dictionary-like interface
		* for storing arbitrary data that needs to be accessible during
		* the processing of the current turn.
		*/
		get turnState() {
			return this._turnState;
		}
		get streamingResponse() {
			return this._streamingResponse;
		}
		/**
		* Emits events to registered middleware handlers.
		*
		* @param handlers Array of handlers to execute
		* @param arg The argument to pass to each handler
		* @param next The function to execute at the end of the middleware chain
		* @returns A promise that resolves to the result from the handlers or next function
		* @private
		*
		* @remarks
		* This internal method implements the middleware pattern, allowing
		* handlers to be chained together with each having the option to
		* short-circuit the chain.
		*/
		async emit(handlers, arg, next) {
			const runHandlers = async ([handler, ...remaining]) => {
				try {
					return handler ? await handler(this, arg, async () => await runHandlers(remaining)) : await Promise.resolve(next());
				} catch (err) {
					return await Promise.reject(err);
				}
			};
			return await runHandlers(handlers);
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/adaptiveCards/adaptiveCardActionExecuteResponseType.js
var require_adaptiveCardActionExecuteResponseType = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AdaptiveCardActionExecuteResponseType = void 0;
	/**
	* Defines the types of responses that can be returned after executing an Adaptive Card action.
	*/
	var AdaptiveCardActionExecuteResponseType;
	(function(AdaptiveCardActionExecuteResponseType) {
		/**
		* Replaces the Adaptive Card only for the user who interacted with it.
		*/
		AdaptiveCardActionExecuteResponseType[AdaptiveCardActionExecuteResponseType["REPLACE_FOR_INTERACTOR"] = 0] = "REPLACE_FOR_INTERACTOR";
		/**
		* Replaces the Adaptive Card for all users.
		*/
		AdaptiveCardActionExecuteResponseType[AdaptiveCardActionExecuteResponseType["REPLACE_FOR_ALL"] = 1] = "REPLACE_FOR_ALL";
		/**
		* Sends a new message containing an Adaptive Card to all users.
		*/
		AdaptiveCardActionExecuteResponseType[AdaptiveCardActionExecuteResponseType["NEW_MESSAGE_FOR_ALL"] = 2] = "NEW_MESSAGE_FOR_ALL";
	})(AdaptiveCardActionExecuteResponseType || (exports.AdaptiveCardActionExecuteResponseType = AdaptiveCardActionExecuteResponseType = {}));
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/adaptiveCards/adaptiveCardsSearchParams.js
var require_adaptiveCardsSearchParams = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.adaptiveCardsSearchParamsZodSchema = void 0;
	const zod_1$2 = __require("zod");
	/**
	* Zod schema for validating AdaptiveCardsSearchParams.
	*/
	exports.adaptiveCardsSearchParamsZodSchema = zod_1$2.z.object({
		queryText: zod_1$2.z.string(),
		dataset: zod_1$2.z.string()
	});
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/adaptiveCards/activityValueParsers.js
var require_activityValueParsers = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.parseValueAction = parseValueAction;
	exports.parseValueActionName = parseValueActionName;
	exports.parseValueContinuation = parseValueContinuation;
	exports.parseValueActionExecuteSelector = parseValueActionExecuteSelector;
	exports.parseValueDataset = parseValueDataset;
	exports.parseValueActionFeedbackLoopData = parseValueActionFeedbackLoopData;
	exports.parseAdaptiveCardInvokeAction = parseAdaptiveCardInvokeAction;
	exports.parseValueSearchQuery = parseValueSearchQuery;
	exports.parseValueQuery = parseValueQuery;
	exports.parseValueAgentMessagePreviewAction = parseValueAgentMessagePreviewAction;
	exports.parseValueAgentActivityPreview = parseValueAgentActivityPreview;
	exports.parseValueCommandId = parseValueCommandId;
	const zod_1$1 = __require("zod");
	const agents_activity_1 = require_src$2();
	const adaptiveCardsSearchParams_1 = require_adaptiveCardsSearchParams();
	/**
	* Parses the given value as a value action.
	*
	* @param {unknown} value - The value to parse.
	* @returns {string} - The parsed value action.
	*/
	function parseValueAction(value) {
		zod_1$1.z.object({ action: zod_1$1.z.string().min(1) }).passthrough().parse(value);
		return value;
	}
	/**
	* Parses the given value as a value action name.
	*
	* @param {unknown} value - The value to parse.
	* @returns {string} - The parsed value action name.
	*/
	function parseValueActionName(value) {
		zod_1$1.z.object({ actionName: zod_1$1.z.string().min(1) }).passthrough().parse(value);
		return value;
	}
	/**
	* Parses the given value as a value continuation.
	*
	* @param {unknown} value - The value to parse.
	* @returns {string} - The parsed value continuation.
	*/
	function parseValueContinuation(value) {
		zod_1$1.z.object({ continuation: zod_1$1.z.string().min(1) }).passthrough().parse(value);
		return value;
	}
	/**
	* Parses the given value as a value action execute selector.
	*
	* @param {unknown} value - The value to parse.
	* @returns {object} - The parsed value action execute selector.
	*/
	function parseValueActionExecuteSelector(value) {
		if (value === void 0 || value === null) return;
		const actionZodSchema = zod_1$1.z.object({
			type: zod_1$1.z.string().min(1),
			verb: zod_1$1.z.string().min(1)
		});
		const safeParsedValue = zod_1$1.z.object({ action: actionZodSchema }).passthrough().safeParse(value);
		if (!safeParsedValue.success) throw new Error(`Invalid action value: ${safeParsedValue.error}`);
		const parsedValue = safeParsedValue.data;
		return { action: {
			type: parsedValue.action.type,
			verb: parsedValue.action.verb
		} };
	}
	/**
	* Parses the given value as a dataset.
	*
	* @param {unknown} value - The value to parse.
	* @returns {object} - The parsed dataset.
	*/
	function parseValueDataset(value) {
		if (value === void 0 || value === null) return;
		return { dataset: zod_1$1.z.object({ dataset: zod_1$1.z.string().min(1) }).passthrough().parse(value).dataset };
	}
	/**
	* Parses the given value as action feedback loop data.
	*
	* @param {unknown} value - The value to parse.
	* @returns {object} - The parsed action feedback loop data.
	*/
	function parseValueActionFeedbackLoopData(value) {
		const parsedValue = zod_1$1.z.object({ actionValue: zod_1$1.z.object({
			reaction: zod_1$1.z.union([zod_1$1.z.literal("like"), zod_1$1.z.literal("dislike")]),
			feedback: zod_1$1.z.union([zod_1$1.z.string().min(1), zod_1$1.z.record(zod_1$1.z.string(), zod_1$1.z.any())])
		}) }).passthrough().parse(value);
		return { actionValue: {
			reaction: parsedValue.actionValue.reaction,
			feedback: parsedValue.actionValue.feedback
		} };
	}
	/**
	* Parses the given value as an adaptive card invoke action.
	*
	* @param {unknown} value - The value to parse.
	* @returns {AdaptiveCardInvokeAction} - The parsed adaptive card invoke action.
	*/
	function parseAdaptiveCardInvokeAction(value) {
		agents_activity_1.adaptiveCardInvokeActionZodSchema.passthrough().parse(value);
		return value;
	}
	/**
	* Parses the given value as a search query.
	*
	* @param {unknown} value - The value to parse.
	* @returns {object} - The parsed search query.
	*/
	function parseValueSearchQuery(value) {
		const queryOptionsZodSchema = zod_1$1.z.object({
			top: zod_1$1.z.number(),
			skip: zod_1$1.z.number()
		});
		const validSearchValue = adaptiveCardsSearchParams_1.adaptiveCardsSearchParamsZodSchema.extend({ queryOptions: queryOptionsZodSchema }).passthrough().parse(value);
		return {
			queryOptions: {
				top: validSearchValue.queryOptions.top,
				skip: validSearchValue.queryOptions.skip
			},
			queryText: validSearchValue.queryText,
			dataset: validSearchValue.dataset
		};
	}
	/**
	* Parses the given value as a query.
	*
	* @param {unknown} value - The value to parse.
	* @returns {object} - The parsed query.
	*/
	function parseValueQuery(value) {
		return { url: zod_1$1.z.object({ url: zod_1$1.z.string().min(1) }).passthrough().parse(value).url };
	}
	/**
	* Parses the given value as an activity message preview action.
	*
	* @param {unknown} value - The value to parse.
	* @returns {object} - The parsed message preview action.
	*/
	function parseValueAgentMessagePreviewAction(value) {
		return { botMessagePreviewAction: zod_1$1.z.object({ botMessagePreviewAction: zod_1$1.z.string().min(1) }).passthrough().parse(value).botMessagePreviewAction };
	}
	/**
	* Parses the given value as an activity preview.
	*
	* @param {unknown} value - The value to parse.
	* @returns {object} - The parsed activity preview.
	*/
	function parseValueAgentActivityPreview(value) {
		return { botActivityPreview: zod_1$1.z.object({ botActivityPreview: zod_1$1.z.array(agents_activity_1.activityZodSchema.partial()) }).passthrough().parse(value).botActivityPreview };
	}
	/**
	* Parses the given value as a command ID.
	*
	* @param {unknown} value - The value to parse.
	* @returns {object} - The parsed command ID.
	*/
	function parseValueCommandId(value) {
		return { commandId: zod_1$1.z.object({ commandId: zod_1$1.z.string().min(1) }).passthrough().parse(value).commandId };
	}
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/adaptiveCards/adaptiveCardsActions.js
var require_adaptiveCardsActions = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AdaptiveCardsActions = exports.ACTION_INVOKE_NAME = void 0;
	const agents_activity_1 = require_src$2();
	const __1 = require_src();
	const adaptiveCardActionExecuteResponseType_1 = require_adaptiveCardActionExecuteResponseType();
	const activityValueParsers_1 = require_activityValueParsers();
	exports.ACTION_INVOKE_NAME = "adaptiveCard/action";
	const ACTION_EXECUTE_TYPE = "Action.Execute";
	const DEFAULT_ACTION_SUBMIT_FILTER = "verb";
	const SEARCH_INVOKE_NAME = "application/search";
	var AdaptiveCardInvokeResponseType;
	(function(AdaptiveCardInvokeResponseType) {
		/**
		* Indicates a response containing an Adaptive Card.
		*/
		AdaptiveCardInvokeResponseType["ADAPTIVE"] = "application/vnd.microsoft.card.adaptive";
		/**
		* Indicates a response containing a message activity.
		*/
		AdaptiveCardInvokeResponseType["MESSAGE"] = "application/vnd.microsoft.activity.message";
		/**
		* Indicates a response containing a search result.
		*/
		AdaptiveCardInvokeResponseType["SEARCH"] = "application/vnd.microsoft.search.searchResponse";
	})(AdaptiveCardInvokeResponseType || (AdaptiveCardInvokeResponseType = {}));
	/**
	* A class to handle Adaptive Card actions such as executing actions, submitting actions, and performing searches.
	*
	* @typeParam TState - The type of the TurnState used in the application.
	*/
	var AdaptiveCardsActions = class {
		/**
		* Constructs an instance of AdaptiveCardsActions.
		* @param app - The Teams application instance.
		*/
		constructor(app) {
			this._app = app;
		}
		/**
		* Registers a handler for the `Action.Execute` event.
		*
		* @typeParam TData - The type of the data passed to the handler.
		* @param verb - A string, RegExp, RouteSelector, or an array of these to match the action verb.
		* @param handler - A function to handle the action execution.
		* @returns The Teams application instance.
		*/
		actionExecute(verb, handler) {
			var _a, _b;
			let actionExecuteResponseType = (_b = (_a = this._app.options.adaptiveCardsOptions) === null || _a === void 0 ? void 0 : _a.actionExecuteResponseType) !== null && _b !== void 0 ? _b : adaptiveCardActionExecuteResponseType_1.AdaptiveCardActionExecuteResponseType.REPLACE_FOR_INTERACTOR;
			(Array.isArray(verb) ? verb : [verb]).forEach((v) => {
				const selector = createActionExecuteSelector(v);
				this._app.addRoute(selector, async (context, state) => {
					var _a;
					const a = context === null || context === void 0 ? void 0 : context.activity;
					const invokeAction = (0, activityValueParsers_1.parseValueActionExecuteSelector)(a.value);
					if ((a === null || a === void 0 ? void 0 : a.type) !== agents_activity_1.ActivityTypes.Invoke || (a === null || a === void 0 ? void 0 : a.name) !== exports.ACTION_INVOKE_NAME || (invokeAction === null || invokeAction === void 0 ? void 0 : invokeAction.action.type) !== ACTION_EXECUTE_TYPE) throw new Error(`Unexpected AdaptiveCards.actionExecute() triggered for activity type: ${invokeAction === null || invokeAction === void 0 ? void 0 : invokeAction.action.type}`);
					if (invokeAction.action.verb !== v) console.log(`AdaptiveCards.actionExecute() triggered for verb: ${invokeAction.action.verb} does not match expected verb: ${v}`);
					const result = await handler(context, state, (_a = a.value.action) !== null && _a !== void 0 ? _a : {});
					if (!context.turnState.get(__1.INVOKE_RESPONSE_KEY)) {
						let response;
						if (typeof result === "string") {
							response = {
								statusCode: 200,
								type: AdaptiveCardInvokeResponseType.MESSAGE,
								value: result
							};
							await sendInvokeResponse(context, response);
						} else {
							if (result.refresh && actionExecuteResponseType !== adaptiveCardActionExecuteResponseType_1.AdaptiveCardActionExecuteResponseType.NEW_MESSAGE_FOR_ALL) actionExecuteResponseType = adaptiveCardActionExecuteResponseType_1.AdaptiveCardActionExecuteResponseType.REPLACE_FOR_ALL;
							const activity = __1.MessageFactory.attachment(__1.CardFactory.adaptiveCard(result));
							response = {
								statusCode: 200,
								type: AdaptiveCardInvokeResponseType.ADAPTIVE,
								value: result
							};
							if (actionExecuteResponseType === adaptiveCardActionExecuteResponseType_1.AdaptiveCardActionExecuteResponseType.NEW_MESSAGE_FOR_ALL) {
								await sendInvokeResponse(context, {
									statusCode: 200,
									type: AdaptiveCardInvokeResponseType.MESSAGE,
									value: "Your response was sent to the app"
								});
								await context.sendActivity(activity);
							} else if (actionExecuteResponseType === adaptiveCardActionExecuteResponseType_1.AdaptiveCardActionExecuteResponseType.REPLACE_FOR_ALL) {
								activity.id = context.activity.replyToId;
								await context.updateActivity(activity);
								await sendInvokeResponse(context, response);
							} else await sendInvokeResponse(context, response);
						}
					}
				}, true);
			});
			return this._app;
		}
		/**
		* Registers a handler for the Action.Submit event.
		*
		* @typeParam TData - The type of the data passed to the handler.
		* @param verb - A string, RegExp, RouteSelector, or an array of these to match the action verb.
		* @param handler - A function to handle the action submission.
		* @returns The Teams application instance.
		*/
		actionSubmit(verb, handler) {
			var _a, _b;
			const filter = (_b = (_a = this._app.options.adaptiveCardsOptions) === null || _a === void 0 ? void 0 : _a.actionSubmitFilter) !== null && _b !== void 0 ? _b : DEFAULT_ACTION_SUBMIT_FILTER;
			(Array.isArray(verb) ? verb : [verb]).forEach((v) => {
				const selector = createActionSubmitSelector(v, filter);
				this._app.addRoute(selector, async (context, state) => {
					var _a;
					const a = context === null || context === void 0 ? void 0 : context.activity;
					if ((a === null || a === void 0 ? void 0 : a.type) !== agents_activity_1.ActivityTypes.Message || (a === null || a === void 0 ? void 0 : a.text) || typeof (a === null || a === void 0 ? void 0 : a.value) !== "object") throw new Error(`Unexpected AdaptiveCards.actionSubmit() triggered for activity type: ${a === null || a === void 0 ? void 0 : a.type}`);
					await handler(context, state, (_a = (0, activityValueParsers_1.parseAdaptiveCardInvokeAction)(a.value)) !== null && _a !== void 0 ? _a : {});
				});
			});
			return this._app;
		}
		/**
		* Registers a handler for the search event.
		*
		* @param dataset - A string, RegExp, RouteSelector, or an array of these to match the dataset.
		* @param handler - A function to handle the search query.
		* @returns The Teams application instance.
		*/
		search(dataset, handler) {
			(Array.isArray(dataset) ? dataset : [dataset]).forEach((ds) => {
				const selector = createSearchSelector(ds);
				this._app.addRoute(selector, async (context, state) => {
					var _a, _b, _c, _d, _e, _f;
					const a = context === null || context === void 0 ? void 0 : context.activity;
					if ((a === null || a === void 0 ? void 0 : a.type) !== "invoke" || (a === null || a === void 0 ? void 0 : a.name) !== SEARCH_INVOKE_NAME) throw new Error(`Unexpected AdaptiveCards.search() triggered for activity type: ${a === null || a === void 0 ? void 0 : a.type}`);
					const parsedQuery = (0, activityValueParsers_1.parseValueSearchQuery)(a.value);
					const results = await handler(context, state, {
						count: (_b = (_a = parsedQuery.queryOptions) === null || _a === void 0 ? void 0 : _a.top) !== null && _b !== void 0 ? _b : 25,
						skip: (_d = (_c = parsedQuery.queryOptions) === null || _c === void 0 ? void 0 : _c.skip) !== null && _d !== void 0 ? _d : 0,
						parameters: {
							queryText: (_e = parsedQuery.queryText) !== null && _e !== void 0 ? _e : "",
							dataset: (_f = parsedQuery.dataset) !== null && _f !== void 0 ? _f : ""
						}
					});
					if (!context.turnState.get(__1.INVOKE_RESPONSE_KEY)) {
						const response = {
							type: AdaptiveCardInvokeResponseType.SEARCH,
							value: { results }
						};
						await context.sendActivity(agents_activity_1.Activity.fromObject({
							value: {
								body: response,
								status: 200
							},
							type: agents_activity_1.ActivityTypes.InvokeResponse
						}));
					}
				}, true);
			});
			return this._app;
		}
	};
	exports.AdaptiveCardsActions = AdaptiveCardsActions;
	function createActionExecuteSelector(verb) {
		if (typeof verb === "function") return verb;
		else if (verb instanceof RegExp) return (context) => {
			var _a;
			const a = context === null || context === void 0 ? void 0 : context.activity;
			const valueAction = (0, activityValueParsers_1.parseValueActionExecuteSelector)(a.value);
			if ((a === null || a === void 0 ? void 0 : a.type) === agents_activity_1.ActivityTypes.Invoke && (a === null || a === void 0 ? void 0 : a.name) === exports.ACTION_INVOKE_NAME && ((_a = valueAction === null || valueAction === void 0 ? void 0 : valueAction.action) === null || _a === void 0 ? void 0 : _a.type) === ACTION_EXECUTE_TYPE && typeof valueAction.action.verb === "string") return Promise.resolve(verb.test(valueAction.action.verb));
			else return Promise.resolve(false);
		};
		else return (context) => {
			var _a, _b;
			const a = context === null || context === void 0 ? void 0 : context.activity;
			const valueAction = (0, activityValueParsers_1.parseValueActionExecuteSelector)(a.value);
			if ((a === null || a === void 0 ? void 0 : a.type) === agents_activity_1.ActivityTypes.Invoke && (a === null || a === void 0 ? void 0 : a.name) === exports.ACTION_INVOKE_NAME && ((_a = valueAction === null || valueAction === void 0 ? void 0 : valueAction.action) === null || _a === void 0 ? void 0 : _a.type) === ACTION_EXECUTE_TYPE && ((_b = valueAction.action) === null || _b === void 0 ? void 0 : _b.verb) === verb) return Promise.resolve(true);
			else return Promise.resolve(false);
		};
	}
	function createActionSubmitSelector(verb, filter) {
		if (typeof verb === "function") return verb;
		else if (verb instanceof RegExp) return (context) => {
			const a = context === null || context === void 0 ? void 0 : context.activity;
			if ((a === null || a === void 0 ? void 0 : a.type) === agents_activity_1.ActivityTypes.Message && !(a === null || a === void 0 ? void 0 : a.text) && typeof (a === null || a === void 0 ? void 0 : a.value) === "object" && typeof (a === null || a === void 0 ? void 0 : a.value)[filter] === "string") return Promise.resolve(verb.test(a.value[filter]));
			else return Promise.resolve(false);
		};
		else return (context) => {
			const a = context === null || context === void 0 ? void 0 : context.activity;
			const isSubmit = (a === null || a === void 0 ? void 0 : a.type) === agents_activity_1.ActivityTypes.Message && !(a === null || a === void 0 ? void 0 : a.text) && typeof (a === null || a === void 0 ? void 0 : a.value) === "object";
			return Promise.resolve(isSubmit && (a === null || a === void 0 ? void 0 : a.value)[filter] === verb);
		};
	}
	function createSearchSelector(dataset) {
		if (typeof dataset === "function") return dataset;
		else if (dataset instanceof RegExp) return (context) => {
			const a = context === null || context === void 0 ? void 0 : context.activity;
			const valueDataset = (0, activityValueParsers_1.parseValueDataset)(a.value);
			if ((a === null || a === void 0 ? void 0 : a.type) === agents_activity_1.ActivityTypes.Invoke && (a === null || a === void 0 ? void 0 : a.name) === SEARCH_INVOKE_NAME && typeof (valueDataset === null || valueDataset === void 0 ? void 0 : valueDataset.dataset) === "string") return Promise.resolve(dataset.test(valueDataset === null || valueDataset === void 0 ? void 0 : valueDataset.dataset));
			else return Promise.resolve(false);
		};
		else return (context) => {
			const a = context === null || context === void 0 ? void 0 : context.activity;
			const isSearch = (a === null || a === void 0 ? void 0 : a.type) === agents_activity_1.ActivityTypes.Invoke && (a === null || a === void 0 ? void 0 : a.name) === SEARCH_INVOKE_NAME;
			return Promise.resolve(isSearch);
		};
	}
	async function sendInvokeResponse(context, response) {
		await context.sendActivity(agents_activity_1.Activity.fromObject({
			value: {
				body: response,
				status: 200
			},
			type: agents_activity_1.ActivityTypes.InvokeResponse
		}));
	}
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/adaptiveCards/adaptiveCardsOptions.js
var require_adaptiveCardsOptions = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/adaptiveCards/query.js
var require_query = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/adaptiveCards/index.js
var require_adaptiveCards = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$13) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$13, p)) __createBinding(exports$13, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_adaptiveCardsActions(), exports);
	__exportStar(require_adaptiveCardsOptions(), exports);
	__exportStar(require_adaptiveCardActionExecuteResponseType(), exports);
	__exportStar(require_adaptiveCardsSearchParams(), exports);
	__exportStar(require_query(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/turnStateEntry.js
var require_turnStateEntry = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.TurnStateEntry = void 0;
	/**
	* Represents an entry in the turn state that can be tracked for changes and stored.
	*/
	var TurnStateEntry = class {
		/**
		* Creates a new instance of TurnStateEntry.
		* @param value - The initial value for the entry.
		* @param storageKey - Optional storage key used to persist the entry.
		*/
		constructor(value, storageKey) {
			this._deleted = false;
			this._value = value || {};
			this._storageKey = storageKey;
			this._hash = JSON.stringify(this._value);
		}
		/**
		* Gets whether the entry value has changed since its creation or last update.
		* @returns True if the value has changed, otherwise false.
		*/
		get hasChanged() {
			return JSON.stringify(this._value) !== this._hash;
		}
		/**
		* Gets whether the entry has been marked for deletion.
		* @returns True if the entry is marked for deletion, otherwise false.
		*/
		get isDeleted() {
			return this._deleted;
		}
		/**
		* Gets the current value of the entry. If the entry was marked for deletion,
		* it will be reset to an empty object and marked as not deleted.
		* @returns The current value of the entry.
		*/
		get value() {
			if (this.isDeleted) {
				this._value = {};
				this._deleted = false;
			}
			return this._value;
		}
		/**
		* Gets the storage key associated with this entry.
		* @returns The storage key, or undefined if no storage key was specified.
		*/
		get storageKey() {
			return this._storageKey;
		}
		/**
		* Marks the entry for deletion.
		*/
		delete() {
			this._deleted = true;
		}
		/**
		* Replaces the current value with a new value.
		* @param value - The new value to set. If undefined, an empty object will be used.
		*/
		replace(value) {
			this._value = value || {};
		}
	};
	exports.TurnStateEntry = TurnStateEntry;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/turnState.js
var require_turnState = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.TurnState = void 0;
	const turnStateEntry_1 = require_turnStateEntry();
	const logger = (0, require_logger().debug)("agents:turnState");
	const CONVERSATION_SCOPE = "conversation";
	const USER_SCOPE = "user";
	const TEMP_SCOPE = "temp";
	/**
	* Base class defining a collection of turn state scopes.
	*
	* @typeParam TConversationState - Type for conversation-scoped state
	* @typeParam TUserState - Type for user-scoped state
	*
	* @remarks
	* Developers can create a derived class that extends `TurnState` to add additional state scopes.
	*
	* @example
	* ```javascript
	* class MyTurnState extends TurnState {
	*   protected async onComputeStorageKeys(context) {
	*     const keys = await super.onComputeStorageKeys(context);
	*     keys['myScope'] = `myScopeKey`;
	*     return keys;
	*   }
	*
	*   public get myScope() {
	*     const scope = this.getScope('myScope');
	*     if (!scope) {
	*       throw new Error(`MyTurnState hasn't been loaded. Call load() first.`);
	*     }
	*     return scope.value;
	*   }
	*
	*   public set myScope(value) {
	*     const scope = this.getScope('myScope');
	*     if (!scope) {
	*       throw new Error(`MyTurnState hasn't been loaded. Call load() first.`);
	*     }
	*     scope.replace(value);
	*   }
	* }
	* ```
	*
	*/
	var TurnState = class {
		constructor() {
			this._scopes = {};
			this._isLoaded = false;
			this._stateNotLoadedString = "TurnState hasn't been loaded. Call load() first.";
		}
		/**
		* Gets the conversation-scoped state.
		*
		* @returns The conversation state object
		* @throws Error if state hasn't been loaded
		*
		* @remarks
		* This state is shared by all users in the same conversation.
		*/
		get conversation() {
			const scope = this.getScope(CONVERSATION_SCOPE);
			if (!scope) throw new Error(this._stateNotLoadedString);
			return scope.value;
		}
		/**
		* Sets the conversation-scoped state.
		*
		* @param value - The new conversation state object
		* @throws Error if state hasn't been loaded
		*/
		set conversation(value) {
			const scope = this.getScope(CONVERSATION_SCOPE);
			if (!scope) throw new Error(this._stateNotLoadedString);
			scope.replace(value);
		}
		/**
		* Gets whether the state has been loaded from storage
		*
		* @returns True if the state has been loaded, false otherwise
		*/
		get isLoaded() {
			return this._isLoaded;
		}
		/**
		* Gets the user-scoped state.
		*
		* @returns The user state object
		* @throws Error if state hasn't been loaded
		*
		* @remarks
		* This state is unique to each user and persists across conversations.
		*/
		get user() {
			const scope = this.getScope(USER_SCOPE);
			if (!scope) throw new Error(this._stateNotLoadedString);
			return scope.value;
		}
		/**
		* Sets the user-scoped state.
		*
		* @param value - The new user state object
		* @throws Error if state hasn't been loaded
		*/
		set user(value) {
			const scope = this.getScope(USER_SCOPE);
			if (!scope) throw new Error(this._stateNotLoadedString);
			scope.replace(value);
		}
		/**
		* Marks the conversation state for deletion.
		*
		* @throws Error if state hasn't been loaded
		*
		* @remarks
		* The state will be deleted from storage on the next call to save().
		*/
		deleteConversationState() {
			const scope = this.getScope(CONVERSATION_SCOPE);
			if (!scope) throw new Error(this._stateNotLoadedString);
			scope.delete();
		}
		/**
		* Marks the user state for deletion.
		*
		* @throws Error if state hasn't been loaded
		*
		* @remarks
		* The state will be deleted from storage on the next call to save().
		*/
		deleteUserState() {
			const scope = this.getScope(USER_SCOPE);
			if (!scope) throw new Error(this._stateNotLoadedString);
			scope.delete();
		}
		/**
		* Gets a specific state scope by name.
		*
		* @param scope - The name of the scope to retrieve
		* @returns The state entry for the scope, or undefined if not found
		*/
		getScope(scope) {
			return this._scopes[scope];
		}
		/**
		* Deletes a value from state by dot-notation path.
		*
		* @param path - The path to the value to delete
		*
		* @remarks
		* Format: "scope.property" or just "property" (defaults to temp scope)
		* The temp scope is internal-only, not persisted to storage, and exists only for the current turn.
		*/
		deleteValue(path) {
			const { scope, name } = this.getScopeAndName(path);
			if (Object.prototype.hasOwnProperty.call(scope.value, name)) delete scope.value[name];
		}
		/**
		* Checks if a value exists in state by dot-notation path.
		*
		* @param path - The path to check
		* @returns True if the value exists, false otherwise
		*
		* @remarks
		* Format: "scope.property" or just "property" (defaults to temp scope)
		*/
		hasValue(path) {
			const { scope, name } = this.getScopeAndName(path);
			return Object.prototype.hasOwnProperty.call(scope.value, name);
		}
		/**
		* Gets a value from state by dot-notation path.
		*
		* @typeParam TValue - The type of the value to retrieve
		* @param path - The path to the value
		* @returns The value at the specified path
		*
		* @remarks
		* Format: "scope.property" or just "property" (defaults to temp scope)
		*/
		getValue(path) {
			const { scope, name } = this.getScopeAndName(path);
			return scope.value[name];
		}
		/**
		* Sets a value in state by dot-notation path.
		*
		* @param path - The path to set
		* @param value - The value to set
		*
		* @remarks
		* Format: "scope.property" or just "property" (defaults to temp scope)
		*/
		setValue(path, value) {
			const { scope, name } = this.getScopeAndName(path);
			scope.value[name] = value;
		}
		/**
		* Loads state from storage into memory.
		*
		* @param context - The turn context
		* @param storage - Optional storage provider (if not provided, state will be in-memory only)
		* @param force - If true, forces a reload from storage even if state is already loaded
		* @returns Promise that resolves to true if state was loaded, false if it was already loaded
		*/
		load(context, storage, force = false) {
			if (this._isLoaded && !force) return Promise.resolve(false);
			if (!this._loadingPromise) this._loadingPromise = new Promise((resolve, reject) => {
				this._isLoaded = true;
				const keys = [];
				this.onComputeStorageKeys(context).then(async (scopes) => {
					for (const key in scopes) if (Object.prototype.hasOwnProperty.call(scopes, key)) keys.push(scopes[key]);
					const items = storage ? await storage.read(keys) : {};
					for (const key in scopes) if (Object.prototype.hasOwnProperty.call(scopes, key)) {
						const storageKey = scopes[key];
						const value = items[storageKey];
						this._scopes[key] = new turnStateEntry_1.TurnStateEntry(value, storageKey);
					}
					this._scopes[TEMP_SCOPE] = new turnStateEntry_1.TurnStateEntry({});
					this._isLoaded = true;
					this._loadingPromise = void 0;
					resolve(true);
				}).catch((err) => {
					logger.error(err);
					this._loadingPromise = void 0;
					reject(err);
				});
			});
			return this._loadingPromise;
		}
		/**
		* Saves state changes to storage.
		*
		* @param context - The turn context
		* @param storage - Optional storage provider (if not provided, state changes won't be persisted)
		* @returns Promise that resolves when the save operation is complete
		* @throws Error if state hasn't been loaded
		*
		* @remarks
		* Only changed scopes will be persisted.
		*/
		async save(context, storage) {
			if (!this._isLoaded && this._loadingPromise) await this._loadingPromise;
			if (!this._isLoaded) throw new Error(this._stateNotLoadedString);
			let changes;
			let deletions;
			for (const key in this._scopes) {
				if (!Object.prototype.hasOwnProperty.call(this._scopes, key)) continue;
				const entry = this._scopes[key];
				if (entry.storageKey) {
					if (entry.isDeleted) if (deletions) deletions.push(entry.storageKey);
					else deletions = [entry.storageKey];
					else if (entry.hasChanged) {
						if (!changes) changes = {};
						changes[entry.storageKey] = entry.value;
					}
				}
			}
			if (storage) {
				const promises = [];
				if (changes) promises.push(storage.write(changes));
				if (deletions) promises.push(storage.delete(deletions));
				if (promises.length > 0) await Promise.all(promises);
			}
		}
		/**
		* Computes the storage keys for each scope based on the turn context.
		*
		* @param context - The turn context
		* @returns Promise that resolves to a dictionary of scope names to storage keys
		*
		* @remarks
		* Override this method in derived classes to add or modify storage keys.
		*
		* @protected
		*/
		onComputeStorageKeys(context) {
			var _a, _b, _c;
			const activity = context.activity;
			const channelId = activity === null || activity === void 0 ? void 0 : activity.channelId;
			const agentId = (_a = activity === null || activity === void 0 ? void 0 : activity.recipient) === null || _a === void 0 ? void 0 : _a.id;
			const conversationId = (_b = activity === null || activity === void 0 ? void 0 : activity.conversation) === null || _b === void 0 ? void 0 : _b.id;
			const userId = (_c = activity === null || activity === void 0 ? void 0 : activity.from) === null || _c === void 0 ? void 0 : _c.id;
			if (!channelId) throw new Error("missing context.activity.channelId");
			if (!agentId) throw new Error("missing context.activity.recipient.id");
			if (!conversationId) throw new Error("missing context.activity.conversation.id");
			if (!userId) throw new Error("missing context.activity.from.id");
			const keys = {};
			keys[CONVERSATION_SCOPE] = `${channelId}/${agentId}/conversations/${conversationId}`;
			keys[USER_SCOPE] = `${channelId}/${agentId}/users/${userId}`;
			return Promise.resolve(keys);
		}
		/**
		* Parses a dot-notation path into scope and property name.
		*
		* @param path - The path to parse (format: "scope.property" or just "property")
		* @returns Object containing the scope entry and property name
		*
		* @remarks
		* If no scope is specified, defaults to the temp scope.
		*
		* @private
		*/
		getScopeAndName(path) {
			const parts = path.split(".");
			if (parts.length > 2) throw new Error(`Invalid state path: ${path}`);
			else if (parts.length === 1) parts.unshift(TEMP_SCOPE);
			const scope = this.getScope(parts[0]);
			if (scope === void 0) throw new Error(`Invalid state scope: ${parts[0]}`);
			return {
				scope,
				name: parts[1]
			};
		}
	};
	exports.TurnState = TurnState;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/routeRank.js
var require_routeRank = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.RouteRank = void 0;
	/**
	* Defines the priority ranking for route evaluation in the agent hosting framework.
	*
	* @remarks
	* Routes are evaluated in ascending order of their rank values, allowing for precise
	* control over which routes are processed first when multiple routes could match
	* the same request.
	*
	* @example
	* ```typescript
	* // High priority route that should be evaluated first
	* this.onMessage('urgent', handler, undefined, RouteRank.First);
	*
	* // Normal priority route with default ranking
	* this.onMessage('data', handler, undefined, RouteRank.Unspecified);
	*
	* // Fallback route that should be evaluated last
	* this.onActivity('message', fallbackHandler, undefined, RouteRank.Last);
	*
	* // Multiple routes with same pattern - first ranked executes first
	* this.onMessage('dupText', handler1, undefined, RouteRank.Last);
	* this.onMessage('dupText', handler2, undefined, RouteRank.First); // This executes first
	* ```
	*
	*/
	var RouteRank;
	(function(RouteRank) {
		/**
		* Highest priority rank (value: 0).
		*
		* Routes with this rank are evaluated
		* before any other routes. Use this for critical routes that must take precedence
		* over all others, such as high-priority message handlers or override handlers
		* that should execute before any other matching routes.
		*/
		RouteRank[RouteRank["First"] = 0] = "First";
		/**
		* Lowest priority rank (value: Number.MAX_VALUE).
		*
		* Routes with this rank are
		* evaluated last, after all other routes have been considered. Ideal for
		* catch-all message handlers, fallback activity handlers, or default responses
		* that should only match when no other routes apply.
		*/
		RouteRank[RouteRank["Last"] = Number.MAX_VALUE] = "Last";
		/**
		* Default priority rank (value: Number.MAX_VALUE / 2).
		*
		* This is the standard
		* rank for most routes that don't require special ordering. Routes with this
		* rank are evaluated after high-priority routes but before low-priority ones.
		* Use this when you don't need to specify a particular evaluation order.
		*/
		RouteRank[RouteRank["Unspecified"] = Number.MAX_VALUE / 2] = "Unspecified";
	})(RouteRank || (exports.RouteRank = RouteRank = {}));
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/routeList.js
var require_routeList = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.RouteList = void 0;
	const routeRank_1 = require_routeRank();
	var RouteList = class {
		constructor() {
			this._routes = [];
		}
		addRoute(selector, handler, isInvokeRoute = false, rank = routeRank_1.RouteRank.Unspecified, authHandlers = [], isAgenticRoute = false) {
			this._routes.push({
				selector,
				handler,
				isInvokeRoute,
				rank,
				authHandlers,
				isAgenticRoute
			});
			this._routes.sort((a, b) => {
				var _a, _b;
				const getPriority = (route) => {
					if (route.isAgenticRoute && route.isInvokeRoute) return 0;
					if (route.isInvokeRoute) return 1;
					if (route.isAgenticRoute) return 2;
					return 3;
				};
				const priorityA = getPriority(a);
				const priorityB = getPriority(b);
				if (priorityA !== priorityB) return priorityA - priorityB;
				return ((_a = a.rank) !== null && _a !== void 0 ? _a : 0) - ((_b = b.rank) !== null && _b !== void 0 ? _b : 0);
			});
			return this;
		}
		[Symbol.iterator]() {
			return this._routes[Symbol.iterator]();
		}
	};
	exports.RouteList = RouteList;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/transcript/transcriptLogger.js
var require_transcriptLogger = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/transcript/transcriptStore.js
var require_transcriptStore = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/transcript/transcriptLoggerMiddleware.js
var require_transcriptLoggerMiddleware = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.TranscriptLoggerMiddleware = void 0;
	const agents_activity_1 = require_src$2();
	const appLogger = (0, require_logger().debug)("agents:rest-client");
	/**
	* Middleware for logging agent conversations to a transcript logger.
	*/
	var TranscriptLoggerMiddleware = class {
		/**
		* Creates a new instance of the TranscriptLoggerMiddleware class.
		* @param logger The transcript logger to use.
		* @throws Will throw an error if the logger is not provided.
		*/
		constructor(logger) {
			if (!logger) throw new Error("TranscriptLoggerMiddleware requires a TranscriptLogger instance.");
			this.logger = logger;
		}
		/**
		* Called each time the agent processes a turn.
		* @param context The context object for the turn.
		* @param next The next middleware or handler to call.
		*/
		async onTurn(context, next) {
			const transcript = [];
			if (context.activity && context.activity.from) {
				if (!context.activity.from.role) context.activity.from.role = agents_activity_1.RoleTypes.User;
				this.logActivity(transcript, this.cloneActivity(context.activity));
			}
			context.onSendActivities(async (ctx, activities, next) => {
				const responses = await next();
				activities.forEach((activity, index) => {
					const clonedActivity = this.cloneActivity(activity);
					clonedActivity.id = responses && responses[index] ? responses[index].id : clonedActivity.id;
					if (!clonedActivity.id) {
						const prefix = `g_${Math.random().toString(36).slice(2, 8)}`;
						if (clonedActivity.timestamp) clonedActivity.id = `${prefix}${new Date(clonedActivity.timestamp).getTime().toString()}`;
						else clonedActivity.id = `${prefix}${(/* @__PURE__ */ new Date()).getTime().toString()}`;
					}
					this.logActivity(transcript, clonedActivity);
				});
				return responses;
			});
			context.onUpdateActivity(async (ctx, activity, next) => {
				const response = await next();
				const updateActivity = this.cloneActivity(activity);
				updateActivity.type = agents_activity_1.ActivityTypes.MessageUpdate;
				this.logActivity(transcript, updateActivity);
				return response;
			});
			context.onDeleteActivity(async (ctx, reference, next) => {
				await next();
			});
			await next();
			while (transcript.length) try {
				const activity = transcript.shift();
				if (activity) {
					const maybePromise = this.logger.logActivity(activity);
					if (maybePromise instanceof Promise) maybePromise.catch((err) => {
						this.transcriptLoggerErrorHandler(err);
					});
				}
			} catch (err) {
				this.transcriptLoggerErrorHandler(err);
			}
		}
		/**
		* Logs an activity to the transcript.
		* @param transcript The transcript array to log the activity to.
		* @param activity The activity to log.
		*/
		logActivity(transcript, activity) {
			if (!activity.timestamp) activity.timestamp = /* @__PURE__ */ new Date();
			if (!(activity.type === agents_activity_1.ActivityTypes.Event && activity.name === agents_activity_1.ActivityEventNames.ContinueConversation)) transcript.push(activity);
		}
		/**
		* Creates a deep copy of an activity.
		* @param activity The activity to clone.
		* @returns A deep copy of the activity.
		*/
		cloneActivity(activity) {
			return Object.assign({}, activity);
		}
		/**
		* Handles errors that occur during logging.
		* @param err The error that occurred.
		*/
		transcriptLoggerErrorHandler(err) {
			if (err instanceof Error) {
				appLogger.error(`TranscriptLoggerMiddleware logActivity failed: "${err.message}"`);
				appLogger.error(JSON.stringify(err.stack));
			} else appLogger.error(`TranscriptLoggerMiddleware logActivity failed: "${JSON.stringify(err)}"`);
		}
	};
	exports.TranscriptLoggerMiddleware = TranscriptLoggerMiddleware;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/transcript/consoleTranscriptLogger.js
var require_consoleTranscriptLogger = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ConsoleTranscriptLogger = void 0;
	/**
	* A transcript logger that logs activities to the console.
	*/
	var ConsoleTranscriptLogger = class {
		/**
		* Logs an activity to the console.
		* @param activity The activity to log.
		* @throws Will throw an error if the activity is not provided.
		*/
		logActivity(activity) {
			if (!activity) throw new Error("Activity is required.");
			console.log("Activity Log:", activity);
		}
	};
	exports.ConsoleTranscriptLogger = ConsoleTranscriptLogger;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/transcript/index.js
var require_transcript = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$12) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$12, p)) __createBinding(exports$12, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_transcriptLogger(), exports);
	__exportStar(require_transcriptStore(), exports);
	__exportStar(require_transcriptLoggerMiddleware(), exports);
	__exportStar(require_consoleTranscriptLogger(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/middlewareSet.js
var require_middlewareSet = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MiddlewareSet = void 0;
	const logger = (0, require_logger().debug)("agents:middleware");
	/**
	* Represents a set of middleware.
	*/
	var MiddlewareSet = class {
		/**
		* Initializes a new instance of the MiddlewareSet class.
		* @param middlewares The middleware handlers or middleware objects to use.
		*/
		constructor(...middlewares) {
			this.middleware = [];
			this.use(...middlewares);
		}
		/**
		* Handles the turn of the middleware.
		* @param context The turn context.
		* @param next The next function to call.
		* @returns A promise representing the asynchronous operation.
		*/
		async onTurn(context, next) {
			return await this.run(context, next);
		}
		/**
		* Adds middleware to the set.
		* @param middlewares The middleware handlers or middleware objects to add.
		* @returns The current MiddlewareSet instance.
		*/
		use(...middlewares) {
			middlewares.forEach((plugin) => {
				if (typeof plugin === "function" || typeof plugin === "object" && plugin.onTurn) this.middleware.push(typeof plugin === "function" ? plugin : async (context, next) => await plugin.onTurn(context, next));
				else throw new Error("MiddlewareSet.use(): invalid plugin type being added.");
			});
			return this;
		}
		/**
		* Runs the middleware chain.
		* @param context The turn context.
		* @param next The next function to call.
		* @returns A promise representing the asynchronous operation.
		*/
		async run(context, next) {
			return await this.middleware.reduceRight((nextHandler, currentHandler) => async () => await currentHandler(context, nextHandler), next)().catch((err) => {
				logger.error("Error in middleware chain:", err);
				throw err;
			});
		}
	};
	exports.MiddlewareSet = MiddlewareSet;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/baseAdapter.js
var require_baseAdapter = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.BaseAdapter = void 0;
	const middlewareSet_1 = require_middlewareSet();
	const logger = (0, require_logger().debug)("agents:base-adapter");
	/**
	* Abstract base class for all adapters in the Agents framework.
	*
	* @remarks
	* This class provides core functionality for handling conversations, managing middleware,
	* authentication, and error handling. Adapters are responsible for translating between
	* the Agents framework and specific communication channels (like Teams, Web Chat, etc.).
	*
	* Key features:
	* - Middleware pipeline for processing incoming and outgoing activities
	* - Error handling and recovery mechanisms
	* - Authentication provider integration
	* - Abstract methods for channel-specific operations
	* - Context management with revocable proxies for security
	*/
	var BaseAdapter = class {
		constructor() {
			/**
			* The middleware set used to process the pipeline of middleware handlers.
			*/
			this.middleware = new middlewareSet_1.MiddlewareSet();
			this.turnError = async (context, error) => {
				logger.error(`\n [onTurnError] unhandled error: ${error}`);
				await context.sendTraceActivity("OnTurnError Trace", `${error}`, "https://www.botframework.com/schemas/error", "TurnError");
				await context.sendActivity("The agent encountered an error or bug.");
				await context.sendActivity("To continue to run this agent, please fix the source code.");
			};
			/**
			* Symbol key used to store connector client instances in the TurnContext.
			*/
			this.ConnectorClientKey = Symbol("ConnectorClient");
			/**
			* Symbol key used to store User Token Client instances in the TurnContext.
			*/
			this.UserTokenClientKey = Symbol("UserTokenClient");
		}
		/**
		* Gets the error handler for the adapter.
		* @returns The current error handler function.
		*/
		get onTurnError() {
			return this.turnError;
		}
		/**
		* Sets the error handler for the adapter.
		* @param value - The error handler function to set.
		*/
		set onTurnError(value) {
			this.turnError = value;
		}
		/**
		* Adds middleware to the adapter's middleware pipeline.
		* @param middlewares - The middleware to add.
		* @returns The adapter instance.
		*/
		use(...middlewares) {
			this.middleware.use(...middlewares);
			return this;
		}
		/**
		* This method creates a revocable proxy for the given target object.
		* If the environment does not support Proxy.revocable, it returns the original object.
		* @remarks
		* This is used to enhance security by allowing the proxy to be revoked after use,
		* preventing further access to the underlying object.
		*
		* @param target The target object to be proxied.
		* @param handler Optional proxy handler to customize behavior.
		* @returns An object containing the proxy and a revoke function.
		*/
		makeRevocable(target, handler) {
			if (typeof Proxy !== "undefined" && Proxy.revocable) return Proxy.revocable(target, handler != null ? handler : {});
			else return {
				proxy: target,
				revoke: () => {}
			};
		}
		/**
		* Runs the middleware pipeline in sequence.
		* @param context - The TurnContext for the current turn.
		* @param next - The next function to call in the pipeline.
		* @returns A promise representing the completion of the middleware pipeline.
		*/
		async runMiddleware(context, next) {
			if (context && context.activity && context.activity.locale) context.locale = context.activity.locale;
			const pContext = this.makeRevocable(context);
			try {
				await this.middleware.run(pContext.proxy, async () => await next(pContext.proxy));
			} catch (err) {
				if (this.onTurnError) if (err instanceof Error) await this.onTurnError(pContext.proxy, err);
				else throw new Error("Unknown error type: " + err.message);
				else throw err;
			} finally {
				pContext.revoke();
			}
		}
	};
	exports.BaseAdapter = BaseAdapter;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/activityWireCompat.js
var require_activityWireCompat = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.normalizeIncomingActivity = normalizeIncomingActivity;
	exports.normalizeOutgoingActivity = normalizeOutgoingActivity;
	exports.normalizeTokenExchangeState = normalizeTokenExchangeState;
	/**
	* @private
	* Normalizes an incoming payload by converting the `bot` property in `relatesTo` to `agent`.
	* This ensures compatibility with the activity wire protocol.
	*
	* @param payload - The incoming payload object to normalize.
	* @returns The normalized payload object with `bot` replaced by `agent` in `relatesTo`.
	*/
	function normalizeIncomingActivity(payload) {
		if (payload["relatesTo"] && payload["relatesTo"]["bot"]) {
			const relatesTo = payload["relatesTo"];
			const ov = relatesTo["bot"];
			delete relatesTo["bot"];
			relatesTo["agent"] = ov;
		}
		return payload;
	}
	/**
	* @private
	* Normalizes an outgoing payload by converting the `agent` property in `relatesTo` to `bot`.
	* This ensures compatibility with the activity wire protocol.
	*
	* @param payload - The outgoing payload object to normalize.
	* @returns The normalized payload object with `agent` replaced by `bot` in `relatesTo`.
	*/
	function normalizeOutgoingActivity(payload) {
		if (!payload) return payload;
		const modifiedPayload = JSON.parse(JSON.stringify(payload));
		if (modifiedPayload && modifiedPayload["relatesTo"] && modifiedPayload["relatesTo"]["agent"]) {
			const relatesTo = modifiedPayload["relatesTo"];
			const ov = relatesTo["agent"];
			delete relatesTo["agent"];
			relatesTo["bot"] = ov;
		}
		if (modifiedPayload && modifiedPayload["_channelId"]) {
			modifiedPayload["channelId"] = modifiedPayload["_channelId"].toString();
			delete modifiedPayload["_channelId"];
		}
		return modifiedPayload;
	}
	function normalizeTokenExchangeState(payload) {
		if (payload["conversation"] && payload["conversation"]["agent"]) {
			const conversation = payload["conversation"];
			const ov = conversation["agent"];
			delete conversation["agent"];
			conversation["bot"] = ov;
		}
		return payload;
	}
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/package.json
var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = {
		"$schema": "https://json.schemastore.org/package.json",
		"name": "@microsoft/agents-hosting",
		"version": "1.3.1",
		"homepage": "https://github.com/microsoft/Agents-for-js",
		"repository": {
			"type": "git",
			"url": "git+https://github.com/microsoft/Agents-for-js.git"
		},
		"author": {
			"name": "Microsoft",
			"email": "agentssdk@microsoft.com",
			"url": "https://aka.ms/Agents"
		},
		"description": "Microsoft 365 Agents SDK for JavaScript",
		"keywords": ["Agents"],
		"main": "dist/src/index.js",
		"types": "dist/src/index.d.ts",
		"dependencies": {
			"@azure/core-auth": "^1.10.1",
			"@azure/msal-node": "^5.0.4",
			"@microsoft/agents-activity": "1.3.1",
			"axios": "^1.13.5",
			"jsonwebtoken": "^9.0.3",
			"jwks-rsa": "^3.2.2",
			"object-path": "^0.11.8",
			"zod": "3.25.75"
		},
		"license": "MIT",
		"files": [
			"README.md",
			"dist/src",
			"src",
			"package.json"
		],
		"exports": {
			".": {
				"types": "./dist/src/index.d.ts",
				"import": "./dist/src/index.js",
				"require": "./dist/src/index.js"
			},
			"./package.json": "./package.json"
		},
		"engines": { "node": ">=20.0.0" },
		"devDependencies": { "@types/object-path": "^0.11.4" }
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/getProductInfo.js
var require_getProductInfo = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.getProductInfo = void 0;
	const package_json_1 = require_package();
	const os_1 = __importDefault(__require("os"));
	/**
	* Generates a string containing information about the SDK version and runtime environment.
	* This is used for telemetry and User-Agent headers in HTTP requests.
	*
	* @returns A formatted string containing the SDK version, Node.js version, and OS details
	*/
	const getProductInfo = () => `agents-sdk-js/${package_json_1.version} nodejs/${process.version} ${os_1.default.platform()}-${os_1.default.arch()}/${os_1.default.release()}`;
	exports.getProductInfo = getProductInfo;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/headerPropagation.js
var require_headerPropagation = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.HeaderPropagation = void 0;
	/**
	* A class that implements the HeaderPropagationCollection interface.
	* It filters the incoming request headers based on the definition provided and loads them into the outgoing headers collection.
	*/
	var HeaderPropagation = class {
		get incoming() {
			return this._incomingRequests;
		}
		get outgoing() {
			return this._outgoingHeaders;
		}
		constructor(headers) {
			this._outgoingHeaders = {};
			this._headersToPropagate = ["x-ms-correlation-id"];
			if (!headers) throw new Error("Headers must be provided.");
			this._incomingRequests = this.normalizeHeaders(headers);
			this.propagate(this._headersToPropagate);
		}
		propagate(headers) {
			for (const key of headers !== null && headers !== void 0 ? headers : []) {
				const lowerKey = key.toLowerCase();
				if (this._incomingRequests[lowerKey] && !this._outgoingHeaders[lowerKey]) this._outgoingHeaders[lowerKey] = this._incomingRequests[lowerKey];
			}
		}
		add(headers) {
			for (const [key, value] of Object.entries(headers !== null && headers !== void 0 ? headers : {})) {
				const lowerKey = key.toLowerCase();
				if (!this._incomingRequests[lowerKey] && !this._outgoingHeaders[lowerKey]) this._outgoingHeaders[lowerKey] = value;
			}
		}
		concat(headers) {
			var _a;
			for (const [key, value] of Object.entries(headers !== null && headers !== void 0 ? headers : {})) {
				const lowerKey = key.toLowerCase();
				if (this._incomingRequests[lowerKey] && !this._headersToPropagate.includes(lowerKey)) this._outgoingHeaders[lowerKey] = `${(_a = this._outgoingHeaders[lowerKey]) !== null && _a !== void 0 ? _a : this._incomingRequests[lowerKey]} ${value}`.trim();
			}
		}
		override(headers) {
			for (const [key, value] of Object.entries(headers !== null && headers !== void 0 ? headers : {})) {
				const lowerKey = key.toLowerCase();
				if (!this._headersToPropagate.includes(lowerKey)) this._outgoingHeaders[lowerKey] = value;
			}
		}
		/**
		* Normalizes the headers by lowercasing the keys and ensuring the values are strings.
		* @param headers The headers to normalize.
		* @returns A new object with normalized headers.
		*/
		normalizeHeaders(headers) {
			return Object.entries(headers).reduce((acc, [key, value]) => {
				if (value) acc[key.toLowerCase()] = Array.isArray(value) ? value.join(" ") : value;
				return acc;
			}, {});
		}
	};
	exports.HeaderPropagation = HeaderPropagation;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/connectorClient.js
var require_connectorClient = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ConnectorClient = exports.getProductInfo = void 0;
	/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */
	const axios_1 = __importDefault(require_axios());
	const logger_1 = require_logger();
	const agents_activity_1 = require_src$2();
	const errorHelper_1 = require_errorHelper();
	const activityWireCompat_1 = require_activityWireCompat();
	const getProductInfo_1 = require_getProductInfo();
	Object.defineProperty(exports, "getProductInfo", {
		enumerable: true,
		get: function() {
			return getProductInfo_1.getProductInfo;
		}
	});
	const headerPropagation_1 = require_headerPropagation();
	const logger = (0, logger_1.debug)("agents:connector-client");
	exports.ConnectorClient = class ConnectorClient {
		/**
		* Private constructor for the ConnectorClient.
		* @param axInstance - The AxiosInstance to use for HTTP requests.
		*/
		constructor(axInstance) {
			this._axiosInstance = axInstance;
			this._axiosInstance.interceptors.request.use((config) => {
				const { method, url, data, headers, params } = config;
				const { Authorization, authorization, ...headersToLog } = headers || {};
				logger.debug("Request: ", {
					host: this._axiosInstance.getUri(),
					url,
					data,
					method,
					params,
					headers: headersToLog
				});
				return config;
			});
			this._axiosInstance.interceptors.response.use((config) => {
				const { status, statusText, config: requestConfig } = config;
				logger.debug("Response: ", {
					status,
					statusText,
					host: this._axiosInstance.getUri(),
					url: requestConfig === null || requestConfig === void 0 ? void 0 : requestConfig.url,
					data: config.config.data,
					method: requestConfig === null || requestConfig === void 0 ? void 0 : requestConfig.method
				});
				return config;
			}, (error) => {
				const { code, message, stack, response } = error;
				const errorDetails = {
					code,
					host: this._axiosInstance.getUri(),
					url: error.config.url,
					method: error.config.method,
					data: error.config.data,
					message: message + JSON.stringify(response === null || response === void 0 ? void 0 : response.data),
					stack
				};
				return Promise.reject(errorDetails);
			});
		}
		get axiosInstance() {
			return this._axiosInstance;
		}
		/**
		* Creates a new instance of ConnectorClient with authentication.
		* @param baseURL - The base URL for the API.
		* @param authConfig - The authentication configuration.
		* @param authProvider - The authentication provider.
		* @param scope - The scope for the authentication token.
		* @param headers - Optional headers to propagate in the request.
		* @returns A new instance of ConnectorClient.
		*/
		static async createClientWithAuth(baseURL, authConfig, authProvider, scope, headers) {
			const token = await authProvider.getAccessToken(authConfig, scope);
			return this.createClientWithToken(baseURL, token, headers);
		}
		/**
		* Creates a new instance of ConnectorClient with token.
		* @param baseURL - The base URL for the API.
		* @param token - The authentication token.
		* @param headers - Optional headers to propagate in the request.
		* @returns A new instance of ConnectorClient.
		*/
		static createClientWithToken(baseURL, token, headers) {
			const headerPropagation = headers !== null && headers !== void 0 ? headers : new headerPropagation_1.HeaderPropagation({});
			const userAgent = headerPropagation.outgoing["user-agent"];
			const productInfo = (0, getProductInfo_1.getProductInfo)();
			if (!userAgent) headerPropagation.add({ "User-Agent": productInfo });
			else if (!userAgent.includes(productInfo)) headerPropagation.concat({ "User-Agent": productInfo });
			headerPropagation.override({
				Accept: "application/json",
				"Content-Type": "application/json"
			});
			const axiosInstance = axios_1.default.create({
				baseURL,
				headers: headerPropagation.outgoing
			});
			if (token && token.length > 1) axiosInstance.defaults.headers.common.Authorization = `Bearer ${token}`;
			return new ConnectorClient(axiosInstance);
		}
		/**
		* Retrieves a list of conversations.
		* @param continuationToken - The continuation token for pagination.
		* @returns A list of conversations.
		*/
		async getConversations(continuationToken) {
			const config = {
				method: "get",
				url: "/v3/conversations",
				params: continuationToken ? { continuationToken } : void 0
			};
			return (await this._axiosInstance(config)).data;
		}
		async getConversationMember(userId, conversationId) {
			if (!userId || !conversationId) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.UserIdAndConversationIdRequired);
			const config = {
				method: "get",
				url: `v3/conversations/${conversationId}/members/${userId}`,
				headers: { "Content-Type": "application/json" }
			};
			return (await this._axiosInstance(config)).data;
		}
		/**
		* Creates a new conversation.
		* @param body - The conversation parameters.
		* @returns The conversation resource response.
		*/
		async createConversation(body) {
			const payload = {
				...body,
				activity: (0, activityWireCompat_1.normalizeOutgoingActivity)(body.activity)
			};
			const config = {
				method: "post",
				url: "/v3/conversations",
				headers: { "Content-Type": "application/json" },
				data: payload
			};
			return (await this._axiosInstance(config)).data;
		}
		/**
		* Replies to an activity in a conversation.
		* @param conversationId - The ID of the conversation.
		* @param activityId - The ID of the activity.
		* @param body - The activity object.
		* @returns The resource response.
		*/
		async replyToActivity(conversationId, activityId, body) {
			logger.debug(`Replying to activity: ${activityId} in conversation: ${conversationId}`);
			if (!conversationId || !activityId) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConversationIdAndActivityIdRequired);
			const config = {
				method: "post",
				url: `v3/conversations/${this.conditionallyTruncateConversationId(conversationId, body)}/activities/${encodeURIComponent(activityId)}`,
				headers: { "Content-Type": "application/json" },
				data: (0, activityWireCompat_1.normalizeOutgoingActivity)(body)
			};
			const response = await this._axiosInstance(config);
			logger.info("Reply to conversation/activity: ", response.data.id, activityId);
			return response.data;
		}
		/**
		* Trim the conversationId to a fixed length when creating the URL. This is applied only in specific API calls for agentic calls.
		* @param conversationId The ID of the conversation to potentially truncate.
		* @param activity The activity object used to determine if truncation is necessary.
		* @returns The original or truncated conversationId, depending on the channel and activity role.
		*/
		conditionallyTruncateConversationId(conversationId, activity) {
			var _a, _b;
			if ((activity.channelIdChannel === agents_activity_1.Channels.Msteams || activity.channelIdChannel === agents_activity_1.Channels.Agents) && (((_a = activity.from) === null || _a === void 0 ? void 0 : _a.role) === agents_activity_1.RoleTypes.AgenticIdentity || ((_b = activity.from) === null || _b === void 0 ? void 0 : _b.role) === agents_activity_1.RoleTypes.AgenticUser)) {
				let maxLength = 150;
				if (process.env.MAX_APX_CONVERSATION_ID_LENGTH && !isNaN(parseInt(process.env.MAX_APX_CONVERSATION_ID_LENGTH, 10))) maxLength = parseInt(process.env.MAX_APX_CONVERSATION_ID_LENGTH, 10);
				return conversationId.length > maxLength ? conversationId.substring(0, maxLength) : conversationId;
			} else return conversationId;
		}
		/**
		* Sends an activity to a conversation.
		* @param conversationId - The ID of the conversation.
		* @param body - The activity object.
		* @returns The resource response.
		*/
		async sendToConversation(conversationId, body) {
			logger.debug(`Send to conversation: ${conversationId} activity: ${body.id}`);
			if (!conversationId) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConversationIdRequired);
			const config = {
				method: "post",
				url: `v3/conversations/${this.conditionallyTruncateConversationId(conversationId, body)}/activities`,
				headers: { "Content-Type": "application/json" },
				data: (0, activityWireCompat_1.normalizeOutgoingActivity)(body)
			};
			return (await this._axiosInstance(config)).data;
		}
		/**
		* Updates an activity in a conversation.
		* @param conversationId - The ID of the conversation.
		* @param activityId - The ID of the activity.
		* @param body - The activity object.
		* @returns The resource response.
		*/
		async updateActivity(conversationId, activityId, body) {
			if (!conversationId || !activityId) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConversationIdAndActivityIdRequired);
			const config = {
				method: "put",
				url: `v3/conversations/${conversationId}/activities/${activityId}`,
				headers: { "Content-Type": "application/json" },
				data: (0, activityWireCompat_1.normalizeOutgoingActivity)(body)
			};
			return (await this._axiosInstance(config)).data;
		}
		/**
		* Deletes an activity from a conversation.
		* @param conversationId - The ID of the conversation.
		* @param activityId - The ID of the activity.
		* @returns A promise that resolves when the activity is deleted.
		*/
		async deleteActivity(conversationId, activityId) {
			if (!conversationId || !activityId) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConversationIdAndActivityIdRequired);
			const config = {
				method: "delete",
				url: `v3/conversations/${conversationId}/activities/${activityId}`,
				headers: { "Content-Type": "application/json" }
			};
			return (await this._axiosInstance(config)).data;
		}
		/**
		* Uploads an attachment to a conversation.
		* @param conversationId - The ID of the conversation.
		* @param body - The attachment data.
		* @returns The resource response.
		*/
		async uploadAttachment(conversationId, body) {
			if (conversationId === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConversationIdRequired);
			const config = {
				method: "post",
				url: `v3/conversations/${conversationId}/attachments`,
				headers: { "Content-Type": "application/json" },
				data: body
			};
			return (await this._axiosInstance(config)).data;
		}
		/**
		* Retrieves attachment information by attachment ID.
		* @param attachmentId - The ID of the attachment.
		* @returns The attachment information.
		*/
		async getAttachmentInfo(attachmentId) {
			if (attachmentId === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.AttachmentIdRequired);
			const config = {
				method: "get",
				url: `v3/attachments/${attachmentId}`,
				headers: { "Content-Type": "application/json" }
			};
			return (await this._axiosInstance(config)).data;
		}
		/**
		* Retrieves an attachment by attachment ID and view ID.
		* @param attachmentId - The ID of the attachment.
		* @param viewId - The ID of the view.
		* @returns The attachment as a readable stream.
		*/
		async getAttachment(attachmentId, viewId) {
			if (attachmentId === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.AttachmentIdRequired);
			if (viewId === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ViewIdRequired);
			const config = {
				method: "get",
				url: `v3/attachments/${attachmentId}/views/${viewId}`,
				headers: { "Content-Type": "application/json" }
			};
			return (await this._axiosInstance(config)).data;
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/oauth/customUserTokenAPI.js
var require_customUserTokenAPI = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.getTokenServiceEndpoint = void 0;
	const getTokenServiceEndpoint = () => {
		var _a;
		return (_a = process.env.TOKEN_SERVICE_ENDPOINT) !== null && _a !== void 0 ? _a : "https://api.botframework.com";
	};
	exports.getTokenServiceEndpoint = getTokenServiceEndpoint;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/oauth/userTokenClient.js
var require_userTokenClient = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.UserTokenClient = void 0;
	const axios_1 = __importDefault(require_axios());
	const agents_activity_1 = require_src$2();
	const logger_1 = require_logger();
	const activityWireCompat_1 = require_activityWireCompat();
	const getProductInfo_1 = require_getProductInfo();
	const headerPropagation_1 = require_headerPropagation();
	const customUserTokenAPI_1 = require_customUserTokenAPI();
	const logger = (0, logger_1.debug)("agents:user-token-client");
	exports.UserTokenClient = class UserTokenClient {
		constructor(param) {
			this.msAppId = "";
			if (typeof param === "string") {
				const baseURL = (0, customUserTokenAPI_1.getTokenServiceEndpoint)();
				this.client = axios_1.default.create({
					baseURL,
					headers: {
						Accept: "application/json",
						"User-Agent": (0, getProductInfo_1.getProductInfo)()
					}
				});
			} else this.client = param;
			this.client.interceptors.request.use((config) => {
				const { method, url, data, headers, params } = config;
				const { Authorization, authorization, ...headersToLog } = headers || {};
				logger.debug("Request: ", {
					host: this.client.getUri(),
					url,
					data,
					method,
					params,
					headers: headersToLog
				});
				return config;
			});
			this.client.interceptors.response.use((config) => {
				const { status, statusText, config: requestConfig, headers } = config;
				const { Authorization, authorization, ...headersToLog } = headers || {};
				const { token, ...redactedData } = (requestConfig === null || requestConfig === void 0 ? void 0 : requestConfig.data) || {};
				logger.debug("Response: ", {
					status,
					statusText,
					host: this.client.getUri(),
					url: requestConfig === null || requestConfig === void 0 ? void 0 : requestConfig.url,
					data: redactedData,
					method: requestConfig === null || requestConfig === void 0 ? void 0 : requestConfig.method,
					headers: headersToLog
				});
				return config;
			}, (error) => {
				const { code, status, message, stack, response } = error;
				const { headers } = response || {};
				const errorDetails = {
					code,
					host: this.client.getUri(),
					url: error.config.url,
					method: error.config.method,
					data: error.config.data,
					message: message + JSON.stringify(response === null || response === void 0 ? void 0 : response.data),
					headers,
					stack
				};
				logger.debug("Response error: ", errorDetails);
				if (errorDetails.url === "/api/usertoken/GetToken" && status !== 404) return Promise.reject(errorDetails);
			});
		}
		/**
		* Creates a new instance of UserTokenClient with authentication.
		* @param baseURL - The base URL for the API.
		* @param authConfig - The authentication configuration.
		* @param authProvider - The authentication provider.
		* @param scope - The scope for the authentication token.
		* @param headers - Optional headers to propagate in the request.
		* @returns A new instance of ConnectorClient.
		*/
		static async createClientWithScope(baseURL, authProvider, scope, headers) {
			const headerPropagation = headers !== null && headers !== void 0 ? headers : new headerPropagation_1.HeaderPropagation({});
			const userAgent = headerPropagation.outgoing["user-agent"];
			const productInfo = (0, getProductInfo_1.getProductInfo)();
			if (!userAgent) headerPropagation.add({ "User-Agent": productInfo });
			else if (!userAgent.includes(productInfo)) headerPropagation.concat({ "User-Agent": productInfo });
			headerPropagation.override({
				Accept: "application/json",
				"Content-Type": "application/json"
			});
			const axiosInstance = axios_1.default.create({
				baseURL,
				headers: headerPropagation.outgoing
			});
			const token = await (authProvider === null || authProvider === void 0 ? void 0 : authProvider.getAccessToken(scope));
			if (token && token.length > 1) axiosInstance.defaults.headers.common.Authorization = `Bearer ${token}`;
			return new UserTokenClient(axiosInstance);
		}
		/**
		* Gets the user token.
		* @param connectionName The connection name.
		* @param channelIdComposite The channel ID.
		* @param userId The user ID.
		* @param code The optional code.
		* @returns A promise that resolves to the user token.
		*/
		async getUserToken(connectionName, channelIdComposite, userId, code) {
			const [channelId] = agents_activity_1.Activity.parseChannelId(channelIdComposite);
			const params = {
				connectionName,
				channelId,
				userId,
				code
			};
			const response = await this.client.get("/api/usertoken/GetToken", { params });
			if (response === null || response === void 0 ? void 0 : response.data) return response.data;
			return { token: void 0 };
		}
		/**
		* Signs the user out.
		* @param userId The user ID.
		* @param connectionName The connection name.
		* @param channelIdComposite The channel ID.
		* @returns A promise that resolves when the sign-out operation is complete.
		*/
		async signOut(userId, connectionName, channelIdComposite) {
			const [channelId] = agents_activity_1.Activity.parseChannelId(channelIdComposite);
			const params = {
				userId,
				connectionName,
				channelId
			};
			if ((await this.client.delete("/api/usertoken/SignOut", { params })).status !== 200) throw new Error("Failed to sign out");
		}
		/**
		* Gets the sign-in resource.
		* @param msAppId The application ID.
		* @param connectionName The connection name.
		* @param conversation The conversation reference.
		* @param relatesTo Optional. The related conversation reference.
		* @returns A promise that resolves to the signing resource.
		*/
		async getSignInResource(msAppId, connectionName, conversation, relatesTo) {
			const tokenExchangeState = {
				connectionName,
				conversation,
				relatesTo,
				msAppId
			};
			const tokenExchangeStateNormalized = (0, activityWireCompat_1.normalizeTokenExchangeState)(tokenExchangeState);
			const params = { state: Buffer.from(JSON.stringify(tokenExchangeStateNormalized)).toString("base64") };
			return (await this.client.get("/api/botsignin/GetSignInResource", { params })).data;
		}
		/**
		* Exchanges the token.
		* @param userId The user ID.
		* @param connectionName The connection name.
		* @param channelIdComposite The channel ID.
		* @param tokenExchangeRequest The token exchange request.
		* @returns A promise that resolves to the exchanged token.
		*/
		async exchangeTokenAsync(userId, connectionName, channelIdComposite, tokenExchangeRequest) {
			const [channelId] = agents_activity_1.Activity.parseChannelId(channelIdComposite);
			const params = {
				userId,
				connectionName,
				channelId
			};
			const response = await this.client.post("/api/usertoken/exchange", tokenExchangeRequest, { params });
			if (response === null || response === void 0 ? void 0 : response.data) return response.data;
			else return { token: void 0 };
		}
		/**
		* Gets the token or sign-in resource.
		* @param userId The user ID.
		* @param connectionName The connection name.
		* @param channelIdComposite The channel ID.
		* @param conversation The conversation reference.
		* @param relatesTo The related conversation reference.
		* @param code The code.
		* @param finalRedirect The final redirect URL.
		* @param fwdUrl The forward URL.
		* @returns A promise that resolves to the token or sign-in resource response.
		*/
		async getTokenOrSignInResource(userId, connectionName, channelIdComposite, conversation, relatesTo, code, finalRedirect = "", fwdUrl = "") {
			const [channelId] = agents_activity_1.Activity.parseChannelId(channelIdComposite);
			const params = {
				userId,
				connectionName,
				channelId,
				state: Buffer.from(JSON.stringify({
					conversation,
					relatesTo,
					connectionName,
					msAppId: this.msAppId
				})).toString("base64"),
				code,
				finalRedirect,
				fwdUrl
			};
			return (await this.client.get("/api/usertoken/GetTokenOrSignInResource", { params })).data;
		}
		/**
		* Gets the token status.
		* @param userId The user ID.
		* @param channelIdComposite The channel ID.
		* @param include The optional include parameter.
		* @returns A promise that resolves to the token status.
		*/
		async getTokenStatus(userId, channelIdComposite, include = null) {
			const [channelId] = agents_activity_1.Activity.parseChannelId(channelIdComposite);
			const params = {
				userId,
				channelId,
				include
			};
			return (await this.client.get("/api/usertoken/GetTokenStatus", { params })).data;
		}
		/**
		* Gets the AAD tokens.
		* @param userId The user ID.
		* @param connectionName The connection name.
		* @param channelIdComposite The channel ID.
		* @param resourceUrls The resource URLs.
		* @returns A promise that resolves to the AAD tokens.
		*/
		async getAadTokens(userId, connectionName, channelIdComposite, resourceUrls) {
			const [channelId] = agents_activity_1.Activity.parseChannelId(channelIdComposite);
			const params = {
				userId,
				connectionName,
				channelId
			};
			return (await this.client.post("/api/usertoken/GetAadTokens", resourceUrls, { params })).data;
		}
		updateAuthToken(token) {
			this.client.defaults.headers.common.Authorization = `Bearer ${token}`;
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/oauth/userTokenClient.types.js
var require_userTokenClient_types = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/oauth/index.js
var require_oauth = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$11) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$11, p)) __createBinding(exports$11, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_userTokenClient(), exports);
	__exportStar(require_userTokenClient_types(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cloudAdapter.js
var require_cloudAdapter = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
		Object.defineProperty(o, "default", {
			enumerable: true,
			value: v
		});
	}) : function(o, v) {
		o["default"] = v;
	});
	var __importStar = exports && exports.__importStar || (function() {
		var ownKeys = function(o) {
			ownKeys = Object.getOwnPropertyNames || function(o) {
				var ar = [];
				for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
				return ar;
			};
			return ownKeys(o);
		};
		return function(mod) {
			if (mod && mod.__esModule) return mod;
			var result = {};
			if (mod != null) {
				for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
			}
			__setModuleDefault(result, mod);
			return result;
		};
	})();
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.CloudAdapter = void 0;
	const activityHandler_1 = require_activityHandler();
	const baseAdapter_1 = require_baseAdapter();
	const turnContext_1 = require_turnContext();
	const connectorClient_1 = require_connectorClient();
	const authConfiguration_1 = require_authConfiguration();
	const authConstants_1 = require_authConstants();
	const msalConnectionManager_1 = require_msalConnectionManager();
	const agents_activity_1 = require_src$2();
	const errorHelper_1 = require_errorHelper();
	const uuid = __importStar(__require("uuid"));
	const logger_1 = require_logger();
	const statusCodes_1 = require_statusCodes();
	const activityWireCompat_1 = require_activityWireCompat();
	const oauth_1 = require_oauth();
	const headerPropagation_1 = require_headerPropagation();
	const customUserTokenAPI_1 = require_customUserTokenAPI();
	const logger = (0, logger_1.debug)("agents:cloud-adapter");
	exports.CloudAdapter = class CloudAdapter extends baseAdapter_1.BaseAdapter {
		/**
		* Creates an instance of CloudAdapter.
		* @param authConfig - The authentication configuration for securing communications.
		* @param authProvider - No longer used.
		* @param userTokenClient - No longer used.
		*/
		constructor(authConfig, authProvider, userTokenClient) {
			super();
			authConfig = (0, authConfiguration_1.getAuthConfigWithDefaults)(authConfig);
			this.connectionManager = new msalConnectionManager_1.MsalConnectionManager(void 0, void 0, authConfig);
		}
		/**
		* Determines whether a connector client is needed based on the delivery mode and service URL of the given activity.
		*
		* @param activity - The activity to evaluate.
		* @returns true if a ConnectorClient is needed, false otherwise.
		*  A connector client is required if the activity's delivery mode is not "ExpectReplies"
		*  and the service URL is not null or empty.
		* @protected
		*/
		resolveIfConnectorClientIsNeeded(activity) {
			if (!activity) throw new TypeError("`activity` parameter required");
			switch (activity.deliveryMode) {
				case agents_activity_1.DeliveryModes.ExpectReplies:
					if (!activity.serviceUrl) {
						logger.debug("DeliveryMode = ExpectReplies, connector client is not needed");
						return false;
					}
					break;
				default: break;
			}
			return true;
		}
		/**
		* Creates a connector client for a specific service URL and scope.
		*
		* @param serviceUrl - The URL of the service to connect to.
		* @param scope - The authentication scope to use.
		* @param identity - The identity used to select the token provider.
		* @param headers - Optional headers to propagate in the request.
		* @returns A promise that resolves to a ConnectorClient instance.
		* @protected
		*/
		async createConnectorClient(serviceUrl, scope, identity, headers) {
			const token = await this.connectionManager.getTokenProvider(identity, serviceUrl).getAccessToken(scope);
			return connectorClient_1.ConnectorClient.createClientWithToken(serviceUrl, token, headers);
		}
		/**
		* Creates a connector client for a specific identity and activity.
		*
		* @param identity - The identity used to select the token provider.
		* @param activity - The activity used to select the token provider.
		* @param headers - Optional headers to propagate in the request.
		* @returns A promise that resolves to a ConnectorClient instance.
		* @protected
		*/
		async createConnectorClientWithIdentity(identity, activity, headers) {
			var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
			if (!(identity === null || identity === void 0 ? void 0 : identity.aud)) return connectorClient_1.ConnectorClient.createClientWithToken(activity.serviceUrl, null, headers);
			let connectorClient;
			const tokenProvider = this.connectionManager.getTokenProviderFromActivity(identity, activity);
			if (activity.isAgenticRequest()) {
				logger.debug("Activity is from an agentic source, using special scope", activity.recipient);
				const agenticInstanceId = activity.getAgenticInstanceId();
				const agenticUserId = activity.getAgenticUser();
				if (((_b = (_a = activity.recipient) === null || _a === void 0 ? void 0 : _a.role) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === agents_activity_1.RoleTypes.AgenticIdentity.toLowerCase() && agenticInstanceId) {
					const token = await tokenProvider.getAgenticInstanceToken((_c = activity.getAgenticTenantId()) !== null && _c !== void 0 ? _c : "", agenticInstanceId);
					connectorClient = connectorClient_1.ConnectorClient.createClientWithToken(activity.serviceUrl, token, headers);
				} else if (((_e = (_d = activity.recipient) === null || _d === void 0 ? void 0 : _d.role) === null || _e === void 0 ? void 0 : _e.toLowerCase()) === agents_activity_1.RoleTypes.AgenticUser.toLowerCase() && agenticInstanceId && agenticUserId) {
					const scope = (_g = (_f = tokenProvider.connectionSettings) === null || _f === void 0 ? void 0 : _f.scope) !== null && _g !== void 0 ? _g : authConstants_1.ApxProductionScope;
					const token = await tokenProvider.getAgenticUserToken((_h = activity.getAgenticTenantId()) !== null && _h !== void 0 ? _h : "", agenticInstanceId, agenticUserId, [scope]);
					connectorClient = connectorClient_1.ConnectorClient.createClientWithToken(activity.serviceUrl, token, headers);
				} else throw new Error("Could not create connector client for agentic user");
			} else {
				const scope = (_k = (_j = identity.azp) !== null && _j !== void 0 ? _j : identity.appid) !== null && _k !== void 0 ? _k : "https://api.botframework.com";
				const token = await tokenProvider.getAccessToken(scope);
				connectorClient = connectorClient_1.ConnectorClient.createClientWithToken(activity.serviceUrl, token, headers);
			}
			return connectorClient;
		}
		/**
		* Creates the JwtPayload object with the provided appId.
		* @param appId The bot's appId.
		* @returns The JwtPayload object containing the appId as aud.
		*/
		static createIdentity(appId) {
			return { aud: appId };
		}
		/**
		* Sets the connector client on the turn context.
		*
		* @param context - The current turn context.
		* @protected
		*/
		setConnectorClient(context, connectorClient) {
			context.turnState.set(this.ConnectorClientKey, connectorClient);
		}
		/**
		* Creates a user token client for a specific service URL and scope.
		*
		* @param identity - The identity used to select the token provider.
		* @param tokenServiceEndpoint - The endpoint to connect to.
		* @param scope - The authentication scope to use.
		* @param audience - No longer used.
		* @param headers - Optional headers to propagate in the request
		* @returns A promise that resolves to a UserTokenClient instance.
		* @protected
		*/
		async createUserTokenClient(identity, tokenServiceEndpoint = (0, customUserTokenAPI_1.getTokenServiceEndpoint)(), scope = "https://api.botframework.com", audience = "https://api.botframework.com", headers) {
			if (!(identity === null || identity === void 0 ? void 0 : identity.aud)) return oauth_1.UserTokenClient.createClientWithScope(tokenServiceEndpoint, null, scope, headers);
			const tokenProvider = this.connectionManager.getTokenProvider(identity, tokenServiceEndpoint);
			return oauth_1.UserTokenClient.createClientWithScope(tokenServiceEndpoint, tokenProvider, scope, headers);
		}
		/**
		* Sets the user token client on the turn context.
		*
		* @param context - The current turn context.
		* @protected
		*/
		setUserTokenClient(context, userTokenClient) {
			context.turnState.set(this.UserTokenClientKey, userTokenClient);
		}
		/**
		* @deprecated This function will not be supported in future versions.  Create TurnContext directly.
		* Creates a TurnContext for the given activity and logic.
		* @param activity - The activity to process.
		* @param logic - The logic to execute.
		* @param identity - The identity used for the new context.
		* @returns The created TurnContext.
		*/
		createTurnContext(activity, logic, identity) {
			return new turnContext_1.TurnContext(this, activity, identity);
		}
		/**
		* Sends multiple activities to the conversation.
		* @param context - The TurnContext for the current turn.
		* @param activities - The activities to send.
		* @returns A promise representing the array of ResourceResponses for the sent activities.
		*/
		async sendActivities(context, activities) {
			var _a;
			if (!context) throw agents_activity_1.ExceptionHelper.generateException(TypeError, errorHelper_1.Errors.ContextParameterRequired);
			if (!activities) throw agents_activity_1.ExceptionHelper.generateException(TypeError, errorHelper_1.Errors.ActivitiesParameterRequired);
			if (activities.length === 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.EmptyActivitiesArray);
			const responses = [];
			for (const activity of activities) {
				delete activity.id;
				let response = { id: "" };
				if (activity.type === agents_activity_1.ActivityTypes.InvokeResponse) context.turnState.set(activityHandler_1.INVOKE_RESPONSE_KEY, activity);
				else if (activity.type === agents_activity_1.ActivityTypes.Trace && activity.channelId !== agents_activity_1.Channels.Emulator) {} else {
					if (!activity.serviceUrl || activity.conversation == null || !activity.conversation.id) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.InvalidActivityObject);
					if (activity.replyToId) response = await context.turnState.get(this.ConnectorClientKey).replyToActivity(activity.conversation.id, activity.replyToId, activity);
					else response = await context.turnState.get(this.ConnectorClientKey).sendToConversation(activity.conversation.id, activity);
				}
				if (!response) response = { id: (_a = activity.id) !== null && _a !== void 0 ? _a : "" };
				responses.push(response);
			}
			return responses;
		}
		/**
		* Processes an incoming request and sends the response.
		* @param request - The incoming request.
		* @param res - The response to send.
		* @param logic - The logic to execute.
		* @param headerPropagation - Optional function to handle header propagation.
		*/
		async process(request, res, logic, headerPropagation) {
			var _a, _b;
			const headers = new headerPropagation_1.HeaderPropagation(request.headers);
			if (headerPropagation && typeof headerPropagation === "function") {
				headerPropagation(headers);
				logger.debug("Headers to propagate: ", headers);
			}
			const end = (status, body, isInvokeResponseOrExpectReplies = false) => {
				res.status(status);
				if (isInvokeResponseOrExpectReplies) res.setHeader("content-type", "application/json");
				if (body) res.send(body);
				res.end();
			};
			if (!request.body) throw new TypeError("`request.body` parameter required, make sure express.json() is used as middleware");
			const incoming = (0, activityWireCompat_1.normalizeIncomingActivity)(request.body);
			const activity = agents_activity_1.Activity.fromObject(incoming);
			logger.info(`--> Processing incoming activity, type:${activity.type} channel:${activity.channelId}`);
			if (!this.isValidChannelActivity(activity)) return end(statusCodes_1.StatusCodes.BAD_REQUEST);
			logger.debug("Received activity: ", activity);
			const context = new turnContext_1.TurnContext(this, activity, request.user);
			if (this.resolveIfConnectorClientIsNeeded(activity)) {
				const connectorClient = await this.createConnectorClientWithIdentity(request.user, activity, headers);
				this.setConnectorClient(context, connectorClient);
			}
			if (!activity.isAgenticRequest()) {
				const userTokenClient = await this.createUserTokenClient(request.user, void 0, void 0, void 0, headers);
				this.setUserTokenClient(context, userTokenClient);
			}
			if ((activity === null || activity === void 0 ? void 0 : activity.type) === agents_activity_1.ActivityTypes.InvokeResponse || (activity === null || activity === void 0 ? void 0 : activity.type) === agents_activity_1.ActivityTypes.Invoke || (activity === null || activity === void 0 ? void 0 : activity.deliveryMode) === agents_activity_1.DeliveryModes.ExpectReplies) {
				await this.runMiddleware(context, logic);
				const invokeResponse = this.processTurnResults(context);
				logger.debug("Activity Response (invoke/expect replies): ", invokeResponse);
				return end((_a = invokeResponse === null || invokeResponse === void 0 ? void 0 : invokeResponse.status) !== null && _a !== void 0 ? _a : statusCodes_1.StatusCodes.OK, invokeResponse === null || invokeResponse === void 0 ? void 0 : invokeResponse.body, true);
			}
			await this.runMiddleware(context, logic);
			const invokeResponse = this.processTurnResults(context);
			return end((_b = invokeResponse === null || invokeResponse === void 0 ? void 0 : invokeResponse.status) !== null && _b !== void 0 ? _b : statusCodes_1.StatusCodes.OK, invokeResponse === null || invokeResponse === void 0 ? void 0 : invokeResponse.body);
		}
		isValidChannelActivity(activity) {
			var _a, _b;
			if (activity == null) {
				logger.warn("BadRequest: Missing activity");
				return false;
			}
			if (activity.type == null || activity.type === "") {
				logger.warn("BadRequest: Missing activity type");
				return false;
			}
			if (((_a = activity.conversation) === null || _a === void 0 ? void 0 : _a.id) == null || ((_b = activity.conversation) === null || _b === void 0 ? void 0 : _b.id) === "") {
				logger.warn("BadRequest: Missing conversation.Id");
				return false;
			}
			return true;
		}
		/**
		* Updates an activity.
		* @param context - The TurnContext for the current turn.
		* @param activity - The activity to update.
		* @returns A promise representing the ResourceResponse for the updated activity.
		*/
		async updateActivity(context, activity) {
			if (!context) throw new TypeError("`context` parameter required");
			if (!activity) throw new TypeError("`activity` parameter required");
			if (!activity.serviceUrl || activity.conversation == null || !activity.conversation.id || !activity.id) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.InvalidActivityObject);
			const response = await context.turnState.get(this.ConnectorClientKey).updateActivity(activity.conversation.id, activity.id, activity);
			return response.id ? { id: response.id } : void 0;
		}
		/**
		* Deletes an activity.
		* @param context - The TurnContext for the current turn.
		* @param reference - The conversation reference of the activity to delete.
		* @returns A promise representing the completion of the delete operation.
		*/
		async deleteActivity(context, reference) {
			if (!context) throw new TypeError("`context` parameter required");
			if (!reference || !reference.serviceUrl || reference.conversation == null || !reference.conversation.id || !reference.activityId) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.InvalidConversationReference);
			await context.turnState.get(this.ConnectorClientKey).deleteActivity(reference.conversation.id, reference.activityId);
		}
		/**
		* Continues a conversation.
		* @param botAppIdOrIdentity - The bot identity to use when continuing the conversation. This can be either:
		* a string containing the bot's App ID (botId) or a JwtPayload object containing identity claims (must include aud).
		* @param reference - The conversation reference to continue.
		* @param logic - The logic to execute.
		* @param isResponse - No longer used.
		* @returns A promise representing the completion of the continue operation.
		*/
		async continueConversation(botAppIdOrIdentity, reference, logic, isResponse = false) {
			if (!reference || !reference.serviceUrl || reference.conversation == null || !reference.conversation.id) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ContinueConversationInvalidReference);
			if (!botAppIdOrIdentity) throw new TypeError("continueConversation: botAppIdOrIdentity is required");
			const botAppId = typeof botAppIdOrIdentity === "string" ? botAppIdOrIdentity : botAppIdOrIdentity.aud;
			const identity = typeof botAppIdOrIdentity !== "string" ? botAppIdOrIdentity : CloudAdapter.createIdentity(botAppId);
			const context = new turnContext_1.TurnContext(this, agents_activity_1.Activity.getContinuationActivity(reference), identity);
			const connectorClient = await this.createConnectorClientWithIdentity(identity, context.activity);
			this.setConnectorClient(context, connectorClient);
			if (!context.activity.isAgenticRequest()) {
				const userTokenClient = await this.createUserTokenClient(identity);
				this.setUserTokenClient(context, userTokenClient);
			}
			await this.runMiddleware(context, logic);
		}
		/**
		* Processes the turn results and returns an InvokeResponse if applicable.
		* @param context - The TurnContext for the current turn.
		* @returns The InvokeResponse if applicable, otherwise undefined.
		*/
		processTurnResults(context) {
			logger.info("<--Sending back turn results");
			if (context.activity.deliveryMode === agents_activity_1.DeliveryModes.ExpectReplies) return {
				status: statusCodes_1.StatusCodes.OK,
				body: { activities: context.bufferedReplyActivities }
			};
			if (context.activity.type === agents_activity_1.ActivityTypes.Invoke) {
				const activityInvokeResponse = context.turnState.get(activityHandler_1.INVOKE_RESPONSE_KEY);
				if (!activityInvokeResponse) return { status: statusCodes_1.StatusCodes.NOT_IMPLEMENTED };
				return activityInvokeResponse.value;
			}
		}
		/**
		* Creates an activity to represent the result of creating a conversation.
		* @param createdConversationId - The ID of the created conversation.
		* @param channelId - The channel ID.
		* @param serviceUrl - The service URL.
		* @param conversationParameters - The conversation parameters.
		* @returns The created activity.
		*/
		createCreateActivity(createdConversationId, channelId, serviceUrl, conversationParameters) {
			const activity = new agents_activity_1.Activity(agents_activity_1.ActivityTypes.Event);
			activity.name = agents_activity_1.ActivityEventNames.CreateConversation;
			activity.channelId = channelId;
			activity.serviceUrl = serviceUrl;
			activity.id = createdConversationId !== null && createdConversationId !== void 0 ? createdConversationId : uuid.v4();
			activity.conversation = {
				conversationType: void 0,
				id: createdConversationId,
				isGroup: conversationParameters.isGroup,
				name: void 0,
				tenantId: conversationParameters.tenantId
			};
			activity.channelData = conversationParameters.channelData;
			activity.recipient = conversationParameters.agent;
			return activity;
		}
		/**
		* Creates a conversation.
		* @param agentAppId - The agent application ID.
		* @param channelId - The channel ID.
		* @param serviceUrl - The service URL.
		* @param audience - The audience.
		* @param conversationParameters - The conversation parameters.
		* @param logic - The logic to execute.
		* @returns A promise representing the completion of the create operation.
		*/
		async createConversationAsync(agentAppId, channelId, serviceUrl, audience, conversationParameters, logic) {
			if (typeof serviceUrl !== "string" || !serviceUrl) throw new TypeError("`serviceUrl` must be a non-empty string");
			if (!conversationParameters) throw new TypeError("`conversationParameters` must be defined");
			if (!logic) throw new TypeError("`logic` must be defined");
			const identity = CloudAdapter.createIdentity(audience);
			const restClient = await this.createConnectorClient(serviceUrl, audience, identity);
			const userTokenClient = await this.createUserTokenClient(identity);
			const createConversationResult = await restClient.createConversation(conversationParameters);
			const createActivity = this.createCreateActivity(createConversationResult.id, channelId, serviceUrl, conversationParameters);
			const context = new turnContext_1.TurnContext(this, createActivity, CloudAdapter.createIdentity(agentAppId));
			this.setConnectorClient(context, restClient);
			this.setUserTokenClient(context, userTokenClient);
			await this.runMiddleware(context, logic);
		}
		/**
		* @deprecated This function will not be supported in future versions.  Use TurnContext.turnState.get<ConnectorClient>(CloudAdapter.ConnectorClientKey).
		* Uploads an attachment.
		* @param context - The context for the turn.
		* @param conversationId - The conversation ID.
		* @param attachmentData - The attachment data.
		* @returns A promise representing the ResourceResponse for the uploaded attachment.
		*/
		async uploadAttachment(context, conversationId, attachmentData) {
			if (context === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ContextRequired);
			if (conversationId === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ConversationIdRequired);
			if (attachmentData === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.AttachmentDataRequired);
			return await context.turnState.get(this.ConnectorClientKey).uploadAttachment(conversationId, attachmentData);
		}
		/**
		* @deprecated This function will not be supported in future versions.  Use TurnContext.turnState.get<ConnectorClient>(CloudAdapter.ConnectorClientKey).
		* Gets attachment information.
		* @param context - The context for the turn.
		* @param attachmentId - The attachment ID.
		* @returns A promise representing the AttachmentInfo for the requested attachment.
		*/
		async getAttachmentInfo(context, attachmentId) {
			if (context === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ContextRequired);
			if (attachmentId === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.AttachmentIdRequired);
			return await context.turnState.get(this.ConnectorClientKey).getAttachmentInfo(attachmentId);
		}
		/**
		* @deprecated This function will not be supported in future versions.  Use TurnContext.turnState.get<ConnectorClient>(CloudAdapter.ConnectorClientKey).
		* Gets an attachment.
		* @param context - The context for the turn.
		* @param attachmentId - The attachment ID.
		* @param viewId - The view ID.
		* @returns A promise representing the NodeJS.ReadableStream for the requested attachment.
		*/
		async getAttachment(context, attachmentId, viewId) {
			if (context === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ContextRequired);
			if (attachmentId === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.AttachmentIdRequired);
			if (viewId === void 0) throw agents_activity_1.ExceptionHelper.generateException(Error, errorHelper_1.Errors.ViewIdRequired);
			return await context.turnState.get(this.ConnectorClientKey).getAttachment(attachmentId, viewId);
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/auth/authorization.js
var require_authorization = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.UserAuthorization = void 0;
	const logger_1 = require_logger();
	const turnState_1 = require_turnState();
	const logger = (0, logger_1.debug)("agents:authorization");
	/**
	* Class responsible for managing authorization and OAuth flows.
	* Handles multiple OAuth providers and manages the complete authentication lifecycle.
	*
	* @remarks
	* The Authorization class provides a centralized way to handle OAuth authentication
	* flows within the agent application. It supports multiple authentication handlers,
	* token exchange, on-behalf-of flows, and provides event handlers for success/failure scenarios.
	*
	* Key features:
	* - Multiple OAuth provider support
	* - Token caching and exchange
	* - On-behalf-of (OBO) token flows
	* - Sign-in success/failure event handling
	* - Automatic configuration from environment variables
	*
	*/
	var UserAuthorization = class {
		/**
		* Creates a new instance of Authorization.
		* @param manager The AuthorizationManager instance to manage handlers.
		*/
		constructor(manager) {
			this.manager = manager;
		}
		/**
		* Gets the token for a specific auth handler.
		*
		* @param context - The context object for the current turn.
		* @param authHandlerId - ID of the auth handler to use.
		* @returns A promise that resolves to the token response from the OAuth provider.
		* @throws {Error} If the auth handler is not configured.
		*
		* @remarks
		* This method retrieves an existing token for the specified auth handler.
		* The token may be cached and will be retrieved from the OAuth provider if needed.
		*
		* @example
		* ```typescript
		* const tokenResponse = await auth.getToken(context, 'microsoft');
		* if (tokenResponse.token) {
		*   console.log('User is authenticated');
		* }
		* ```
		*
		* @public
		*/
		async getToken(context, authHandlerId) {
			const { token } = await this.getHandler(authHandlerId).token(context);
			return { token };
		}
		/**
		* @internal
		* Internal implementation of exchangeToken method.
		* Handles both overloads and performs the actual token exchange logic.
		*/
		async exchangeToken(context, authHandlerId, options) {
			if (authHandlerId instanceof Array && typeof options === "string") {
				logger.warn("Authorization.exchangeToken(context, scopes, authHandlerId) is deprecated. Use Authorization.exchangeToken(context, authHandlerId, options) instead.");
				const [handlerId, handlerScopes] = [options, authHandlerId];
				return this.exchangeToken(context, handlerId, { scopes: handlerScopes });
			}
			if (typeof authHandlerId === "string" && typeof options !== "string") {
				const { token } = await this.getHandler(authHandlerId).token(context, options);
				return { token };
			}
			throw new Error("Invalid parameters for exchangeToken method.");
		}
		/**
		* Signs out the current user.
		*
		* @param context - The context object for the current turn.
		* @param state - The state object for the current turn.
		* @param authHandlerId - Optional ID of the auth handler to use for sign out. If not provided, signs out from all handlers.
		* @returns A promise that resolves when sign out is complete.
		* @throws {Error} If the specified auth handler is not configured.
		*
		* @remarks
		* This method clears the user's token and resets the authentication state.
		* If no specific authHandlerId is provided, it signs out from all configured handlers.
		* This ensures complete cleanup of authentication state across all providers.
		*
		* @example
		* ```typescript
		* // Sign out from specific handler
		* await auth.signOut(context, state, 'microsoft');
		*
		* // Sign out from all handlers
		* await auth.signOut(context, state);
		* ```
		*
		* @public
		*/
		async signOut(context, state, authHandlerId) {
			if (authHandlerId) await this.getHandler(authHandlerId).signout(context);
			else for (const handler of Object.values(this.manager.handlers)) await handler.signout(context);
		}
		/**
		* Sets a handler to be called when sign-in is successfully completed.
		*
		* @param handler - The handler function to call on successful sign-in.
		*
		* @remarks
		* This method allows you to register a callback that will be invoked whenever
		* a user successfully completes the authentication process. The handler receives
		* the turn context, state, and the ID of the auth handler that was used.
		*
		* @example
		* ```typescript
		* auth.onSignInSuccess(async (context, state, authHandlerId) => {
		*   await context.sendActivity(`Welcome! You signed in using ${authHandlerId}.`);
		*   // Perform any post-authentication setup
		* });
		* ```
		*
		* @public
		*/
		onSignInSuccess(handler) {
			for (const authHandler of Object.values(this.manager.handlers)) authHandler.onSuccess((context) => handler(context, new turnState_1.TurnState(), authHandler.id));
		}
		/**
		* Sets a handler to be called when sign-in fails.
		*
		* @param handler - The handler function to call on sign-in failure.
		*
		* @remarks
		* This method allows you to register a callback that will be invoked whenever
		* a user's authentication attempt fails. The handler receives the turn context,
		* state, auth handler ID, and an optional error message describing the failure.
		*
		* Common failure scenarios include:
		* - User cancels the authentication process
		* - Invalid credentials or expired tokens
		* - Network connectivity issues
		* - OAuth provider errors
		*
		* @example
		* ```typescript
		* auth.onSignInFailure(async (context, state, authHandlerId, errorMessage) => {
		*   await context.sendActivity(`Sign-in failed: ${errorMessage || 'Unknown error'}`);
		*   await context.sendActivity('Please try signing in again.');
		* });
		* ```
		*
		* @public
		*/
		onSignInFailure(handler) {
			for (const authHandler of Object.values(this.manager.handlers)) authHandler.onFailure((context, reason) => handler(context, new turnState_1.TurnState(), authHandler.id, reason));
		}
		/**
		* Gets the auth handler by ID or throws an error if not found.
		*
		* @param id - ID of the auth handler to retrieve.
		* @returns The auth handler instance.
		* @throws {Error} If the auth handler with the specified ID is not configured.
		* @private
		*/
		getHandler(id) {
			if (!Object.prototype.hasOwnProperty.call(this.manager.handlers, id)) throw new Error(`Cannot find auth handler with ID '${id}'. Ensure it is configured in the agent application options.`);
			return this.manager.handlers[id];
		}
	};
	exports.UserAuthorization = UserAuthorization;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/auth/types.js
var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AuthorizationHandlerStatus = void 0;
	/**
	* Represents the status of a handler registration attempt.
	*/
	var AuthorizationHandlerStatus;
	(function(AuthorizationHandlerStatus) {
		/** The handler has approved the request - validation passed */
		AuthorizationHandlerStatus["APPROVED"] = "approved";
		/** The handler registration is pending further action */
		AuthorizationHandlerStatus["PENDING"] = "pending";
		/** The handler has rejected the request - validation failed */
		AuthorizationHandlerStatus["REJECTED"] = "rejected";
		/** The handler has ignored the request - no action taken */
		AuthorizationHandlerStatus["IGNORED"] = "ignored";
		/** The handler requires revalidation */
		AuthorizationHandlerStatus["REVALIDATE"] = "revalidate";
	})(AuthorizationHandlerStatus || (exports.AuthorizationHandlerStatus = AuthorizationHandlerStatus = {}));
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/messageFactory.js
var require_messageFactory = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MessageFactory = void 0;
	/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */
	const agents_activity_1 = require_src$2();
	/**
	* A factory class for creating various types of message activities.
	*/
	var MessageFactory = class {
		/**
		* Creates a text message activity.
		* @param text The text of the message.
		* @param speak (Optional) The text to be spoken by the agent.
		* @param inputHint (Optional) The input hint for the message.
		* @returns The created text message activity.
		*/
		static text(text, speak, inputHint) {
			let msgObj = {};
			msgObj = {
				type: agents_activity_1.ActivityTypes.Message,
				text,
				inputHint: inputHint || agents_activity_1.InputHints.AcceptingInput
			};
			if (speak) msgObj = {
				...msgObj,
				speak
			};
			return agents_activity_1.Activity.fromObject(msgObj);
		}
		/**
		* Creates a message activity with suggested actions.
		* @param actions The suggested actions.
		* @param text (Optional) The text of the message.
		* @param speak (Optional) The text to be spoken by the agent.
		* @param inputHint (Optional) The input hint for the message.
		* @returns The created message activity with suggested actions.
		*/
		static suggestedActions(actions, text, speak, inputHint) {
			const formattedActions = (actions || []).map((action) => {
				if (typeof action === "object") return action;
				else return {
					type: agents_activity_1.ActionTypes.ImBack,
					value: { text: action.toString() },
					title: action.toString(),
					channelData: void 0
				};
			});
			const msgObj = {
				type: agents_activity_1.ActivityTypes.Message,
				inputHint: inputHint || agents_activity_1.InputHints.AcceptingInput,
				suggestedActions: {
					actions: formattedActions,
					to: []
				}
			};
			const msg = agents_activity_1.Activity.fromObject(msgObj);
			if (text) msg.text = text;
			if (speak) msg.speak = speak;
			return msg;
		}
		/**
		* Creates a message activity with a single attachment.
		* @param attachment The attachment to include in the message.
		* @param text (Optional) The text of the message.
		* @param speak (Optional) The text to be spoken by the agent.
		* @param inputHint (Optional) The input hint for the message.
		* @returns The created message activity with an attachment.
		*/
		static attachment(attachment, text, speak, inputHint) {
			return attachmentActivity(agents_activity_1.AttachmentLayoutTypes.List, [attachment], text, speak, inputHint);
		}
		/**
		* Creates a message activity with a list of attachments.
		* @param attachments The list of attachments to include in the message.
		* @param text (Optional) The text of the message.
		* @param speak (Optional) The text to be spoken by the agent.
		* @param inputHint (Optional) The input hint for the message.
		* @returns The created message activity with a list of attachments.
		*/
		static list(attachments, text, speak, inputHint) {
			return attachmentActivity(agents_activity_1.AttachmentLayoutTypes.List, attachments, text, speak, inputHint);
		}
		/**
		* Creates a message activity with a carousel of attachments.
		* @param attachments The list of attachments to include in the carousel.
		* @param text (Optional) The text of the message.
		* @param speak (Optional) The text to be spoken by the agent.
		* @param inputHint (Optional) The input hint for the message.
		* @returns The created message activity with a carousel of attachments.
		*/
		static carousel(attachments, text, speak, inputHint) {
			return attachmentActivity(agents_activity_1.AttachmentLayoutTypes.Carousel, attachments, text, speak, inputHint);
		}
		/**
		* Creates a message activity with content from a URL.
		* @param url The URL of the content.
		* @param contentType The content type of the attachment.
		* @param name (Optional) The name of the attachment.
		* @param text (Optional) The text of the message.
		* @param speak (Optional) The text to be spoken by the agent.
		* @param inputHint (Optional) The input hint for the message.
		* @returns The created message activity with content from a URL.
		*/
		static contentUrl(url, contentType, name, text, speak, inputHint) {
			const a = {
				contentType,
				contentUrl: url
			};
			if (name) a.name = name;
			return attachmentActivity(agents_activity_1.AttachmentLayoutTypes.List, [a], text, speak, inputHint);
		}
	};
	exports.MessageFactory = MessageFactory;
	/**
	* Creates a message activity with attachments.
	* @param attachmentLayout The layout for the attachments.
	* @param attachments The list of attachments to include in the message.
	* @param text (Optional) The text of the message.
	* @param speak (Optional) The text to be spoken by the agent.
	* @param inputHint (Optional) The input hint for the message.
	* @returns The created message activity with attachments.
	*/
	function attachmentActivity(attachmentLayout, attachments, text, speak, inputHint) {
		const msgObj = {
			type: agents_activity_1.ActivityTypes.Message,
			attachmentLayout,
			attachments,
			inputHint: inputHint || agents_activity_1.InputHints.AcceptingInput
		};
		const msg = agents_activity_1.Activity.fromObject(msgObj);
		if (text) msg.text = text;
		if (speak) msg.speak = speak;
		return msg;
	}
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/animationCard.js
var require_animationCard = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/audioCard.js
var require_audioCard = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/cardFactory.js
var require_cardFactory = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.CardFactory = void 0;
	const agents_activity_1 = require_src$2();
	/**
	* Factory class for creating various types of cards.
	*/
	var CardFactory = class CardFactory {
		/**
		* Creates an adaptive card attachment.
		* @param card The adaptive card content.
		* @returns The adaptive card attachment.
		*/
		static adaptiveCard(card) {
			return {
				contentType: CardFactory.contentTypes.adaptiveCard,
				content: card
			};
		}
		/**
		* Creates an animation card attachment.
		* @param title The title of the card.
		* @param media The media URLs or objects.
		* @param buttons The optional buttons for the card.
		* @param other Additional properties for the card.
		* @returns The animation card attachment.
		*/
		static animationCard(title, media, buttons, other) {
			return CardFactory.mediaCard(CardFactory.contentTypes.animationCard, title, media, buttons, other);
		}
		/**
		* Creates an audio card attachment.
		* @param title The title of the card.
		* @param media The media URLs or objects.
		* @param buttons The optional buttons for the card.
		* @param other Additional properties for the card.
		* @returns The audio card attachment.
		*/
		static audioCard(title, media, buttons, other) {
			return CardFactory.mediaCard(CardFactory.contentTypes.audioCard, title, media, buttons, other);
		}
		/**
		* Creates a hero card attachment.
		* @param title The title of the card.
		* @param text The optional text for the card.
		* @param images The optional images for the card.
		* @param buttons The optional buttons for the card.
		* @param other Additional properties for the card.
		* @returns The hero card attachment.
		*/
		static heroCard(title, text, images, buttons, other) {
			const a = CardFactory.thumbnailCard(title, text, images, buttons, other);
			a.contentType = CardFactory.contentTypes.heroCard;
			return a;
		}
		/**
		* Creates a receipt card attachment.
		* @param card The receipt card content.
		* @returns The receipt card attachment.
		*/
		static receiptCard(card) {
			return {
				contentType: CardFactory.contentTypes.receiptCard,
				content: card
			};
		}
		/**
		* Creates an O365 connector card attachment.
		* @param card The O365 connector card content.
		* @returns The O365 connector card attachment.
		*/
		static o365ConnectorCard(card) {
			return {
				contentType: CardFactory.contentTypes.o365ConnectorCard,
				content: card
			};
		}
		/**
		* Creates a thumbnail card attachment.
		* @param title The title of the card.
		* @param text The optional text for the card.
		* @param images The optional images for the card.
		* @param buttons The optional buttons for the card.
		* @param other Additional properties for the card.
		* @returns The thumbnail card attachment.
		*/
		static thumbnailCard(title, text, images, buttons, other) {
			if (typeof text !== "string") {
				other = buttons;
				buttons = images;
				images = text;
				text = void 0;
			}
			const card = { ...other };
			if (title) card.title = title;
			if (text) card.text = text;
			if (images) card.images = CardFactory.images(images);
			if (buttons) card.buttons = CardFactory.actions(buttons);
			return {
				contentType: CardFactory.contentTypes.thumbnailCard,
				content: card
			};
		}
		/**
		* Creates a video card attachment.
		* @param title The title of the card.
		* @param media The media URLs or objects.
		* @param buttons The optional buttons for the card.
		* @param other Additional properties for the card.
		* @returns The video card attachment.
		*/
		static videoCard(title, media, buttons, other) {
			return CardFactory.mediaCard(CardFactory.contentTypes.videoCard, title, media, buttons, other);
		}
		/**
		* Converts an array of image URLs or objects to an array of CardImage objects.
		* @param images The image URLs or objects.
		* @returns The array of CardImage objects.
		*/
		static images(images) {
			const list = [];
			(images || []).forEach((img) => {
				if (typeof img === "object") list.push(img);
				else list.push({ url: img });
			});
			return list;
		}
		/**
		* Converts an array of action URLs or objects to an array of CardAction objects.
		* @param actions The action URLs or objects.
		* @returns The array of CardAction objects.
		*/
		static actions(actions) {
			const list = [];
			(actions || []).forEach((a) => {
				if (typeof a === "object") list.push(a);
				else list.push({
					type: agents_activity_1.ActionTypes.ImBack,
					value: a.toString(),
					title: a.toString(),
					channelData: void 0
				});
			});
			return list;
		}
		/**
		* Creates an OAuth card attachment.
		* @param connectionName The connection name.
		* @param title The title of the card.
		* @param text The optional text for the card.
		* @param signingResource The signing resource.
		* @param enableSso The option to enable SSO when authenticating using AAD. Defaults to true.
		* @returns The OAuth card attachment.
		*/
		static oauthCard(connectionName, title, text, signingResource, enableSso = true) {
			const card = {
				buttons: [{
					type: agents_activity_1.ActionTypes.Signin,
					title,
					value: signingResource.signInLink,
					channelData: void 0
				}],
				connectionName,
				tokenExchangeResource: enableSso ? signingResource.tokenExchangeResource : void 0,
				tokenPostResource: signingResource.tokenPostResource
			};
			if (text) card.text = text;
			return {
				contentType: CardFactory.contentTypes.oauthCard,
				content: card
			};
		}
		/**
		* Creates a sign-in card attachment.
		* @param title The title of the card.
		* @param url The URL for the sign-in button.
		* @param text The optional text for the card.
		* @returns The sign-in card attachment.
		*/
		static signinCard(title, url, text) {
			const card = { buttons: [{
				type: agents_activity_1.ActionTypes.Signin,
				title,
				value: url,
				channelData: void 0
			}] };
			if (text) card.text = text;
			return {
				contentType: CardFactory.contentTypes.signinCard,
				content: card
			};
		}
		/**
		* Converts an array of media URLs or objects to an array of MediaUrl objects.
		* @param links The media URLs or objects.
		* @returns The array of MediaUrl objects.
		*/
		static media(links) {
			const list = [];
			(links || []).forEach((lnk) => {
				if (typeof lnk === "object") list.push(lnk);
				else list.push({ url: lnk });
			});
			return list;
		}
		/**
		* Creates a media card attachment.
		* @param contentType The content type of the card.
		* @param title The title of the card.
		* @param media The media URLs or objects.
		* @param buttons The optional buttons for the card.
		* @param other Additional properties for the card.
		* @returns The media card attachment.
		*/
		static mediaCard(contentType, title, media, buttons, other) {
			const card = { ...other };
			if (title) card.title = title;
			card.media = CardFactory.media(media);
			if (buttons) card.buttons = CardFactory.actions(buttons);
			return {
				contentType,
				content: card
			};
		}
	};
	exports.CardFactory = CardFactory;
	/**
	* The content types supported by the card factory.
	*/
	CardFactory.contentTypes = {
		adaptiveCard: "application/vnd.microsoft.card.adaptive",
		animationCard: "application/vnd.microsoft.card.animation",
		audioCard: "application/vnd.microsoft.card.audio",
		heroCard: "application/vnd.microsoft.card.hero",
		receiptCard: "application/vnd.microsoft.card.receipt",
		o365ConnectorCard: "application/vnd.microsoft.teams.card.o365connector",
		thumbnailCard: "application/vnd.microsoft.card.thumbnail",
		videoCard: "application/vnd.microsoft.card.video",
		oauthCard: "application/vnd.microsoft.card.oauth",
		signinCard: "application/vnd.microsoft.card.signin"
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/cardImage.js
var require_cardImage = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/fact.js
var require_fact = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/heroCard.js
var require_heroCard = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/mediaUrl.js
var require_mediaUrl = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/o365ConnectorCard.js
var require_o365ConnectorCard = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/o365ConnectorCardActionBase.js
var require_o365ConnectorCardActionBase = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/o365ConnectorCardFact.js
var require_o365ConnectorCardFact = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/o365ConnectorCardImage.js
var require_o365ConnectorCardImage = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/o365ConnectorCardSection.js
var require_o365ConnectorCardSection = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/receiptCard.js
var require_receiptCard = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/receiptItem.js
var require_receiptItem = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/taskModuleAction.js
var require_taskModuleAction = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.TaskModuleAction = void 0;
	/**
	* Represents a task module action.
	*/
	var TaskModuleAction = class {
		constructor(title, value) {
			this.type = "invoke";
			this.title = title;
			let data;
			if (!value) data = JSON.parse("{}");
			else if (typeof value === "object") data = value;
			else data = JSON.parse(value);
			data.type = "task/fetch";
			this.value = data;
		}
	};
	exports.TaskModuleAction = TaskModuleAction;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/thumbnailCard.js
var require_thumbnailCard = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/videoCard.js
var require_videoCard = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/thumbnailUrl.js
var require_thumbnailUrl = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/adaptiveCard.js
var require_adaptiveCard = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/cards/index.js
var require_cards = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$10) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$10, p)) __createBinding(exports$10, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_animationCard(), exports);
	__exportStar(require_audioCard(), exports);
	__exportStar(require_cardFactory(), exports);
	__exportStar(require_cardImage(), exports);
	__exportStar(require_fact(), exports);
	__exportStar(require_heroCard(), exports);
	__exportStar(require_mediaUrl(), exports);
	__exportStar(require_o365ConnectorCard(), exports);
	__exportStar(require_o365ConnectorCardActionBase(), exports);
	__exportStar(require_o365ConnectorCardFact(), exports);
	__exportStar(require_o365ConnectorCardImage(), exports);
	__exportStar(require_o365ConnectorCardSection(), exports);
	__exportStar(require_receiptCard(), exports);
	__exportStar(require_receiptItem(), exports);
	__exportStar(require_taskModuleAction(), exports);
	__exportStar(require_thumbnailCard(), exports);
	__exportStar(require_videoCard(), exports);
	__exportStar(require_thumbnailUrl(), exports);
	__exportStar(require_adaptiveCard(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/auth/handlerStorage.js
var require_handlerStorage = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.HandlerStorage = void 0;
	exports.HandlerStorage = class HandlerStorage {
		/**
		* Creates an instance of the HandlerStorage.
		* @param storage The storage provider.
		* @param context The turn context.
		*/
		constructor(storage, context) {
			this.storage = storage;
			this.context = context;
		}
		/**
		* Gets the unique key for a handler session.
		*/
		get key() {
			var _a, _b, _c;
			const channelId = (_a = this.context.activity.channelId) === null || _a === void 0 ? void 0 : _a.trim();
			const userId = (_c = (_b = this.context.activity.from) === null || _b === void 0 ? void 0 : _b.id) === null || _c === void 0 ? void 0 : _c.trim();
			if (!channelId || !userId) throw new Error(`Both 'activity.channelId' and 'activity.from.id' are required to generate the ${HandlerStorage.name} key.`);
			return `auth/${channelId}/${userId}`;
		}
		/**
		* Reads the active handler state from storage.
		*/
		async read() {
			const ongoing = await this.storage.read([this.key]);
			return ongoing === null || ongoing === void 0 ? void 0 : ongoing[this.key];
		}
		/**
		* Writes handler state to storage.
		*/
		write(data) {
			return this.storage.write({ [this.key]: data });
		}
		/**
		* Deletes handler state from storage.
		*/
		async delete() {
			try {
				await this.storage.delete([this.key]);
			} catch (error) {
				if (error instanceof Error && "code" in error && error.code === 404) return;
				throw error;
			}
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/auth/handlers/azureBotAuthorization.js
var require_azureBotAuthorization = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AzureBotAuthorization = void 0;
	const logger_1 = require_logger();
	const types_1 = require_types();
	const messageFactory_1 = require_messageFactory();
	const cards_1 = require_cards();
	const jsonwebtoken_1 = __importDefault(require_jsonwebtoken());
	const handlerStorage_1 = require_handlerStorage();
	const agents_activity_1 = require_src$2();
	const logger = (0, logger_1.debug)("agents:authorization:azurebot");
	const DEFAULT_SIGN_IN_ATTEMPTS = 2;
	var Category;
	(function(Category) {
		Category["SIGNIN"] = "signin";
		Category["UNKNOWN"] = "unknown";
	})(Category || (Category = {}));
	exports.AzureBotAuthorization = class AzureBotAuthorization {
		/**
		* Creates an instance of the AzureBotAuthorization.
		* @param id The unique identifier for the handler.
		* @param options The settings for the handler.
		* @param app The agent application instance.
		*/
		constructor(id, options, settings) {
			this.id = id;
			this.settings = settings;
			this._key = `${AzureBotAuthorization.name}/${this.id}`;
			/**
			* Predefined messages with dynamic placeholders.
			*/
			this.messages = {
				invalidCode: (code) => {
					var _a, _b;
					return ((_b = (_a = this._options.messages) === null || _a === void 0 ? void 0 : _a.invalidCode) !== null && _b !== void 0 ? _b : "Invalid **{code}** code entered. Please try again with a new sign-in request.").replaceAll("{code}", code);
				},
				invalidCodeFormat: (attemptsLeft) => {
					var _a, _b;
					return ((_b = (_a = this._options.messages) === null || _a === void 0 ? void 0 : _a.invalidCodeFormat) !== null && _b !== void 0 ? _b : "Please enter a valid **6-digit** code format (_e.g. 123456_).\r\n**{attemptsLeft} attempt(s) left...**").replaceAll("{attemptsLeft}", attemptsLeft.toString());
				},
				maxAttemptsExceeded: (maxAttempts) => {
					var _a, _b;
					return ((_b = (_a = this._options.messages) === null || _a === void 0 ? void 0 : _a.maxAttemptsExceeded) !== null && _b !== void 0 ? _b : "You have exceeded the maximum number of sign-in attempts ({maxAttempts}). Please try again with a new sign-in request.").replaceAll("{maxAttempts}", maxAttempts.toString());
				}
			};
			if (!this.settings.storage) throw new Error(this.prefix("The 'storage' option is not available in the app options. Ensure that the app is properly configured."));
			if (!this.settings.connections) throw new Error(this.prefix("The 'connections' option is not available in the app options. Ensure that the app is properly configured."));
			this._options = this.loadOptions(options);
		}
		/**
		* Loads and validates the authorization handler options.
		*/
		loadOptions(settings) {
			var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
			const result = {
				name: (_a = settings.name) !== null && _a !== void 0 ? _a : process.env[`${this.id}_connectionName`],
				title: (_c = (_b = settings.title) !== null && _b !== void 0 ? _b : process.env[`${this.id}_connectionTitle`]) !== null && _c !== void 0 ? _c : "Sign-in",
				text: (_e = (_d = settings.text) !== null && _d !== void 0 ? _d : process.env[`${this.id}_connectionText`]) !== null && _e !== void 0 ? _e : "Please sign-in to continue",
				maxAttempts: (_f = settings.maxAttempts) !== null && _f !== void 0 ? _f : parseInt(process.env[`${this.id}_maxAttempts`]),
				messages: {
					invalidCode: (_h = (_g = settings.messages) === null || _g === void 0 ? void 0 : _g.invalidCode) !== null && _h !== void 0 ? _h : process.env[`${this.id}_messages_invalidCode`],
					invalidCodeFormat: (_k = (_j = settings.messages) === null || _j === void 0 ? void 0 : _j.invalidCodeFormat) !== null && _k !== void 0 ? _k : process.env[`${this.id}_messages_invalidCodeFormat`],
					maxAttemptsExceeded: (_m = (_l = settings.messages) === null || _l === void 0 ? void 0 : _l.maxAttemptsExceeded) !== null && _m !== void 0 ? _m : process.env[`${this.id}_messages_maxAttemptsExceeded`]
				},
				obo: {
					connection: (_p = (_o = settings.obo) === null || _o === void 0 ? void 0 : _o.connection) !== null && _p !== void 0 ? _p : process.env[`${this.id}_obo_connection`],
					scopes: (_r = (_q = settings.obo) === null || _q === void 0 ? void 0 : _q.scopes) !== null && _r !== void 0 ? _r : this.loadScopes(process.env[`${this.id}_obo_scopes`])
				},
				enableSso: process.env[`${this.id}_enableSso`] !== "false"
			};
			if (!result.name) throw new Error(this.prefix(`The 'name' property or '${this.id}_connectionName' env variable is required to initialize the handler.`));
			return result;
		}
		/**
		* Maximum number of attempts for magic code entry.
		*/
		get maxAttempts() {
			const attempts = this._options.maxAttempts;
			const result = typeof attempts === "number" && Number.isFinite(attempts) ? Math.round(attempts) : NaN;
			return result > 0 ? result : DEFAULT_SIGN_IN_ATTEMPTS;
		}
		/**
		* Sets a handler to be called when a user successfully signs in.
		* @param callback The callback function to be invoked on successful sign-in.
		*/
		onSuccess(callback) {
			this._onSuccess = callback;
		}
		/**
		* Sets a handler to be called when a user fails to sign in.
		* @param callback The callback function to be invoked on sign-in failure.
		*/
		onFailure(callback) {
			this._onFailure = callback;
		}
		/**
		* Retrieves the token for the user, optionally using on-behalf-of flow for specified scopes.
		* @param context The turn context.
		* @param options Optional options for token acquisition, including connection and scopes for on-behalf-of flow.
		* @returns The token response containing the token or undefined if not available.
		*/
		async token(context, options) {
			var _a;
			let { token } = this.getContext(context);
			if (!(token === null || token === void 0 ? void 0 : token.trim())) {
				const { activity } = context;
				const { tokenResponse } = await (await this.getUserTokenClient(context)).getTokenOrSignInResource((_a = activity.from) === null || _a === void 0 ? void 0 : _a.id, this._options.name, activity.channelId, activity.getConversationReference(), activity.relatesTo, "");
				token = tokenResponse === null || tokenResponse === void 0 ? void 0 : tokenResponse.token;
			}
			if (!(token === null || token === void 0 ? void 0 : token.trim())) return { token: void 0 };
			return await this.handleOBO(token, options);
		}
		/**
		* Signs out the user from the service.
		* @param context The turn context.
		* @returns True if the signout was successful, false otherwise.
		*/
		async signout(context) {
			var _a;
			const user = (_a = context.activity.from) === null || _a === void 0 ? void 0 : _a.id;
			const channel = context.activity.channelId;
			const connection = this._options.name;
			if (!channel || !user) throw new Error(this.prefix("Both 'activity.channelId' and 'activity.from.id' are required to perform signout."));
			logger.debug(this.prefix(`Signing out User '${user}' from => Channel: '${channel}', Connection: '${connection}'`), context.activity);
			await (await this.getUserTokenClient(context)).signOut(user, connection, channel);
			return true;
		}
		/**
		* Initiates the sign-in process for the handler.
		* @param context The turn context.
		* @param active Optional active handler data.
		* @returns The status of the sign-in attempt.
		*/
		async signin(context, active) {
			var _a, _b, _c;
			const { activity } = context;
			const [category] = (_b = (_a = activity.name) === null || _a === void 0 ? void 0 : _a.split("/")) !== null && _b !== void 0 ? _b : [Category.UNKNOWN];
			const storage = new handlerStorage_1.HandlerStorage(this.settings.storage, context);
			if (!active) return this.setToken(storage, context);
			logger.debug(this.prefix("Sign-in active session detected"), active.activity);
			if (active.attemptsLeft <= 0) {
				logger.warn(this.prefix("Maximum sign-in attempts exceeded"), activity);
				await context.sendActivity(messageFactory_1.MessageFactory.text(this.messages.maxAttemptsExceeded(this.maxAttempts)));
				return types_1.AuthorizationHandlerStatus.REJECTED;
			}
			if (category === Category.SIGNIN) {
				await storage.write({
					...active,
					category
				});
				const status = await this.handleSignInActivities(context);
				if (status !== types_1.AuthorizationHandlerStatus.IGNORED) return status;
			} else if (active.category === Category.SIGNIN) {
				logger.warn(this.prefix("The incoming activity will be revalidated due to a change in the sign-in flow"), activity);
				return types_1.AuthorizationHandlerStatus.REVALIDATE;
			}
			const { status, code } = await this.codeVerification(storage, context, active);
			if (status !== types_1.AuthorizationHandlerStatus.APPROVED) return status;
			try {
				const result = await this.setToken(storage, context, active, code);
				if (result !== types_1.AuthorizationHandlerStatus.APPROVED) {
					await this.sendInvokeResponse(context, { status: 404 });
					return result;
				}
				await this.sendInvokeResponse(context, { status: 200 });
				await ((_c = this._onSuccess) === null || _c === void 0 ? void 0 : _c.call(this, context));
				return result;
			} catch (error) {
				await this.sendInvokeResponse(context, { status: 500 });
				if (error instanceof Error) error.message = this.prefix(error.message);
				throw error;
			}
		}
		/**
		* Handles on-behalf-of token acquisition.
		*/
		async handleOBO(token, options) {
			var _a, _b, _c;
			const oboConnection = (_a = options === null || options === void 0 ? void 0 : options.connection) !== null && _a !== void 0 ? _a : (_b = this._options.obo) === null || _b === void 0 ? void 0 : _b.connection;
			const oboScopes = (options === null || options === void 0 ? void 0 : options.scopes) && options.scopes.length > 0 ? options.scopes : (_c = this._options.obo) === null || _c === void 0 ? void 0 : _c.scopes;
			if (!oboScopes || oboScopes.length === 0) return { token };
			if (!this.isExchangeable(token)) throw new Error(this.prefix("The current token is not exchangeable for an on-behalf-of flow. Ensure the token audience starts with 'api://'."));
			try {
				const newToken = await (oboConnection ? this.settings.connections.getConnection(oboConnection) : this.settings.connections.getDefaultConnection()).acquireTokenOnBehalfOf(oboScopes, token);
				logger.debug(this.prefix("Successfully acquired on-behalf-of token"), {
					connection: oboConnection,
					scopes: oboScopes
				});
				return { token: newToken };
			} catch (error) {
				logger.error(this.prefix("Failed to exchange on-behalf-of token"), {
					connection: oboConnection,
					scopes: oboScopes
				}, error);
				return { token: void 0 };
			}
		}
		/**
		* Checks if a token is exchangeable for an on-behalf-of flow.
		*/
		isExchangeable(token) {
			if (!token || typeof token !== "string") return false;
			const payload = jsonwebtoken_1.default.decode(token);
			return (Array.isArray(payload.aud) ? payload.aud : [payload.aud]).some((aud) => typeof aud === "string" && aud.startsWith("api://"));
		}
		/**
		* Sets the token from the token response or initiates the sign-in flow.
		*/
		async setToken(storage, context, active, code) {
			var _a;
			const { activity } = context;
			const { tokenResponse, signInResource } = await (await this.getUserTokenClient(context)).getTokenOrSignInResource((_a = activity.from) === null || _a === void 0 ? void 0 : _a.id, this._options.name, activity.channelId, activity.getConversationReference(), activity.relatesTo, code !== null && code !== void 0 ? code : "");
			if (!tokenResponse && active) {
				logger.warn(this.prefix("Invalid code entered. Restarting sign-in flow"), activity);
				await context.sendActivity(messageFactory_1.MessageFactory.text(this.messages.invalidCode(code !== null && code !== void 0 ? code : "")));
				return types_1.AuthorizationHandlerStatus.REJECTED;
			}
			if (!tokenResponse) {
				logger.debug(this.prefix("Cannot find token. Sending sign-in card"), activity);
				const oCard = cards_1.CardFactory.oauthCard(this._options.name, this._options.title, this._options.text, signInResource, this._options.enableSso);
				await context.sendActivity(messageFactory_1.MessageFactory.attachment(oCard));
				await storage.write({
					activity,
					id: this.id,
					...active !== null && active !== void 0 ? active : {},
					attemptsLeft: this.maxAttempts
				});
				return types_1.AuthorizationHandlerStatus.PENDING;
			}
			logger.debug(this.prefix("Successfully acquired token"), activity);
			this.setContext(context, { token: tokenResponse.token });
			return types_1.AuthorizationHandlerStatus.APPROVED;
		}
		/**
		* Handles sign-in related activities.
		*/
		async handleSignInActivities(context) {
			var _a, _b, _c, _d;
			const { activity } = context;
			if (activity.name === "signin/verifyState") return types_1.AuthorizationHandlerStatus.IGNORED;
			const userTokenClient = await this.getUserTokenClient(context);
			if (activity.name === "signin/tokenExchange") {
				const tokenExchangeInvokeRequest = activity.value;
				const tokenExchangeRequest = { token: tokenExchangeInvokeRequest === null || tokenExchangeInvokeRequest === void 0 ? void 0 : tokenExchangeInvokeRequest.token };
				if (!(tokenExchangeRequest === null || tokenExchangeRequest === void 0 ? void 0 : tokenExchangeRequest.token)) {
					const reason = "The Agent received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.";
					await this.sendInvokeResponse(context, {
						status: 400,
						body: {
							connectionName: this._options.name,
							failureDetail: reason
						}
					});
					logger.error(this.prefix(reason));
					await ((_a = this._onFailure) === null || _a === void 0 ? void 0 : _a.call(this, context, reason));
					return types_1.AuthorizationHandlerStatus.REJECTED;
				}
				if (tokenExchangeInvokeRequest.connectionName !== this._options.name) {
					const reason = `The Agent received an InvokeActivity with a TokenExchangeInvokeRequest for a different connection name ('${tokenExchangeInvokeRequest.connectionName}') than expected ('${this._options.name}').`;
					await this.sendInvokeResponse(context, {
						status: 400,
						body: {
							id: tokenExchangeInvokeRequest.id,
							connectionName: this._options.name,
							failureDetail: reason
						}
					});
					logger.error(this.prefix(reason));
					await ((_b = this._onFailure) === null || _b === void 0 ? void 0 : _b.call(this, context, reason));
					return types_1.AuthorizationHandlerStatus.REJECTED;
				}
				const { token } = await userTokenClient.exchangeTokenAsync((_c = activity.from) === null || _c === void 0 ? void 0 : _c.id, this._options.name, activity.channelId, tokenExchangeRequest);
				if (!token) {
					const reason = "The MS Teams token service didn't send back the exchanged token. Waiting for MS Teams to send another signin/tokenExchange request. After multiple failed attempts, the user will be asked to enter the magic code.";
					await this.sendInvokeResponse(context, {
						status: 412,
						body: {
							id: tokenExchangeInvokeRequest.id,
							connectionName: this._options.name,
							failureDetail: reason
						}
					});
					logger.debug(this.prefix(reason));
					return types_1.AuthorizationHandlerStatus.PENDING;
				}
				await this.sendInvokeResponse(context, {
					status: 200,
					body: {
						id: tokenExchangeInvokeRequest.id,
						connectionName: this._options.name
					}
				});
				logger.debug(this.prefix("Successfully exchanged token"));
				this.setContext(context, { token });
				await ((_d = this._onSuccess) === null || _d === void 0 ? void 0 : _d.call(this, context));
				return types_1.AuthorizationHandlerStatus.APPROVED;
			}
			if (activity.name === "signin/failure") {
				await this.sendInvokeResponse(context, { status: 200 });
				const reason = "Failed to sign-in";
				const value = activity.value;
				logger.error(this.prefix(reason), value, activity);
				if (this._onFailure) await this._onFailure(context, value.message || reason);
				else await context.sendActivity(messageFactory_1.MessageFactory.text(`${reason}. Please try again.`));
				return types_1.AuthorizationHandlerStatus.REJECTED;
			}
			logger.error(this.prefix(`Unknown sign-in activity name: ${activity.name}`), activity);
			return types_1.AuthorizationHandlerStatus.REJECTED;
		}
		/**
		* Verifies the magic code provided by the user.
		*/
		async codeVerification(storage, context, active) {
			if (!active) {
				logger.debug(this.prefix("No active session found. Skipping code verification."), context.activity);
				return { status: types_1.AuthorizationHandlerStatus.IGNORED };
			}
			const { activity } = context;
			let state = activity.text;
			if (activity.name === "signin/verifyState") {
				logger.debug(this.prefix("Getting code from activity.value"), activity);
				const { state: teamsState } = activity.value;
				state = teamsState;
			}
			if (state === "CancelledByUser") {
				await this.sendInvokeResponse(context, { status: 200 });
				logger.warn(this.prefix("Sign-in process was cancelled by the user"), activity);
				return { status: types_1.AuthorizationHandlerStatus.REJECTED };
			}
			if (!(state === null || state === void 0 ? void 0 : state.match(/^\d{6}$/))) {
				logger.warn(this.prefix(`Invalid magic code entered. Attempts left: ${active.attemptsLeft}`), activity);
				await context.sendActivity(messageFactory_1.MessageFactory.text(this.messages.invalidCodeFormat(active.attemptsLeft)));
				await storage.write({
					...active,
					attemptsLeft: active.attemptsLeft - 1
				});
				return { status: types_1.AuthorizationHandlerStatus.PENDING };
			}
			await this.sendInvokeResponse(context, { status: 200 });
			logger.debug(this.prefix("Code verification successful"), activity);
			return {
				status: types_1.AuthorizationHandlerStatus.APPROVED,
				code: state
			};
		}
		/**
		* Sets the authorization context in the turn state.
		*/
		setContext(context, data) {
			return context.turnState.set(this._key, () => data);
		}
		/**
		* Gets the authorization context from the turn state.
		*/
		getContext(context) {
			var _a;
			const result = context.turnState.get(this._key);
			return (_a = result === null || result === void 0 ? void 0 : result()) !== null && _a !== void 0 ? _a : { token: void 0 };
		}
		/**
		* Gets the user token client from the turn context.
		*/
		async getUserTokenClient(context) {
			const userTokenClient = context.turnState.get(context.adapter.UserTokenClientKey);
			if (!userTokenClient) throw new Error(this.prefix("The 'userTokenClient' is not available in the adapter. Ensure that the adapter supports user token operations."));
			return userTokenClient;
		}
		/**
		* Sends an InvokeResponse activity if the channel is Microsoft Teams, including Copilot within MS Teams.
		*/
		sendInvokeResponse(context, response) {
			const [parentChannel] = agents_activity_1.Activity.parseChannelId(context.activity.channelId);
			if (parentChannel !== agents_activity_1.Channels.Msteams) return Promise.resolve();
			return context.sendActivity(agents_activity_1.Activity.fromObject({
				type: agents_activity_1.ActivityTypes.InvokeResponse,
				value: response
			}));
		}
		/**
		* Prefixes a message with the handler ID.
		*/
		prefix(message) {
			return `[handler:${this.id}] ${message}`;
		}
		/**
		* Loads the OAuth scopes from the environment variables.
		*/
		loadScopes(value) {
			var _a;
			return (_a = value === null || value === void 0 ? void 0 : value.split(",").reduce((acc, scope) => {
				const trimmed = scope.trim();
				if (trimmed) acc.push(trimmed);
				return acc;
			}, [])) !== null && _a !== void 0 ? _a : [];
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/auth/handlers/agenticAuthorization.js
var require_agenticAuthorization = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AgenticAuthorization = void 0;
	const agents_activity_1 = require_src$2();
	const types_1 = require_types();
	const logger = (0, agents_activity_1.debug)("agents:authorization:agentic");
	exports.AgenticAuthorization = class AgenticAuthorization {
		/**
		* Creates an instance of the AgenticAuthorization class.
		* @param id The unique identifier for the authorization handler.
		* @param options The options for configuring the authorization handler.
		* @param settings The settings for the authorization handler.
		*/
		constructor(id, options, settings) {
			this.id = id;
			this.settings = settings;
			this._key = `${AgenticAuthorization.name}/${this.id}`;
			if (!this.settings.connections) throw new Error(this.prefix("The 'connections' option is not available in the app options. Ensure that the app is properly configured."));
			this._options = this.loadOptions(options);
		}
		/**
		* Loads and validates the authorization handler options.
		*/
		loadOptions(settings) {
			var _a, _b;
			const result = {
				type: "agentic",
				altBlueprintConnectionName: (_a = settings.altBlueprintConnectionName) !== null && _a !== void 0 ? _a : process.env[`${this.id}_altBlueprintConnectionName`],
				scopes: (_b = settings.scopes) !== null && _b !== void 0 ? _b : this.loadScopes(process.env[`${this.id}_scopes`])
			};
			if (!result.scopes || result.scopes.length === 0) throw new Error(this.prefix("At least one scope must be specified for the Agentic authorization handler."));
			return result;
		}
		/**
		* @inheritdoc
		*/
		signin() {
			return Promise.resolve(types_1.AuthorizationHandlerStatus.IGNORED);
		}
		/**
		* @inheritdoc
		*/
		signout() {
			return Promise.resolve(false);
		}
		/**
		* @inheritdoc
		*/
		async token(context, options) {
			var _a, _b, _c, _d, _e, _f, _g;
			try {
				const scopes = (options === null || options === void 0 ? void 0 : options.scopes) || this._options.scopes;
				const tokenResponse = this.getContext(context, scopes);
				if (tokenResponse.token) {
					logger.debug(this.prefix("Using cached Agentic user token"));
					return tokenResponse;
				}
				let connection;
				if ((_a = this._options.altBlueprintConnectionName) === null || _a === void 0 ? void 0 : _a.trim()) connection = this.settings.connections.getConnection(this._options.altBlueprintConnectionName);
				else connection = this.settings.connections.getTokenProvider(context.identity, (_b = context.activity.serviceUrl) !== null && _b !== void 0 ? _b : "");
				const token = await connection.getAgenticUserToken((_c = context.activity.getAgenticTenantId()) !== null && _c !== void 0 ? _c : "", (_d = context.activity.getAgenticInstanceId()) !== null && _d !== void 0 ? _d : "", (_e = context.activity.getAgenticUser()) !== null && _e !== void 0 ? _e : "", scopes);
				this.setContext(context, scopes, { token });
				(_f = this._onSuccess) === null || _f === void 0 || _f.call(this, context);
				return { token };
			} catch (error) {
				const reason = "Error retrieving Agentic user token";
				logger.error(this.prefix(reason), error);
				(_g = this._onFailure) === null || _g === void 0 || _g.call(this, context, `${reason}: ${error.message}`);
				return { token: void 0 };
			}
		}
		/**
		* @inheritdoc
		*/
		onSuccess(callback) {
			this._onSuccess = callback;
		}
		/**
		* @inheritdoc
		*/
		onFailure(callback) {
			this._onFailure = callback;
		}
		/**
		* Prefixes a message with the handler ID.
		*/
		prefix(message) {
			return `[handler:${this.id}] ${message}`;
		}
		/**
		* Sets the authorization context in the turn state.
		* @param context The turn context in which to set the authorization data.
		* @param scopes The OAuth scopes associated with the authorization context.
		* @param data The token response to store in the turn state.
		*/
		setContext(context, scopes, data) {
			return context.turnState.set(`${this._key}:${scopes.join(";")}`, () => data);
		}
		/**
		* Gets the authorization context from the turn state.
		* @param scopes The OAuth scopes for which the context is being retrieved.
		*/
		getContext(context, scopes) {
			var _a;
			const result = context.turnState.get(`${this._key}:${scopes.join(";")}`);
			return (_a = result === null || result === void 0 ? void 0 : result()) !== null && _a !== void 0 ? _a : { token: void 0 };
		}
		/**
		* Loads the OAuth scopes from the environment variables.
		*/
		loadScopes(value) {
			var _a;
			return (_a = value === null || value === void 0 ? void 0 : value.split(",").reduce((acc, scope) => {
				const trimmed = scope.trim();
				if (trimmed) acc.push(trimmed);
				return acc;
			}, [])) !== null && _a !== void 0 ? _a : [];
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/auth/handlers/index.js
var require_handlers = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$9) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$9, p)) __createBinding(exports$9, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_azureBotAuthorization(), exports);
	__exportStar(require_agenticAuthorization(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/auth/authorizationManager.js
var require_authorizationManager = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AuthorizationManager = void 0;
	const agents_activity_1 = require_src$2();
	const handlers_1 = require_handlers();
	const handlerStorage_1 = require_handlerStorage();
	const types_1 = require_types();
	const logger = (0, agents_activity_1.debug)("agents:authorization:manager");
	/**
	* Manages multiple authorization handlers and their interactions.
	* Processes authorization requests and maintains handler states.
	* @remarks
	* This class is responsible for coordinating the authorization process
	* across multiple handlers, ensuring that each handler is invoked in
	* the correct order and with the appropriate context.
	*/
	var AuthorizationManager = class {
		/**
		* Creates an instance of the AuthorizationManager.
		* @param app The agent application instance.
		*/
		constructor(app, connections) {
			this.app = app;
			this._handlers = {};
			if (!app.options.storage) throw new Error("Storage is required for Authorization. Ensure that a storage provider is configured in the AgentApplication options.");
			if (app.options.authorization === void 0 || Object.keys(app.options.authorization).length === 0) throw new Error("The AgentApplication.authorization does not have any auth handlers");
			const settings = {
				storage: app.options.storage,
				connections
			};
			for (const [id, handler] of Object.entries(app.options.authorization)) {
				const options = this.loadOptions(id, handler);
				if (options.type === "agentic") this._handlers[id] = new handlers_1.AgenticAuthorization(id, options, settings);
				else this._handlers[id] = new handlers_1.AzureBotAuthorization(id, options, settings);
			}
		}
		/**
		* Loads and validates the authorization handler options.
		*/
		loadOptions(id, options) {
			var _a, _b;
			const result = {
				...options,
				type: (_b = (_a = options.type) !== null && _a !== void 0 ? _a : process.env[`${id}_type`]) === null || _b === void 0 ? void 0 : _b.toLowerCase()
			};
			const supportedTypes = ["agentic", void 0];
			if (!supportedTypes.includes(result.type)) throw new Error(`Unsupported authorization handler type: '${result.type}' for auth handler: '${id}'. Supported types are: '${supportedTypes.filter(Boolean).join("', '")}'.`);
			return result;
		}
		/**
		* Gets the registered authorization handlers.
		* @returns A record of authorization handlers by their IDs.
		*/
		get handlers() {
			return this._handlers;
		}
		/**
		* Processes an authorization request.
		* @param context The turn context.
		* @param getHandlerIds A function to retrieve the handler IDs for the current activity.
		* @returns The result of the authorization process.
		*/
		async process(context, getHandlerIds) {
			var _a, _b, _c, _d, _e;
			const storage = new handlerStorage_1.HandlerStorage(this.app.options.storage, context);
			let active = await this.active(storage, getHandlerIds);
			if (active !== void 0 && ((_a = active === null || active === void 0 ? void 0 : active.data.activity.conversation) === null || _a === void 0 ? void 0 : _a.id) !== ((_b = context.activity.conversation) === null || _b === void 0 ? void 0 : _b.id)) {
				logger.warn("Discarding the active session due to the conversation has changed during an active sign-in process", active === null || active === void 0 ? void 0 : active.data.activity);
				await storage.delete();
				return { authorized: true };
			}
			const handlers = (_e = (_c = active === null || active === void 0 ? void 0 : active.handlers) !== null && _c !== void 0 ? _c : this.mapHandlers((_d = await getHandlerIds(context.activity)) !== null && _d !== void 0 ? _d : [])) !== null && _e !== void 0 ? _e : [];
			for (const handler of handlers) {
				const status = await this.signin(storage, handler, context, active === null || active === void 0 ? void 0 : active.data);
				logger.debug(this.prefix(handler.id, `Sign-in status: ${status}`));
				if (status === types_1.AuthorizationHandlerStatus.IGNORED) {
					await storage.delete();
					continue;
				}
				if (status === types_1.AuthorizationHandlerStatus.PENDING) return { authorized: false };
				if (status === types_1.AuthorizationHandlerStatus.REJECTED) {
					await storage.delete();
					return { authorized: false };
				}
				if (status === types_1.AuthorizationHandlerStatus.REVALIDATE) {
					await storage.delete();
					return this.process(context, getHandlerIds);
				}
				if (status !== types_1.AuthorizationHandlerStatus.APPROVED) throw new Error(this.prefix(handler.id, `Unexpected registration status: ${status}`));
				await storage.delete();
				if (active) {
					context._activity = agents_activity_1.Activity.fromObject(active.data.activity);
					active = void 0;
				}
			}
			return { authorized: true };
		}
		/**
		* Gets the active handler session from storage.
		*/
		async active(storage, getHandlerIds) {
			var _a;
			const data = await storage.read();
			if (!data) return;
			const handlerIds = await getHandlerIds(agents_activity_1.Activity.fromObject(data.activity));
			let handlers = this.mapHandlers(handlerIds !== null && handlerIds !== void 0 ? handlerIds : []);
			handlers = (_a = handlers.sort((a, b) => {
				if (a.id === data.id) return -1;
				if (b.id === data.id) return 1;
				return 0;
			})) !== null && _a !== void 0 ? _a : [];
			return {
				data,
				handlers
			};
		}
		/**
		* Attempts to sign in using the specified handler and options.
		*/
		async signin(storage, handler, context, active) {
			try {
				return await handler.signin(context, active);
			} catch (cause) {
				await storage.delete();
				throw new Error(this.prefix(handler.id, "Failed to sign in"), { cause });
			}
		}
		/**
		* Maps an array of handler IDs to their corresponding handler instances.
		*/
		mapHandlers(ids) {
			let unknownHandlers = "";
			const handlers = ids.map((id) => {
				if (!this._handlers[id]) unknownHandlers += ` ${id}`;
				return this._handlers[id];
			});
			if (unknownHandlers) throw new Error(`Cannot find auth handlers with ID(s): ${unknownHandlers}`);
			return handlers;
		}
		/**
		* Prefixes a message with the handler ID.
		*/
		prefix(id, message) {
			return `[handler:${id}] ${message}`;
		}
	};
	exports.AuthorizationManager = AuthorizationManager;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/auth/index.js
var require_auth = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$8) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$8, p)) __createBinding(exports$8, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_authorization(), exports);
	__exportStar(require_authorizationManager(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/agentApplication.js
var require_agentApplication = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AgentApplication = void 0;
	const agents_activity_1 = require_src$2();
	const logger_1 = require_logger();
	const turnContext_1 = require_turnContext();
	const adaptiveCards_1 = require_adaptiveCards();
	const turnState_1 = require_turnState();
	const routeRank_1 = require_routeRank();
	const routeList_1 = require_routeList();
	const transcript_1 = require_transcript();
	const cloudAdapter_1 = require_cloudAdapter();
	const auth_1 = require_auth();
	const logger = (0, logger_1.debug)("agents:app");
	const TYPING_TIMER_DELAY = 1e3;
	/**
	* Main application class for handling agent conversations and routing.
	*
	* @typeParam TState - The state type extending TurnState.
	*
	* @remarks
	* The AgentApplication class provides a framework for building conversational agents.
	* It handles routing activities to appropriate handlers, manages conversation state,
	* supports authentication flows, and provides various event handling capabilities.
	*
	* Key features:
	* - Activity routing based on type, content, or custom selectors
	* - State management with automatic load/save
	* - OAuth authentication support
	* - Typing indicators and long-running message support
	* - Extensible architecture with custom extensions
	* - Event handlers for before/after turn processing
	*
	* @example
	* ```typescript
	* const app = new AgentApplication<MyState>({
	*   storage: new MemoryStorage(),
	*   adapter: myAdapter
	* });
	*
	* app.onMessage('hello', async (context, state) => {
	*   await context.sendActivity('Hello there!');
	* });
	*
	* await app.run(turnContext);
	* ```
	*
	*/
	var AgentApplication = class {
		/**
		* Creates a new instance of AgentApplication.
		*
		* @param options - Optional configuration options for the application.
		*
		* @remarks
		* The constructor initializes the application with default settings and applies
		* any provided options. It sets up the adapter, authorization, and other core
		* components based on the configuration.
		*
		* Default options:
		* - startTypingTimer: false
		* - longRunningMessages: false
		* - removeRecipientMention: true
		* - turnStateFactory: Creates a new TurnState instance
		*
		* @example
		* ```typescript
		* const app = new AgentApplication({
		*   storage: new MemoryStorage(),
		*   adapter: myAdapter,
		*   startTypingTimer: true,
		*   authorization: { connectionName: 'oauth' },
		*   transcriptLogger: myTranscriptLogger,
		* });
		* ```
		*/
		constructor(options) {
			var _a;
			this._routes = new routeList_1.RouteList();
			this._beforeTurn = [];
			this._afterTurn = [];
			this._extensions = [];
			this._options = {
				...options,
				turnStateFactory: (options === null || options === void 0 ? void 0 : options.turnStateFactory) || (() => new turnState_1.TurnState()),
				startTypingTimer: (options === null || options === void 0 ? void 0 : options.startTypingTimer) !== void 0 ? options.startTypingTimer : false,
				longRunningMessages: (options === null || options === void 0 ? void 0 : options.longRunningMessages) !== void 0 ? options.longRunningMessages : false,
				removeRecipientMention: (options === null || options === void 0 ? void 0 : options.removeRecipientMention) !== void 0 ? options.removeRecipientMention : true,
				transcriptLogger: (options === null || options === void 0 ? void 0 : options.transcriptLogger) || void 0
			};
			this._adaptiveCards = new adaptiveCards_1.AdaptiveCardsActions(this);
			if (this._options.adapter) this._adapter = this._options.adapter;
			else this._adapter = new cloudAdapter_1.CloudAdapter();
			if (this._options.authorization) {
				this._authorizationManager = new auth_1.AuthorizationManager(this, this._adapter.connectionManager);
				this._authorization = new auth_1.UserAuthorization(this._authorizationManager);
			}
			if (this._options.longRunningMessages && !this._adapter && !this._options.agentAppId) throw new Error("The Application.longRunningMessages property is unavailable because no adapter was configured in the app.");
			if (this._options.transcriptLogger) if (!this._options.adapter) throw new Error("The Application.transcriptLogger property is unavailable because no adapter was configured in the app.");
			else (_a = this._adapter) === null || _a === void 0 || _a.use(new transcript_1.TranscriptLoggerMiddleware(this._options.transcriptLogger));
			logger.debug("AgentApplication created with options:", this._options);
		}
		/**
		* Gets the authorization instance for the application.
		*
		* @returns The authorization instance.
		* @throws Error if no authentication options were configured.
		*/
		get authorization() {
			if (!this._authorization) throw new Error("The Application.authorization property is unavailable because no authorization options were configured.");
			return this._authorization;
		}
		/**
		* Gets the options used to configure the application.
		*
		* @returns The application options.
		*/
		get options() {
			return this._options;
		}
		/**
		* Gets the adapter used by the application.
		*
		* @returns The adapter instance.
		*/
		get adapter() {
			return this._adapter;
		}
		/**
		* Gets the adaptive cards actions handler for the application.
		*
		* @returns The adaptive cards actions instance.
		*
		* @remarks
		* The adaptive cards actions handler provides functionality for handling
		* adaptive card interactions, such as submit actions and other card-based events.
		*
		* @example
		* ```typescript
		* app.adaptiveCards.actionSubmit('doStuff', async (context, state, data) => {
		*   await context.sendActivity(`Received data: ${JSON.stringify(data)}`);
		* });
		* ```
		*/
		get adaptiveCards() {
			return this._adaptiveCards;
		}
		/**
		* Sets an error handler for the application.
		*
		* @param handler - The error handler function to be called when an error occurs.
		* @returns The current instance of the application.
		*
		* @remarks
		* This method allows you to handle any errors that occur during turn processing.
		* The handler will receive the turn context and the error that occurred.
		*
		* @example
		* ```typescript
		* app.onError(async (context, error) => {
		*   console.error(`An error occurred: ${error.message}`);
		*   await context.sendActivity('Sorry, something went wrong!');
		* });
		* ```
		*
		*/
		onError(handler) {
			if (this._adapter) this._adapter.onTurnError = handler;
			return this;
		}
		/**
		* Adds a new route to the application for handling activities.
		*
		* @param selector - The selector function that determines if a route should handle the current activity.
		* @param handler - The handler function that will be called if the selector returns true.
		* @param isInvokeRoute - Whether this route is for invoke activities. Defaults to false.
		* @param rank - The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.
		* @param authHandlers - Array of authentication handler names for this route. Defaults to empty array.
		* @param isAgenticRoute - Whether this route is for agentic requests only. Defaults to false.
		* @returns The current instance of the application.
		*
		* @remarks
		* Routes are evaluated by rank order (if provided), otherwise, in the order they are added.
		* Invoke-based activities receive special treatment and are matched separately as they typically
		* have shorter execution timeouts.
		*
		* @example
		* ```typescript
		* app.addRoute(
		*   async (context) => context.activity.type === ActivityTypes.Message,
		*   async (context, state) => {
		*     await context.sendActivity('I received your message');
		*   },
		*   false, // isInvokeRoute
		*   RouteRank.First // rank
		* );
		* ```
		*
		*/
		addRoute(selector, handler, isInvokeRoute = false, rank = routeRank_1.RouteRank.Unspecified, authHandlers = [], isAgenticRoute = false) {
			this._routes.addRoute(selector, handler, isInvokeRoute, rank, authHandlers, isAgenticRoute);
			return this;
		}
		/**
		* Adds a handler for specific activity types.
		*
		* @param type - The activity type(s) to handle. Can be a string, RegExp, RouteSelector, or array of these types.
		* @param handler - The handler function that will be called when the specified activity type is received.
		* @param authHandlers - Array of authentication handler names for this activity. Defaults to empty array.
		* @param rank - The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.
		* @param isAgenticRoute - Indicates if this handler is for agentic requests only. Defaults to false.
		* @returns The current instance of the application.
		*
		* @remarks
		* This method allows you to register handlers for specific activity types such as 'message', 'conversationUpdate', etc.
		* You can specify multiple activity types by passing an array.
		*
		* @example
		* ```typescript
		* app.onActivity(ActivityTypes.Message, async (context, state) => {
		*   await context.sendActivity('I received your message');
		* });
		* ```
		*
		*/
		onActivity(type, handler, authHandlers = [], rank = routeRank_1.RouteRank.Unspecified, isAgenticRoute = false) {
			(Array.isArray(type) ? type : [type]).forEach((t) => {
				const selector = this.createActivitySelector(t, isAgenticRoute);
				this.addRoute(selector, handler, false, rank, authHandlers, isAgenticRoute);
			});
			return this;
		}
		/**
		* Adds a handler for conversation update events.
		*
		* @param event - The conversation update event to handle (e.g., 'membersAdded', 'membersRemoved').
		* @param handler - The handler function that will be called when the specified event occurs.
		* @param authHandlers - Array of authentication handler names for this event. Defaults to empty array.
		* @param rank - The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.
		* @param isAgenticRoute - Indicates if this handler is for agentic requests only. Defaults to false.
		* @returns The current instance of the application.
		* @throws Error if the handler is not a function.
		*
		* @remarks
		* Conversation update events occur when the state of a conversation changes, such as when members join or leave.
		*
		* @example
		* ```typescript
		* app.onConversationUpdate('membersAdded', async (context, state) => {
		*   const membersAdded = context.activity.membersAdded;
		*   for (const member of membersAdded) {
		*     if (member.id !== context.activity.recipient.id) {
		*       await context.sendActivity('Hello and welcome!');
		*     }
		*   }
		* });
		* ```
		*
		*/
		onConversationUpdate(event, handler, authHandlers = [], rank = routeRank_1.RouteRank.Unspecified, isAgenticRoute = false) {
			if (typeof handler !== "function") throw new Error(`ConversationUpdate 'handler' for ${event} is ${typeof handler}. Type of 'handler' must be a function.`);
			const selector = this.createConversationUpdateSelector(event, isAgenticRoute);
			this.addRoute(selector, handler, false, rank, authHandlers, isAgenticRoute);
			return this;
		}
		/**
		* Continues a conversation asynchronously.
		*
		* @param conversationReferenceOrContext - The conversation reference or turn context.
		* @param logic - The logic to execute during the conversation.
		* @returns A promise that resolves when the conversation logic has completed.
		* @throws Error if the adapter is not configured.
		*/
		async continueConversationAsync(botAppIdOrIdentity, conversationReferenceOrContext, logic) {
			if (!this._adapter) throw new Error("You must configure the Application with an 'adapter' before calling Application.continueConversationAsync()");
			if (!this.options.agentAppId) logger.warn("Calling Application.continueConversationAsync() without a configured 'agentAppId'. In production environments, a 'agentAppId' is required.");
			let reference;
			if ("activity" in conversationReferenceOrContext) reference = conversationReferenceOrContext.activity.getConversationReference();
			else reference = conversationReferenceOrContext;
			await this._adapter.continueConversation(botAppIdOrIdentity, reference, logic);
		}
		/**
		* Adds a handler for message activities that match the specified keyword or pattern.
		*
		* @param keyword - The keyword, pattern, or selector function to match against message text.
		*                  Can be a string, RegExp, RouteSelector, or array of these types.
		* @param handler - The handler function that will be called when a matching message is received.
		* @param authHandlers - Array of authentication handler names for this message handler. Defaults to empty array.
		* @param rank - The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.
		* @param isAgenticRoute - Indicates if this handler is for agentic requests only. Defaults to false.
		* @returns The current instance of the application.
		*
		* @remarks
		* This method allows you to register handlers for specific message patterns.
		* If keyword is a string, it matches messages containing that string.
		* If keyword is a RegExp, it tests the message text against the regular expression.
		* If keyword is a function, it calls the function with the context to determine if the message matches.
		*
		* @example
		* ```typescript
		* app.onMessage('hello', async (context, state) => {
		*   await context.sendActivity('Hello there!');
		* });
		*
		* app.onMessage(/help/i, async (context, state) => {
		*   await context.sendActivity('How can I help you?');
		* });
		* ```
		*
		*/
		onMessage(keyword, handler, authHandlers = [], rank = routeRank_1.RouteRank.Unspecified, isAgenticRoute = false) {
			(Array.isArray(keyword) ? keyword : [keyword]).forEach((k) => {
				const selector = this.createMessageSelector(k, isAgenticRoute);
				this.addRoute(selector, handler, false, rank, authHandlers, isAgenticRoute);
			});
			return this;
		}
		/**
		* Sets a handler to be called when a user successfully signs in.
		*
		* @param handler - The handler function to be called after successful sign-in.
		* @returns The current instance of the application.
		* @throws Error if authentication options were not configured.
		*
		* @remarks
		* This method allows you to perform actions after a user has successfully authenticated.
		* The handler will receive the turn context and state.
		*
		* @example
		* ```typescript
		* app.onSignInSuccess(async (context, state) => {
		*   await context.sendActivity('You have successfully signed in!');
		* });
		* ```
		*
		*/
		onSignInSuccess(handler) {
			if (this.options.authorization) this.authorization.onSignInSuccess(handler);
			else throw new Error("The Application.authorization property is unavailable because no authorization options were configured.");
			return this;
		}
		/**
		* Sets a handler to be called when a sign-in attempt fails.
		*
		* @param handler - The handler function to be called after a failed sign-in attempt.
		* @returns The current instance of the application.
		* @throws Error if authentication options were not configured.
		*
		* @remarks
		* This method allows you to handle cases where a user fails to authenticate,
		* such as when they cancel the sign-in process or an error occurs.
		*
		* @example
		* ```typescript
		* app.onSignInFailure(async (context, state) => {
		*   await context.sendActivity('Sign-in failed. Please try again.');
		* });
		* ```
		*
		*/
		onSignInFailure(handler) {
			if (this.options.authorization) this.authorization.onSignInFailure(handler);
			else throw new Error("The Application.authorization property is unavailable because no authorization options were configured.");
			return this;
		}
		/**
		* Adds a handler for message reaction added events.
		*
		* @param handler - The handler function that will be called when a message reaction is added.
		* @param rank - The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.
		* @param isAgenticRoute - Indicates if this handler is for agentic requests only. Defaults to false.
		* @returns The current instance of the application.
		*
		* @remarks
		* This method registers a handler that will be invoked when a user adds a reaction to a message,
		* such as a like, heart, or other emoji reaction.
		*
		* @example
		* ```typescript
		* app.onMessageReactionAdded(async (context, state) => {
		*   const reactionsAdded = context.activity.reactionsAdded;
		*   if (reactionsAdded && reactionsAdded.length > 0) {
		*     await context.sendActivity(`Thanks for your ${reactionsAdded[0].type} reaction!`);
		*   }
		* });
		* ```
		*
		*/
		onMessageReactionAdded(handler, rank = routeRank_1.RouteRank.Unspecified, isAgenticRoute = false) {
			const selector = async (context) => {
				return context.activity.type === agents_activity_1.ActivityTypes.MessageReaction && Array.isArray(context.activity.reactionsAdded) && context.activity.reactionsAdded.length > 0 && (!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest());
			};
			this.addRoute(selector, handler, false, rank, [], isAgenticRoute);
			return this;
		}
		/**
		* Adds a handler for message reaction removed events.
		*
		* @param handler - The handler function that will be called when a message reaction is removed.
		* @param rank - The rank of the route, used to determine the order of evaluation. Defaults to RouteRank.Unspecified.
		* @param isAgenticRoute - Indicates if this handler is for agentic requests only. Defaults to false.
		* @returns The current instance of the application.
		*
		* @remarks
		* This method registers a handler that will be invoked when a user removes a reaction from a message,
		* such as unliking or removing an emoji reaction.
		*
		* @example
		* ```typescript
		* app.onMessageReactionRemoved(async (context, state) => {
		*   const reactionsRemoved = context.activity.reactionsRemoved;
		*   if (reactionsRemoved && reactionsRemoved.length > 0) {
		*     await context.sendActivity(`You removed your ${reactionsRemoved[0].type} reaction.`);
		*   }
		* });
		* ```
		*
		*/
		onMessageReactionRemoved(handler, rank = routeRank_1.RouteRank.Unspecified, isAgenticRoute = false) {
			const selector = async (context) => {
				return context.activity.type === agents_activity_1.ActivityTypes.MessageReaction && Array.isArray(context.activity.reactionsRemoved) && context.activity.reactionsRemoved.length > 0 && (!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest());
			};
			this.addRoute(selector, handler, false, rank, void 0, isAgenticRoute);
			return this;
		}
		/**
		* Executes the application logic for a given turn context.
		*
		* @param turnContext - The context for the current turn of the conversation.
		* @returns A promise that resolves when the application logic has completed.
		*
		* @remarks
		* This method is the entry point for processing a turn in the conversation.
		* It delegates the actual processing to the `runInternal` method, which handles
		* the core logic for routing and executing handlers.
		*
		* @example
		* ```typescript
		* const app = new AgentApplication();
		* await app.run(turnContext);
		* ```
		*
		*/
		async run(turnContext) {
			await this.runInternal(turnContext);
		}
		/**
		* Executes the application logic for a given turn context.
		*
		* @param turnContext - The context for the current turn of the conversation.
		* @returns A promise that resolves to true if a handler was executed, false otherwise.
		*
		* @remarks
		* This is the core internal method that processes a turn in the conversation.
		* It handles routing and executing handlers based on the activity type and content.
		* While this method is public, it's typically called internally by the `run` method.
		*
		* The method performs the following operations:
		* 1. Starts typing timer if configured
		* 2. Processes mentions if configured
		* 3. Loads turn state
		* 4. Handles authentication flows
		* 5. Downloads files if file downloaders are configured
		* 6. Executes before-turn event handlers
		* 7. Routes to appropriate handlers
		* 8. Executes after-turn event handlers
		* 9. Saves turn state
		*
		* @example
		* ```typescript
		* const handled = await app.runInternal(turnContext);
		* if (!handled) {
		*   console.log('No handler matched the activity');
		* }
		* ```
		*
		*/
		async runInternal(turnContext) {
			if (turnContext.activity.type === agents_activity_1.ActivityTypes.Typing) return false;
			logger.info("Running application with activity:", turnContext.activity.id);
			return await this.startLongRunningCall(turnContext, async (context) => {
				var _a, _b;
				try {
					if (this._options.startTypingTimer) this.startTypingTimer(context);
					if (this._options.removeRecipientMention && context.activity.type === agents_activity_1.ActivityTypes.Message) context.activity.removeRecipientMention();
					if (this._options.normalizeMentions && context.activity.type === agents_activity_1.ActivityTypes.Message) context.activity.normalizeMentions();
					const { storage, turnStateFactory } = this._options;
					const state = turnStateFactory();
					await state.load(context, storage);
					const { authorized } = (_b = await ((_a = this._authorizationManager) === null || _a === void 0 ? void 0 : _a.process(context, async (activity) => {
						var _a;
						const route = await this.getRoute(new turnContext_1.TurnContext(context.adapter, activity, turnContext.identity));
						return (_a = route === null || route === void 0 ? void 0 : route.authHandlers) !== null && _a !== void 0 ? _a : [];
					}))) !== null && _b !== void 0 ? _b : { authorized: true };
					if (!authorized) {
						await state.save(context, storage);
						return false;
					}
					const route = await this.getRoute(context);
					if (!route) {
						logger.debug("No matching route found for activity:", context.activity);
						return false;
					}
					if (Array.isArray(this._options.fileDownloaders) && this._options.fileDownloaders.length > 0) for (let i = 0; i < this._options.fileDownloaders.length; i++) await this._options.fileDownloaders[i].downloadAndStoreFiles(context, state);
					if (!await this.callEventHandlers(context, state, this._beforeTurn)) {
						await state.save(context, storage);
						return false;
					}
					await route.handler(context, state);
					if (await this.callEventHandlers(context, state, this._afterTurn)) await state.save(context, storage);
					return true;
				} catch (err) {
					logger.error(err);
					throw err;
				} finally {
					this.stopTypingTimer();
				}
			});
		}
		/**
		* Finds the appropriate route for the given context.
		*/
		async getRoute(context) {
			for (const route of this._routes) if (await route.selector(context)) return route;
		}
		/**
		* Sends a proactive message to a conversation.
		*
		* @param context - The turn context or conversation reference to use.
		* @param activityOrText - The activity or text to send.
		* @param speak - Optional text to be spoken by the bot on a speech-enabled channel.
		* @param inputHint - Optional input hint for the activity.
		* @returns A promise that resolves to the resource response from sending the activity.
		*
		* @remarks
		* This method allows you to send messages proactively to a conversation, outside the normal turn flow.
		*
		* @example
		* ```typescript
		* // With conversation reference
		* await app.sendProactiveActivity(conversationReference, 'Important notification!');
		*
		* // From an existing context
		* await app.sendProactiveActivity(turnContext, 'Important notification!');
		* ```
		*
		*/
		async sendProactiveActivity(botAppIdOrIdentity, context, activityOrText, speak, inputHint) {
			let response;
			await this.continueConversationAsync(botAppIdOrIdentity, context, async (ctx) => {
				response = await ctx.sendActivity(activityOrText, speak, inputHint);
			});
			return response;
		}
		/**
		* Starts a typing indicator timer for the current turn context.
		*
		* @param context - The turn context for the current conversation.
		* @returns void
		*
		* @remarks
		* This method starts a timer that sends typing activity indicators to the user
		* at regular intervals. The typing indicator continues until a message is sent
		* or the timer is explicitly stopped.
		*
		* The typing indicator helps provide feedback to users that the agent is processing
		* their message, especially when responses might take time to generate.
		*
		* @example
		* ```typescript
		* app.startTypingTimer(turnContext);
		* // Do some processing...
		* await turnContext.sendActivity('Response after processing');
		* // Typing timer automatically stops when sending a message
		* ```
		*
		*/
		startTypingTimer(context) {
			if (context.activity.type === agents_activity_1.ActivityTypes.Message && !this._typingTimer) {
				let timerRunning = true;
				context.onSendActivities(async (context, activities, next) => {
					var _a;
					if (timerRunning) {
						for (let i = 0; i < activities.length; i++) if (activities[i].type === agents_activity_1.ActivityTypes.Message || ((_a = activities[i].channelData) === null || _a === void 0 ? void 0 : _a.streamType)) {
							this.stopTypingTimer();
							timerRunning = false;
							await lastSend;
							break;
						}
					}
					return next();
				});
				let lastSend = Promise.resolve();
				const onTimeout = async () => {
					try {
						lastSend = context.sendActivity(agents_activity_1.Activity.fromObject({ type: agents_activity_1.ActivityTypes.Typing }));
						await lastSend;
					} catch (err) {
						logger.error(err);
						this._typingTimer = void 0;
						timerRunning = false;
						lastSend = Promise.resolve();
					}
					if (timerRunning) this._typingTimer = setTimeout(onTimeout, TYPING_TIMER_DELAY);
				};
				this._typingTimer = setTimeout(onTimeout, TYPING_TIMER_DELAY);
			}
		}
		/**
		* Registers an extension with the application.
		*
		* @typeParam T - The extension type extending AgentExtension.
		* @param extension - The extension instance to register.
		* @param regcb - Callback function called after successful registration.
		* @throws Error if the extension is already registered.
		*
		* @remarks
		* Extensions provide a way to add custom functionality to the application.
		* Each extension can only be registered once to prevent conflicts.
		*
		* @example
		* ```typescript
		* const myExtension = new MyCustomExtension();
		* app.registerExtension(myExtension, (ext) => {
		*   console.log('Extension registered:', ext.name);
		* });
		* ```
		*
		*/
		registerExtension(extension, regcb) {
			if (this._extensions.includes(extension)) throw new Error("Extension already registered");
			this._extensions.push(extension);
			regcb(extension);
		}
		/**
		* Stops the typing indicator timer if it's currently running.
		*
		* @returns void
		*
		* @remarks
		* This method clears the typing indicator timer to prevent further typing indicators
		* from being sent. It's typically called automatically when a message is sent, but
		* can also be called manually to stop the typing indicator.
		*
		* @example
		* ```typescript
		* app.startTypingTimer(turnContext);
		* // Do some processing...
		* app.stopTypingTimer(); // Manually stop the typing indicator
		* ```
		*
		*/
		stopTypingTimer() {
			if (this._typingTimer) {
				clearTimeout(this._typingTimer);
				this._typingTimer = void 0;
			}
		}
		/**
		* Adds an event handler for specified turn events.
		*
		* @param event - The turn event(s) to handle. Can be 'beforeTurn', 'afterTurn', or other custom events.
		* @param handler - The handler function that will be called when the event occurs.
		* @returns The current instance of the application.
		*
		* @remarks
		* Turn events allow you to execute logic before or after the main turn processing.
		* Handlers added for 'beforeTurn' are executed before routing logic.
		* Handlers added for 'afterTurn' are executed after routing logic.
		*
		* @example
		* ```typescript
		* app.onTurn('beforeTurn', async (context, state) => {
		*   console.log('Processing before turn');
		*   return true; // Continue execution
		* });
		* ```
		*
		*/
		onTurn(event, handler) {
			(Array.isArray(event) ? event : [event]).forEach((e) => {
				switch (e) {
					case "beforeTurn":
						this._beforeTurn.push(handler);
						break;
					case "afterTurn":
						this._afterTurn.push(handler);
						break;
					default:
						this._beforeTurn.push(handler);
						break;
				}
			});
			return this;
		}
		/**
		* Calls a series of event handlers in sequence.
		*
		* @param context - The turn context for the current conversation.
		* @param state - The current turn state.
		* @param handlers - Array of event handlers to call.
		* @returns A promise that resolves to true if all handlers returned true, false otherwise.
		*/
		async callEventHandlers(context, state, handlers) {
			for (let i = 0; i < handlers.length; i++) if (!await handlers[i](context, state)) return false;
			return true;
		}
		/**
		* Starts a long-running call, potentially in a new conversation context.
		*
		* @param context - The turn context for the current conversation.
		* @param handler - The handler function to execute.
		* @returns A promise that resolves to the result of the handler.
		*/
		startLongRunningCall(context, handler) {
			if (context.activity.type === agents_activity_1.ActivityTypes.Message && this._options.longRunningMessages) return new Promise((resolve, reject) => {
				this.continueConversationAsync(context.identity, context, async (ctx) => {
					try {
						for (const key in context.activity) ctx.activity[key] = context.activity[key];
						resolve(await handler(ctx));
					} catch (err) {
						logger.error(err);
						reject(err);
					}
				});
			});
			else return handler(context);
		}
		/**
		* Creates a selector function for activity types.
		*
		* @param type - The activity type to match. Can be a string, RegExp, or RouteSelector function.
		* @param isAgenticRoute - Indicates if the route is for agentic requests only. Defaults to false.
		* @returns A RouteSelector function that matches the specified activity type.
		*/
		createActivitySelector(type, isAgenticRoute = false) {
			if (typeof type === "function") return type;
			else if (type instanceof RegExp) return (context) => {
				var _a;
				return Promise.resolve(((_a = context === null || context === void 0 ? void 0 : context.activity) === null || _a === void 0 ? void 0 : _a.type) ? type.test(context.activity.type) && (!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest()) : false);
			};
			else {
				const typeName = type.toString().toLocaleLowerCase();
				return (context) => {
					var _a;
					return Promise.resolve(((_a = context === null || context === void 0 ? void 0 : context.activity) === null || _a === void 0 ? void 0 : _a.type) ? context.activity.type.toLocaleLowerCase() === typeName && (!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest()) : false);
				};
			}
		}
		/**
		* Creates a selector function for conversation update events.
		*
		* @param event - The conversation update event to match.
		* @param isAgenticRoute - Indicates if the route is for agentic requests only. Defaults to false.
		* @returns A RouteSelector function that matches the specified conversation update event.
		*/
		createConversationUpdateSelector(event, isAgenticRoute = false) {
			switch (event) {
				case "membersAdded": return (context) => {
					var _a, _b;
					return Promise.resolve((!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest()) && ((_a = context === null || context === void 0 ? void 0 : context.activity) === null || _a === void 0 ? void 0 : _a.type) === agents_activity_1.ActivityTypes.ConversationUpdate && Array.isArray((_b = context === null || context === void 0 ? void 0 : context.activity) === null || _b === void 0 ? void 0 : _b.membersAdded) && context.activity.membersAdded.length > 0);
				};
				case "membersRemoved": return (context) => {
					var _a, _b;
					return Promise.resolve((!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest()) && ((_a = context === null || context === void 0 ? void 0 : context.activity) === null || _a === void 0 ? void 0 : _a.type) === agents_activity_1.ActivityTypes.ConversationUpdate && Array.isArray((_b = context === null || context === void 0 ? void 0 : context.activity) === null || _b === void 0 ? void 0 : _b.membersRemoved) && context.activity.membersRemoved.length > 0);
				};
				default: return (context) => {
					var _a, _b, _c;
					return Promise.resolve((!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest()) && ((_a = context === null || context === void 0 ? void 0 : context.activity) === null || _a === void 0 ? void 0 : _a.type) === agents_activity_1.ActivityTypes.ConversationUpdate && ((_c = (_b = context === null || context === void 0 ? void 0 : context.activity) === null || _b === void 0 ? void 0 : _b.channelData) === null || _c === void 0 ? void 0 : _c.eventType) === event);
				};
			}
		}
		/**
		* Creates a selector function for message content matching.
		*
		* @param keyword - The keyword, pattern, or selector function to match against message text.
		* @param isAgenticRoute - Indicates if the route is for agentic requests only. Defaults to false.
		* @returns A RouteSelector function that matches messages based on the specified keyword.
		*/
		createMessageSelector(keyword, isAgenticRoute = false) {
			if (typeof keyword === "function") return keyword;
			else if (keyword instanceof RegExp) return (context) => {
				var _a;
				if (((_a = context === null || context === void 0 ? void 0 : context.activity) === null || _a === void 0 ? void 0 : _a.type) === agents_activity_1.ActivityTypes.Message && context.activity.text && (!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest())) return Promise.resolve(keyword.test(context.activity.text));
				else return Promise.resolve(false);
			};
			else {
				const k = keyword.toString().toLocaleLowerCase();
				return (context) => {
					var _a;
					if (((_a = context === null || context === void 0 ? void 0 : context.activity) === null || _a === void 0 ? void 0 : _a.type) === agents_activity_1.ActivityTypes.Message && context.activity.text && (!isAgenticRoute || isAgenticRoute && context.activity.isAgenticRequest())) return Promise.resolve(context.activity.text.toLocaleLowerCase() === k);
					else return Promise.resolve(false);
				};
			}
		}
	};
	exports.AgentApplication = AgentApplication;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/agentApplicationBuilder.js
var require_agentApplicationBuilder = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AgentApplicationBuilder = void 0;
	const agentApplication_1 = require_agentApplication();
	/**
	* Builder class for creating and configuring AgentApplication instances.
	* @typeParam TState Type extending TurnState that will be used by the application
	*/
	var AgentApplicationBuilder = class {
		constructor() {
			this._options = {};
		}
		/**
		* Gets the current options for the AgentApplication being built.
		* @returns The current options object
		*/
		get options() {
			return this._options;
		}
		/**
		* Sets the storage provider for the AgentApplication.
		* @param storage The storage implementation to use
		* @returns This builder instance for chaining
		*/
		withStorage(storage) {
			this._options.storage = storage;
			return this;
		}
		/**
		* Sets the factory function to create new TurnState instances.
		* @param turnStateFactory Function that creates a new TurnState
		* @returns This builder instance for chaining
		*/
		withTurnStateFactory(turnStateFactory) {
			this._options.turnStateFactory = turnStateFactory;
			return this;
		}
		/**
		* Configures whether the agent should display typing indicators.
		* @param startTypingTimer Whether to show typing indicators
		* @returns This builder instance for chaining
		*/
		/**
		* Sets authentication options for the AgentApplication.
		* @param authHandlers The user identity authentication options
		* @returns This builder instance for chaining
		*/
		withAuthorization(authHandlers) {
			this._options.authorization = authHandlers;
			return this;
		}
		/**
		* Builds and returns a new AgentApplication instance configured with the provided options.
		* @returns A new AgentApplication instance
		*/
		build() {
			return new agentApplication_1.AgentApplication(this._options);
		}
	};
	exports.AgentApplicationBuilder = AgentApplicationBuilder;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/agentApplicationOptions.js
var require_agentApplicationOptions = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/appRoute.js
var require_appRoute = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/routeHandler.js
var require_routeHandler = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/routeSelector.js
var require_routeSelector = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/attachmentDownloader.js
var require_attachmentDownloader = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AttachmentDownloader = void 0;
	const axios_1 = __importDefault(require_axios());
	const logger_1 = require_logger();
	const auth_1 = require_auth$1();
	const logger = (0, logger_1.debug)("agents:attachmentDownloader");
	/**
	* A utility class for downloading input files from activity attachments.
	*
	* @typeParam TState - The type of the turn state used in the application.
	*
	* @remarks
	* This class provides functionality to filter and download attachments from a turn context,
	* supporting various content types and handling authentication for secure URLs.
	*
	*/
	var AttachmentDownloader = class {
		/**
		* Creates an instance of AttachmentDownloader.
		* This class is responsible for downloading input files from attachments.
		*
		* @param stateKey The key to store files in state. Defaults to 'inputFiles'.
		*/
		constructor(stateKey = "inputFiles") {
			this._httpClient = axios_1.default.create();
			this._stateKey = stateKey;
		}
		/**
		* Downloads files from the attachments in the current turn context.
		*
		* @param context The turn context containing the activity with attachments.
		* @returns A promise that resolves to an array of downloaded input files.
		*/
		async downloadFiles(context) {
			var _a;
			const attachments = (_a = context.activity.attachments) === null || _a === void 0 ? void 0 : _a.filter((a) => !a.contentType.startsWith("text/html"));
			if (!attachments || attachments.length === 0) {
				logger.info("No Attachments to download");
				return Promise.resolve([]);
			}
			const accessToken = await new auth_1.MsalTokenProvider().getAccessToken((0, auth_1.loadAuthConfigFromEnv)(), "https://api.botframework.com");
			const files = [];
			for (const attachment of attachments) {
				const file = await this.downloadFile(attachment, accessToken);
				if (file) files.push(file);
			}
			logger.info("Attachments downloaded");
			return files;
		}
		/**
		* Downloads files from the attachments in the current turn context and stores them in state.
		*
		* @param context The turn context containing the activity with attachments.
		* @param state The turn state to store the files in.
		* @returns A promise that resolves when the downloaded files are stored.
		*/
		async downloadAndStoreFiles(context, state) {
			const files = await this.downloadFiles(context);
			state.setValue(this._stateKey, files);
		}
		async downloadFile(attachment, accessToken) {
			if (attachment.contentUrl && attachment.contentUrl.startsWith("https://") || attachment.contentUrl && attachment.contentUrl.startsWith("http://localhost")) {
				let headers;
				if (accessToken.length > 0) headers = { Authorization: `Bearer ${accessToken}` };
				const response = await this._httpClient.get(attachment.contentUrl, {
					headers,
					responseType: "arraybuffer"
				});
				const content = Buffer.from(response.data, "binary");
				let contentType = attachment.contentType;
				if (contentType === "image/*") contentType = "image/png";
				return {
					content,
					contentType,
					contentUrl: attachment.contentUrl
				};
			} else return {
				content: Buffer.from(attachment.content),
				contentType: attachment.contentType,
				contentUrl: attachment.contentUrl
			};
		}
	};
	exports.AttachmentDownloader = AttachmentDownloader;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/conversationUpdateEvents.js
var require_conversationUpdateEvents = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/turnEvents.js
var require_turnEvents = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/inputFileDownloader.js
var require_inputFileDownloader = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/appMemory.js
var require_appMemory = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/extensions.js
var require_extensions = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AgentExtension = void 0;
	const routeRank_1 = require_routeRank();
	/**
	* Represents an extension that adds channel-specific routing functionality to an agent application.
	* This class allows you to register routes that are only active for a specific channel.
	*
	* @typeParam TState - The type of turn state that extends TurnState
	*/
	var AgentExtension = class {
		/**
		* Creates a new AgentExtension instance for the specified channel.
		*
		* @param channelId - The channel ID that this extension will be associated with
		*/
		constructor(channelId) {
			this.channelId = channelId;
		}
		/**
		* Adds a route to the agent application that is only active for the channel specified in this extension.
		* This method creates a channel-specific route by wrapping the provided route selector with an additional
		* check to ensure the incoming activity matches the extension's channel ID.
		*
		* @param app - The agent application instance to add the route to
		* @param routeSelector - A function that determines if the route should handle the incoming activity
		* @param routeHandler - The handler function that will process the activity when the route is matched
		* @param isInvokeRoute - Optional. Whether this route handles invoke activities. Defaults to false
		* @param rank - Optional. The priority rank of this route for routing precedence. Defaults to RouteRank.Unspecified
		*
		* @example
		* ```typescript
		* const teamsExtension = new AgentExtension<MyState>('msteams');
		* teamsExtension.addRoute(
		*   app,
		*   (context) => context.activity.type === 'message',
		*   async (context, state) => {
		*     // Handle Teams-specific message
		*     await context.sendActivity('Hello from Teams!');
		*   }
		* );
		* ```
		*/
		addRoute(app, routeSelector, routeHandler, isInvokeRoute = false, rank = routeRank_1.RouteRank.Unspecified) {
			const ensureChannelMatches = async (context) => {
				return context.activity.channelId === this.channelId && routeSelector(context);
			};
			app.addRoute(ensureChannelMatches, routeHandler, isInvokeRoute, rank);
		}
	};
	exports.AgentExtension = AgentExtension;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/streaming/citation.js
var require_citation = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/teamsAttachmentDownloader.js
var require_teamsAttachmentDownloader = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.TeamsAttachmentDownloader = exports.M365AttachmentDownloader = void 0;
	const agents_activity_1 = require_src$2();
	const logger_1 = require_logger();
	const axios_1 = __importDefault(require_axios());
	const zod_1 = __require("zod");
	const logger = (0, logger_1.debug)("agents:M365AttachmentDownloader");
	/**
	* Downloads attachments from Teams and M365 using the bots access token.
	*/
	var M365AttachmentDownloader = class {
		constructor(stateKey = "inputFiles") {
			this._httpClient = axios_1.default.create();
			this._stateKey = stateKey;
		}
		/**
		* Download any files relative to the current user's input.
		*
		* @param {TurnContext} context Context for the current turn of conversation.
		* @returns {Promise<InputFile[]>} Promise that resolves to an array of downloaded input files.
		*/
		async downloadFiles(context) {
			var _a;
			if (context.activity.channelId !== agents_activity_1.Channels.Msteams && context.activity.channelId !== agents_activity_1.Channels.M365Copilot) return Promise.resolve([]);
			const attachments = (_a = context.activity.attachments) === null || _a === void 0 ? void 0 : _a.filter((a) => a.contentType && !a.contentType.startsWith("text/html"));
			if (!attachments || attachments.length === 0) return Promise.resolve([]);
			const connectorClient = context.turnState.get(context.adapter.ConnectorClientKey);
			this._httpClient.defaults.headers = connectorClient.axiosInstance.defaults.headers;
			const files = [];
			for (const attachment of attachments) {
				const file = await this.downloadFile(attachment);
				if (file) files.push(file);
			}
			return files;
		}
		/**
		* @private
		* @param {Attachment} attachment - Attachment to download.
		* @returns {Promise<InputFile>} - Promise that resolves to the downloaded input file.
		*/
		async downloadFile(attachment) {
			let inputFile;
			if (attachment.contentUrl && attachment.contentUrl.startsWith("https://")) try {
				const parsed = zod_1.z.object({ downloadUrl: zod_1.z.string().url() }).safeParse(attachment.content);
				const downloadUrl = parsed.success ? parsed.data.downloadUrl : attachment.contentUrl;
				const response = await this._httpClient.get(downloadUrl, { responseType: "arraybuffer" });
				inputFile = {
					content: Buffer.from(response.data, "binary"),
					contentType: response.headers["content-type"] || "application/octet-stream",
					contentUrl: attachment.contentUrl
				};
			} catch (error) {
				logger.error(`Failed to download Teams attachment: ${error}`);
				return;
			}
			else {
				if (!attachment.content) {
					logger.error("Attachment missing content");
					return;
				}
				if (!(attachment.content instanceof ArrayBuffer) && !Buffer.isBuffer(attachment.content)) {
					logger.error("Attachment content is not ArrayBuffer or Buffer");
					return;
				}
				inputFile = {
					content: Buffer.from(attachment.content),
					contentType: attachment.contentType,
					contentUrl: attachment.contentUrl
				};
			}
			return inputFile;
		}
		/**
		* Downloads files from the attachments in the current turn context and stores them in state.
		*
		* @param context The turn context containing the activity with attachments.
		* @param state The turn state to store the files in.
		* @returns A promise that resolves when the downloaded files are stored.
		*/
		async downloadAndStoreFiles(context, state) {
			const files = await this.downloadFiles(context);
			state.setValue(this._stateKey, files);
		}
	};
	exports.M365AttachmentDownloader = M365AttachmentDownloader;
	/**
	* @deprecated Use {@link M365AttachmentDownloader} from @microsoft/agents-hosting instead.
	*/
	var TeamsAttachmentDownloader = class extends M365AttachmentDownloader {};
	exports.TeamsAttachmentDownloader = TeamsAttachmentDownloader;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/app/index.js
var require_app = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$7) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$7, p)) __createBinding(exports$7, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_agentApplication(), exports);
	__exportStar(require_agentApplicationBuilder(), exports);
	__exportStar(require_agentApplicationOptions(), exports);
	__exportStar(require_appRoute(), exports);
	__exportStar(require_routeHandler(), exports);
	__exportStar(require_routeList(), exports);
	__exportStar(require_routeRank(), exports);
	__exportStar(require_routeSelector(), exports);
	__exportStar(require_attachmentDownloader(), exports);
	__exportStar(require_conversationUpdateEvents(), exports);
	__exportStar(require_turnState(), exports);
	__exportStar(require_turnEvents(), exports);
	__exportStar(require_turnStateEntry(), exports);
	__exportStar(require_inputFileDownloader(), exports);
	__exportStar(require_appMemory(), exports);
	__exportStar(require_extensions(), exports);
	__exportStar(require_adaptiveCards(), exports);
	__exportStar(require_streamingResponse(), exports);
	__exportStar(require_citation(), exports);
	__exportStar(require_teamsAttachmentDownloader(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/attachmentData.js
var require_attachmentData = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/attachmentInfo.js
var require_attachmentInfo = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/attachmentView.js
var require_attachmentView = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/conversationMembers.js
var require_conversationMembers = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/conversationResourceResponse.js
var require_conversationResourceResponse = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/conversationsResult.js
var require_conversationsResult = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/resourceResponse.js
var require_resourceResponse = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright(c) Microsoft Corporation.All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/connector-client/index.js
var require_connector_client = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$6) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$6, p)) __createBinding(exports$6, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_attachmentData(), exports);
	__exportStar(require_attachmentInfo(), exports);
	__exportStar(require_attachmentView(), exports);
	__exportStar(require_connectorClient(), exports);
	__exportStar(require_conversationMembers(), exports);
	__exportStar(require_conversationResourceResponse(), exports);
	__exportStar(require_conversationsResult(), exports);
	__exportStar(require_resourceResponse(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/adaptiveCardAuthentication.js
var require_adaptiveCardAuthentication = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/adaptiveCardInvokeResponse.js
var require_adaptiveCardInvokeResponse = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/adaptiveCardInvokeValue.js
var require_adaptiveCardInvokeValue = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/invokeResponse.js
var require_invokeResponse = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/searchInvokeOptions.js
var require_searchInvokeOptions = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/searchInvokeResponse.js
var require_searchInvokeResponse = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/searchInvokeValue.js
var require_searchInvokeValue = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/tokenExchangeInvokeRequest.js
var require_tokenExchangeInvokeRequest = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/invoke/index.js
var require_invoke = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$5) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$5, p)) __createBinding(exports$5, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_adaptiveCardAuthentication(), exports);
	__exportStar(require_adaptiveCardInvokeResponse(), exports);
	__exportStar(require_adaptiveCardInvokeValue(), exports);
	__exportStar(require_invokeException(), exports);
	__exportStar(require_invokeResponse(), exports);
	__exportStar(require_searchInvokeOptions(), exports);
	__exportStar(require_searchInvokeResponse(), exports);
	__exportStar(require_searchInvokeValue(), exports);
	__exportStar(require_tokenExchangeInvokeRequest(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/state/agentStatePropertyAccesor.js
var require_agentStatePropertyAccesor = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AgentStatePropertyAccessor = void 0;
	/**
	* Provides typed access to an Agent state property with automatic state loading and persistence management.
	*
	* @typeParam T The type of the property being accessed. Can be any serializable type.
	*
	* @remarks
	* `AgentStatePropertyAccessor` simplifies working with persisted state by abstracting
	* the complexity of loading state from storage and manipulating specific properties.
	* It provides a type-safe interface for state management with automatic handling of:
	*
	* - **Lazy Loading**: State is loaded from storage only when first accessed
	* - **Type Safety**: Full TypeScript support with generic type parameters
	* - **Default Values**: Automatic deep cloning of default values to prevent reference issues
	* - **Memory Management**: Efficient in-memory caching with explicit persistence control
	* - **Custom Keys**: Support for custom storage keys for advanced scenarios
	*
	* ### Key Features
	*
	* Key features of `AgentStatePropertyAccessor` include:
	* - [Type Safety](#type-safety)
	* - [Automatic Default Value Handling](#automatic-default-value-handling)
	* - [Explicit Persistence Control](#explicit-persistence-control)
	*
	* #### Type Safety
	* The accessor provides compile-time type checking when using TypeScript:
	* ```typescript
	* interface UserProfile {
	*   name: string;
	*   preferences: { theme: string; language: string };
	* }
	* const userProfile = userState.createProperty<UserProfile>("userProfile");
	* ```
	*
	* #### Automatic Default Value Handling
	* When a property doesn't exist, default values are automatically cloned and stored:
	* ```typescript
	* // If userProfile doesn't exist, the default will be cloned and saved
	* const profile = await userProfile.get(context, {
	*   name: "Anonymous",
	*   preferences: { theme: "light", language: "en" }
	* });
	* ```
	*
	* #### Explicit Persistence Control
	* Changes are kept in memory until explicitly persisted:
	* ```typescript
	* // Modify the state
	* const counter = await counterProperty.get(context, 0);
	* await counterProperty.set(context, counter + 1);
	*
	* // Changes are only in memory at this point
	* // Persist to storage
	* await userState.saveChanges(context);
	* ```
	*
	* ### Usage Examples
	*
	* @example Basic Usage
	* ```typescript
	* // Create a property accessor
	* const userProfile = userState.createProperty<UserProfile>("userProfile");
	*
	* // Get with default value
	* const profile = await userProfile.get(context, {
	*   name: "",
	*   preferences: { theme: "light", language: "en" }
	* });
	*
	* // Modify the profile
	* profile.preferences.theme = "dark";
	*
	* // Save the changes
	* await userProfile.set(context, profile);
	* await userState.saveChanges(context); // Persist to storage
	* ```
	*
	* @example Working with Primitive Types
	* ```typescript
	* const counterProperty = userState.createProperty<number>("counter");
	*
	* // Increment counter
	* const currentCount = await counterProperty.get(context, 0);
	* await counterProperty.set(context, currentCount + 1);
	* await userState.saveChanges(context);
	* ```
	*
	* @example Conditional Logic
	* ```typescript
	* const settingsProperty = userState.createProperty<Settings>("settings");
	*
	* // Check if property exists
	* const settings = await settingsProperty.get(context);
	* if (settings === undefined) {
	*   // Property doesn't exist, initialize with defaults
	*   await settingsProperty.set(context, getDefaultSettings());
	* }
	* ```
	*
	* @example Custom Storage Keys
	* ```typescript
	* // Store state with a custom key for multi-tenant scenarios
	* const customKey = { key: `tenant_${tenantId}` };
	* const tenantData = await dataProperty.get(context, defaultData, customKey);
	* await dataProperty.set(context, updatedData, customKey);
	* ```
	*
	* ### Important Notes
	*
	* - **Thread Safety**: This class is not thread-safe. Ensure proper synchronization in concurrent scenarios.
	* - **Memory Usage**: State objects are kept in memory until the context is disposed.
	* - **Persistence**: Always call `state.saveChanges(context)` to persist changes to storage.
	* - **Deep Cloning**: Default values are deep cloned using JSON serialization, which may not work with complex objects containing functions or circular references.
	*
	* @see {@link AgentState.createProperty} for creating property accessors
	* @see {@link StatePropertyAccessor} for the interface definition
	*/
	var AgentStatePropertyAccessor = class {
		/**
		* Creates a new instance of AgentStatePropertyAccessor.
		*
		* @param state The agent state object that manages the backing storage for this property
		* @param name The unique name of the property within the state object. This name is used as the key in the state storage.
		*
		* @remarks
		* This constructor is typically not called directly. Instead, use {@link AgentState.createProperty}
		* to create property accessors, which ensures proper integration with the state management system.
		*
		* @example
		* ```typescript
		* // Recommended way - use AgentState.createProperty
		* const userProfile = userState.createProperty<UserProfile>("userProfile");
		*
		* // Direct construction (not recommended)
		* const accessor = new AgentStatePropertyAccessor<UserProfile>(userState, "userProfile");
		* ```
		*
		*/
		constructor(state, name) {
			this.state = state;
			this.name = name;
		}
		/**
		* Deletes the property from the state storage.
		*
		* @param context The turn context for the current conversation turn
		* @param customKey Optional custom key for accessing state in a specific storage location.
		* Useful for multi-tenant scenarios or when state needs to be partitioned.
		* @returns A promise that resolves when the delete operation is complete
		*
		* @remarks
		* This operation removes the property from the in-memory state object but does not
		* automatically persist the change to the underlying storage. You must call
		* `state.saveChanges(context)` afterwards to persist the deletion.
		*
		* - If the property doesn't exist, this operation is a no-op
		* - The deletion only affects the in-memory state until `saveChanges()` is called
		* - After deletion, subsequent `get()` calls will return `undefined` (or the default value if provided)
		*
		* @example Basic usage
		* ```typescript
		* const userSettings = userState.createProperty<UserSettings>("settings");
		*
		* // Delete the user settings
		* await userSettings.delete(context);
		*
		* // Persist the deletion to storage
		* await userState.saveChanges(context);
		*
		* // Verify deletion
		* const settings = await userSettings.get(context); // Returns undefined
		* ```
		*
		* @example Custom key usage
		* ```typescript
		* const tenantKey = { key: `tenant_${tenantId}` };
		* await userSettings.delete(context, tenantKey);
		* await userState.saveChanges(context);
		* ```
		*
		*/
		async delete(context, customKey) {
			const obj = await this.state.load(context, false, customKey);
			if (Object.prototype.hasOwnProperty.call(obj, this.name)) delete obj[this.name];
		}
		/**
		* Retrieves the value of the property from state storage.
		*
		* @param context The turn context for the current conversation turn
		* @param defaultValue Optional default value to use if the property doesn't exist.
		*                    When provided, this value is deep cloned and stored in state.
		* @param customKey Optional custom key for accessing state in a specific storage location.
		*                  Useful for multi-tenant scenarios or when state needs to be partitioned.
		*
		* @returns A promise that resolves to the property value, the cloned default value, or `undefined`
		*
		* @remarks
		* This method provides intelligent default value handling:
		* - If the property exists, its value is returned
		* - If the property doesn't exist and a default value is provided, the default is deep cloned,
		*   stored in state, and returned
		* - If the property doesn't exist and no default is provided, `undefined` is returned
		*
		* **Deep Cloning**: Default values are deep cloned using JSON serialization to prevent
		* reference sharing issues. This means:
		* - Functions, symbols, and circular references will be lost
		* - Dates become strings (use Date constructor to restore)
		* - Complex objects with prototypes lose their prototype chain
		*
		* **Performance**: The first access loads state from storage; subsequent accesses use
		* the in-memory cached version until the context is disposed.
		*
		* @example Basic usage
		* ```typescript
		* const counterProperty = userState.createProperty<number>("counter");
		*
		* // Get with default value
		* const count = await counterProperty.get(context, 0);
		* console.log(count); // 0 if property doesn't exist, otherwise the stored value
		* ```
		*
		* @example Complex object with default
		* ```typescript
		* interface UserProfile {
		*   name: string;
		*   preferences: { theme: string; notifications: boolean };
		* }
		*
		* const userProfile = userState.createProperty<UserProfile>("profile");
		* const profile = await userProfile.get(context, {
		*   name: "Anonymous",
		*   preferences: { theme: "light", notifications: true }
		* });
		* ```
		*
		* @example Checking for existence
		* ```typescript
		* const profile = await userProfile.get(context);
		* if (profile === undefined) {
		*   console.log("Profile has not been set yet");
		* } else {
		*   console.log(`Welcome back, ${profile.name}!`);
		* }
		* ```
		*
		* @example Custom key usage
		* ```typescript
		* const tenantKey = { key: `tenant_${tenantId}` };
		* const tenantData = await dataProperty.get(context, defaultData, tenantKey);
		* ```
		*
		*/
		async get(context, defaultValue, customKey) {
			const obj = await this.state.load(context, false, customKey);
			if (!Object.prototype.hasOwnProperty.call(obj, this.name) && defaultValue !== void 0) {
				const clone = typeof defaultValue === "object" || Array.isArray(defaultValue) ? JSON.parse(JSON.stringify(defaultValue)) : defaultValue;
				obj[this.name] = clone;
			}
			return obj[this.name];
		}
		/**
		* Sets the value of the property in state storage.
		*
		* @param context The turn context for the current conversation turn
		* @param value The value to assign to the property. Can be any serializable value.
		* @param customKey Optional custom key for accessing state in a specific storage location.
		*                  Useful for multi-tenant scenarios or when state needs to be partitioned.
		*
		* @returns A promise that resolves when the set operation is complete
		*
		* @remarks
		* This operation updates the property in the in-memory state object but does not
		* automatically persist the change to the underlying storage. You must call
		* `state.saveChanges(context)` afterwards to persist the changes.
		*
		* **Memory vs Storage**: Changes are immediately reflected in memory and will be
		* available to subsequent `get()` calls within the same context, but are not
		* persisted to storage until `saveChanges()` is called.
		*
		* **Value References**: The exact value reference is stored (no cloning occurs).
		* Ensure you don't modify objects after setting them unless you intend for those
		* changes to be reflected in state.
		*
		* **Type Safety**: When using TypeScript, the value must match the property's
		* declared type parameter.
		*
		* @example Basic usage
		* ```typescript
		* const counterProperty = userState.createProperty<number>("counter");
		*
		* // Set a new value
		* await counterProperty.set(context, 42);
		*
		* // Persist to storage
		* await userState.saveChanges(context);
		* ```
		*
		* @example Complex object
		* ```typescript
		* const userProfile = userState.createProperty<UserProfile>("profile");
		*
		* const newProfile: UserProfile = {
		*   name: "John Doe",
		*   preferences: { theme: "dark", notifications: false }
		* };
		*
		* await userProfile.set(context, newProfile);
		* await userState.saveChanges(context);
		* ```
		*
		* @example Incremental updates
		* ```typescript
		* // Get current value, modify, then set
		* const settings = await settingsProperty.get(context, getDefaultSettings());
		* settings.theme = "dark";
		* settings.lastUpdated = new Date();
		*
		* await settingsProperty.set(context, settings);
		* await userState.saveChanges(context);
		* ```
		*
		* @example Custom key usage
		* ```typescript
		* const tenantKey = { key: `tenant_${tenantId}` };
		* await dataProperty.set(context, updatedData, tenantKey);
		* await userState.saveChanges(context);
		* ```
		*
		*/
		async set(context, value, customKey) {
			const obj = await this.state.load(context, false, customKey);
			obj[this.name] = value;
		}
	};
	exports.AgentStatePropertyAccessor = AgentStatePropertyAccessor;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/state/agentState.js
var require_agentState = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AgentState = void 0;
	const node_crypto_1 = __require("node:crypto");
	const agentStatePropertyAccesor_1 = require_agentStatePropertyAccesor();
	const logger = (0, require_logger().debug)("agents:state");
	/**
	* Manages the state of an Agent across turns in a conversation.
	*
	* @remarks
	* AgentState provides functionality to persist and retrieve state data using
	* a storage provider. It handles caching state in the turn context for performance,
	* calculating change hashes to detect modifications, and managing property accessors
	* for typed access to state properties.
	*/
	var AgentState = class {
		/**
		* Creates a new instance of AgentState.
		*
		* @param storage The storage provider used to persist state between turns
		* @param storageKey A factory function that generates keys for storing state data
		*/
		constructor(storage, storageKey) {
			this.storage = storage;
			this.storageKey = storageKey;
			this.stateKey = Symbol("state");
			/**
			* Calculates a hash for the specified state object to detect changes.
			*
			* @param item The state object to calculate the hash for
			* @returns A string hash representing the state
			*
			* @remarks
			* The eTag property is excluded from the hash calculation.
			* @private
			*/
			this.calculateChangeHash = (item) => {
				const { eTag, ...rest } = item;
				const result = JSON.stringify(rest);
				return (0, node_crypto_1.createHash)("sha256", { encoding: "utf-8" }).update(result).digest("hex");
			};
		}
		/**
		* Creates a property accessor for the specified property.
		*
		* @param name The name of the property to access
		* @returns A property accessor for the specified property
		*
		* @remarks
		* Property accessors provide typed access to properties within the state object.
		*/
		createProperty(name) {
			return new agentStatePropertyAccesor_1.AgentStatePropertyAccessor(this, name);
		}
		/**
		* Loads the state from storage into the turn context.
		*
		* @param context The turn context to load state into
		* @param force If true, forces a reload from storage even if state is cached
		* @param customKey Optional custom storage key to use instead of the default
		* @returns A promise that resolves to the loaded state object
		*
		* @remarks
		* If state is already cached in the turn context and force is not set, the cached version will be used.
		*/
		async load(context, force = false, customKey) {
			const cached = context.turnState.get(this.stateKey);
			if (force || !cached || !cached.state) {
				const key = await this.getStorageOrCustomKey(customKey, context);
				logger.info(`Reading storage with key ${key}`);
				const state = (await this.storage.read([key]))[key] || {};
				const hash = this.calculateChangeHash(state);
				context.turnState.set(this.stateKey, {
					state,
					hash
				});
				return state;
			}
			return cached.state;
		}
		/**
		* Saves the state to storage if it has changed since it was loaded.
		*
		* @param context The turn context containing the state to save
		* @param force If true, forces a save to storage even if no changes are detected
		* @param customKey Optional custom storage key to use instead of the default
		* @returns A promise that resolves when the save operation is complete
		*
		* @remarks
		* Change detection uses a hash of the state object to determine if saving is necessary.
		*/
		async saveChanges(context, force = false, customKey) {
			let cached = context.turnState.get(this.stateKey);
			if (force || cached && cached.hash !== this.calculateChangeHash(cached === null || cached === void 0 ? void 0 : cached.state)) {
				if (!cached) cached = {
					state: {},
					hash: ""
				};
				cached.state.eTag = "*";
				const changes = {};
				const key = await this.getStorageOrCustomKey(customKey, context);
				changes[key] = cached.state;
				logger.info(`Writing storage with key ${key}`);
				await this.storage.write(changes);
				cached.hash = this.calculateChangeHash(cached.state);
				context.turnState.set(this.stateKey, cached);
			}
		}
		/**
		* Determines whether to use a custom key or generate one from the context.
		*
		* @param customKey Optional custom key with channel and conversation IDs
		* @param context The turn context used to generate a key if no custom key is provided
		* @returns The storage key to use
		* @private
		*/
		async getStorageOrCustomKey(customKey, context) {
			let key;
			if (customKey && customKey.channelId && customKey.conversationId) key = `${customKey.channelId}/conversations/${customKey.conversationId}`;
			else key = await this.storageKey(context);
			return key;
		}
		/**
		* Clears the state by setting it to an empty object in the turn context.
		*
		* @param context The turn context containing the state to clear
		* @returns A promise that resolves when the clear operation is complete
		*
		* @remarks
		* This does not remove the state from storage, it only clears the in-memory representation.
		* Call saveChanges() after this to persist the empty state to storage.
		*
		*/
		async clear(context) {
			context.turnState.set(this.stateKey, {
				state: {},
				hash: ""
			});
		}
		/**
		* Deletes the state from both the turn context and storage.
		*
		* @param context The turn context containing the state to delete
		* @param customKey Optional custom storage key to use instead of the default
		* @returns A promise that resolves when the delete operation is complete
		*/
		async delete(context, customKey) {
			if (context.turnState.has(this.stateKey)) context.turnState.delete(this.stateKey);
			const key = await this.getStorageOrCustomKey(customKey, context);
			logger.info(`Deleting storage with key ${key}`);
			await this.storage.delete([key]);
		}
		/**
		* Gets the state from the turn context without loading it from storage.
		*
		* @param context The turn context containing the state to get
		* @returns The state object, or undefined if no state is found in the turn context
		*/
		get(context) {
			const cached = context.turnState.get(this.stateKey);
			return typeof cached === "object" && typeof cached.state === "object" ? cached.state : void 0;
		}
	};
	exports.AgentState = AgentState;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/state/userState.js
var require_userState = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.UserState = void 0;
	const agentState_1 = require_agentState();
	/**
	* Manages the state of a user.
	*/
	var UserState = class extends agentState_1.AgentState {
		/**
		* Creates a new instance of UserState.
		* @param storage The storage provider.
		*/
		constructor(storage, namespace = "") {
			super(storage, (context) => {
				const key = this.getStorageKey(context);
				return key !== null && key !== void 0 ? key : /* @__PURE__ */ new Error("UserState: overridden getStorageKey method did not return a key.");
			});
			this.namespace = namespace;
		}
		getStorageKey(context) {
			const activity = context.activity;
			const channelId = activity.channelId;
			const userId = activity && activity.from != null && activity.from.id ? activity.from.id : void 0;
			if (!channelId) throw new Error("missing activity.channelId");
			if (!userId) throw new Error("missing activity.from.id");
			return `${channelId}/users/${userId}/${this.namespace}`;
		}
	};
	exports.UserState = UserState;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/state/conversationState.js
var require_conversationState = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.ConversationState = void 0;
	const agentState_1 = require_agentState();
	/**
	* Manages the state of a conversation.
	*/
	var ConversationState = class extends agentState_1.AgentState {
		/**
		* Creates a new instance of ConversationState.
		* @param storage The storage provider.
		*/
		constructor(storage, namespace = "") {
			super(storage, (context) => {
				const key = this.getStorageKey(context);
				return key !== null && key !== void 0 ? key : /* @__PURE__ */ new Error("ConversationState: overridden getStorageKey method did not return a key.");
			});
			this.namespace = namespace;
		}
		getStorageKey(context) {
			const activity = context.activity;
			const channelId = activity.channelId;
			const conversationId = activity && activity.conversation != null && activity.conversation.id ? activity.conversation.id : void 0;
			if (!channelId) throw new Error("missing activity.channelId");
			if (!conversationId) throw new Error("missing activity.conversation.id");
			return `${channelId}/conversations/${conversationId}/${this.namespace}`;
		}
	};
	exports.ConversationState = ConversationState;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/state/index.js
var require_state = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$4) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$4, p)) __createBinding(exports$4, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_userState(), exports);
	__exportStar(require_conversationState(), exports);
	__exportStar(require_agentStatePropertyAccesor(), exports);
	__exportStar(require_agentState(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/storage/storage.js
var require_storage$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/storage/memoryStorage.js
var require_memoryStorage = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.MemoryStorage = void 0;
	const logger = (0, require_logger().debug)("agents:memory-storage");
	exports.MemoryStorage = class MemoryStorage {
		/**
		* Creates a new instance of the MemoryStorage class.
		*
		* @param memory An optional initial memory store to seed the storage with data
		*/
		constructor(memory = {}) {
			this.memory = memory;
			/**
			* Counter used to generate unique eTags for stored items
			*/
			this.etag = 1;
		}
		/**
		* Gets a single shared instance of the MemoryStorage class.
		*
		* @returns The singleton instance of MemoryStorage
		*
		* @remarks
		* Using this method ensures that the same storage instance is used across
		* the application, allowing for shared state without passing references.
		*
		*/
		static getSingleInstance() {
			if (!MemoryStorage.instance) MemoryStorage.instance = new MemoryStorage();
			return MemoryStorage.instance;
		}
		/**
		* Reads storage items from memory.
		*
		* @param keys The keys of the items to read
		* @returns A promise that resolves to the read items
		* @throws Will throw an error if keys are not provided or the array is empty
		*/
		async read(keys) {
			if (!keys || keys.length === 0) throw new ReferenceError("Keys are required when reading.");
			const data = {};
			for (const key of keys) {
				logger.debug(`Reading key: ${key}`);
				const item = this.memory[key];
				if (item) data[key] = JSON.parse(item);
			}
			return data;
		}
		/**
		* Writes storage items to memory.
		*
		* @param changes The items to write, indexed by key
		* @returns A promise that resolves when the write operation is complete
		* @throws Will throw an error if changes are not provided or if there's an eTag conflict
		*
		* @remarks
		* This method supports optimistic concurrency control through eTags.
		* If an item has an eTag, it will only be updated if the existing item
		* has the same eTag. If an item has an eTag of '*' or no eTag, it will
		* always be written regardless of the current state.
		*/
		async write(changes) {
			if (!changes || changes.length === 0) throw new ReferenceError("Changes are required when writing.");
			for (const [key, newItem] of Object.entries(changes)) {
				logger.debug(`Writing key: ${key}`);
				const oldItemStr = this.memory[key];
				if (!oldItemStr || newItem.eTag === "*" || !newItem.eTag) this.saveItem(key, newItem);
				else {
					const oldItem = JSON.parse(oldItemStr);
					if (newItem.eTag === oldItem.eTag) this.saveItem(key, newItem);
					else throw new Error(`Storage: error writing "${key}" due to eTag conflict.`);
				}
			}
		}
		/**
		* Deletes storage items from memory.
		*
		* @param keys The keys of the items to delete
		* @returns A promise that resolves when the delete operation is complete
		*/
		async delete(keys) {
			logger.debug(`Deleting keys: ${keys.join(", ")}`);
			for (const key of keys) delete this.memory[key];
		}
		/**
		* Saves an item to memory with a new eTag.
		*
		* @param key The key of the item to save
		* @param item The item to save
		*
		* @remarks
		* This private method handles the details of:
		* - Creating a clone of the item to prevent modification of the original
		* - Generating a new eTag for optimistic concurrency control
		* - Converting the item to a JSON string for storage
		*
		* @private
		*/
		saveItem(key, item) {
			const clone = Object.assign({}, item, { eTag: (this.etag++).toString() });
			this.memory[key] = JSON.stringify(clone);
		}
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/storage/fileStorage.js
var require_fileStorage = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __importDefault = exports && exports.__importDefault || function(mod) {
		return mod && mod.__esModule ? mod : { "default": mod };
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.FileStorage = void 0;
	const path_1 = __importDefault(__require("path"));
	const fs_1 = __importDefault(__require("fs"));
	/**
	* A file-based storage implementation that persists data to the local filesystem.
	*
	* @remarks
	* FileStorage stores all data in a single JSON file named 'state.json' within a specified folder.
	* This implementation is suitable for development scenarios, local testing, and single-instance
	* deployments where shared state across multiple instances is not required.
	*
	* The storage format is a simple key-value JSON object where keys are strings and values
	* can be any JSON-serializable data. All operations are synchronous file I/O operations
	* wrapped in Promise interfaces to match the Storage contract.
	*
	* ### Warning
	* This implementation does not provide:
	* - Thread safety for concurrent access
	* - Optimistic concurrency control (eTag support)
	* - Atomic operations across multiple keys
	* - Scale for large datasets
	*
	* For production scenarios requiring these features, consider using
	* database-backed storage implementations instead.
	*
	* @example
	* ```typescript
	* const storage = new FileStorage('./data');
	*
	* // Write some data
	* await storage.write({
	*   'user123': { name: 'John', lastSeen: new Date().toISOString() },
	*   'conversation456': { turn: 5, context: 'discussing weather' }
	* });
	*
	* // Read specific keys
	* const data = await storage.read(['user123']);
	* console.log(data.user123); // { name: 'John', lastSeen: '...' }
	*
	* // Delete data
	* await storage.delete(['conversation456']);
	* ```
	*
	*/
	var FileStorage = class {
		/**
		* Creates a new FileStorage instance that stores data in the specified folder.
		*
		* @param folder The absolute or relative path to the folder where the state.json file will be stored
		* @throws May throw filesystem errors if the folder cannot be created or accessed
		*
		* @remarks
		* The constructor performs the following initialization steps:
		* 1. Creates the target folder if it doesn't exist (including parent directories)
		* 2. Creates an empty state.json file if it doesn't exist
		* 3. Loads existing data from state.json into memory for fast access
		*
		*/
		constructor(folder) {
			this._folder = folder;
			if (!fs_1.default.existsSync(folder)) fs_1.default.mkdirSync(folder, { recursive: true });
			if (!fs_1.default.existsSync(path_1.default.join(folder, "state.json"))) fs_1.default.writeFileSync(path_1.default.join(folder, "state.json"), "{}");
			const data = fs_1.default.readFileSync(path_1.default.join(folder, "state.json"), "utf8");
			this._stateFile = JSON.parse(data);
		}
		/**
		* Reads store items from the filesystem storage.
		*
		* @param keys Array of keys to read from storage
		* @returns Promise resolving to an object containing the requested items (keys that don't exist are omitted)
		* @throws ReferenceError if keys array is empty or undefined
		*
		* @remarks
		* This method reads from the in-memory cache that was loaded during construction,
		* making it very fast but potentially returning stale data if the file was
		* modified by external processes.
		*
		*/
		read(keys) {
			return new Promise((resolve, reject) => {
				if (!keys || keys.length === 0) reject(/* @__PURE__ */ new ReferenceError("Keys are required when reading."));
				else {
					const data = {};
					for (const key of keys) {
						const item = this._stateFile[key];
						if (item) data[key] = item;
					}
					resolve(data);
				}
			});
		}
		/**
		* Writes store items to the filesystem storage.
		*
		* @param changes Object containing key-value pairs to write to storage
		* @returns Promise that resolves when the write operation completes
		*
		* @remarks
		* This method updates both the in-memory cache and writes the entire state
		* to the state.json file. The file is written with pretty-printing (2-space indentation)
		* for better readability during development and debugging.
		*
		* > [!NOTE]
		* > This implementation does not support eTag-based optimistic concurrency control.
		* > Any eTag values in the changes object are ignored.
		*
		*/
		write(changes) {
			const keys = Object.keys(changes);
			for (const key of keys) this._stateFile[key] = changes[key];
			fs_1.default.writeFileSync(this._folder + "/state.json", JSON.stringify(this._stateFile, null, 2));
			return Promise.resolve();
		}
		/**
		* Deletes store items from the filesystem storage.
		*
		* @param keys Array of keys to delete from storage
		* @returns Promise that resolves when the delete operation completes
		*
		* @throws ReferenceError if keys array is empty or undefined
		*
		* @remarks
		* This method removes the specified keys from both the in-memory cache
		* and writes the updated state to the state.json file. Keys that don't
		* exist in storage are silently ignored.
		*
		*/
		delete(keys) {
			return new Promise((resolve, reject) => {
				if (!keys || keys.length === 0) reject(/* @__PURE__ */ new ReferenceError("Keys are required when deleting."));
				else {
					for (const key of keys) delete this._stateFile[key];
					fs_1.default.writeFileSync(this._folder + "/state.json", JSON.stringify(this._stateFile, null, 2));
				}
				resolve();
			});
		}
	};
	exports.FileStorage = FileStorage;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/storage/index.js
var require_storage = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$3) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$3, p)) __createBinding(exports$3, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_storage$1(), exports);
	__exportStar(require_memoryStorage(), exports);
	__exportStar(require_fileStorage(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/agent-client/agentClient.js
var require_agentClient = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.AgentClient = void 0;
	const auth_1 = require_auth$1();
	const agents_activity_1 = require_src$2();
	const uuid_1$1 = __require("uuid");
	const logger = (0, require_logger().debug)("agents:agent-client");
	/**
	* Client for communicating with other agents through HTTP requests.
	* Manages configuration, authentication, and activity exchange with target agents.
	*/
	var AgentClient = class {
		/**
		* Creates a new instance of the AgentClient class.
		*
		* @param agentConfigKey The name of the agent, used to locate configuration in environment variables
		* @throws Error if required configuration is missing
		*/
		constructor(agentConfigKey) {
			this.agentClientConfig = this.loadAgentClientConfig(agentConfigKey);
		}
		/**
		* Sends an activity to another agent and handles the conversation state.
		*
		* @param activity The activity to send to the target agent
		* @param authConfig Authentication configuration used to obtain access tokens
		* @param conversationState State manager to store conversation data
		* @param context The current turn context
		* @returns A promise that resolves to the HTTP status text of the agent response
		* @throws Error if the request to the agent endpoint fails
		*/
		async postActivity(activity, authConfig, conversationState, context) {
			const activityCopy = activity.clone();
			activityCopy.serviceUrl = this.agentClientConfig.serviceUrl;
			activityCopy.recipient = {
				...activityCopy.recipient,
				role: agents_activity_1.RoleTypes.Skill
			};
			activityCopy.relatesTo = {
				serviceUrl: activity.serviceUrl,
				activityId: activityCopy.id,
				channelId: activityCopy.channelId,
				locale: activityCopy.locale,
				conversation: {
					id: activity.conversation.id,
					...activityCopy.conversation
				}
			};
			activityCopy.conversation.id = (0, uuid_1$1.v4)();
			const conversationDataAccessor = conversationState.createProperty(activityCopy.conversation.id);
			const convRef = await conversationDataAccessor.set(context, {
				conversationReference: activity.getConversationReference(),
				nameRequested: false
			}, {
				channelId: activityCopy.channelId,
				conversationId: activityCopy.conversation.id
			});
			const stateChanges = JSON.stringify(convRef);
			logger.debug("stateChanges: ", stateChanges);
			const token = await new auth_1.MsalTokenProvider(authConfig).getAccessToken(this.agentClientConfig.clientId);
			logger.debug("agent request: ", activityCopy);
			let authHeader = "";
			if (token.trim().length > 0) authHeader = `Bearer ${token}`;
			await conversationState.saveChanges(context, false, {
				channelId: activityCopy.channelId,
				conversationId: activityCopy.conversation.id
			});
			const response = await fetch(this.agentClientConfig.endPoint, {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Authorization: authHeader,
					"x-ms-conversation-id": activityCopy.conversation.id
				},
				body: JSON.stringify(activityCopy)
			});
			if (!response.ok) {
				await conversationDataAccessor.delete(context, {
					channelId: activityCopy.channelId,
					conversationId: activityCopy.conversation.id
				});
				throw new Error(`Failed to post activity to agent: ${response.statusText}`);
			}
			return response.statusText;
		}
		/**
		* Loads agent configuration from environment variables based on the agent name.
		*
		* @param agentName The name of the agent to load configuration for
		* @returns The agent client configuration
		* @throws Error if any required configuration is missing
		* @private
		*/
		loadAgentClientConfig(agentName) {
			if (agentName) if (process.env[`${agentName}_endpoint`] !== void 0 && process.env[`${agentName}_clientId`] !== void 0 && process.env[`${agentName}_serviceUrl`] !== void 0) return {
				endPoint: process.env[`${agentName}_endpoint`],
				clientId: process.env[`${agentName}_clientId`],
				serviceUrl: process.env[`${agentName}_serviceUrl`]
			};
			else throw new Error(`Missing agent client config for agent ${agentName}`);
			else throw new Error("Agent name is required");
		}
	};
	exports.AgentClient = AgentClient;
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/agent-client/agentResponseHandler.js
var require_agentResponseHandler = /* @__PURE__ */ __commonJSMin(((exports) => {
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.configureResponseController = void 0;
	const agents_activity_1 = require_src$2();
	const cloudAdapter_1 = require_cloudAdapter();
	const turnContext_1 = require_turnContext();
	const uuid_1 = __require("uuid");
	const activityWireCompat_1 = require_activityWireCompat();
	const logger = (0, require_logger().debug)("agents:agent-client");
	/**
	* To enable Agent to Agent communication, configures the agent response controller endpoint for handling incoming activities from external services.
	*
	* @remarks
	* This function sets up a POST endpoint that receives activities (messages, events, etc.) from external
	* services and processes them through the bot framework's activity handling pipeline. It's typically used
	* when the agent needs to receive and respond to activities from channels or services that send activities
	* to a specific webhook endpoint.
	*
	* The endpoint expects activities to be sent to:
	* `POST /api/agentresponse/v3/conversations/{conversationId}/activities/{activityId}`
	*
	* The function handles:
	* - Normalizing incoming activity data from the request body
	* - Retrieving conversation references from conversation state
	* - Continuing conversations using the stored conversation reference
	* - Processing EndOfConversation activities by cleaning up conversation state
	* - Sending activities through the turn context and returning responses
	*
	* @param app - The Express application instance to configure the route on
	* @param adapter - The CloudAdapter instance used for processing bot framework activities and managing conversations
	* @param agent - The ActivityHandler instance that contains the bot's logic for processing different types of activities
	* @param conversationState - The ConversationState instance used for managing conversation-specific state and conversation references
	*
	* @example
	* ```typescript
	* const app = express();
	* const adapter = new CloudAdapter();
	* const agent = new MyActivityHandler();
	* const conversationState = new ConversationState(memoryStorage);
	*
	* configureResponseController(app, adapter, agent, conversationState);
	* ```
	*/
	const configureResponseController = (app, adapter, agent, conversationState) => {
		app.post("/api/agentresponse/v3/conversations/:conversationId/activities/:activityId", handleResponse(adapter, agent, conversationState));
	};
	exports.configureResponseController = configureResponseController;
	const handleResponse = (adapter, handler, conversationState) => async (req, res) => {
		var _a, _b;
		const incoming = (0, activityWireCompat_1.normalizeIncomingActivity)(req.body);
		const activity = agents_activity_1.Activity.fromObject(incoming);
		logger.debug("received response: ", activity);
		const connection = adapter.connectionManager.getDefaultConnection();
		const appId = (_b = (_a = connection === null || connection === void 0 ? void 0 : connection.connectionSettings) === null || _a === void 0 ? void 0 : _a.clientId) !== null && _b !== void 0 ? _b : "";
		const myTurnContext = new turnContext_1.TurnContext(adapter, activity, cloudAdapter_1.CloudAdapter.createIdentity(appId));
		const conversationDataAccessor = conversationState.createProperty(req.params.conversationId);
		const conversationRefState = await conversationDataAccessor.get(myTurnContext, void 0, {
			channelId: activity.channelId,
			conversationId: req.params.conversationId
		});
		const conversationRef = JSON.stringify(conversationRefState.conversationReference);
		console.log("conversationRef", conversationRef);
		const callback = async (turnContext) => {
			activity.applyConversationReference(conversationRefState.conversationReference);
			turnContext.activity.id = req.params.activityId;
			let response;
			if (activity.type === agents_activity_1.ActivityTypes.EndOfConversation) {
				await conversationDataAccessor.delete(turnContext, {
					channelId: activity.channelId,
					conversationId: activity.conversation.id
				});
				applyActivityToTurnContext(turnContext, activity);
				await handler.run(turnContext);
				response = (0, uuid_1.v4)().replace(/-/g, "");
			} else response = await turnContext.sendActivity(activity);
			res.status(200).send(response);
		};
		await adapter.continueConversation(myTurnContext.identity, conversationRefState.conversationReference, callback);
	};
	const applyActivityToTurnContext = (turnContext, activity) => {
		turnContext.activity.channelData = activity.channelData;
		turnContext.activity.code = activity.code;
		turnContext.activity.entities = activity.entities;
		turnContext.activity.locale = activity.locale;
		turnContext.activity.localTimestamp = activity.localTimestamp;
		turnContext.activity.name = activity.name;
		turnContext.activity.relatesTo = activity.relatesTo;
		turnContext.activity.replyToId = activity.replyToId;
		turnContext.activity.timestamp = activity.timestamp;
		turnContext.activity.text = activity.text;
		turnContext.activity.type = activity.type;
		turnContext.activity.value = activity.value;
	};
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/agent-client/index.js
var require_agent_client = /* @__PURE__ */ __commonJSMin(((exports) => {
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$2) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$2, p)) __createBinding(exports$2, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	__exportStar(require_agentClient(), exports);
	__exportStar(require_agentResponseHandler(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@microsoft+agents-hosting@1.3.1/node_modules/@microsoft/agents-hosting/dist/src/index.js
var require_src = /* @__PURE__ */ __commonJSMin(((exports) => {
	/**
	* Copyright (c) Microsoft Corporation. All rights reserved.
	* Licensed under the MIT License.
	*/
	var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		var desc = Object.getOwnPropertyDescriptor(m, k);
		if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
			enumerable: true,
			get: function() {
				return m[k];
			}
		};
		Object.defineProperty(o, k2, desc);
	}) : (function(o, m, k, k2) {
		if (k2 === void 0) k2 = k;
		o[k2] = m[k];
	}));
	var __exportStar = exports && exports.__exportStar || function(m, exports$1) {
		for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
	};
	Object.defineProperty(exports, "__esModule", { value: true });
	exports.HostingErrors = exports.authorizeJWT = void 0;
	__exportStar(require_auth$1(), exports);
	var jwt_middleware_1 = require_jwt_middleware();
	Object.defineProperty(exports, "authorizeJWT", {
		enumerable: true,
		get: function() {
			return jwt_middleware_1.authorizeJWT;
		}
	});
	__exportStar(require_app(), exports);
	__exportStar(require_cards(), exports);
	__exportStar(require_connector_client(), exports);
	var errorHelper_1 = require_errorHelper();
	Object.defineProperty(exports, "HostingErrors", {
		enumerable: true,
		get: function() {
			return errorHelper_1.Errors;
		}
	});
	__exportStar(require_invoke(), exports);
	__exportStar(require_oauth(), exports);
	__exportStar(require_state(), exports);
	__exportStar(require_storage(), exports);
	__exportStar(require_transcript(), exports);
	__exportStar(require_activityHandler(), exports);
	__exportStar(require_baseAdapter(), exports);
	__exportStar(require_cloudAdapter(), exports);
	__exportStar(require_middlewareSet(), exports);
	__exportStar(require_messageFactory(), exports);
	__exportStar(require_statusCodes(), exports);
	__exportStar(require_turnContext(), exports);
	__exportStar(require_turnContextStateCollection(), exports);
	__exportStar(require_storage$1(), exports);
	__exportStar(require_headerPropagation(), exports);
	__exportStar(require_agent_client(), exports);
}));
//#endregion
export default require_src();
export {};