import { $ as getCore, C as emitEvent, H as assertDefined, Q as BaseError, V as isCookieEnabled, Y as getDefaultClient, a as DYNAMIC_WAAS_METADATA, b as NoWalletProviderFoundError, n as isWaasWalletProvider, o as isUserMissingMfaAuth, t as InvalidParamError, v as getWalletProviderRegistry, x as getChainFromVerifiedCredentialChain } from "./InvalidParamError-BKr8fFc1.native.esm.js";
import { JwtVerifiedCredentialFormatEnum, WalletProviderEnum } from "@dynamic-labs/sdk-api-core";

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

//#endregion
//#region src/errors/InvalidWalletProviderKeyError.ts
var InvalidWalletProviderKeyError = class extends 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
/** @notInstrumented */
const splitWalletProviderKey = (walletProviderKey) => {
	const [normalizedWalletNameWithChain, walletProviderType, suffix, ...rest] = walletProviderKey.split(":");
	if (!normalizedWalletNameWithChain || !Object.values(WalletProviderEnum).includes(walletProviderType) || rest.length > 0) throw new InvalidWalletProviderKeyError(walletProviderKey);
	return {
		normalizedWalletNameWithChain,
		suffix,
		walletProviderType
	};
};

//#endregion
//#region src/modules/wallets/utils/normalizeAddress/normalizeAddress.ts
/** @notInstrumented */
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
/** @notInstrumented */
const formatWalletAccountId = ({ address, chain, walletProviderKey }) => {
	const { normalizedWalletNameWithChain } = splitWalletProviderKey(walletProviderKey);
	return `${normalizedWalletNameWithChain}:${normalizeAddress({
		address,
		chain
	})}`;
};

//#endregion
//#region src/modules/wallets/utils/convertUnverifiedWalletAccountToWalletAccount/convertUnverifiedWalletAccountToWalletAccount.ts
/** @notInstrumented */
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.
* @notInstrumented
*/
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).
* @notInstrumented
*/
const formatWalletProviderKey = ({ suffix, chain, displayName, walletProviderType }) => {
	return `${normalizeWalletNameWithChain({
		chain,
		displayName
	})}:${walletProviderType}${suffix ? `:${suffix}` : ""}`;
};

//#endregion
//#region src/modules/wallets/walletProvider/walletProviderKeyMap/getWalletProviderKeyFromVerifiedCredential/getWalletProviderKeyFromVerifiedCredential.ts
/** @notInstrumented */
const getWalletProviderKeyFromVerifiedCredential = ({ verifiedCredential }, client) => {
	const { walletProviderKeyMap } = 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.
	*/
	assertDefined(verifiedCredential.walletName, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing walletName`);
	assertDefined(verifiedCredential.walletProvider, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing walletProvider`);
	assertDefined(verifiedCredential.chain, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing chain`);
	return { walletProviderKey: formatWalletProviderKey({
		chain: getChainFromVerifiedCredentialChain(verifiedCredential.chain),
		displayName: verifiedCredential.walletName,
		walletProviderType: verifiedCredential.walletProvider
	}) };
};

//#endregion
//#region src/modules/wallets/utils/convertVerifiedCredentialToWalletAccount/convertVerifiedCredentialToWalletAccount.ts
/** @notInstrumented */
const convertVerifiedCredentialToWalletAccount = ({ verifiedCredential }, client) => {
	assertDefined(verifiedCredential.address, "Missing address in verified credential");
	assertDefined(verifiedCredential.chain, "Missing chain in verified credential");
	const chain = getChainFromVerifiedCredentialChain(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
/** @notInstrumented */
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 === JwtVerifiedCredentialFormatEnum.Blockchain).forEach((verifiedWalletAccount) => {
		try {
			const walletAccount = convertVerifiedCredentialToWalletAccount({ verifiedCredential: verifiedWalletAccount }, client);
			walletAccountsMap.set(walletAccount.id, walletAccount);
		} catch (error) {
			/**
			* A verified credential can be missing the data required to resolve its
			* wallet provider (e.g. a legacy credential without a walletName). Skip
			* it instead of throwing so a single unconvertible credential does not
			* abort the whole mapping — which, during client initialization, would
			* otherwise fail init and leave the app stuck loading. The wallet stays
			* absent until the user reconnects it.
			*/
			getCore(client).logger.debug(`Skipping verified credential ${verifiedWalletAccount.id}: unable to convert to wallet account`, error);
		}
	});
	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.
* @notInstrumented
* @hook Exposed as a hook so consumers get the reactive list of wallet accounts.
*/
const getWalletAccounts = (client = getDefaultClient()) => {
	const { unverifiedWalletAccounts, user } = getCore(client).state.get();
	return getWalletAccountsFromState({
		unverifiedWalletAccounts,
		user
	}, client);
};

//#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.
* @notInstrumented
*/
const emitWalletAccountsChangedEvent = (client) => {
	emitEvent({
		args: { walletAccounts: getWalletAccounts(client) },
		event: "walletAccountsChanged"
	}, client);
};

//#endregion
//#region src/modules/auth/updateAuthFromVerifyResponse/checkAndRaiseWalletAccountsChangedEvent/checkAndRaiseWalletAccountsChangedEvent.ts
/** @notInstrumented */
const checkAndRaiseWalletAccountsChangedEvent = ({ previousState }, client) => {
	const core = 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/wallets/getWalletProviders/getWalletProviders.ts
/**
* Get all available wallet providers to interact with internally.
* @notInstrumented
*/
const getWalletProviders = (client) => {
	return getWalletProviderRegistry(client).listProviders();
};

//#endregion
//#region src/modules/waas/findWaasWalletProviderByChain/findWaasWalletProviderByChain.ts
/** @notInstrumented */
const findWaasWalletProviderByChain = ({ chain }, client) => {
	const providers = getWalletProviders(client);
	const waasProviderKey = formatWalletProviderKey({
		chain,
		displayName: DYNAMIC_WAAS_METADATA.displayName,
		walletProviderType: 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.
* @notInstrumented
*/
const isWaasWalletAccount = ({ walletAccount }) => {
	return walletAccount.walletProviderKey.includes(DYNAMIC_WAAS_METADATA.normalizedWalletName);
};

//#endregion
//#region src/modules/waas/initializeWaasClientsForEagerRecovery/initializeWaasClientsForEagerRecovery.ts
/**
* On login, boots the WaaS client once per chain so the SDK eagerly recovers
* key shares itself (the `eagerlyRecoverKeyShares` capability) instead of the
* host looping per wallet. Booting calls `initialize()`, which sends the auth
* token the iframe needs to self-recover.
*
* @notInstrumented
*/
const initializeWaasClientsForEagerRecovery = async (client) => {
	/**
	* Booting triggers recovery, which fails if the user is missing the MFA auth.
	* This early return avoids attempting a call we know will fail and just adds
	* noise to the logs.
	*/
	if (isUserMissingMfaAuth(client)) return;
	const waasChains = new Set(getWalletAccounts(client).filter((walletAccount) => isWaasWalletAccount({ walletAccount })).map((walletAccount) => walletAccount.chain));
	await Promise.all([...waasChains].map(async (chain) => {
		const provider = findWaasWalletProviderByChain({ chain }, client);
		/**
		* The environment might not have the embedded wallet extensions installed.
		* In that case there is no provider for the chain and nothing to boot.
		*/
		if (!provider) return;
		try {
			await provider.getWaasClient();
		} catch (error) {
			getCore(client).logger.warn("[initializeWaasClientsForEagerRecovery] failed to boot waas client", error);
		}
	}));
};

//#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, ... }
* ```
* @notInstrumented
*/
const decodeJwt = (jwt) => {
	try {
		const parts = jwt.split(".");
		if (parts.length !== 3) throw new 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 InvalidParamError) throw error;
		throw new 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
* @notInstrumented
*/
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
* @notInstrumented
*/
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
* @notInstrumented
*/
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
/** @notInstrumented */
const updateAuthFromVerifyResponse = ({ response }, client) => {
	const core = 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 && isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=${minifiedJwt}; expires=${sessionExpiresAt.toUTCString()}; path=/; SameSite=Lax`);
	checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);
	if (!previousState.user && Boolean(newState.user)) initializeWaasClientsForEagerRecovery(client);
};

//#endregion
//#region src/modules/wallets/utils/getVerifiedCredentialForWalletAccount/getVerifiedCredentialForWalletAccount.ts
/** @notInstrumented */
const getVerifiedCredentialForWalletAccount = ({ walletAccount }, client) => {
	return client.user?.verifiedCredentials.find((vc) => vc.id === walletAccount.verifiedCredentialId);
};

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

//#endregion
export { normalizeAddress as _, parseElevatedAccessToken as a, setCookie as b, findWaasWalletProviderByChain as c, emitWalletAccountsChangedEvent as d, DYNAMIC_AUTH_COOKIE_NAME as f, formatWalletAccountId as g, normalizeWalletNameWithChain as h, upsertElevatedAccessToken as i, getWalletProviders as l, formatWalletProviderKey as m, getVerifiedCredentialForWalletAccount as n, initializeWaasClientsForEagerRecovery as o, getWalletAccounts as p, updateAuthFromVerifyResponse as r, isWaasWalletAccount as s, getWalletProviderByKey as t, checkAndRaiseWalletAccountsChangedEvent as u, splitWalletProviderKey as v, InvalidWalletProviderKeyError as y };
//# sourceMappingURL=getWalletProviderByKey-BhisAyZg.native.esm.js.map