@walletconnect/utils
Version:
Utilities for WalletConnect Protocol
1 lines • 685 kB
Source Map (JSON)
{"version":3,"file":"index.cjs","sources":["../src/caip.ts","../src/misc.ts","../../../node_modules/@noble/hashes/esm/_u64.js","../../../node_modules/@noble/hashes/esm/crypto.js","../../../node_modules/@noble/hashes/esm/utils.js","../../../node_modules/@noble/hashes/esm/sha3.js","../../../node_modules/@noble/hashes/esm/_md.js","../../../node_modules/@noble/hashes/esm/sha2.js","../../../node_modules/@noble/hashes/esm/_blake.js","../../../node_modules/@noble/hashes/esm/blake2.js","../src/signatures.ts","../src/cacao.ts","../../../node_modules/@noble/ciphers/esm/utils.js","../../../node_modules/@noble/ciphers/esm/_arx.js","../../../node_modules/@noble/ciphers/esm/_poly1305.js","../../../node_modules/@noble/ciphers/esm/chacha.js","../../../node_modules/@noble/hashes/esm/hmac.js","../../../node_modules/@noble/hashes/esm/hkdf.js","../../../node_modules/@noble/hashes/esm/sha256.js","../../../node_modules/@noble/curves/esm/utils.js","../../../node_modules/@noble/curves/esm/abstract/modular.js","../../../node_modules/@noble/curves/esm/abstract/curve.js","../../../node_modules/@noble/curves/esm/abstract/edwards.js","../../../node_modules/@noble/curves/esm/abstract/hash-to-curve.js","../../../node_modules/@noble/curves/esm/abstract/montgomery.js","../../../node_modules/@noble/curves/esm/ed25519.js","../../../node_modules/@noble/curves/esm/abstract/weierstrass.js","../../../node_modules/@noble/curves/esm/_shortw_utils.js","../../../node_modules/@noble/curves/esm/nist.js","../../../node_modules/@noble/curves/esm/p256.js","../src/crypto.ts","../src/relay.ts","../src/uri.ts","../src/namespaces.ts","../src/errors.ts","../src/validators.ts","../src/network.ts","../src/memoryStore.ts","../src/polkadot.ts","../src/logger.ts"],"sourcesContent":["import { SessionTypes, ProposalTypes } from \"@walletconnect/types\";\n\ninterface ChainIdParams {\n namespace: string;\n reference: string;\n}\n\ninterface AccountIdParams extends ChainIdParams {\n address: string;\n}\n\nconst CAIP_DELIMITER = \":\";\n\nexport function parseChainId(chain: string): ChainIdParams {\n const [namespace, reference] = chain.split(CAIP_DELIMITER);\n return { namespace, reference };\n}\n\nexport function formatChainId(params: ChainIdParams): string {\n const { namespace, reference } = params;\n return [namespace, reference].join(CAIP_DELIMITER);\n}\n\nexport function parseAccountId(account: string): AccountIdParams {\n const [namespace, reference, address] = account.split(CAIP_DELIMITER);\n return { namespace, reference, address };\n}\n\nexport function formatAccountId(params: AccountIdParams): string {\n const { namespace, reference, address } = params;\n return [namespace, reference, address].join(CAIP_DELIMITER);\n}\n\nexport function getUniqueValues(array: string[], parser: (str: string) => string): string[] {\n const unique: string[] = [];\n array.forEach((str) => {\n const value = parser(str);\n if (!unique.includes(value)) unique.push(value);\n });\n return unique;\n}\n\nexport function getAddressFromAccount(account: string) {\n const { address } = parseAccountId(account);\n return address;\n}\n\nexport function getChainFromAccount(account: string) {\n const { namespace, reference } = parseAccountId(account);\n const chain = formatChainId({ namespace, reference });\n return chain;\n}\n\nexport function formatAccountWithChain(address: string, chain: string) {\n const { namespace, reference } = parseChainId(chain);\n const account = formatAccountId({ namespace, reference, address });\n return account;\n}\n\nexport function getAddressesFromAccounts(accounts: string[]) {\n return getUniqueValues(accounts, getAddressFromAccount);\n}\n\nexport function getChainsFromAccounts(accounts: string[]) {\n return getUniqueValues(accounts, getChainFromAccount);\n}\n\nexport function getAccountsFromNamespaces(\n namespaces: SessionTypes.Namespaces,\n keys: string[] = [],\n): string[] {\n const accounts: string[] = [];\n Object.keys(namespaces).forEach((key) => {\n if (keys.length && !keys.includes(key)) return;\n const ns = namespaces[key];\n accounts.push(...ns.accounts);\n });\n return accounts;\n}\n\nexport function getChainsFromNamespaces(\n namespaces: SessionTypes.Namespaces,\n keys: string[] = [],\n): string[] {\n const chains: string[] = [];\n Object.keys(namespaces).forEach((key) => {\n if (keys.length && !keys.includes(key)) return;\n const ns = namespaces[key];\n chains.push(...getChainsFromAccounts(ns.accounts));\n });\n return chains;\n}\n\nexport function getChainsFromRequiredNamespaces(\n requiredNamespaces: ProposalTypes.RequiredNamespaces,\n keys: string[] = [],\n): string[] {\n const chains: string[] = [];\n Object.keys(requiredNamespaces).forEach((key) => {\n if (keys.length && !keys.includes(key)) return;\n const ns = requiredNamespaces[key];\n chains.push(...getChainsFromNamespace(key, ns));\n });\n return chains;\n}\n\nexport function getChainsFromNamespace(\n namespace: string,\n namespaceProps: ProposalTypes.BaseRequiredNamespace,\n) {\n // check if chainId is provided in the key as `eip155:1` or in the namespace as chains[]\n return namespace.includes(\":\") ? [namespace] : namespaceProps.chains || [];\n}\n","import { detect } from \"detect-browser\";\nimport { FIVE_MINUTES, fromMiliseconds, toMiliseconds } from \"@walletconnect/time\";\nimport {\n SignClientTypes,\n RelayerClientMetadata,\n EngineTypes,\n RelayerTypes,\n} from \"@walletconnect/types\";\nimport { getDocument, getLocation, getNavigator } from \"@walletconnect/window-getters\";\nimport { getWindowMetadata } from \"@walletconnect/window-metadata\";\nimport { ErrorResponse } from \"@walletconnect/jsonrpc-utils\";\nimport { IKeyValueStorage } from \"@walletconnect/keyvaluestorage\";\n\n// -- constants -----------------------------------------//\nexport const REACT_NATIVE_PRODUCT = \"ReactNative\";\n\nexport const ENV_MAP = {\n reactNative: \"react-native\",\n node: \"node\",\n browser: \"browser\",\n unknown: \"unknown\",\n};\n\nexport const EMPTY_SPACE = \" \";\n\nexport const COLON = \":\";\n\nexport const SLASH = \"/\";\n\nexport const DEFAULT_DEPTH = 2;\n\nexport const ONE_THOUSAND = 1000;\n\nexport const SDK_TYPE = \"js\";\n\n// -- env -----------------------------------------------//\n\nexport function isNode(): boolean {\n return (\n typeof process !== \"undefined\" &&\n typeof process.versions !== \"undefined\" &&\n typeof process.versions.node !== \"undefined\"\n );\n}\n\nexport function isReactNative(): boolean {\n return !getDocument() && !!getNavigator() && navigator.product === REACT_NATIVE_PRODUCT;\n}\n\nexport function isAndroid(): boolean {\n return (\n isReactNative() &&\n typeof global !== \"undefined\" &&\n typeof (global as any)?.Platform !== \"undefined\" &&\n (global as any)?.Platform.OS === \"android\"\n );\n}\n\nexport function isIos(): boolean {\n return (\n isReactNative() &&\n typeof global !== \"undefined\" &&\n typeof (global as any)?.Platform !== \"undefined\" &&\n (global as any)?.Platform.OS === \"ios\"\n );\n}\n\nexport function isBrowser(): boolean {\n return !isNode() && !!getNavigator() && !!getDocument();\n}\n\nexport function getEnvironment(): string {\n if (isReactNative()) return ENV_MAP.reactNative;\n if (isNode()) return ENV_MAP.node;\n if (isBrowser()) return ENV_MAP.browser;\n return ENV_MAP.unknown;\n}\n\nexport function getAppId(): string | undefined {\n try {\n if (\n isReactNative() &&\n typeof global !== \"undefined\" &&\n typeof (global as any)?.Application !== \"undefined\"\n ) {\n return (global as any).Application?.applicationId;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n// -- query -----------------------------------------------//\n\nexport function appendToQueryString(\n queryString: string,\n newQueryParams: Record<string, string | number | boolean | undefined>,\n): string {\n const urlSearchParams = new URLSearchParams(queryString);\n\n Object.entries(newQueryParams)\n .sort(([a], [b]) => a.localeCompare(b))\n .forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n urlSearchParams.set(key, String(value));\n }\n });\n\n return urlSearchParams.toString();\n}\n\n// -- metadata ----------------------------------------------//\n\nexport function populateAppMetadata(metadata?: SignClientTypes.Metadata): SignClientTypes.Metadata {\n const appMetadata = getAppMetadata();\n try {\n if (metadata?.url && appMetadata.url) {\n if (new URL(metadata.url).host !== new URL(appMetadata.url).host) {\n console.warn(\n `The configured WalletConnect 'metadata.url':${metadata.url} differs from the actual page url:${appMetadata.url}. This is probably unintended and can lead to issues.`,\n );\n metadata.url = appMetadata.url;\n }\n }\n\n if (metadata?.icons?.length && metadata.icons.length > 0) {\n metadata.icons = metadata.icons.filter((icon) => icon !== \"\");\n }\n\n return {\n ...appMetadata,\n ...metadata,\n url: metadata?.url || appMetadata.url,\n name: metadata?.name || appMetadata.name,\n description: metadata?.description || appMetadata.description,\n icons:\n metadata?.icons?.length && metadata.icons.length > 0 ? metadata.icons : appMetadata.icons,\n };\n } catch (error) {\n console.warn(\"Error populating app metadata\", error);\n return metadata || appMetadata;\n }\n}\n\nexport function getAppMetadata(): SignClientTypes.Metadata {\n return (\n getWindowMetadata() || {\n name: \"\",\n description: \"\",\n url: \"\",\n icons: [\"\"],\n }\n );\n}\n\nexport function getRelayClientMetadata(protocol: string, version: number): RelayerClientMetadata {\n const env = getEnvironment();\n\n const metadata: RelayerClientMetadata = { protocol, version, env };\n if (env === \"browser\") {\n metadata.host = getLocation()?.host || \"unknown\";\n }\n return metadata;\n}\n\n// -- rpcUrl ----------------------------------------------//\n\nexport function getJavascriptOS() {\n const env = getEnvironment();\n // global.Platform is set by react-native-compat\n if (\n env === ENV_MAP.reactNative &&\n typeof global !== \"undefined\" &&\n typeof (global as any)?.Platform !== \"undefined\"\n ) {\n const { OS, Version } = (global as any).Platform;\n return [OS, Version].join(\"-\");\n }\n\n const info = detect();\n if (info === null) return \"unknown\";\n const os = info.os ? info.os.replace(\" \", \"\").toLowerCase() : \"unknown\";\n if (info.type === \"browser\") {\n return [os, info.name, info.version].join(\"-\");\n }\n return [os, info.version].join(\"-\");\n}\n\nexport function getJavascriptID() {\n const env = getEnvironment();\n return env === ENV_MAP.browser ? [env, getLocation()?.host || \"unknown\"].join(\":\") : env;\n}\n\nexport function formatUA(protocol: string, version: number, sdkVersion: string) {\n const os = getJavascriptOS();\n const id = getJavascriptID();\n return [[protocol, version].join(\"-\"), [SDK_TYPE, sdkVersion].join(\"-\"), os, id].join(\"/\");\n}\nconsole;\n\nexport function formatRelayRpcUrl({\n protocol,\n version,\n relayUrl,\n sdkVersion,\n auth,\n projectId,\n useOnCloseEvent,\n bundleId,\n packageName,\n}: RelayerTypes.RpcUrlParams) {\n const splitUrl = relayUrl.split(\"?\");\n const ua = formatUA(protocol, version, sdkVersion);\n const params = {\n auth,\n ua,\n projectId,\n useOnCloseEvent: useOnCloseEvent || undefined,\n packageName: packageName || undefined,\n bundleId: bundleId || undefined,\n };\n const queryString = appendToQueryString(splitUrl[1] || \"\", params);\n return splitUrl[0] + \"?\" + queryString;\n}\n\nexport function getHttpUrl(url: string) {\n // regex from https://stackoverflow.com/questions/3883871/regexp-to-grab-protocol-from-url\n const matches = url.match(/^[^:]+(?=:\\/\\/)/gi) || [];\n let protocol = matches[0];\n const domain = typeof protocol !== \"undefined\" ? url.split(\"://\")[1] : url;\n protocol = protocol === \"wss\" ? \"https\" : \"http\";\n return [protocol, domain].join(\"://\");\n}\n\n// -- assert ------------------------------------------------- //\n\nexport function assertType(obj: any, key: string, type: string) {\n // eslint-disable-next-line valid-typeof\n if (!obj[key] || typeof obj[key] !== type) {\n throw new Error(`Missing or invalid \"${key}\" param`);\n }\n}\n\n// -- context ------------------------------------------------- //\n\nexport function parseContextNames(context: string, depth = DEFAULT_DEPTH) {\n return getLastItems(context.split(SLASH), depth);\n}\n\nexport function formatMessageContext(context: string): string {\n return parseContextNames(context).join(EMPTY_SPACE);\n}\n\n// -- array ------------------------------------------------- //\n\nexport function hasOverlap(a: any[], b: any[]): boolean {\n const matches = a.filter((x) => b.includes(x));\n return matches.length === a.length;\n}\n\nexport function getLastItems(arr: any[], depth = DEFAULT_DEPTH): any[] {\n return arr.slice(Math.max(arr.length - depth, 0));\n}\n\n// -- map ------------------------------------------------- //\n\nexport function mapToObj<T = any>(map: Map<string, T>): Record<string, T> {\n return Object.fromEntries(map.entries());\n}\n\nexport function objToMap<T = any>(obj: Record<string, T>): Map<string, T> {\n return new Map<string, T>(Object.entries<T>(obj));\n}\n\nexport function mapEntries<A = any, B = any>(\n obj: Record<string, A>,\n cb: (x: A) => B,\n): Record<string, B> {\n const res: any = {};\n Object.keys(obj).forEach((key) => {\n res[key] = cb(obj[key]);\n });\n return res;\n}\n\n// -- enum ------------------------------------------------- //\n\n// source: https://github.com/microsoft/TypeScript/issues/3192#issuecomment-261720275\nexport const enumify = <T extends { [index: string]: U }, U extends string>(x: T): T => x;\n\n// -- string ------------------------------------------------- //\n\nexport function capitalizeWord(word: string) {\n return word.trim().replace(/^\\w/, (c) => c.toUpperCase());\n}\n\nexport function capitalize(str: string) {\n return str\n .split(EMPTY_SPACE)\n .map((w) => capitalizeWord(w))\n .join(EMPTY_SPACE);\n}\n\n// -- promises --------------------------------------------- //\nexport function createDelayedPromise<T>(\n expiry: number = FIVE_MINUTES,\n expireErrorMessage?: string,\n) {\n const timeout = toMiliseconds(expiry || FIVE_MINUTES);\n let cacheResolve: undefined | ((value: T | PromiseLike<T>) => void);\n let cacheReject: undefined | ((value?: ErrorResponse) => void);\n let cacheTimeout: undefined | NodeJS.Timeout;\n let result: Promise<Awaited<T>> | Promise<T> | undefined;\n\n const done = () =>\n new Promise<T>((promiseResolve, promiseReject) => {\n if (result) {\n return promiseResolve(result);\n }\n cacheTimeout = setTimeout(() => {\n const err = new Error(expireErrorMessage);\n result = Promise.reject(err);\n promiseReject(err);\n }, timeout);\n cacheResolve = promiseResolve;\n cacheReject = promiseReject;\n });\n const resolve = (value?: T) => {\n if (cacheTimeout && cacheResolve) {\n clearTimeout(cacheTimeout);\n cacheResolve(value as T);\n result = Promise.resolve(value) as Promise<Awaited<T>>;\n }\n };\n const reject = (value?: ErrorResponse) => {\n if (cacheTimeout && cacheReject) {\n clearTimeout(cacheTimeout);\n cacheReject(value);\n }\n };\n\n return {\n resolve,\n reject,\n done,\n };\n}\n\nexport function createExpiringPromise<T>(\n promise: Promise<T>,\n expiry: number,\n expireErrorMessage?: string,\n) {\n return new Promise(async (resolve, reject) => {\n const timeout = setTimeout(() => reject(new Error(expireErrorMessage)), expiry);\n try {\n const result = await promise;\n resolve(result);\n } catch (error) {\n reject(error);\n }\n clearTimeout(timeout);\n });\n}\n\n// -- expirer --------------------------------------------- //\n\nexport function formatExpirerTarget(type: \"topic\" | \"id\", value: string | number): string {\n if (typeof value === \"string\" && value.startsWith(`${type}:`)) return value;\n if (type.toLowerCase() === \"topic\") {\n if (typeof value !== \"string\")\n throw new Error(`Value must be \"string\" for expirer target type: topic`);\n return `topic:${value}`;\n } else if (type.toLowerCase() === \"id\") {\n if (typeof value !== \"number\")\n throw new Error(`Value must be \"number\" for expirer target type: id`);\n return `id:${value}`;\n }\n throw new Error(`Unknown expirer target type: ${type}`);\n}\n\nexport function formatTopicTarget(topic: string): string {\n return formatExpirerTarget(\"topic\", topic);\n}\n\nexport function formatIdTarget(id: number): string {\n return formatExpirerTarget(\"id\", id);\n}\n\nexport function parseExpirerTarget(target: string) {\n const [type, value] = target.split(\":\");\n const parsed: { id?: number; topic?: string } = { id: undefined, topic: undefined };\n if (type === \"topic\" && typeof value === \"string\") {\n parsed.topic = value;\n } else if (type === \"id\" && Number.isInteger(Number(value))) {\n parsed.id = Number(value);\n } else {\n throw new Error(`Invalid target, expected id:number or topic:string, got ${type}:${value}`);\n }\n\n return parsed;\n}\n\nexport function calcExpiry(ttl: number, now?: number): number {\n return fromMiliseconds((now || Date.now()) + toMiliseconds(ttl));\n}\n\nexport function isExpired(expiry: number) {\n return Date.now() >= toMiliseconds(expiry);\n}\n\n// -- events ---------------------------------------------- //\n\nexport function engineEvent(event: EngineTypes.Event, id?: number | string | undefined) {\n return `${event}${id ? `:${id}` : \"\"}`;\n}\n\nexport function mergeArrays<T>(a: T[] = [], b: T[] = []): T[] {\n return [...new Set([...a, ...b])];\n}\n\nexport async function handleDeeplinkRedirect({\n id,\n topic,\n wcDeepLink,\n}: {\n id: number;\n topic: string;\n wcDeepLink: string;\n}) {\n try {\n if (!wcDeepLink) return;\n\n const json = typeof wcDeepLink === \"string\" ? JSON.parse(wcDeepLink) : wcDeepLink;\n const deeplink = json?.href;\n if (typeof deeplink !== \"string\") return;\n const link = formatDeeplinkUrl(deeplink, id, topic);\n const env = getEnvironment();\n\n if (env === ENV_MAP.browser) {\n if (!getDocument()?.hasFocus()) {\n console.warn(\"Document does not have focus, skipping deeplink.\");\n return;\n }\n\n openDeeplink(link);\n } else if (env === ENV_MAP.reactNative) {\n // global.Linking is set by react-native-compat\n if (typeof (global as any)?.Linking !== \"undefined\") {\n await (global as any).Linking.openURL(link);\n }\n }\n } catch (err) {\n // Silent error, just log in console\n // eslint-disable-next-line no-console\n console.error(err);\n }\n}\n\nexport function formatDeeplinkUrl(deeplink: string, requestId: number, sessionTopic: string) {\n const payload = `requestId=${requestId}&sessionTopic=${sessionTopic}`;\n if (deeplink.endsWith(\"/\")) deeplink = deeplink.slice(0, -1);\n let link = `${deeplink}`;\n if (deeplink.startsWith(\"https://t.me\")) {\n const startApp = deeplink.includes(\"?\") ? \"&startapp=\" : \"?startapp=\";\n link = `${link}${startApp}${toBase64(payload, true)}`;\n } else {\n link = `${link}/wc?${payload}`;\n }\n return link;\n}\n\nexport function openDeeplink(url: string) {\n let target = \"_self\";\n if (isIframe()) {\n target = \"_top\";\n } else if (isTelegram() || url.startsWith(\"https://\") || url.startsWith(\"http://\")) {\n target = \"_blank\";\n }\n\n window.open(url, target, \"noreferrer noopener\");\n}\n\nexport async function getDeepLink(storage: IKeyValueStorage, key: string) {\n let link: string | undefined = \"\";\n try {\n if (isBrowser()) {\n link = localStorage.getItem(key) as string;\n if (link) return link;\n }\n link = await storage.getItem(key);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n return link;\n}\n\nexport function getCommonValuesInArrays<T = string | number | boolean>(arr1: T[], arr2: T[]): T[] {\n return arr1.filter((value) => arr2.includes(value));\n}\n\nexport function getSearchParamFromURL(url: string, param: any) {\n const include = url.includes(param);\n if (!include) return null;\n const params = url.split(/([&,?,=])/);\n const index = params.indexOf(param);\n const value = params[index + 2];\n return value;\n}\n\nexport function uuidv4() {\n if (typeof crypto !== \"undefined\" && crypto?.randomUUID) {\n return crypto.randomUUID();\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/gu, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n\n return v.toString(16);\n });\n}\n\nexport function isTestRun() {\n return typeof process !== \"undefined\" && process.env.IS_VITEST === \"true\";\n}\n\nexport function isTelegram() {\n return (\n typeof window !== \"undefined\" &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (Boolean((window as any).TelegramWebviewProxy) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Boolean((window as any).Telegram) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Boolean((window as any).TelegramWebviewProxyProto))\n );\n}\n\nexport function isIframe() {\n try {\n return window.self !== window.top;\n } catch {\n return false;\n }\n}\n\nexport function toBase64(input: string, removePadding = false): string {\n const encoded = Buffer.from(input).toString(\"base64\");\n return removePadding ? encoded.replace(/[=]/g, \"\") : encoded;\n}\n\nexport function fromBase64(encodedString: string): string {\n return Buffer.from(encodedString, \"base64\").toString(\"utf-8\");\n}\n\nexport function sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport class LimitedSet<T> {\n private limit: number;\n private set: Set<T>;\n\n constructor({ limit }: { limit: number }) {\n this.limit = limit;\n this.set = new Set<T>();\n }\n\n add(item: T) {\n if (this.set.has(item)) return;\n\n if (this.set.size >= this.limit) {\n // Remove the oldest entry (FIFO)\n const firstKey = this.set.values().next().value;\n if (firstKey) {\n this.set.delete(firstKey);\n }\n }\n\n this.set.add(item);\n }\n\n has(item: T) {\n return this.set.has(item);\n }\n}\n","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createHasher, createXOFer, Hash, swap32IfBE, toBytes, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/** Keccak sponge function. */\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n this.enableXOF = false;\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\nconst genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n//# sourceMappingURL=sha3.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modul