const require_getNetworkProviderFromNetworkId = require('./getNetworkProviderFromNetworkId-CY555AiJ.cjs');
const require_InvalidParamError = require('./InvalidParamError-D-SHhcTB.cjs');
let _dynamic_labs_sdk_api_core = require("@dynamic-labs/sdk-api-core");

//#region src/utils/setCookie/setCookie.ts
/**
* Sefelly sets the cookie in the browser.
* @not-instrumented
*/
const setCookie = (cookie) => {
	document.cookie = cookie;
};

//#endregion
//#region src/modules/clientEvents/clientEvents.ts
/**
* Adds an event listener for Dynamic client events.
*
* This function allows you to listen for various events emitted by the Dynamic client,
* such as authentication state changes, wallet connections, and more.
*
* @param params.event - The event name to listen for.
* @param params.listener - The callback function to execute when the event is fired.
* @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
* @returns A function that can be called to remove the listener.
* @instrumented
*/
const onEvent = ({ event, listener }, client = require_InvalidParamError.getDefaultClient()) => {
	const { eventEmitter } = require_InvalidParamError.getCore(client);
	eventEmitter.on(event, listener);
	return () => {
		eventEmitter.off(event, listener);
	};
};
/**
* Removes an event listener from Dynamic client events.
*
* This function unsubscribes a previously registered event listener
* from the specified Dynamic client event.
*
* @param params.event - The event name to remove the listener from.
* @param params.listener - The callback function to remove.
* @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
* @instrumented
*/
const offEvent = ({ event, listener }, client = require_InvalidParamError.getDefaultClient()) => {
	const { eventEmitter } = require_InvalidParamError.getCore(client);
	eventEmitter.off(event, listener);
};
/**
* Adds a one-time event listener for Dynamic client events.
*
* This function listens for an event that will automatically remove itself
* after being triggered once.
*
* @param params.event - The event name to listen for.
* @param params.listener - The callback function to execute when the event is fired.
* @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
* @returns A function that can be called to remove the listener before it fires.
* @instrumented
*/
const onceEvent = ({ event, listener }, client = require_InvalidParamError.getDefaultClient()) => {
	const { eventEmitter } = require_InvalidParamError.getCore(client);
	eventEmitter.once(event, listener);
	return () => {
		eventEmitter.off(event, listener);
	};
};
/**
* Emits a Dynamic client event.
*
* This function triggers an event that will be received by all registered
* listeners for the specified event type.
*
* @param params.event - The event name to emit.
* @param params.args - The arguments to pass to event listeners.
* @param client - The Dynamic client instance.
* @not-instrumented
*/
const emitEvent = ({ event, args }, client) => {
	const { eventEmitter } = require_InvalidParamError.getCore(client);
	eventEmitter.emit(event, args);
};
const __onEvent_impl = onEvent;
const __onEvent_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __onEvent_impl,
	functionName: "onEvent",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});
const __offEvent_impl = offEvent;
const __offEvent_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __offEvent_impl,
	functionName: "offEvent",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});
const __onceEvent_impl = onceEvent;
const __onceEvent_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __onceEvent_impl,
	functionName: "onceEvent",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/errors/InvalidWalletProviderKeyError.ts
var InvalidWalletProviderKeyError = class extends require_InvalidParamError.BaseError {
	constructor(value) {
		super({
			cause: null,
			code: "invalid_wallet_provider_key",
			docsUrl: null,
			name: "InvalidWalletProviderKeyError",
			shortMessage: `Invalid wallet provider key: ${value}. Key must be in the format of <normalizedWalletNameWithChain>:<walletProviderType>[:<suffix>]`
		});
	}
};

//#endregion
//#region src/modules/wallets/walletProvider/splitWalletProviderKey/splitWalletProviderKey.ts
/** @not-instrumented */
const splitWalletProviderKey = (walletProviderKey) => {
	const [normalizedWalletNameWithChain, walletProviderType, suffix, ...rest] = walletProviderKey.split(":");
	if (!normalizedWalletNameWithChain || !Object.values(_dynamic_labs_sdk_api_core.WalletProviderEnum).includes(walletProviderType) || rest.length > 0) throw new InvalidWalletProviderKeyError(walletProviderKey);
	return {
		normalizedWalletNameWithChain,
		suffix,
		walletProviderType
	};
};

//#endregion
//#region src/modules/wallets/utils/normalizeAddress/normalizeAddress.ts
/** @not-instrumented */
const normalizeAddress = ({ address, chain }) => {
	let normalizedAddress = address;
	if (normalizedAddress?.startsWith("0x")) normalizedAddress = normalizedAddress.slice(2);
	normalizedAddress = ["EVM", "FLOW"].includes(chain) ? normalizedAddress?.toLowerCase() : normalizedAddress;
	return normalizedAddress;
};

//#endregion
//#region src/modules/wallets/utils/formatWalletAccountId/formatWalletAccountId.ts
/** @not-instrumented */
const formatWalletAccountId = ({ address, chain, walletProviderKey }) => {
	const { normalizedWalletNameWithChain } = splitWalletProviderKey(walletProviderKey);
	return `${normalizedWalletNameWithChain}:${normalizeAddress({
		address,
		chain
	})}`;
};

//#endregion
//#region src/modules/wallets/utils/convertUnverifiedWalletAccountToWalletAccount/convertUnverifiedWalletAccountToWalletAccount.ts
/** @not-instrumented */
const convertUnverifiedWalletAccountToWalletAccount = ({ unverifiedWalletAccount }) => ({
	address: unverifiedWalletAccount.address,
	addressesWithTypes: unverifiedWalletAccount.addressesWithTypes,
	chain: unverifiedWalletAccount.chain,
	id: formatWalletAccountId({
		address: unverifiedWalletAccount.address,
		chain: unverifiedWalletAccount.chain,
		walletProviderKey: unverifiedWalletAccount.walletProviderKey
	}),
	lastSelectedAt: unverifiedWalletAccount.lastSelectedAt,
	verifiedCredentialId: null,
	walletProviderKey: unverifiedWalletAccount.walletProviderKey
});

//#endregion
//#region src/modules/wallets/utils/normalizeWalletNameWithChain/normalizeWalletNameWithChain.ts
/**
* Format the raw wallet name and chain to get the value we can use for
* verified credentials' `walletName` field.
* @not-instrumented
*/
const normalizeWalletNameWithChain = ({ displayName, chain }) => {
	const sanitizedWalletName = displayName.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
	const chainLowered = chain.toLocaleLowerCase();
	if (sanitizedWalletName.endsWith(chainLowered)) return sanitizedWalletName;
	return `${sanitizedWalletName}${chainLowered}`;
};

//#endregion
//#region src/modules/wallets/utils/formatWalletProviderKey/formatWalletProviderKey.ts
/**
* Assembles the wallet provider key from the wallet name, chain, and wallet provider type.
*
* The suffix is optional and can be used to add a uniquely identifying string to the key, which
* might be necessary for some wallet providers (like Wallet Connect).
*
* IMPORTANT: Do NOT add a suffix unless absolutely necessary, as it will cause the wallet account
* to not be able to find its wallet provider when connecting to a new device (it won't be possible
* to determine the full key just from the Verified Credential data).
* @not-instrumented
*/
const formatWalletProviderKey = ({ suffix, chain, displayName, walletProviderType }) => {
	return `${normalizeWalletNameWithChain({
		chain,
		displayName
	})}:${walletProviderType}${suffix ? `:${suffix}` : ""}`;
};

//#endregion
//#region src/modules/wallets/walletProvider/walletProviderKeyMap/getWalletProviderKeyFromVerifiedCredential/getWalletProviderKeyFromVerifiedCredential.ts
/** @not-instrumented */
const getWalletProviderKeyFromVerifiedCredential = ({ verifiedCredential }, client) => {
	const { walletProviderKeyMap } = require_InvalidParamError.getCore(client).state.get();
	const storedWalletProviderKey = walletProviderKeyMap[verifiedCredential.id];
	if (storedWalletProviderKey) return { walletProviderKey: storedWalletProviderKey };
	/**
	* We fallback to comprising the wallet provider key from walletName and walletProvider.
	*
	* Some wallet provider types (like Wallet Connect) also use a special suffix for their wallet provider
	* keys, so this won't be enough for them.
	* Therefore, for those specific wallet providers, the wallet account will remain without a wallet provider
	* and will require reconnection.
	* Read walletProvider.types.ts for more info.
	*/
	require_InvalidParamError.assertDefined(verifiedCredential.walletName, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing walletName`);
	require_InvalidParamError.assertDefined(verifiedCredential.walletProvider, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing walletProvider`);
	require_InvalidParamError.assertDefined(verifiedCredential.chain, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing chain`);
	return { walletProviderKey: formatWalletProviderKey({
		chain: require_InvalidParamError.__getChainFromVerifiedCredentialChain_wrapped(verifiedCredential.chain),
		displayName: verifiedCredential.walletName,
		walletProviderType: verifiedCredential.walletProvider
	}) };
};

//#endregion
//#region src/modules/wallets/utils/convertVerifiedCredentialToWalletAccount/convertVerifiedCredentialToWalletAccount.ts
/** @not-instrumented */
const convertVerifiedCredentialToWalletAccount = ({ verifiedCredential }, client) => {
	require_InvalidParamError.assertDefined(verifiedCredential.address, "Missing address in verified credential");
	require_InvalidParamError.assertDefined(verifiedCredential.chain, "Missing chain in verified credential");
	const chain = require_InvalidParamError.__getChainFromVerifiedCredentialChain_wrapped(verifiedCredential.chain);
	const { walletProviderKey } = getWalletProviderKeyFromVerifiedCredential({ verifiedCredential }, client);
	const walletAccountId = formatWalletAccountId({
		address: verifiedCredential.address,
		chain,
		walletProviderKey
	});
	return {
		address: verifiedCredential.address,
		addressesWithTypes: verifiedCredential.walletAdditionalAddresses,
		chain,
		hardwareWalletVendor: verifiedCredential.walletProperties?.hardwareWallet,
		id: walletAccountId,
		lastSelectedAt: verifiedCredential.lastSelectedAt ?? null,
		verifiedCredentialId: verifiedCredential.id,
		walletProviderKey
	};
};

//#endregion
//#region src/modules/wallets/getWalletAccounts/getWalletAccountsFromState/getWalletAccountsFromState.ts
/** @not-instrumented */
const getWalletAccountsFromState = ({ unverifiedWalletAccounts, user }, client) => {
	const walletAccountsMap = /* @__PURE__ */ new Map();
	/**
	* Handle the unverified wallet accounts before the user verified credentials
	* so the later verified wallet accounts can override the unverified wallet accounts
	*/
	unverifiedWalletAccounts.forEach((unverifiedWalletAccount) => {
		const walletAccount = convertUnverifiedWalletAccountToWalletAccount({ unverifiedWalletAccount });
		walletAccountsMap.set(walletAccount.id, walletAccount);
	});
	(user?.verifiedCredentials ?? []).filter((verified) => verified.format === _dynamic_labs_sdk_api_core.JwtVerifiedCredentialFormatEnum.Blockchain).forEach((verifiedWalletAccount) => {
		const walletAccount = convertVerifiedCredentialToWalletAccount({ verifiedCredential: verifiedWalletAccount }, client);
		walletAccountsMap.set(walletAccount.id, walletAccount);
	});
	return Array.from(walletAccountsMap.values());
};

//#endregion
//#region src/modules/wallets/getWalletAccounts/getWalletAccounts.ts
/**
* Retrieves all wallet accounts associated with the current session.
*
* This function returns both verified and unverified wallet accounts,
* combining data from user credentials and local unverified accounts.
* You can differentiate between verified and unverified wallet accounts by
* checking the `verifiedCredentialId` property.
*
* @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
* @returns An array of wallet accounts associated with the session.
* @instrumented
*/
const getWalletAccounts = (client = require_InvalidParamError.getDefaultClient()) => {
	const { unverifiedWalletAccounts, user } = require_InvalidParamError.getCore(client).state.get();
	return getWalletAccountsFromState({
		unverifiedWalletAccounts,
		user
	}, client);
};
const __getWalletAccounts_impl = getWalletAccounts;
const __getWalletAccounts_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __getWalletAccounts_impl,
	functionName: "getWalletAccounts",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/errors/NoWalletProviderFoundError.ts
var NoWalletProviderFoundError = class extends require_InvalidParamError.BaseError {
	constructor({ walletProviderKey }) {
		super({
			cause: null,
			code: "no_wallet_provider_found_error",
			docsUrl: null,
			name: "NoWalletProviderFoundError",
			shortMessage: `No wallet provider found with key: ${walletProviderKey}`
		});
	}
};

//#endregion
//#region src/services/runtimeServices/createRuntimeServiceAccessKey/createRuntimeServiceAccessKey.ts
/**
* Creates a service accessor function that manages service instantiation and caching.
* The returned function will either retrieve an existing service from the registry or
* create a new one using the provided builder function.
*
* @template - The type of service to be created/accessed
* @param key - Unique identifier for the service in the registry
* @param builder - Function that creates the service instance when called with a DynamicClient
* @instrumented
*/
const createRuntimeServiceAccessKey = (key, builder) => (client) => {
	const { runtimeServices } = require_InvalidParamError.getCore(client);
	const currentService = runtimeServices.getByKey(key);
	if (currentService) return currentService;
	const service = builder(client);
	runtimeServices.register(key, service);
	return service;
};
const __createRuntimeServiceAccessKey_impl = createRuntimeServiceAccessKey;
const __createRuntimeServiceAccessKey_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __createRuntimeServiceAccessKey_impl,
	functionName: "createRuntimeServiceAccessKey",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/modules/wallets/walletProviderRegistry/createWalletProviderRegistry/createWalletProviderRegistry.ts
/**
* Creates a new wallet provider registry that manages wallet providers with priority-based registration.
*
* @returns The wallet provider registry instance
*
* @example
* ```typescript
* const registry = createWalletProviderRegistry();
*
* registry.register({
*   priority: WalletProviderPriority.WALLET_SDK,
*   walletProvider: myWalletProvider
* });
*
* const provider = registry.getByKey('my-wallet-key');
* const providers = registry.listProviders();
* ```
* @not-instrumented
*/
const createWalletProviderRegistry = (client) => {
	const registry = /* @__PURE__ */ new Map();
	return {
		getByKey: (key) => registry.get(key)?.walletProvider,
		listProviders: () => Array.from(registry.values()).map((v) => v.walletProvider),
		register: (args) => {
			const existingEntry = registry.get(args.walletProvider.key);
			if (existingEntry) {
				if (existingEntry.priority < args.priority) {
					registry.set(args.walletProvider.key, args);
					emitEvent({
						args: { walletProviderKey: args.walletProvider.key },
						event: "walletProviderChanged"
					}, client);
				}
			} else {
				registry.set(args.walletProvider.key, args);
				emitEvent({
					args: { walletProvider: args.walletProvider },
					event: "walletProviderRegistered"
				}, client);
				emitEvent({
					args: { walletProviderKey: args.walletProvider.key },
					event: "walletProviderChanged"
				}, client);
			}
		},
		unregister: (key) => {
			registry.delete(key);
			emitEvent({
				args: { walletProviderKey: key },
				event: "walletProviderUnregistered"
			}, client);
		}
	};
};

//#endregion
//#region src/modules/wallets/walletProviderRegistry/getWalletProviderRegistry/getWalletProviderRegistry.ts
/**
* This function provides access to a shared instance of the wallet provider registry.
*
* It ensures that the same registry instance is used throughout the client to maintaining
* consistency of registered wallet providers across different parts of the codebase.
*
* @returns The wallet provider registry instance
*
* @example
* ```typescript
* // Get the registry instance
* const registry = getWalletProviderRegistry();
*
* // Register a wallet provider
* registry.register({
*   priority: WalletProviderPriority.WALLET_SDK,
*   walletProvider: myWalletProvider
* });
*
* // Retrieve a specific provider
* const provider = registry.getByKey('metamaskevm');
* ```
*/
const getWalletProviderRegistry = __createRuntimeServiceAccessKey_wrapped("walletProviderRegistry", (client) => createWalletProviderRegistry(client));

//#endregion
//#region src/modules/wallets/walletProviderRegistry/walletProviderRegistry.types.ts
let WalletProviderPriority = /* @__PURE__ */ function(WalletProviderPriority$1) {
	/**
	* Highest priority should be used by wallet providers that implement
	* the most reliable wallet integration.
	* example: The SDK provided by the wallet provider.
	*/
	WalletProviderPriority$1[WalletProviderPriority$1["WALLET_SDK"] = 100] = "WALLET_SDK";
	/**
	* Medium priority should be used by wallet providers that implement
	* a wallet integration via some reliable standard.
	* example: A wallet provider that uses EIP6963 announcement.
	*/
	WalletProviderPriority$1[WalletProviderPriority$1["WALLET_SELF_ANNOUNCEMENT_STANDARD"] = 50] = "WALLET_SELF_ANNOUNCEMENT_STANDARD";
	/**
	* Low priority should be used by wallet providers that implement
	* a wallet integration on a less reliable standard.
	* example: A wallet provider that uses window.ethereum, where the
	* window key can be overridden by other extensions.
	*/
	WalletProviderPriority$1[WalletProviderPriority$1["WINDOW_INJECT"] = 20] = "WINDOW_INJECT";
	return WalletProviderPriority$1;
}({});

//#endregion
//#region src/modules/wallets/utils/getWalletProviderFromWalletAccount/getWalletProviderFromWalletAccount.ts
/** @instrumented */
const getWalletProviderFromWalletAccount = ({ walletAccount }, client) => {
	const walletProvider = getWalletProviderRegistry(client).getByKey(walletAccount.walletProviderKey);
	if (!walletProvider) throw new NoWalletProviderFoundError({ walletProviderKey: walletAccount.walletProviderKey });
	return walletProvider;
};
const __getWalletProviderFromWalletAccount_impl = getWalletProviderFromWalletAccount;
const __getWalletProviderFromWalletAccount_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __getWalletProviderFromWalletAccount_impl,
	functionName: "getWalletProviderFromWalletAccount",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/modules/auth/consts.ts
const DYNAMIC_AUTH_COOKIE_NAME = "DYNAMIC_JWT_TOKEN";

//#endregion
//#region src/modules/wallets/emitWalletAccountsChangedEvent/emitWalletAccountsChangedEvent.ts
/**
* Emits the `walletAccountsChanged` event.
* @not-instrumented
*/
const emitWalletAccountsChangedEvent = (client) => {
	emitEvent({
		args: { walletAccounts: __getWalletAccounts_wrapped(client) },
		event: "walletAccountsChanged"
	}, client);
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/checkAndRaiseWalletAccountsChangedEvent/checkAndRaiseWalletAccountsChangedEvent.ts
/** @not-instrumented */
const checkAndRaiseWalletAccountsChangedEvent = ({ previousState }, client) => {
	const core = require_InvalidParamError.getCore(client);
	if (getWalletAccountsHash(previousState, client) !== getWalletAccountsHash(core.state.get(), client)) emitWalletAccountsChangedEvent(client);
};
const getWalletAccountsHash = (state, client) => getWalletAccountsFromState(state, client).map((walletAccount) => JSON.stringify(walletAccount)).sort().join("-");

//#endregion
//#region src/modules/mfa/isUserMissingMfaAuth/isUserMissingMfaAuth.ts
/**
* Checks if the user requires additional MFA authentication.
*
* This function determines if the current user session requires
* additional multi-factor authentication to access certain features.
*
* @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
* @returns True if the user needs additional MFA authentication, false otherwise.
* @not-instrumented
*/
const isUserMissingMfaAuth = (client = require_InvalidParamError.getDefaultClient()) => {
	const user = client.user;
	require_InvalidParamError.assertDefined(user, "User not logged in");
	return Boolean(user.scope?.includes("requiresAdditionalAuth"));
};

//#endregion
//#region src/modules/wallets/getWalletProviders/getWalletProviders.ts
/**
* Get all available wallet providers to interact with internally.
* @instrumented
*/
const getWalletProviders = (client) => {
	return getWalletProviderRegistry(client).listProviders();
};
const __getWalletProviders_impl = getWalletProviders;
const __getWalletProviders_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __getWalletProviders_impl,
	functionName: "getWalletProviders",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/modules/waas/isWaasWalletProvider/isWaasWalletProvider.ts
/** @not-instrumented */
const isWaasWalletProvider = (walletProvider) => {
	return walletProvider.key.includes(require_InvalidParamError.DYNAMIC_WAAS_METADATA.normalizedWalletName);
};

//#endregion
//#region src/modules/waas/findWaasWalletProviderByChain/findWaasWalletProviderByChain.ts
/** @not-instrumented */
const findWaasWalletProviderByChain = ({ chain }, client) => {
	const providers = __getWalletProviders_wrapped(client);
	const waasProviderKey = formatWalletProviderKey({
		chain,
		displayName: require_InvalidParamError.DYNAMIC_WAAS_METADATA.displayName,
		walletProviderType: _dynamic_labs_sdk_api_core.WalletProviderEnum.EmbeddedWallet
	});
	const waasProvider = providers.find((provider) => provider.key === waasProviderKey && provider.chain === chain);
	if (!waasProvider || !isWaasWalletProvider(waasProvider)) return null;
	return waasProvider;
};

//#endregion
//#region src/modules/waas/isWaasWalletAccount/isWaasWalletAccount.ts
/**
* This function determines whether the provided wallet account is a Dynamic
* WaaS wallet account.
*
* @param params.walletAccount - The wallet account to check.
* @returns True if the wallet account is a WaaS wallet account, false otherwise.
* @not-instrumented
*/
const isWaasWalletAccount = ({ walletAccount }) => {
	return walletAccount.walletProviderKey.includes(require_InvalidParamError.DYNAMIC_WAAS_METADATA.normalizedWalletName);
};

//#endregion
//#region src/modules/waas/restoreUserSharesForAllWalletAccounts/restoreUserSharesForAllWalletAccounts.ts
/** @not-instrumented */
const restoreUserSharesForAllWalletAccounts = async (client) => {
	/**
	* Restoring the user shares will fails if the user is missing the MFA auth.
	* This early return prevents the attempt to restore the user shares to fail
	* when we know it will fails and just add noise to the logs.
	*/
	if (isUserMissingMfaAuth(client)) return;
	const waasWalletAccounts = __getWalletAccounts_wrapped(client).filter((walletAccount) => isWaasWalletAccount({ walletAccount }));
	await Promise.all(waasWalletAccounts.map(async (walletAccount) => {
		const provider = findWaasWalletProviderByChain({ chain: walletAccount.chain }, client);
		/**
		* The environment might not have the embedded wallet extensions installed.
		* In that case there is no provider for the chain and we can skip restoring the user share.
		*/
		if (!provider) return;
		return provider.restoreUserShareForWalletAccount({ walletAccount });
	}));
};

//#endregion
//#region src/modules/auth/decodeJwt/decodeJwt.ts
/**
* Decodes a JWT token and returns the full payload.
*
* This function extracts and returns the complete JWT payload including scopes,
* expiration time, and other claims.
*
* @param jwt - The JWT token string.
* @returns The decoded JWT payload object.
* @throws InvalidParamError if the token is invalid or cannot be decoded.
*
* @example
* ```typescript
* const payload = decodeJwt(jwt);
* // Returns: { scopes: ['wallet:export'], exp: 1234567890, ... }
* ```
* @not-instrumented
*/
const decodeJwt = (jwt) => {
	try {
		const parts = jwt.split(".");
		if (parts.length !== 3) throw new require_InvalidParamError.InvalidParamError("Invalid JWT format");
		const base64Payload = parts[1].replaceAll("-", "+").replaceAll("_", "/");
		const paddedPayload = base64Payload + "=".repeat((4 - base64Payload.length % 4) % 4);
		const decodedPayload = atob(paddedPayload);
		return JSON.parse(decodedPayload);
	} catch (error) {
		if (error instanceof require_InvalidParamError.InvalidParamError) throw error;
		throw new require_InvalidParamError.InvalidParamError(`Failed to decode JWT: ${error instanceof Error ? error.message : String(error)}`);
	}
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/normalizeScopes/normalizeScopes.ts
/**
* Normalizes scopes by deduplicating and sorting them.
* This creates a canonical representation for comparison.
*
* @param scopes - Array of scope strings (may contain duplicates)
* @returns Normalized, sorted array of unique scopes
* @not-instrumented
*/
const normalizeScopes = (scopes) => {
	return [...new Set(scopes)].sort((a, b) => a.localeCompare(b));
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/parseElevatedAccessToken/parseElevatedAccessToken.ts
/**
* Validates and parses an elevated access token from a JWT string.
* Extracts scopes, expiration, and validates the token structure.
*
* Policy decisions:
* - Tokens without scopes are rejected (returns null)
* - Tokens with empty scopes array are rejected (returns null)
* - Tokens without exp field are rejected (returns null)
* - Expired tokens are rejected (returns null)
*
* @returns Parsed token data or null if token is invalid/expired
* @not-instrumented
*/
const parseElevatedAccessToken = ({ token }) => {
	const payload = decodeJwt(token);
	const filteredScopes = ((payload?.scope)?.split(" ") ?? []).filter((s) => s.length > 0);
	const singleUse = payload.singleUse ?? false;
	if (!filteredScopes || filteredScopes.length === 0) return null;
	if (!payload.exp) return null;
	const expiresAt = /* @__PURE__ */ new Date(payload.exp * 1e3);
	if (expiresAt <= /* @__PURE__ */ new Date()) return null;
	return {
		expiresAt,
		normalizedScopes: normalizeScopes(filteredScopes),
		scopes: filteredScopes,
		singleUse,
		token
	};
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/upsertElevatedAccessToken/upsertElevatedAccessToken.ts
/**
* Upserts an elevated access token into the current tokens array.
*
* Policy: Only one token per normalized scope-set is allowed.
* If a token with the same normalized scopes exists, it is replaced.
* This ensures we don't accumulate multiple tokens for the same scope combination.
*
* @param currentTokens - Current array of elevated access tokens
* @param newToken - New token to upsert
* @returns Updated array of tokens with the new token upserted
* @not-instrumented
*/
const upsertElevatedAccessToken = ({ currentTokens, newToken }) => {
	const newScopeKey = normalizeScopes(newToken.scopes).join(" ");
	return [...currentTokens.filter((existingToken) => {
		return normalizeScopes(existingToken.scopes).join(" ") !== newScopeKey;
	}), {
		expiresAt: newToken.expiresAt,
		scopes: newToken.scopes,
		singleUse: newToken.singleUse,
		token: newToken.token
	}];
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/updateAuthFromVerifyResponse.ts
/** @instrumented */
const updateAuthFromVerifyResponse = ({ response }, client) => {
	const core = require_InvalidParamError.getCore(client);
	const previousState = { ...core.state.get() };
	const { user, minifiedJwt, jwt, expiresAt, mfaToken, elevatedAccessToken } = response;
	const sessionExpiresAt = /* @__PURE__ */ new Date(expiresAt * 1e3);
	const newState = {
		legacyToken: jwt ?? null,
		sessionExpiresAt,
		token: minifiedJwt ?? null,
		user
	};
	if (mfaToken) newState.mfaToken = mfaToken;
	const currentTokens = core.state.get().elevatedAccessTokens || [];
	newState.elevatedAccessTokens = currentTokens;
	if (elevatedAccessToken) {
		const parsedToken = parseElevatedAccessToken({ token: elevatedAccessToken });
		if (parsedToken) newState.elevatedAccessTokens = upsertElevatedAccessToken({
			currentTokens,
			newToken: parsedToken
		});
	}
	core.state.set(newState);
	/**
	* For customers using a sandbox environment with cookies enabled, we need to set the cookie
	* programmatically because Redcoast won't set the cookie via headers. We set the cookie programmatically
	* so customers can access the cookie from document.cookie consistently between sandbox and live environments.
	*/
	if (minifiedJwt && require_InvalidParamError.isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=${minifiedJwt}; expires=${sessionExpiresAt.toUTCString()}; path=/; SameSite=Lax`);
	checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);
	if (!previousState.user && Boolean(newState.user)) restoreUserSharesForAllWalletAccounts(client);
};
const __updateAuthFromVerifyResponse_impl = updateAuthFromVerifyResponse;
const __updateAuthFromVerifyResponse_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __updateAuthFromVerifyResponse_impl,
	functionName: "updateAuthFromVerifyResponse",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
//#region src/modules/wallets/getWalletProviderByKey/getWalletProviderByKey.ts
/** @not-instrumented */
const getWalletProviderByKey = ({ walletProviderKey }, client) => {
	const walletProvider = __getWalletProviders_wrapped(client).find((walletProvider$1) => walletProvider$1.key === walletProviderKey);
	if (!walletProvider) throw new NoWalletProviderFoundError({ walletProviderKey });
	return walletProvider;
};

//#endregion
//#region src/modules/wallets/utils/getVerifiedCredentialForWalletAccount/getVerifiedCredentialForWalletAccount.ts
/** @instrumented */
const getVerifiedCredentialForWalletAccount = ({ walletAccount }, client) => {
	return client.user?.verifiedCredentials.find((vc) => vc.id === walletAccount.verifiedCredentialId);
};
const __getVerifiedCredentialForWalletAccount_impl = getVerifiedCredentialForWalletAccount;
const __getVerifiedCredentialForWalletAccount_wrapped = require_InvalidParamError.instrumentFunction({
	fn: __getVerifiedCredentialForWalletAccount_impl,
	functionName: "getVerifiedCredentialForWalletAccount",
	getCore: () => {
		try {
			return require_InvalidParamError.getCore(require_InvalidParamError.getDefaultClient());
		} catch {
			return;
		}
	}
});

//#endregion
Object.defineProperty(exports, 'DYNAMIC_AUTH_COOKIE_NAME', {
  enumerable: true,
  get: function () {
    return DYNAMIC_AUTH_COOKIE_NAME;
  }
});
Object.defineProperty(exports, 'InvalidWalletProviderKeyError', {
  enumerable: true,
  get: function () {
    return InvalidWalletProviderKeyError;
  }
});
Object.defineProperty(exports, 'NoWalletProviderFoundError', {
  enumerable: true,
  get: function () {
    return NoWalletProviderFoundError;
  }
});
Object.defineProperty(exports, 'WalletProviderPriority', {
  enumerable: true,
  get: function () {
    return WalletProviderPriority;
  }
});
Object.defineProperty(exports, '__createRuntimeServiceAccessKey_wrapped', {
  enumerable: true,
  get: function () {
    return __createRuntimeServiceAccessKey_wrapped;
  }
});
Object.defineProperty(exports, '__getVerifiedCredentialForWalletAccount_wrapped', {
  enumerable: true,
  get: function () {
    return __getVerifiedCredentialForWalletAccount_wrapped;
  }
});
Object.defineProperty(exports, '__getWalletAccounts_wrapped', {
  enumerable: true,
  get: function () {
    return __getWalletAccounts_wrapped;
  }
});
Object.defineProperty(exports, '__getWalletProviderFromWalletAccount_wrapped', {
  enumerable: true,
  get: function () {
    return __getWalletProviderFromWalletAccount_wrapped;
  }
});
Object.defineProperty(exports, '__getWalletProviders_wrapped', {
  enumerable: true,
  get: function () {
    return __getWalletProviders_wrapped;
  }
});
Object.defineProperty(exports, '__offEvent_wrapped', {
  enumerable: true,
  get: function () {
    return __offEvent_wrapped;
  }
});
Object.defineProperty(exports, '__onEvent_wrapped', {
  enumerable: true,
  get: function () {
    return __onEvent_wrapped;
  }
});
Object.defineProperty(exports, '__onceEvent_wrapped', {
  enumerable: true,
  get: function () {
    return __onceEvent_wrapped;
  }
});
Object.defineProperty(exports, '__updateAuthFromVerifyResponse_wrapped', {
  enumerable: true,
  get: function () {
    return __updateAuthFromVerifyResponse_wrapped;
  }
});
Object.defineProperty(exports, 'checkAndRaiseWalletAccountsChangedEvent', {
  enumerable: true,
  get: function () {
    return checkAndRaiseWalletAccountsChangedEvent;
  }
});
Object.defineProperty(exports, 'emitEvent', {
  enumerable: true,
  get: function () {
    return emitEvent;
  }
});
Object.defineProperty(exports, 'emitWalletAccountsChangedEvent', {
  enumerable: true,
  get: function () {
    return emitWalletAccountsChangedEvent;
  }
});
Object.defineProperty(exports, 'findWaasWalletProviderByChain', {
  enumerable: true,
  get: function () {
    return findWaasWalletProviderByChain;
  }
});
Object.defineProperty(exports, 'formatWalletAccountId', {
  enumerable: true,
  get: function () {
    return formatWalletAccountId;
  }
});
Object.defineProperty(exports, 'formatWalletProviderKey', {
  enumerable: true,
  get: function () {
    return formatWalletProviderKey;
  }
});
Object.defineProperty(exports, 'getWalletProviderByKey', {
  enumerable: true,
  get: function () {
    return getWalletProviderByKey;
  }
});
Object.defineProperty(exports, 'getWalletProviderRegistry', {
  enumerable: true,
  get: function () {
    return getWalletProviderRegistry;
  }
});
Object.defineProperty(exports, 'isUserMissingMfaAuth', {
  enumerable: true,
  get: function () {
    return isUserMissingMfaAuth;
  }
});
Object.defineProperty(exports, 'isWaasWalletAccount', {
  enumerable: true,
  get: function () {
    return isWaasWalletAccount;
  }
});
Object.defineProperty(exports, 'isWaasWalletProvider', {
  enumerable: true,
  get: function () {
    return isWaasWalletProvider;
  }
});
Object.defineProperty(exports, 'normalizeAddress', {
  enumerable: true,
  get: function () {
    return normalizeAddress;
  }
});
Object.defineProperty(exports, 'normalizeWalletNameWithChain', {
  enumerable: true,
  get: function () {
    return normalizeWalletNameWithChain;
  }
});
Object.defineProperty(exports, 'parseElevatedAccessToken', {
  enumerable: true,
  get: function () {
    return parseElevatedAccessToken;
  }
});
Object.defineProperty(exports, 'restoreUserSharesForAllWalletAccounts', {
  enumerable: true,
  get: function () {
    return restoreUserSharesForAllWalletAccounts;
  }
});
Object.defineProperty(exports, 'setCookie', {
  enumerable: true,
  get: function () {
    return setCookie;
  }
});
Object.defineProperty(exports, 'splitWalletProviderKey', {
  enumerable: true,
  get: function () {
    return splitWalletProviderKey;
  }
});
Object.defineProperty(exports, 'upsertElevatedAccessToken', {
  enumerable: true,
  get: function () {
    return upsertElevatedAccessToken;
  }
});
//# sourceMappingURL=getVerifiedCredentialForWalletAccount-BqaTVz4z.cjs.map