@swype-org/deposit 0.3.32 → 0.3.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/messages.ts","../src/brandParam.ts","../src/balanceParam.ts","../src/walletBridge/discover.ts","../src/walletBridge/protocol.ts","../src/walletBridge/rpcHost.ts","../src/viewportMetrics.ts","../src/iframeCore.ts","../src/iframe.ts","../src/embeddedIframe.ts","../src/signer.ts","../src/validation.ts","../src/checkout.ts","../src/index.ts"],"names":[],"mappings":";;;AAmBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA;AAAA,EAET,WAAA,CAAY,MAAwB,OAAA,EAAiB;AACnD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAGO,IAAM,aAAA,GAAgB;AAI7B,IAAM,gBAAA,GAAqD;AAAA,EACzD,iBAAA,EACE,0DAAA;AAAA,EACF,kBAAA,EACE,2DAAA;AAAA,EACF,qBAAA,EACE,gDAAA;AAAA,EACF,oBAAA,EACE,0EAAA;AAAA,EACF,uBAAA,EACE,qDAAA;AAAA,EACF,cAAA,EACE,gEAAA;AAAA,EACF,YAAA,EACE,+CAAA;AAAA,EACF,eAAA,EACE;AACJ,CAAA;AAQO,SAAS,kBAAkB,KAAA,EAA6B;AAC7D,EAAA,OAAO,gBAAA,CAAiB,KAAA,CAAM,IAAI,CAAA,IAAK,KAAA,CAAM,OAAA;AAC/C;;;AC3CO,SAAS,sBAAsB,IAAA,EAA+C;AACnF,EAAA,IAAI,CAAC,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACrC,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,GAAA,GAAM,IAAA;AACZ,EAAA,IAAI,GAAA,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MAAA,CAAO,gBAAA,KAAqB,YAAY,OAAO,IAAA;AACnE,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI;AACF,IAAA,KAAA,GAAQ,MAAA,CAAO,gBAAA,CAAiB,IAAI,CAAA,CAAE,WAAA,IAAe,EAAA;AAAA,EACvD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,WAAA,EAAY,CAAE,MAAM,KAAK,CAAA;AAC9C,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,QAAA,CAAS,MAAM,CAAA;AACnC,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,QAAA,CAAS,OAAO,CAAA;AACrC,EAAA,IAAI,IAAA,IAAQ,OAAO,OAAO,QAAA;AAC1B,EAAA,IAAI,MAAM,OAAO,MAAA;AACjB,EAAA,OAAO,IAAA;AACT;AAGO,IAAM,QAAA,GAAW;;;AC3gCjB,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["export type DepositErrorCode =\n | 'DEPOSIT_DISMISSED'\n | 'CHECKOUT_DISMISSED'\n | 'SIGNER_REQUEST_FAILED'\n | 'SIGNER_NETWORK_ERROR'\n | 'SIGNER_RESPONSE_INVALID'\n | 'SIGNER_TIMEOUT'\n | 'FLOW_TIMEOUT'\n | 'INVALID_REQUEST';\n\n/** @deprecated Use {@link DepositErrorCode} instead. */\nexport type CheckoutErrorCode = DepositErrorCode;\n\n/**\n * Structured error thrown by the deposit SDK.\n *\n * Every error carries a machine-readable {@link code} so merchants can\n * branch on failure mode without parsing message strings.\n */\nexport class DepositError extends Error {\n readonly code: DepositErrorCode;\n\n constructor(code: DepositErrorCode, message: string) {\n super(message);\n this.name = 'DepositError';\n this.code = code;\n }\n}\n\n/** @deprecated Use {@link DepositError} instead. */\nexport const CheckoutError = DepositError;\n/** @deprecated Use {@link DepositError} instead. */\nexport type CheckoutError = DepositError;\n\nconst DISPLAY_MESSAGES: Record<DepositErrorCode, string> = {\n DEPOSIT_DISMISSED:\n 'The deposit was dismissed before the transfer completed.',\n CHECKOUT_DISMISSED:\n 'The checkout was dismissed before the transfer completed.',\n SIGNER_REQUEST_FAILED:\n 'Unable to start the payment. Please try again.',\n SIGNER_NETWORK_ERROR:\n 'Unable to reach the payment server. Check your connection and try again.',\n SIGNER_RESPONSE_INVALID:\n 'The payment server returned an unexpected response.',\n SIGNER_TIMEOUT:\n 'The payment server took too long to respond. Please try again.',\n FLOW_TIMEOUT:\n 'The payment flow timed out. Please try again.',\n INVALID_REQUEST:\n 'Invalid payment request. Please check your input.',\n};\n\n/**\n * Return a user-friendly display string for a {@link DepositError}.\n *\n * Merchants can show this directly in their UI without maintaining their own\n * copy for each error code.\n */\nexport function getDisplayMessage(error: DepositError): string {\n return DISPLAY_MESSAGES[error.code] ?? error.message;\n}\n","import type { TransferSummary } from './types.ts';\n\n// ── Wire message shapes (internal protocol — brand-specific names are OK) ──\n\ninterface TransferCompleteMessage {\n type: 'blink:transfer-complete';\n transfer: TransferSummary;\n}\n\ninterface TransferCompleteAckMessage {\n type: 'blink:transfer-complete-ack';\n transferId: string;\n}\n\n/**\n * Parse an incoming `MessageEvent.data` value into a validated transfer\n * completion message, or return `null` if it does not match.\n */\nexport function parseTransferComplete(data: unknown): TransferCompleteMessage | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n\n const msg = data as Record<string, unknown>;\n if (msg.type !== 'blink:transfer-complete') {\n return null;\n }\n\n const transfer = msg.transfer;\n if (!transfer || typeof transfer !== 'object') {\n return null;\n }\n\n const t = transfer as Record<string, unknown>;\n if (typeof t.id !== 'string' || typeof t.status !== 'string') {\n return null;\n }\n\n return {\n type: 'blink:transfer-complete',\n transfer: {\n id: t.id,\n status: t.status,\n amount: parseAmount(t.amount),\n destinations: parseDestinations(t.destinations),\n },\n };\n}\n\nfunction parseAmount(value: unknown): TransferSummary['amount'] {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n const a = value as Record<string, unknown>;\n return {\n amount: Number(a.amount ?? 0),\n currency: String(a.currency ?? ''),\n };\n}\n\nfunction parseDestinations(value: unknown): TransferSummary['destinations'] {\n if (!Array.isArray(value)) {\n return undefined;\n }\n\n return value\n .filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === 'object')\n .map((entry) => ({\n chainId: String(entry.chainId ?? ''),\n address: String(entry.address ?? ''),\n token:\n entry.token && typeof entry.token === 'object'\n ? {\n address: String((entry.token as Record<string, unknown>).address ?? ''),\n symbol: String((entry.token as Record<string, unknown>).symbol ?? ''),\n }\n : undefined,\n }));\n}\n\n/** Build an ACK message to send back to the hosted flow. */\nexport function buildAckMessage(transferId: string): TransferCompleteAckMessage {\n return {\n type: 'blink:transfer-complete-ack',\n transferId,\n };\n}\n\n// ── Close request ─────────────────────────────────────────────────────\n\ninterface CloseRequestMessage {\n type: 'blink:close-request';\n}\n\n/**\n * Parse an incoming `MessageEvent.data` value into a close-request message,\n * or return `null` if it does not match. The hosted flow sends this when\n * the user taps the close / X button inside the iframe.\n */\nexport function parseCloseRequest(data: unknown): CloseRequestMessage | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n const msg = data as Record<string, unknown>;\n if (msg.type !== 'blink:close-request') {\n return null;\n }\n return { type: 'blink:close-request' };\n}\n\n// ── Preload handshake ─────────────────────────────────────────────────\n\ninterface IframeReadyMessage {\n type: 'blink:iframe-ready';\n /**\n * Feature capabilities advertised by the hosted flow. Older webview\n * deployments omit the field entirely — parsed as an empty list so the\n * SDK can downgrade features that need cooperation from the iframe\n * (e.g. `layout-fluid`).\n */\n capabilities: string[];\n}\n\nexport function parseIframeReady(data: unknown): IframeReadyMessage | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n const msg = data as Record<string, unknown>;\n if (msg.type !== 'blink:iframe-ready') {\n return null;\n }\n return { type: 'blink:iframe-ready', capabilities: parseCapabilities(msg.capabilities) };\n}\n\nfunction parseCapabilities(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value.filter((entry): entry is string => typeof entry === 'string');\n}\n\n// ── Reveal (fluid layout) ─────────────────────────────────────────────\n\ninterface RevealMessage {\n type: 'blink:reveal';\n}\n\n// ── Viewport metrics (fluid layout) ───────────────────────────────────\n\ninterface ViewportMessage {\n type: 'blink:viewport';\n /** Merchant page's large-viewport height (100lvh) in CSS px. */\n viewportLvh: number;\n /** Merchant page's `env(safe-area-inset-bottom)` in CSS px. */\n safeAreaBottom: number;\n /**\n * Embedded presentation only: the host's height budget for the inline\n * iframe, in CSS px. Omitted entirely on overlay/fluid loads so the wire\n * shape older webview deployments see is byte-for-byte what it always was.\n */\n embedMaxHeightPx?: number;\n}\n\n/**\n * Build the message that keeps the hosted flow's sheet geometry anchored to\n * the merchant page's *large* viewport. Inside the fluid iframe, `dvh`\n * tracks the current (chrome-dependent) viewport, so without these values\n * the sheet would resize whenever the mobile browser's URL bar collapses or\n * expands — the legacy parent-side sheet (79vh) never did.\n *\n * In embedded presentation it carries `embedMaxHeightPx` as well: there the\n * iframe's own height is a function of its content, so the flow cannot use\n * `dvh` for anything and needs a host-supplied budget to size against.\n */\nexport function buildViewportMessage(\n viewportLvh: number,\n safeAreaBottom: number,\n embedMaxHeightPx?: number,\n): ViewportMessage {\n return {\n type: 'blink:viewport',\n viewportLvh,\n safeAreaBottom,\n ...(embedMaxHeightPx === undefined ? {} : { embedMaxHeightPx }),\n };\n}\n\n// ── Content height (embedded presentation) ────────────────────────────\n\ninterface ContentHeightMessage {\n type: 'blink:content-height';\n /** Rendered height of the hosted flow's card, in CSS px. */\n heightPx: number;\n /**\n * Width the flow would like if the host has room, and the width below which\n * its fixed-width elements start to overflow. Constants from the hosted\n * flow's design envelope, not measurements — a width derived from the width\n * the host granted would just echo back, so a panel could never grow.\n * Absent from older hosted flows that only reported height.\n */\n preferredWidthPx?: number;\n minWidthPx?: number;\n}\n\n/** Upper bound on a reported height — same order as the viewport clamp. */\nconst MAX_CONTENT_HEIGHT_PX = 20_000;\n\n/**\n * Parse the hosted flow's content-height report, or return `null` if it does\n * not match. Sent continuously in embedded presentation (a ResizeObserver on\n * the card) so the host can size the inline iframe element to the flow; the\n * host is a dumb follower here, applying the value without animating it —\n * the SDK's own height transition is what the user sees.\n */\nexport function parseContentHeight(data: unknown): ContentHeightMessage | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n const msg = data as Record<string, unknown>;\n if (msg.type !== 'blink:content-height') {\n return null;\n }\n const raw = msg.heightPx;\n if (typeof raw !== 'number' || !Number.isFinite(raw)) {\n return null;\n }\n const heightPx = Math.round(raw);\n if (heightPx <= 0 || heightPx > MAX_CONTENT_HEIGHT_PX) {\n return null;\n }\n return {\n type: 'blink:content-height',\n heightPx,\n ...parseWidthHint('preferredWidthPx', msg.preferredWidthPx),\n ...parseWidthHint('minWidthPx', msg.minWidthPx),\n };\n}\n\n/** A width hint is optional: drop anything unusable rather than failing the report. */\nfunction parseWidthHint(key: 'preferredWidthPx' | 'minWidthPx', value: unknown) {\n if (typeof value !== 'number' || !Number.isFinite(value)) return {};\n const px = Math.round(value);\n if (px <= 0 || px > MAX_CONTENT_HEIGHT_PX) return {};\n return { [key]: px } as Record<string, number>;\n}\n\n/**\n * Build the message that tells the hosted flow its overlay just became (or\n * already is) visible, so it plays the card entry animation. Only meaningful\n * in fluid layout, where the card chrome lives inside the iframe; other\n * webviews ignore it.\n */\nexport function buildRevealMessage(): RevealMessage {\n return { type: 'blink:reveal' };\n}\n\ninterface SignedPayloadMessage {\n type: 'blink:signed-payload';\n merchantId: string;\n payload: string;\n signature: string;\n /**\n * Display-only merchant balance in USD, already normalized by the host SDK\n * (`balanceParam.ts`: floored to cents, always two fraction digits —\n * `\"20.70\"`). An UNSIGNED sibling of the payload: it is not covered by the\n * signature and the hosted flow re-validates it before display. Omitted\n * entirely when the merchant passed nothing usable, so the wire shape older\n * webview deployments see is byte-for-byte what it always was.\n */\n balance?: string;\n}\n\nexport function buildSignedPayloadMessage(\n merchantId: string,\n payload: string,\n signature: string,\n balance?: string,\n): SignedPayloadMessage {\n return {\n type: 'blink:signed-payload',\n merchantId,\n payload,\n signature,\n ...(balance === undefined ? {} : { balance }),\n };\n}\n","// ── Brand color param (host side) ─────────────────────────────────────\n//\n// The encoder half of the `brand` URL param. The decoder, the palette\n// derivation and the contrast gate all live in the hosted flow\n// (`swype-sdk/src/brandColors.ts`) — that is where the colors are actually\n// used, and it re-validates everything it decodes because the URL is\n// host-controlled input on its way into a stylesheet.\n//\n// So the key map below is one table in two packages. Deliberate: this SDK ships\n// to merchants with zero dependencies and cannot import the hosted flow's\n// module, and duplicating five short strings is a better trade than a shared\n// package for them. They ship together with the webview, and the round trip is\n// covered by tests on both sides — but if you add a key here, add it there.\n\n/** Config key → param key. Mirrors `BRAND_PARAM_KEYS` in swype-sdk. */\nexport const BRAND_COLOR_PARAM_KEYS: Record<string, string> = {\n colorPrimary: 'p',\n colorBackground: 'bg',\n colorText: 't',\n colorDanger: 'd',\n colorBorder: 'b',\n};\n\n/**\n * Normalizes `#rgb` / `#rrggbb` (any case) to lowercase `#rrggbb`. Returns null\n * for anything else, including 8-digit hex: Blink's card is a solid surface, so\n * alpha has no meaning and is rejected rather than silently flattened.\n */\nexport function normalizeBrandHex(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const hex = value.trim().toLowerCase();\n if (!/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/.test(hex)) return null;\n const digits = hex.slice(1);\n if (digits.length === 6) return `#${digits}`;\n return `#${digits[0]}${digits[0]}${digits[1]}${digits[1]}${digits[2]}${digits[2]}`;\n}\n","// ── Merchant balance param (host side) ────────────────────────────────\n//\n// The encoder half of the display-only merchant balance. The decoder lives\n// in the hosted flow (webview-app), which re-validates everything it\n// receives — the postMessage sibling field and the `balance` URL param are\n// both host-controlled input on their way into the deposit header.\n//\n// Validated here as well purely so the merchant sees the complaint in their\n// OWN console (same rationale as `brandParam.ts`): a balance that silently\n// vanishes looks like the SDK ignoring the request. Never forward the\n// merchant's raw value — parse, floor, re-serialize.\n\n/**\n * Exclusive upper bound on an accepted balance, in USD. Mirrors the\n * `MAX_CONTENT_HEIGHT_PX` clamp philosophy in `messages.ts`: a hard cap on\n * merchant-supplied magnitudes, generous enough for any real balance.\n */\nconst MAX_BALANCE_USD = 1e12;\n\n/**\n * Normalizes a merchant-supplied display balance to its canonical wire form,\n * or returns `null` for anything unusable (the caller drops the field).\n *\n * Accepts only a finite number `>= 0` and `< 1e12`. The value is floored to\n * whole cents — a balance never rounds up — and serialized as a plain decimal\n * string with exactly two fraction digits: `20.7` → `\"20.70\"`, `0` → `\"0.00\"`.\n *\n * Flooring detail: `Math.floor(value * 100)` alone is wrong for values whose\n * float64 form sits just under the cent boundary (`0.29 * 100 ===\n * 28.999999999999996`). `toPrecision(15)` strips that representation noise —\n * it lives at significant digit 16–17 — before flooring, so only genuine\n * sub-cent digits are dropped. The cents guard afterwards rejects the one\n * pathological corner where noise-stripping rounds a value within float64\n * noise of the cap up through it (e.g. `999999999999.9999`): dropping it beats\n * emitting a balance at or above the cap.\n */\nexport function normalizeDisplayBalance(value: unknown): string | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) return null;\n if (value < 0 || value >= MAX_BALANCE_USD) return null;\n const cents = Math.floor(Number((value * 100).toPrecision(15)));\n if (cents < 0 || cents >= MAX_BALANCE_USD * 100) return null;\n return (cents / 100).toFixed(2);\n}\n","// ── EIP-6963 Wallet Discoverer (parent-frame) ──────────────────────────\n//\n// Some browser-extension wallets (notably Uniswap and Rainbow) inject\n// `window.ethereum` and dispatch EIP-6963 announcements only into the\n// top-level frame. Inside our cross-origin payment iframe, wagmi's MIPD\n// scan never sees them.\n//\n// This module runs in the parent frame (the merchant page that loads\n// `@swype-org/deposit`). It listens for EIP-6963 announcements, builds a\n// registry of installed providers keyed by their EIP-6963 `info.uuid`,\n// and exposes it for the `rpcHost` to advertise into the iframe.\n//\n// Hand-off contract with the iframe lives in `messages.ts` /\n// `walletBridge/protocol.ts`.\n\nimport type {\n EIP1193Provider,\n EIP6963ProviderDetail,\n EIP6963ProviderInfo,\n} from './protocol.ts';\n\nexport interface RegisteredProvider {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\nexport interface WalletDiscovererHandle {\n /** Snapshot of currently-registered providers. */\n list(): RegisteredProvider[];\n /** Look up a single provider by EIP-6963 uuid. */\n get(uuid: string): EIP1193Provider | undefined;\n /** Subscribe to registry changes. Returns an unsubscribe callback. */\n subscribe(listener: (snapshot: RegisteredProvider[]) => void): () => void;\n /**\n * Re-dispatch `eip6963:requestProvider`. Wallets that wired up after\n * page load (or after the initial sweep) will re-announce in response.\n */\n requestProviders(): void;\n /** Tear down listeners. After this, `list()` returns `[]`. */\n destroy(): void;\n}\n\ninterface AnnounceEvent extends Event {\n detail?: EIP6963ProviderDetail;\n}\n\n/**\n * Start discovering EIP-6963 providers in the current (top-level) frame.\n *\n * Safe to call multiple times — each handle owns its own listeners and\n * registry; calling `destroy()` releases both. In practice, `createIframe`\n * spins one handle per modal open.\n */\nexport function createWalletDiscoverer(): WalletDiscovererHandle {\n if (typeof window === 'undefined') {\n return makeNoopHandle();\n }\n\n const registry = new Map<string, RegisteredProvider>();\n const listeners = new Set<(snapshot: RegisteredProvider[]) => void>();\n let destroyed = false;\n\n const onAnnounce = (event: Event) => {\n if (destroyed) return;\n const detail = (event as AnnounceEvent).detail;\n if (!isValidProviderDetail(detail)) {\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] dropping malformed EIP-6963 announcement', {\n rawInfo: (event as AnnounceEvent).detail\n && ((event as AnnounceEvent).detail as { info?: unknown }).info,\n });\n return;\n }\n\n const existing = registry.get(detail.info.uuid);\n if (existing && existing.provider === detail.provider) {\n return;\n }\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] EIP-6963 announceProvider', {\n rdns: detail.info.rdns,\n name: detail.info.name,\n uuid: detail.info.uuid,\n });\n registry.set(detail.info.uuid, {\n info: { ...detail.info },\n provider: detail.provider,\n });\n notify();\n };\n\n // EIP-6963 requires the page to listen for announcements *first*, then\n // dispatch the request. Wallets respond synchronously with their\n // provider details. Wallets that load late (slow content scripts) will\n // also auto-announce on their own once they're ready.\n window.addEventListener('eip6963:announceProvider', onAnnounce);\n requestProviders();\n\n // Mirror wagmi's `unstable_shimAsyncInject: 2_000` — a few content\n // scripts (Uniswap is one) finish wiring up after `DOMContentLoaded`,\n // so a single sweep can miss them. Re-request a handful of times in\n // the first few seconds, then stop. Each re-request is cheap (one\n // CustomEvent dispatch).\n const RESWEEP_INTERVALS_MS = [500, 1500, 3000, 6000];\n const reSweepTimers: ReturnType<typeof setTimeout>[] = [];\n for (const ms of RESWEEP_INTERVALS_MS) {\n reSweepTimers.push(\n setTimeout(() => {\n if (!destroyed) requestProviders();\n }, ms),\n );\n }\n\n function requestProviders(): void {\n try {\n window.dispatchEvent(new Event('eip6963:requestProvider'));\n } catch {\n // jsdom older than v22 throws on `new Event()` in some setups —\n // safe to swallow; real browsers always succeed here.\n }\n }\n\n function notify(): void {\n const snapshot = list();\n for (const listener of listeners) {\n try {\n listener(snapshot);\n } catch {\n // Listener errors must not break the discoverer.\n }\n }\n }\n\n function list(): RegisteredProvider[] {\n return [...registry.values()];\n }\n\n return {\n list,\n get(uuid: string): EIP1193Provider | undefined {\n return registry.get(uuid)?.provider;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n requestProviders,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n window.removeEventListener('eip6963:announceProvider', onAnnounce);\n for (const t of reSweepTimers) clearTimeout(t);\n registry.clear();\n listeners.clear();\n },\n };\n}\n\nfunction makeNoopHandle(): WalletDiscovererHandle {\n return {\n list: () => [],\n get: () => undefined,\n subscribe: () => () => {},\n requestProviders: () => {},\n destroy: () => {},\n };\n}\n\nfunction isValidProviderDetail(value: unknown): value is EIP6963ProviderDetail {\n if (!value || typeof value !== 'object') return false;\n const detail = value as Record<string, unknown>;\n const info = detail.info as Record<string, unknown> | undefined;\n const provider = detail.provider as Record<string, unknown> | undefined;\n if (!info || !provider) return false;\n if (typeof info.uuid !== 'string' || info.uuid.length === 0) return false;\n if (typeof info.name !== 'string') return false;\n if (typeof info.rdns !== 'string') return false;\n if (typeof provider.request !== 'function') return false;\n return true;\n}\n","// ── Wallet Bridge Wire Protocol ────────────────────────────────────────\n//\n// Shared between parent (`deposit-sdk`) and iframe (`swype-sdk`). Both\n// sides define the same shapes locally — there is no runtime import\n// across the postMessage boundary, only structural conformance via\n// `protocolVersion: 1`. Bumping the version to 2 is a breaking change\n// receivers must opt into; v1 receivers silently drop v2 messages and\n// fall through to legacy behavior.\n//\n// New `type` values are additive within the same `protocolVersion`: any\n// peer that doesn't recognize them returns `null` from\n// `parseBridgeMessage` and the sender falls through to its own\n// timeout/fallback path. Only bump the version when we change the wire\n// shape of an existing message.\n\n/** Current wire-protocol version. Bump on breaking changes. */\nexport const BRIDGE_PROTOCOL_VERSION = 1;\n\n// ── EIP-6963 / EIP-1193 (subset we touch) ──────────────────────────────\n\nexport interface EIP6963ProviderInfo {\n uuid: string;\n name: string;\n icon: string;\n rdns: string;\n}\n\nexport interface EIP1193RequestArgs {\n method: string;\n params?: unknown[] | Record<string, unknown>;\n}\n\nexport interface EIP1193Provider {\n request(args: EIP1193RequestArgs): Promise<unknown>;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n removeListener?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n}\n\nexport interface EIP6963ProviderDetail {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\n// ── Wire messages (both directions tagged with `type`) ─────────────────\n\n/** Iframe → Parent: handshake, sent once on mount. */\nexport interface BridgeHelloMessage {\n type: 'blink:bridge-hello';\n protocolVersion: number;\n}\n\n/** Parent → Iframe: list of installed wallets the iframe can borrow. */\nexport interface WalletsAdvertisedMessage {\n type: 'blink:wallets-advertised';\n protocolVersion: number;\n wallets: AdvertisedWallet[];\n}\n\nexport interface AdvertisedWallet {\n uuid: string;\n rdns: string;\n name: string;\n icon: string;\n}\n\n/** Iframe → Parent: invoke a JSON-RPC method on a top-frame wallet. */\nexport interface RpcRequestMessage {\n type: 'blink:rpc-request';\n protocolVersion: number;\n uuid: string;\n id: string;\n method: string;\n params?: unknown[] | Record<string, unknown>;\n}\n\n/** Parent → Iframe: result of a previous `RpcRequestMessage`. */\nexport interface RpcResponseMessage {\n type: 'blink:rpc-response';\n protocolVersion: number;\n id: string;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\n/** Parent → Iframe: forwarded EIP-1193 event from a top-frame wallet. */\nexport interface RpcEventMessage {\n type: 'blink:rpc-event';\n protocolVersion: number;\n uuid: string;\n event: string;\n args: unknown[];\n}\n\n/**\n * Iframe → Parent: ask \"which advertised wallet has any of these flags\n * (e.g. `isUniswapWallet`) set as a truthy property on its provider?\".\n * Used to disambiguate Reown registry entries that lack `rdns` (e.g.\n * Uniswap, where Reown only ships `injected[].injectedId:\n * 'isUniswapWallet'`). The parent reads `provider[flag]` defensively\n * for each advertised provider and returns the first hit, or null.\n *\n * The parent answers each request once; the response is matched by\n * `id`. Cost is local property reads on already-discovered providers —\n * no network and no cross-frame I/O beyond the postMessage round-trip.\n */\nexport interface ResolveByFlagRequestMessage {\n type: 'blink:resolve-by-flag';\n protocolVersion: number;\n /** Request id, mirrored on the response so the iframe can route it. */\n id: string;\n /** Flag names to test in order; first truthy property wins. */\n flags: string[];\n}\n\n/** Parent → Iframe: result of a previous `ResolveByFlagRequestMessage`. */\nexport interface ResolveByFlagResponseMessage {\n type: 'blink:resolve-by-flag-response';\n protocolVersion: number;\n id: string;\n /** `null` when no advertised provider had any flag set. */\n match: ResolveByFlagMatch | null;\n}\n\nexport interface ResolveByFlagMatch {\n /** EIP-6963 `rdns` of the matched provider. */\n rdns: string;\n /** EIP-6963 `uuid` of the matched provider. */\n uuid: string;\n /** Which flag matched first (lets the caller log/telemeter). */\n flag: string;\n}\n\nexport type BridgeMessage =\n | BridgeHelloMessage\n | WalletsAdvertisedMessage\n | RpcRequestMessage\n | RpcResponseMessage\n | RpcEventMessage\n | ResolveByFlagRequestMessage\n | ResolveByFlagResponseMessage;\n\n// ── JSON-RPC method allowlist ──────────────────────────────────────────\n//\n// Only methods on this list are forwarded to the top-frame provider.\n// Anything else gets a `-32601 Method not allowed` rejection, mirroring\n// the JSON-RPC 2.0 \"Method not found\" error code.\n\nexport const ALLOWED_RPC_METHODS = new Set<string>([\n // Read\n 'eth_accounts',\n 'eth_blockNumber',\n 'eth_call',\n 'eth_chainId',\n 'eth_estimateGas',\n 'eth_gasPrice',\n 'eth_getBalance',\n 'eth_getCode',\n 'eth_getStorageAt',\n 'eth_getTransactionByHash',\n 'eth_getTransactionCount',\n 'eth_getTransactionReceipt',\n 'net_version',\n 'wallet_getCapabilities',\n 'wallet_getCallsStatus',\n // Write / sign\n 'eth_requestAccounts',\n 'eth_sendTransaction',\n 'eth_sendRawTransaction',\n 'eth_sign',\n 'personal_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_sendCalls',\n 'wallet_watchAsset',\n // EIP-2255: lets the SDK revoke the dApp's `eth_accounts` grant before\n // re-prompting on \"+ Add wallet\" / back-from-setup, so MetaMask shows the\n // account picker instead of silently reusing the previously-permitted\n // account. Wallets that don't implement it return method-not-supported,\n // which the SDK swallows.\n 'wallet_revokePermissions',\n]);\n\n// ── Forwarded EIP-1193 events ──────────────────────────────────────────\n\nexport const FORWARDED_PROVIDER_EVENTS = [\n 'accountsChanged',\n 'chainChanged',\n 'connect',\n 'disconnect',\n 'message',\n] as const;\n\nexport type ForwardedProviderEvent = (typeof FORWARDED_PROVIDER_EVENTS)[number];\n\n// ── Parsers (used by both sides) ───────────────────────────────────────\n\nexport function parseBridgeMessage(data: unknown): BridgeMessage | null {\n if (!data || typeof data !== 'object') return null;\n const msg = data as Record<string, unknown>;\n if (msg.protocolVersion !== BRIDGE_PROTOCOL_VERSION) return null;\n switch (msg.type) {\n case 'blink:bridge-hello':\n return msg as unknown as BridgeHelloMessage;\n case 'blink:wallets-advertised':\n return Array.isArray(msg.wallets) ? (msg as unknown as WalletsAdvertisedMessage) : null;\n case 'blink:rpc-request':\n if (typeof msg.uuid !== 'string' || typeof msg.id !== 'string' || typeof msg.method !== 'string') {\n return null;\n }\n return msg as unknown as RpcRequestMessage;\n case 'blink:rpc-response':\n if (typeof msg.id !== 'string') return null;\n return msg as unknown as RpcResponseMessage;\n case 'blink:rpc-event':\n if (typeof msg.uuid !== 'string' || typeof msg.event !== 'string' || !Array.isArray(msg.args)) {\n return null;\n }\n return msg as unknown as RpcEventMessage;\n case 'blink:resolve-by-flag':\n if (typeof msg.id !== 'string' || !Array.isArray(msg.flags)) return null;\n // Defensive: every flag must be a non-empty string. Reject the\n // whole message rather than silently filtering to keep the\n // request/response semantics honest.\n if (!msg.flags.every((f) => typeof f === 'string' && f.length > 0)) return null;\n return msg as unknown as ResolveByFlagRequestMessage;\n case 'blink:resolve-by-flag-response':\n if (typeof msg.id !== 'string') return null;\n // `match` may be null or an object with rdns/uuid/flag; the\n // caller validates the inner shape.\n if (msg.match !== null && (typeof msg.match !== 'object' || !msg.match)) return null;\n return msg as unknown as ResolveByFlagResponseMessage;\n default:\n return null;\n }\n}\n","// ── Wallet Bridge RPC Host (parent-frame) ──────────────────────────────\n//\n// Exposes top-frame EIP-1193 providers to the cross-origin iframe over\n// `postMessage`. Built on top of `WalletDiscovererHandle` (the EIP-6963\n// registry) and the wire protocol in `protocol.ts`.\n//\n// Security model:\n// - Origin-pinned: only `event.origin === iframeOrigin` is honored.\n// - Source-pinned: only messages whose `event.source === iframeWindow`\n// are honored (defends against rogue iframes on the same page).\n// - Method allowlist: anything outside `ALLOWED_RPC_METHODS` rejects\n// with JSON-RPC `-32601 Method not allowed`. Defense in depth — the\n// iframe SDK is trusted, but we don't want a future SDK regression\n// to expose, say, `eth_signTransaction` (offline signing) by accident.\n//\n// Backwards-compat: this host responds to `blink:bridge-hello` with the\n// current advertisement. Old iframes never send the hello and never send\n// `blink:rpc-request`, so the host is silent for them.\n\nimport type { WalletDiscovererHandle, RegisteredProvider } from './discover.ts';\nimport {\n ALLOWED_RPC_METHODS,\n BRIDGE_PROTOCOL_VERSION,\n FORWARDED_PROVIDER_EVENTS,\n parseBridgeMessage,\n type AdvertisedWallet,\n type EIP1193Provider,\n type ResolveByFlagMatch,\n type ResolveByFlagResponseMessage,\n type RpcEventMessage,\n type RpcResponseMessage,\n type WalletsAdvertisedMessage,\n type ForwardedProviderEvent,\n} from './protocol.ts';\n\nexport interface RpcHostHandle {\n /** Tear down listeners and unsubscribe from all bridged providers. */\n detach(): void;\n}\n\nexport interface RpcHostOptions {\n /** Cross-origin iframe window we're talking to. */\n iframeWindow: Window;\n /** Origin of the iframe — origin-pin all postMessage send/receive. */\n iframeOrigin: string;\n /** Discoverer providing the EIP-6963 provider registry. */\n discoverer: WalletDiscovererHandle;\n /** Optional debug logger; defaults to a no-op. */\n log?: (message: string, data?: Record<string, unknown>) => void;\n}\n\ninterface SubscriptionRecord {\n provider: EIP1193Provider;\n listeners: Map<ForwardedProviderEvent, (...args: unknown[]) => void>;\n}\n\n/**\n * Attach an RPC host to the given iframe. Listens on `window` for\n * messages from the iframe and routes allowlisted JSON-RPC calls to the\n * matching top-frame EIP-1193 provider.\n */\nexport function attachRpcHost(options: RpcHostOptions): RpcHostHandle {\n const { iframeWindow, iframeOrigin, discoverer } = options;\n const log = options.log ?? noopLog;\n\n if (typeof window === 'undefined') {\n return { detach: () => {} };\n }\n\n let detached = false;\n const subscriptions = new Map<string, SubscriptionRecord>();\n const unsubscribeFromDiscoverer = discoverer.subscribe((snapshot) => {\n if (detached) return;\n advertiseWallets(snapshot);\n });\n\n function postToIframe(message: object): void {\n if (detached) return;\n try {\n iframeWindow.postMessage(message, iframeOrigin);\n } catch (err) {\n log('postMessage to iframe failed', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n // Advertised-list fingerprint of the last `blink:wallets-advertised`\n // post. Wallets re-announce fresh provider instances on EIP-6963\n // resweeps, which changes the discoverer registry (RPC routing must use\n // the newest instance) without changing the advertised POJO list — those\n // must not be re-broadcast, since each one rebuilds the iframe's wagmi\n // config and can orphan an in-flight connect.\n let lastAdvertisedKey: string | null = null;\n\n function advertiseWallets(snapshot: RegisteredProvider[], opts?: { force?: boolean }): void {\n const wallets: AdvertisedWallet[] = snapshot.map((entry) => ({\n uuid: entry.info.uuid,\n rdns: entry.info.rdns,\n name: entry.info.name,\n icon: entry.info.icon,\n }));\n const key = JSON.stringify(wallets.map((w) => [w.uuid, w.rdns, w.name, w.icon]));\n // `force` is the bridge-hello handshake ack — the iframe's\n // `bridgeAvailable` flag depends on it, so it always posts.\n if (!opts?.force && key === lastAdvertisedKey) {\n log('skipping identical re-advertisement', { count: wallets.length });\n return;\n }\n lastAdvertisedKey = key;\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] advertising wallets', wallets.map((w) => ({\n rdns: w.rdns,\n name: w.name,\n })));\n const message: WalletsAdvertisedMessage = {\n type: 'blink:wallets-advertised',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n wallets,\n };\n postToIframe(message);\n }\n\n function ensureSubscription(uuid: string, provider: EIP1193Provider): void {\n if (subscriptions.has(uuid)) return;\n if (typeof provider.on !== 'function') {\n // No event support — record an empty subscription so we don't keep\n // re-checking on every request.\n subscriptions.set(uuid, { provider, listeners: new Map() });\n return;\n }\n const record: SubscriptionRecord = { provider, listeners: new Map() };\n for (const event of FORWARDED_PROVIDER_EVENTS) {\n const listener = (...args: unknown[]) => {\n const eventMessage: RpcEventMessage = {\n type: 'blink:rpc-event',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n uuid,\n event,\n args,\n };\n postToIframe(eventMessage);\n };\n try {\n provider.on(event, listener);\n record.listeners.set(event, listener);\n } catch (err) {\n log(`provider.on('${event}') threw — skipping that event`, {\n uuid,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n subscriptions.set(uuid, record);\n }\n\n function unsubscribeAll(): void {\n for (const [, record] of subscriptions) {\n const provider = record.provider;\n if (typeof provider.removeListener !== 'function') continue;\n for (const [event, listener] of record.listeners) {\n try {\n provider.removeListener(event, listener);\n } catch {\n // Provider close may have already cleaned up — safe to ignore.\n }\n }\n }\n subscriptions.clear();\n }\n\n function sendError(id: string, code: number, message: string, data?: unknown): void {\n const response: RpcResponseMessage = {\n type: 'blink:rpc-response',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n };\n postToIframe(response);\n }\n\n function sendResult(id: string, result: unknown): void {\n const response: RpcResponseMessage = {\n type: 'blink:rpc-response',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n id,\n result,\n };\n postToIframe(response);\n }\n\n const onMessage = (event: MessageEvent) => {\n if (detached) return;\n if (event.source !== iframeWindow) return;\n if (event.origin !== iframeOrigin) return;\n const message = parseBridgeMessage(event.data);\n if (!message) return;\n\n switch (message.type) {\n case 'blink:bridge-hello': {\n // New-protocol iframe is asking \"are you there?\" Reply with the\n // current registry, even if empty. The iframe uses this to flip\n // its `bridgeAvailable` flag.\n advertiseWallets(discoverer.list(), { force: true });\n // Some wallets only finish wiring up after page load — re-request\n // EIP-6963 announcements once the iframe is alive too.\n discoverer.requestProviders();\n return;\n }\n case 'blink:rpc-request': {\n const { id, uuid, method, params } = message;\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] rpc-request', { uuid, method });\n if (!ALLOWED_RPC_METHODS.has(method)) {\n log('rejecting non-allowlisted method', { uuid, method });\n sendError(id, -32601, `Method not allowed: ${method}`);\n return;\n }\n const provider = discoverer.get(uuid);\n if (!provider) {\n log('no provider for uuid', { uuid, method });\n sendError(id, -32602, `Unknown wallet: ${uuid}`);\n return;\n }\n ensureSubscription(uuid, provider);\n provider\n .request({ method, params })\n .then((result) => {\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] rpc-result', { uuid, method, ok: true });\n sendResult(id, result);\n })\n .catch((err: unknown) => {\n const { code, message: errMessage, data } = normalizeProviderError(err);\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] rpc-error', { uuid, method, code, message: errMessage });\n sendError(id, code, errMessage, data);\n });\n return;\n }\n case 'blink:resolve-by-flag': {\n const match = resolveByFlag(discoverer.list(), message.flags, log);\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] resolveByFlag', {\n flags: message.flags,\n match: match ? { rdns: match.rdns, flag: match.flag } : null,\n });\n const response: ResolveByFlagResponseMessage = {\n type: 'blink:resolve-by-flag-response',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n id: message.id,\n match,\n };\n postToIframe(response);\n return;\n }\n case 'blink:wallets-advertised':\n case 'blink:rpc-response':\n case 'blink:rpc-event':\n case 'blink:resolve-by-flag-response':\n // These are parent → iframe messages. If we receive them, the\n // peer is misconfigured — ignore.\n return;\n }\n };\n\n window.addEventListener('message', onMessage);\n\n return {\n detach() {\n if (detached) return;\n detached = true;\n window.removeEventListener('message', onMessage);\n unsubscribeFromDiscoverer();\n unsubscribeAll();\n },\n };\n}\n\nfunction noopLog(): void {}\n\n/**\n * Walk the registered providers and return the first that has any of\n * the requested flags set as a truthy property (e.g. `isUniswapWallet`,\n * `isRainbow`). Used by the iframe to resolve Reown registry entries\n * that lack `rdns` but ship an `injectedId` flag.\n *\n * Per-provider reads are wrapped in try/catch because some wallets\n * proxy `window.ethereum` and throw on unknown property access.\n */\nfunction resolveByFlag(\n snapshot: RegisteredProvider[],\n flags: string[],\n log: (message: string, data?: Record<string, unknown>) => void,\n): ResolveByFlagMatch | null {\n for (const flag of flags) {\n for (const entry of snapshot) {\n let value: unknown;\n try {\n value = (entry.provider as unknown as Record<string, unknown>)[flag];\n } catch (err) {\n log('provider threw on flag read — skipping', {\n rdns: entry.info.rdns,\n flag,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n if (value) {\n return { rdns: entry.info.rdns, uuid: entry.info.uuid, flag };\n }\n }\n }\n return null;\n}\n\ninterface NormalizedProviderError {\n code: number;\n message: string;\n data?: unknown;\n}\n\n/**\n * Coerce whatever an EIP-1193 provider threw into a JSON-RPC-shaped\n * error. Most wallets already throw `{ code, message, data? }`; we just\n * shape it. Anything else gets a generic -32603 (internal error).\n */\nfunction normalizeProviderError(err: unknown): NormalizedProviderError {\n if (err && typeof err === 'object') {\n const e = err as Record<string, unknown>;\n const code = typeof e.code === 'number' ? e.code : -32603;\n const message =\n typeof e.message === 'string'\n ? e.message\n : err instanceof Error\n ? err.message\n : 'Provider error';\n const data = 'data' in e ? e.data : undefined;\n return data === undefined ? { code, message } : { code, message, data };\n }\n return { code: -32603, message: typeof err === 'string' ? err : 'Provider error' };\n}\n","// ── Merchant-page viewport metrics for the fluid layout ──────────────\n//\n// The fluid iframe fills the overlay (`position: fixed; inset: 0`), which on\n// iOS tracks the *current* viewport — it shrinks and grows as the browser's\n// collapsible chrome (URL bar) shows and hides. Inside the iframe, `dvh`\n// therefore resolves against that moving target, while the legacy\n// parent-side sheet was sized with `79vh` = 79% of the *large* viewport\n// (chrome hidden) — a constant. Only the merchant page can measure the\n// large viewport and its safe-area inset, so the SDK probes them here and\n// ships them to the hosted flow (URL params at creation, `blink:viewport`\n// messages on resize/orientation change).\n\nexport interface ViewportMetrics {\n /** Merchant page's large-viewport height (100lvh) in CSS px, rounded. */\n viewportLvh: number;\n /** Merchant page's `env(safe-area-inset-bottom)` in CSS px, rounded. */\n safeAreaBottom: number;\n}\n\n/**\n * Measure via a hidden fixed probe. `100lvh` needs iOS 15.4+/Chrome 108+;\n * on older browsers the declaration is dropped and the probe collapses to\n * zero height, so `window.innerHeight` (the current viewport) is used\n * instead — a degraded but sane basis. Returns zeros outside a DOM.\n */\nexport function measureViewportMetrics(): ViewportMetrics {\n const unavailable: ViewportMetrics = { viewportLvh: 0, safeAreaBottom: 0 };\n if (\n typeof document === 'undefined' ||\n typeof window === 'undefined' ||\n typeof window.getComputedStyle !== 'function' ||\n !document.body\n ) {\n return unavailable;\n }\n\n // Measurement is a nicety — it must never break the payment flow. Any\n // DOM surprise (exotic embeds, sandboxed contexts) degrades to zeros,\n // which callers treat as \"metrics unavailable\".\n try {\n const probe = document.createElement('div');\n probe.style.cssText =\n 'position:fixed;top:0;left:0;width:0;visibility:hidden;pointer-events:none;' +\n 'height:100lvh;padding-bottom:env(safe-area-inset-bottom,0px)';\n document.body.appendChild(probe);\n\n let viewportLvh = 0;\n let safeAreaBottom = 0;\n try {\n const computed = window.getComputedStyle(probe);\n viewportLvh = Math.round(Number.parseFloat(computed.height) || 0);\n safeAreaBottom = Math.round(Number.parseFloat(computed.paddingBottom) || 0);\n } finally {\n probe.remove();\n }\n\n if (viewportLvh <= 0) {\n // `100lvh` needs iOS 15.4+/Chrome 108+; older browsers drop the\n // declaration and the probe collapses. The current viewport is a\n // degraded but sane basis there.\n viewportLvh = Math.round(window.innerHeight || 0);\n }\n\n return { viewportLvh, safeAreaBottom };\n } catch {\n return unavailable;\n }\n}\n","// ── Shared frame plumbing (presentation-independent) ──────────────────\n//\n// Everything here is common to every way the hosted flow can be presented:\n// the overlay modal (iframe.ts) and the inline embed (embeddedIframe.ts).\n// It deliberately owns the two things that must never be duplicated:\n//\n// 1. The `allow` attribute. Passkey ceremonies are a WebAuthn correctness\n// and security invariant — a presenter that forgot a delegation, or\n// spelled an origin differently, would fail silently at the credential\n// call. One definition, one place.\n// 2. The wallet-bridge attach/detach lifecycle, whose ordering is not\n// obvious (attach eagerly for browsers that populate `contentWindow`\n// synchronously, then again on `load` for the cross-origin case).\n//\n// What is NOT here is presentation: backdrops, scroll locks, dismissal,\n// animations, geometry. Those share nothing between the two modes, which is\n// why this is a shared core with thin presenters rather than one function\n// with a mode flag.\n\nimport { createWalletDiscoverer } from './walletBridge/discover.ts';\nimport { attachRpcHost, type RpcHostHandle } from './walletBridge/rpcHost.ts';\nimport { buildRevealMessage, buildViewportMessage } from './messages.ts';\nimport { measureViewportMetrics } from './viewportMetrics.ts';\n\n/** The iframe element plus the origin every message to it must target. */\nexport interface FrameElement {\n iframe: HTMLIFrameElement;\n iframeOrigin: string;\n}\n\n/**\n * Create the hosted-flow iframe with the Permissions-Policy delegations the\n * flow needs. `publickey-credentials-*` are required for passkey signup and\n * login; `clipboard-write` for copying deposit addresses; `web-share` for\n * handing a Blink Boost card to the OS share sheet.\n *\n * `web-share` defaults to `self`, so without the delegation the hosted flow's\n * `navigator.canShare({ files })` answers false inside this frame — not because\n * the device cannot share, but because we never asked. On mobile that silently\n * routed the Boost share down the DESKTOP path: no share sheet, no image, just\n * X's web composer in a new tab. There is no way for the hosted flow to detect\n * the difference, which is why the delegation belongs here rather than a\n * fallback there.\n */\nexport function createFrameElement(url: string): FrameElement {\n const iframe = document.createElement('iframe');\n iframe.src = url;\n\n const iframeOrigin = new URL(url).origin;\n iframe.allow =\n `publickey-credentials-get ${iframeOrigin}; publickey-credentials-create ${iframeOrigin}; clipboard-write ${iframeOrigin}; web-share ${iframeOrigin}`;\n\n return { iframe, iframeOrigin };\n}\n\nexport interface FrameBridges {\n /**\n * Post `blink:reveal` so the hosted flow plays its entry animation. Safe\n * before load — the hosted page buffers the signal — and idempotent.\n */\n postReveal(): void;\n /**\n * Post the host page's viewport metrics (and, in embedded presentation,\n * the height budget). No-op when the presenter opted out.\n */\n postViewportMetrics(): void;\n detach(): void;\n}\n\nexport interface AttachFrameBridgesOptions extends FrameElement {\n /**\n * Whether this presentation needs viewport metrics at all. The legacy\n * fixed overlay sizes the iframe itself and ignores them; fluid and\n * embedded both depend on them.\n */\n postViewport: boolean;\n /**\n * Embedded presentation: the current height budget, read at post time so a\n * host that changes it mid-flow is picked up by the next resize.\n */\n getEmbedMaxHeightPx?: () => number | undefined;\n /**\n * Whether a freshly loaded document should be revealed immediately. A\n * visible-from-birth frame is \"revealed\" as soon as its document exists; a\n * hidden warm-up waits for an explicit `reveal()`.\n */\n shouldRevealOnLoad: () => boolean;\n}\n\n/**\n * Wire up the top-frame wallet bridge, the reveal/viewport message channel,\n * and the host-viewport listeners for one frame.\n *\n * Wallet bridge: discovers EIP-6963 wallets in this frame (Uniswap, Rainbow,\n * and any other extension that doesn't inject into iframes) and exposes them\n * to the hosted flow over postMessage. Old iframes that don't know about the\n * bridge never send a hello; the host stays silent for them — strictly\n * additive behavior.\n */\nexport function attachFrameBridges(options: AttachFrameBridgesOptions): FrameBridges {\n const { iframe, iframeOrigin, postViewport, getEmbedMaxHeightPx, shouldRevealOnLoad } = options;\n\n let detached = false;\n\n const discoverer = createWalletDiscoverer();\n let rpcHostHandle: RpcHostHandle | null = null;\n\n const attachBridge = () => {\n if (rpcHostHandle) return;\n if (!iframe.contentWindow) return;\n rpcHostHandle = attachRpcHost({\n iframeWindow: iframe.contentWindow,\n iframeOrigin,\n discoverer,\n });\n };\n // Try once now (some browsers populate contentWindow eagerly) and again on\n // `load` for the cross-origin case.\n attachBridge();\n iframe.addEventListener('load', attachBridge);\n\n function postReveal(): void {\n if (detached) return;\n iframe.contentWindow?.postMessage(buildRevealMessage(), iframeOrigin);\n }\n\n function postViewportMetrics(): void {\n if (detached || !postViewport) return;\n const metrics = measureViewportMetrics();\n if (metrics.viewportLvh <= 0) return;\n iframe.contentWindow?.postMessage(\n buildViewportMessage(\n metrics.viewportLvh,\n metrics.safeAreaBottom,\n getEmbedMaxHeightPx?.(),\n ),\n iframeOrigin,\n );\n }\n\n // Keep the hosted flow's geometry anchored to the host page's large\n // viewport across rotations and window resizes. rAF-coalesced — iOS fires\n // resize storms while the browser chrome animates.\n let viewportPostScheduled = false;\n const onViewportChange = () => {\n if (viewportPostScheduled) return;\n viewportPostScheduled = true;\n requestAnimationFrame(() => {\n viewportPostScheduled = false;\n postViewportMetrics();\n });\n };\n if (postViewport) {\n window.addEventListener('resize', onViewportChange);\n window.addEventListener('orientationchange', onViewportChange);\n }\n\n // A visible-from-birth frame (no warm-up) is revealed as soon as its\n // document exists: post the reveal on load so the hosted flow plays its\n // entry animation without waiting for an explicit reveal() call. The\n // hosted page treats blink:reveal as idempotent. Viewport metrics ride\n // along so geometry is settled before first paint even if the URL-param\n // seed went stale during a slow load.\n const onLoadReveal = () => {\n postViewportMetrics();\n if (shouldRevealOnLoad()) postReveal();\n };\n iframe.addEventListener('load', onLoadReveal);\n\n return {\n postReveal,\n postViewportMetrics,\n detach(): void {\n if (detached) return;\n detached = true;\n iframe.removeEventListener('load', attachBridge);\n iframe.removeEventListener('load', onLoadReveal);\n window.removeEventListener('resize', onViewportChange);\n window.removeEventListener('orientationchange', onViewportChange);\n if (rpcHostHandle) {\n rpcHostHandle.detach();\n rpcHostHandle = null;\n }\n discoverer.destroy();\n },\n };\n}\n","import { attachFrameBridges, createFrameElement, type FrameBridges } from './iframeCore.ts';\n\nconst STYLE_ID = 'blink-deposit-styles';\n\nconst CLOSE_DURATION_MS = 280;\nconst MOBILE_SHEET_MAX_VIEWPORT_PX = 640;\nconst MOBILE_SHEET_MAX_SCREEN_PX = 900;\n\n// The iframe's color-scheme must be an explicit `light`, not `normal`: normal\n// resolves to the merchant page's default scheme, so a merchant-declared\n// color-scheme:dark makes Chromium see a scheme mismatch with the light hosted\n// document and paint the cross-origin iframe on an opaque white backplate —\n// solid white over the whole viewport instead of the dim showing the page.\nconst STYLES = `\n@keyframes blink-fade-in{from{opacity:0}to{opacity:1}}\n@keyframes blink-fade-out{from{opacity:1}to{opacity:0}}\n@keyframes blink-slide-up{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}\n@keyframes blink-slide-up-full{from{transform:translateY(100%)}to{transform:translateY(0)}}\n@keyframes blink-slide-down-full{from{transform:translateY(0)}to{transform:translateY(100%)}}\n[data-blink-overlay]{position:fixed;inset:0;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:2147483647;animation:blink-fade-in .2s ease-out;backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px)}\n[data-blink-overlay][data-blink-closing]{animation:blink-fade-out ${CLOSE_DURATION_MS}ms ease-in forwards;pointer-events:none}\n[data-blink-overlay][data-blink-mobile-sheet]{align-items:flex-end;touch-action:none;overscroll-behavior:contain}\n[data-blink-container]{width:min(420px,92vw);height:min(600px,85vh);border-radius:24px;overflow:hidden;box-shadow:0 24px 80px rgba(0,0,0,.4);animation:blink-slide-up .25s ease-out;display:flex;flex-direction:column;background:transparent}\n[data-blink-overlay][data-blink-closing] [data-blink-container]{opacity:0;transition:opacity ${CLOSE_DURATION_MS}ms ease-in}\n[data-blink-container] iframe{width:100%;flex:1;border:none;display:block;background:transparent;color-scheme:light;border-radius:inherit}\n[data-blink-overlay][data-blink-mobile-sheet] [data-blink-container]{width:100%;max-width:100%;height:79vh;border-radius:24px 24px 0 0;box-shadow:0 -8px 40px rgba(0,0,0,.25);animation:blink-slide-up-full .35s cubic-bezier(.32,.72,0,1);padding-bottom:env(safe-area-inset-bottom,0px)}\n[data-blink-overlay][data-blink-mobile-sheet][data-blink-closing] [data-blink-container]{opacity:1;animation:blink-slide-down-full ${CLOSE_DURATION_MS}ms ease-in forwards}\n@media(max-width:${MOBILE_SHEET_MAX_VIEWPORT_PX}px){[data-blink-overlay]{align-items:flex-end;touch-action:none;overscroll-behavior:contain}[data-blink-container]{width:100%;max-width:100%;height:79vh;border-radius:24px 24px 0 0;box-shadow:0 -8px 40px rgba(0,0,0,.25);animation:blink-slide-up-full .35s cubic-bezier(.32,.72,0,1);padding-bottom:env(safe-area-inset-bottom,0px)}[data-blink-overlay][data-blink-closing] [data-blink-container]{opacity:1;animation:blink-slide-down-full ${CLOSE_DURATION_MS}ms ease-in forwards}}\n[data-blink-overlay][data-blink-fluid] [data-blink-container],[data-blink-overlay][data-blink-fluid][data-blink-mobile-sheet] [data-blink-container]{width:100%;max-width:100%;height:100%;max-height:100%;border-radius:0;box-shadow:none;animation:none;background:transparent;padding-bottom:0}\n[data-blink-overlay][data-blink-fluid][data-blink-closing] [data-blink-container]{animation:none;transition:none;opacity:1}\n`;\n\nexport interface IframeHandle {\n readonly contentWindow: Window | null;\n close(): void;\n isClosed(): boolean;\n isHidden(): boolean;\n /**\n * Make a `hidden: true` overlay visible: re-evaluates the mobile-sheet\n * layout for the current viewport, locks body scroll, and attaches the\n * backdrop/Escape dismissal listeners. No-op when already visible or\n * closed. The iframe element is never reparented — moving an iframe in the\n * DOM reloads it, which would throw away the warmed-up document.\n */\n reveal(): void;\n /**\n * Post `blink:reveal` to the hosted flow so it plays its entry animation\n * (fluid mode renders the card chrome inside the iframe). Safe to call\n * before the iframe has loaded — the hosted page buffers the signal, and\n * `createIframe` re-posts on the iframe `load` event while visible.\n */\n postReveal(): void;\n /**\n * Revert a fluid overlay to the legacy fixed-size container by removing\n * `data-blink-fluid` — pure CSS, the iframe is never reparented (moving an\n * iframe in the DOM reloads it). Used when the hosted flow's ready message\n * does not advertise the `layout-fluid` capability (an older webview\n * deployment), so it renders fill-mode into the fixed container as today.\n */\n downgradeToFixed(): void;\n /**\n * Embedded presentation only: size the inline iframe element to the height\n * the hosted flow just reported. No-op for the overlay, whose geometry is\n * viewport-derived and owned by CSS.\n */\n applyContentHeight(heightPx: number): void;\n onClose(callback: () => void): void;\n destroy(): void;\n}\n\nexport interface CreateIframeOptions {\n /**\n * Create the overlay invisible (`display: none`) for background warm-up:\n * the iframe document loads normally, but there is no backdrop, no body\n * scroll-lock, and no dismissal listeners until `reveal()` is called.\n */\n hidden?: boolean;\n /**\n * Full-viewport transparent container: the card/sheet chrome (size, radius,\n * shadow, entry/exit animations) is rendered by the hosted flow inside the\n * iframe instead of by this overlay. The dim + blur backdrop stays on the\n * overlay — an iframe cannot `backdrop-filter` the page behind itself.\n * Requires a webview that understands `layout=fluid`; pair with\n * `downgradeToFixed()` when the ready handshake lacks the capability.\n */\n fluid?: boolean;\n}\n\n/**\n * Create a modal overlay with a cross-origin iframe pointing to the hosted\n * checkout flow. The iframe has the Permissions-Policy attributes required\n * for WebAuthn passkey ceremonies.\n *\n * The overlay is dismissed when the user clicks the backdrop, presses\n * Escape, or the hosted flow sends a `blink:close-request` postMessage.\n */\nexport function createIframe(\n url: string,\n containerElement?: HTMLElement,\n options?: CreateIframeOptions,\n): IframeHandle {\n ensureStyles();\n\n let closed = false;\n let hidden = options?.hidden === true;\n let closeCallback: (() => void) | null = null;\n\n const overlay = document.createElement('div');\n overlay.setAttribute('data-blink-overlay', '');\n if (shouldUseMobileSheetLayout()) {\n overlay.setAttribute('data-blink-mobile-sheet', '');\n }\n if (options?.fluid) {\n overlay.setAttribute('data-blink-fluid', '');\n }\n if (hidden) {\n overlay.style.display = 'none';\n }\n\n const container = document.createElement('div');\n container.setAttribute('data-blink-container', '');\n\n const { iframe, iframeOrigin } = createFrameElement(url);\n\n const handle = document.createElement('div');\n\n container.appendChild(handle);\n container.appendChild(iframe);\n overlay.appendChild(container);\n\n const mountTarget = containerElement ?? document.body;\n mountTarget.appendChild(overlay);\n\n const bridges: FrameBridges = attachFrameBridges({\n iframe,\n iframeOrigin,\n // Only fluid needs them: the legacy fixed overlay sizes the iframe itself.\n postViewport: options?.fluid === true,\n shouldRevealOnLoad: () => !hidden,\n });\n\n let savedOverflow = '';\n let scrollLocked = false;\n\n const onBackdropClick = (event: MouseEvent) => {\n if (event.target === overlay) triggerClose();\n };\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') triggerClose();\n };\n\n const onTouchMove = (event: TouchEvent) => {\n if (event.target === overlay) event.preventDefault();\n };\n\n function lockScroll(): void {\n if (scrollLocked) return;\n scrollLocked = true;\n savedOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n\n function attachDismissalListeners(): void {\n overlay.addEventListener('click', onBackdropClick);\n overlay.addEventListener('touchmove', onTouchMove, { passive: false });\n document.addEventListener('keydown', onKeyDown);\n }\n\n // Hidden warm-up overlays must not trap Escape/scroll while invisible —\n // the host page doesn't know they exist yet.\n if (!hidden) {\n lockScroll();\n attachDismissalListeners();\n }\n\n function removeListeners(): void {\n overlay.removeEventListener('click', onBackdropClick);\n overlay.removeEventListener('touchmove', onTouchMove);\n document.removeEventListener('keydown', onKeyDown);\n }\n\n function unlockScroll(): void {\n if (!scrollLocked) return;\n scrollLocked = false;\n document.body.style.overflow = savedOverflow;\n }\n\n function triggerClose(): void {\n if (closed) return;\n closed = true;\n removeListeners();\n bridges.detach();\n\n overlay.setAttribute('data-blink-closing', '');\n\n let removed = false;\n const removeOverlay = () => {\n if (removed) return;\n removed = true;\n overlay.remove();\n unlockScroll();\n closeCallback?.();\n };\n\n container.addEventListener('animationend', removeOverlay, { once: true });\n setTimeout(removeOverlay, CLOSE_DURATION_MS + 50);\n }\n\n return {\n get contentWindow(): Window | null {\n return iframe.contentWindow;\n },\n\n close(): void {\n triggerClose();\n },\n\n isClosed(): boolean {\n return closed;\n },\n\n isHidden(): boolean {\n return hidden;\n },\n\n reveal(): void {\n if (closed || !hidden) return;\n hidden = false;\n // The viewport may have changed (resize/rotation) since the hidden\n // warm-up overlay was created — re-evaluate the sheet layout now.\n if (shouldUseMobileSheetLayout()) {\n overlay.setAttribute('data-blink-mobile-sheet', '');\n } else {\n overlay.removeAttribute('data-blink-mobile-sheet');\n }\n overlay.style.display = '';\n lockScroll();\n attachDismissalListeners();\n bridges.postViewportMetrics();\n bridges.postReveal();\n },\n\n postReveal(): void {\n bridges.postReveal();\n },\n\n downgradeToFixed(): void {\n overlay.removeAttribute('data-blink-fluid');\n },\n\n applyContentHeight(): void {\n // The overlay's card is sized by CSS against the viewport; content\n // height reports are an embedded-only channel and never arrive here.\n },\n\n onClose(callback: () => void): void {\n closeCallback = callback;\n },\n\n destroy(): void {\n closeCallback = null;\n if (!closed) {\n closed = true;\n removeListeners();\n bridges.detach();\n overlay.remove();\n unlockScroll();\n }\n },\n };\n}\n\nfunction ensureStyles(): void {\n const existingStyle = document.getElementById(STYLE_ID);\n if (existingStyle) {\n if (existingStyle.textContent !== STYLES) {\n existingStyle.textContent = STYLES;\n }\n return;\n }\n const style = document.createElement('style');\n style.id = STYLE_ID;\n style.textContent = STYLES;\n document.head.appendChild(style);\n}\n\n/**\n * Whether this device should get the mobile bottom sheet rather than the\n * centered desktop card. Narrow viewport, or a coarse pointer on a\n * phone-sized screen.\n *\n * Also the predicate `checkout.ts` uses to decide that an *embedded* flow\n * presents as a normal overlay on mobile — one rule for \"this is a phone\", so\n * the presentation and the sheet chrome inside it can never disagree.\n */\nexport function shouldUseMobileSheetLayout(): boolean {\n if (typeof window === 'undefined') return false;\n\n if (window.matchMedia?.(`(max-width: ${MOBILE_SHEET_MAX_VIEWPORT_PX}px)`).matches) {\n return true;\n }\n\n const viewportWidth = window.visualViewport?.width ?? window.innerWidth;\n if (viewportWidth > 0 && viewportWidth <= MOBILE_SHEET_MAX_VIEWPORT_PX) {\n return true;\n }\n\n const hasCoarsePointer = window.matchMedia?.('(pointer: coarse)').matches ?? false;\n if (!hasCoarsePointer) {\n return false;\n }\n\n const shortestScreenSide = Math.min(window.screen.width, window.screen.height);\n return shortestScreenSide > 0 && shortestScreenSide <= MOBILE_SHEET_MAX_SCREEN_PX;\n}\n","// ── Embedded presentation ─────────────────────────────────────────────\n//\n// Mounts the hosted flow INLINE inside a host widget — a payment-method\n// aggregator listing Blink beside Card / Bank / Wallet — instead of as a\n// full-viewport modal.\n//\n// What this deliberately does NOT do, and why:\n//\n// • No overlay, backdrop, blur, or z-index. There is nothing to dim; the\n// host's own panel is the surface.\n// • No body scroll lock. The host already owns page scroll (an aggregator\n// opening its widget in a dialog has typically locked it), and a second\n// lock would fight theirs on teardown.\n// • No backdrop-click or document-level Escape dismissal. Inline, \"the user\n// pressed Escape\" is the host's event to interpret, not ours — stealing\n// it would close Blink out from under a host that meant to close its own\n// dialog. The in-flow close control still posts `blink:close-request`.\n// • No close animation. There is no card flying out; the host removes the\n// element or animates its own panel.\n// • No mobile-sheet heuristic. Inside a host widget the device signals\n// describe the device, not the slot — a narrow embed on a wide desktop\n// would otherwise present as a swipeable bottom sheet.\n//\n// Height is the one thing this presenter actively manages: the hosted flow\n// reports its rendered card height and we size the iframe element to match.\n\nimport { attachFrameBridges, createFrameElement, type FrameBridges } from './iframeCore.ts';\nimport type { IframeHandle } from './iframe.ts';\n\nconst EMBED_STYLE_ID = 'blink-deposit-embed-styles';\n\n// Scoped to `[data-blink-embed]` and injected only by this presenter, so a\n// merchant using the overlay never receives embed CSS and an aggregator never\n// receives a `position: fixed; z-index: 2147483647` rule for an overlay that\n// will never exist on their page.\n//\n// `color-scheme: light` is pinned for the same reason as the overlay: left at\n// `normal` it resolves to the host page's scheme, and a host declaring\n// `color-scheme: dark` makes Chromium see a mismatch against the light hosted\n// document and paint an opaque backplate behind the cross-origin iframe.\n//\n// The hidden warm-up state is `visibility: hidden` + a clipped zero-height\n// wrapper, NOT `display: none`: a display:none subtree has no layout at all,\n// so the flow inside could not measure itself and would report a height of\n// zero the moment it was revealed.\nconst EMBED_STYLES = `\n[data-blink-embed]{display:block;width:100%;position:relative}\n[data-blink-embed][data-blink-embed-hidden]{height:0;overflow:hidden;visibility:hidden;pointer-events:none}\n[data-blink-embed] iframe{display:block;width:100%;height:0;border:none;background:transparent;color-scheme:light}\n`;\n\nexport interface CreateEmbeddedIframeOptions {\n /**\n * Create the frame invisible for background warm-up: the document loads\n * normally but occupies no space in the host's layout and cannot be\n * interacted with until `reveal()`.\n */\n hidden?: boolean;\n /**\n * Hard cap on the iframe element's height, in CSS px. Reported content\n * heights are clamped to it, and it rides along on the viewport message as\n * the basis the flow sizes against.\n *\n * A function is re-read on every post, so a budget derived from the host\n * viewport stays correct across rotation and window resizes. A plain number\n * is fixed for the life of the frame.\n */\n embedMaxHeightPx?: number | (() => number | undefined);\n}\n\n/**\n * Create an inline cross-origin iframe pointing at the hosted flow, mounted\n * into the host's element. Returns the same {@link IframeHandle} shape as the\n * overlay presenter so the `Deposit` lifecycle is presentation-agnostic.\n */\nexport function createEmbeddedIframe(\n url: string,\n containerElement: HTMLElement,\n options?: CreateEmbeddedIframeOptions,\n): IframeHandle {\n ensureEmbedStyles();\n\n // The instance holds this node for its whole life and re-warms a fresh\n // hidden iframe into it after every close. If the host unmounted it (a\n // `{open && …}` around the slot is the usual cause), everything from here on\n // renders into an orphan: the first flow works, every later one is blank,\n // and nothing throws. Say so — a silent blank panel is close to\n // undiagnosable from the outside.\n if (!containerElement.isConnected) {\n console.warn(\n '[blink] The containerElement passed to Deposit is not in the document. '\n + 'Embedded mode renders into it for the life of the instance, so it must '\n + 'be a stable node — render the slot once and hide it with '\n + '`visibility: hidden` (NOT `display: none`, which removes its layout and '\n + 'leaves the warming flow unable to measure itself) instead of unmounting '\n + 'it, or construct a new Deposit against the new node.',\n );\n }\n\n let closed = false;\n let hidden = options?.hidden === true;\n let closeCallback: (() => void) | null = null;\n const readEmbedMaxHeightPx = (): number | undefined =>\n typeof options?.embedMaxHeightPx === 'function'\n ? options.embedMaxHeightPx()\n : options?.embedMaxHeightPx;\n\n const wrapper = document.createElement('div');\n wrapper.setAttribute('data-blink-embed', '');\n if (hidden) {\n wrapper.setAttribute('data-blink-embed-hidden', '');\n }\n\n const { iframe, iframeOrigin } = createFrameElement(url);\n // The card owns its own internal scroll, and the frame is sized to the\n // card, so the frame itself must never scroll. Without this a growth\n // transient (content briefly taller than the last applied height) puts a\n // root scrollbar in the frame; on Windows/Linux that is ~15px of\n // layout-consuming width, which rewraps the card and changes the very\n // height we are converging on. Stripe's embedded checkout sets the same\n // attribute for the same reason.\n iframe.setAttribute('scrolling', 'no');\n // Start at the host's budget rather than the stylesheet's 0. The flow\n // reports its real height as soon as it paints and this shrinks to fit, but\n // starting at zero would mean a visible collapsed frame for however long\n // the document takes to boot — and if a deployment never reports at all,\n // the budget is a correct, usable height rather than an invisible widget.\n const initialBudget = readEmbedMaxHeightPx();\n if (initialBudget !== undefined) {\n iframe.style.height = `${initialBudget}px`;\n }\n wrapper.appendChild(iframe);\n containerElement.appendChild(wrapper);\n\n const bridges: FrameBridges = attachFrameBridges({\n iframe,\n iframeOrigin,\n // Embedded always needs them: the flow has no usable viewport of its own,\n // so the basis it sizes against can only come from here.\n postViewport: true,\n getEmbedMaxHeightPx: readEmbedMaxHeightPx,\n shouldRevealOnLoad: () => !hidden,\n });\n\n function teardown(): void {\n closed = true;\n bridges.detach();\n wrapper.remove();\n }\n\n return {\n get contentWindow(): Window | null {\n return iframe.contentWindow;\n },\n\n close(): void {\n if (closed) return;\n teardown();\n closeCallback?.();\n },\n\n isClosed(): boolean {\n return closed;\n },\n\n isHidden(): boolean {\n return hidden;\n },\n\n reveal(): void {\n if (closed || !hidden) return;\n hidden = false;\n wrapper.removeAttribute('data-blink-embed-hidden');\n warnIfContainerNotRendered(containerElement);\n bridges.postViewportMetrics();\n bridges.postReveal();\n // Deliberately no focus() call. Focusing an element inside a\n // cross-origin iframe makes the outer browser scroll it into view,\n // which yanks the host's page — and inside a focus-trapped dialog it\n // fights the host's own focus guards.\n },\n\n postReveal(): void {\n bridges.postReveal();\n },\n\n downgradeToFixed(): void {\n // No-op: the fixed container is overlay geometry. There is nothing for\n // an inline frame to snap back to, and reintroducing a fixed-size card\n // here would fight the host's own panel.\n },\n\n applyContentHeight(heightPx: number): void {\n if (closed) return;\n const budget = readEmbedMaxHeightPx();\n const capped = budget === undefined ? heightPx : Math.min(heightPx, budget);\n iframe.style.height = `${Math.max(0, Math.round(capped))}px`;\n },\n\n onClose(callback: () => void): void {\n closeCallback = callback;\n },\n\n destroy(): void {\n closeCallback = null;\n if (!closed) teardown();\n },\n };\n}\n\n/**\n * Warns when the flow is being revealed into a container that has no layout —\n * almost always a host hiding its slot with `display: none` between opens.\n *\n * That subtree has no layout at all, so the flow warming inside it cannot\n * measure itself, and the height it reports on reveal is whatever the browser\n * has: nothing. Whether it recovers comes down to whether the host's own display\n * flip lands before this reveal reaches the frame — closing an entire dialog\n * usually wins that race, a panel's own back button usually loses it, and the\n * loser is a blank box at the budget height with nothing in the host's console.\n *\n * Checked at reveal rather than at mount: warming inside a hidden container is\n * fine and expected (the SDK hides its own wrapper with `visibility`), it is\n * being *revealed* while still unrendered that cannot work.\n *\n * `offsetParent` is null for a `display: none` subtree and for `position: fixed`\n * elements, so the zero-rect check carries the verdict and `offsetParent` only\n * distinguishes the cause.\n */\nfunction warnIfContainerNotRendered(containerElement: HTMLElement): void {\n // Never let a diagnostic break a reveal: a host may hand us something that is\n // element-like without being a full HTMLElement, and there is nothing to\n // measure in a non-DOM environment either.\n if (typeof containerElement.getBoundingClientRect !== 'function') return;\n const rect = containerElement.getBoundingClientRect();\n if (rect.width > 0 || rect.height > 0) return;\n const display = typeof getComputedStyle === 'function'\n ? getComputedStyle(containerElement).display\n : '';\n console.warn(\n '[blink] The containerElement has no layout at the moment the flow is '\n + `revealed${display === 'none' ? ' (display: none)' : ''}. A display:none `\n + 'subtree cannot be measured, so the flow may report no height and the '\n + 'panel stays blank at its budget height. Hide the slot with '\n + '`visibility: hidden` (plus `height: 0; overflow: hidden`) instead of '\n + '`display: none`, so it keeps its box while it warms up.',\n );\n}\n\nfunction ensureEmbedStyles(): void {\n const existingStyle = document.getElementById(EMBED_STYLE_ID);\n if (existingStyle) {\n if (existingStyle.textContent !== EMBED_STYLES) {\n existingStyle.textContent = EMBED_STYLES;\n }\n return;\n }\n const style = document.createElement('style');\n style.id = EMBED_STYLE_ID;\n style.textContent = EMBED_STYLES;\n document.head.appendChild(style);\n}\n","import { DepositError } from './errors.ts';\nimport type { SignerFunction, SignerRequest, SignerResponse } from './types.ts';\n\nconst DEFAULT_SIGNER_TIMEOUT_MS = 15_000;\n\n/**\n * Invoke the merchant signer and return the validated response.\n *\n * When `signer` is a URL string the SDK performs a `POST` with a JSON body.\n * When `signer` is a function the SDK delegates entirely to it.\n * In both cases a timeout wrapper is applied via `timeoutMs`.\n */\nexport async function callSigner(\n signer: string | SignerFunction,\n request: SignerRequest,\n timeoutMs?: number,\n): Promise<SignerResponse> {\n const timeout = timeoutMs ?? DEFAULT_SIGNER_TIMEOUT_MS;\n\n const body: SignerResponse =\n typeof signer === 'function'\n ? await invokeSignerFunction(signer, request, timeout)\n : await invokeSignerUrl(signer, request, timeout);\n\n validateSignerResponse(body);\n return body;\n}\n\nasync function invokeSignerUrl(\n signerUrl: string,\n request: SignerRequest,\n timeoutMs: number,\n): Promise<SignerResponse> {\n let response: Response;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n response = await fetch(signerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n } catch (err) {\n if (controller.signal.aborted) {\n throw new DepositError(\n 'SIGNER_TIMEOUT',\n `Signer did not respond within ${timeoutMs}ms.`,\n );\n }\n throw new DepositError(\n 'SIGNER_NETWORK_ERROR',\n 'Unable to reach the merchant signer. Check the signer URL and network connectivity.',\n );\n } finally {\n clearTimeout(timer);\n }\n\n const body = await response.json().catch(() => null) as\n | (Partial<SignerResponse> & { error?: string })\n | null;\n\n if (!response.ok) {\n const detail = body?.error ?? `Signer returned HTTP ${response.status}.`;\n throw new DepositError('SIGNER_REQUEST_FAILED', detail);\n }\n\n return body as SignerResponse;\n}\n\nasync function invokeSignerFunction(\n signer: SignerFunction,\n request: SignerRequest,\n timeoutMs: number,\n): Promise<SignerResponse> {\n return new Promise<SignerResponse>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new DepositError('SIGNER_TIMEOUT', `Signer did not respond within ${timeoutMs}ms.`)),\n timeoutMs,\n );\n\n signer(request).then(\n (result) => { clearTimeout(timer); resolve(result); },\n (err) => {\n clearTimeout(timer);\n if (err instanceof DepositError) {\n reject(err);\n } else {\n reject(new DepositError(\n 'SIGNER_REQUEST_FAILED',\n err instanceof Error ? err.message : 'Signer function threw an error.',\n ));\n }\n },\n );\n });\n}\n\nfunction validateSignerResponse(body: unknown): asserts body is SignerResponse {\n const obj = body as Partial<SignerResponse> | null | undefined;\n if (\n !obj ||\n typeof obj.merchantId !== 'string' ||\n typeof obj.payload !== 'string' ||\n typeof obj.signature !== 'string' ||\n !obj.preview ||\n typeof obj.preview !== 'object'\n ) {\n throw new DepositError(\n 'SIGNER_RESPONSE_INVALID',\n 'Signer response is missing required fields (merchantId, payload, signature, preview).',\n );\n }\n}\n","import { DepositError } from './errors.ts';\nimport type { DepositRequest, SignerRequest } from './types.ts';\n\nconst EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;\nconst TOKEN_ADDRESS_RE = /^0x[a-fA-F0-9]{1,40}$/;\nconst SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\nfunction isValidAddress(value: string): boolean {\n return EVM_ADDRESS_RE.test(value) || SOLANA_ADDRESS_RE.test(value);\n}\n\nfunction isValidTokenAddress(value: string): boolean {\n return TOKEN_ADDRESS_RE.test(value) || SOLANA_ADDRESS_RE.test(value);\n}\n\nexport function validateDepositRequest(request: DepositRequest): void {\n if (request.amount !== null) {\n if (typeof request.amount !== 'number' || !Number.isFinite(request.amount) || request.amount <= 0) {\n throw new DepositError('INVALID_REQUEST', 'amount must be a positive number or null.');\n }\n }\n\n if (!Number.isInteger(request.chainId) || request.chainId <= 0) {\n throw new DepositError('INVALID_REQUEST', 'chainId must be a positive integer.');\n }\n\n if (!isValidAddress(request.address)) {\n throw new DepositError(\n 'INVALID_REQUEST',\n 'address must be a valid EVM (0x-prefixed, 40 hex chars) or Solana (Base58, 32-44 chars) address.',\n );\n }\n\n if (typeof request.token !== 'string' || !isValidTokenAddress(request.token)) {\n throw new DepositError(\n 'INVALID_REQUEST',\n 'token must be a valid EVM (0x-prefixed hex) or Solana (Base58) token address.',\n );\n }\n}\n\nexport function buildSignerRequest(request: DepositRequest, webviewBaseUrl: string): SignerRequest {\n const base: SignerRequest = {\n amount: request.amount,\n chainId: request.chainId,\n address: request.address,\n token: request.token,\n callbackScheme: request.callbackScheme ?? null,\n url: webviewBaseUrl,\n version: 'v1',\n };\n\n if (request.reference) base.reference = request.reference;\n if (request.metadata && Object.keys(request.metadata).length > 0) {\n base.metadata = request.metadata;\n }\n\n return base;\n}\n","import { DepositError } from './errors.ts';\nimport {\n parseTransferComplete,\n parseCloseRequest,\n parseContentHeight,\n parseIframeReady,\n buildAckMessage,\n buildSignedPayloadMessage,\n} from './messages.ts';\nimport { BRAND_COLOR_PARAM_KEYS, normalizeBrandHex } from './brandParam.ts';\nimport { normalizeDisplayBalance } from './balanceParam.ts';\nimport { createIframe, shouldUseMobileSheetLayout, type IframeHandle } from './iframe.ts';\nimport { createEmbeddedIframe } from './embeddedIframe.ts';\nimport { measureViewportMetrics } from './viewportMetrics.ts';\nimport { callSigner } from './signer.ts';\nimport { validateDepositRequest, buildSignerRequest } from './validation.ts';\nimport type { DepositConfig, DepositStatus, DepositRequest, DepositResult, SignerResponse } from './types.ts';\n\nexport const DEFAULT_WEBVIEW_BASE_URL = 'https://pay.blink.cash';\nexport const SANDBOX_WEBVIEW_BASE_URL = 'https://pay-sandbox.blink.cash';\n\n/** How long `requestDeposit` waits for `blink:iframe-ready` before falling back to URL params. */\nconst IFRAME_READY_TIMEOUT_MS = 2_000;\n\n/**\n * How long a background warm-up iframe may take to signal ready. Generous on\n * purpose: the warm-up happens while the user hasn't acted yet, so a slow\n * connection finishing at 10s still produces a fully warmed flow. The strict\n * 2s budget only applies once `requestDeposit` is actually waiting.\n */\nconst WARM_IFRAME_READY_TIMEOUT_MS = 60_000;\n\n/**\n * Capability the hosted flow must advertise on `blink:iframe-ready` for the\n * full-viewport fluid layout (card chrome rendered inside the iframe). A\n * ready message without it means an older webview deployment — the overlay\n * is downgraded to the legacy fixed-size container before payload delivery.\n */\nconst LAYOUT_FLUID_CAPABILITY = 'layout-fluid';\n\n/** Fraction of the host viewport used as the default embedded height budget. */\nconst DEFAULT_EMBED_MAX_HEIGHT_FRACTION = 0.9;\n\ninterface IframeReadyResult {\n ready: boolean;\n fluidCapable: boolean;\n}\n\n/**\n * The one dismissal error. Every route out of a flow that isn't completion or a\n * failure produces this: the flow's own close control, the overlay backdrop,\n * Escape, and the host calling {@link Deposit.close} — so an integrator writes a\n * single `DEPOSIT_DISMISSED` branch rather than one per affordance.\n */\nfunction dismissedError(): DepositError {\n return new DepositError(\n 'DEPOSIT_DISMISSED',\n 'The deposit was dismissed before the transfer completed.',\n );\n}\n\nconst IFRAME_NOT_READY: IframeReadyResult = { ready: false, fluidCapable: false };\n\n/**\n * Resolves the hosted-flow base URL from config.\n *\n * Precedence: explicit `webviewBaseUrl` > `environment: 'sandbox'` > production default.\n */\nexport function resolveWebviewBaseUrl(\n config: Pick<DepositConfig, 'webviewBaseUrl' | 'environment'>,\n): string {\n if (config.webviewBaseUrl) return config.webviewBaseUrl;\n return config.environment === 'sandbox' ? SANDBOX_WEBVIEW_BASE_URL : DEFAULT_WEBVIEW_BASE_URL;\n}\n\ntype EventMap = {\n complete: (result: DepositResult) => void;\n error: (error: DepositError) => void;\n close: () => void;\n 'status-change': (status: DepositStatus) => void;\n /**\n * Embedded presentation only: the hosted flow's rendered height changed and\n * the inline iframe has already been resized to match. Hosts that size their\n * own panel around the iframe follow it from here.\n *\n * `heightPx` fires on every frame of the flow's own height transition —\n * apply it directly, with NO CSS transition on the host side, or two\n * independent animations of the same quantity fight each other and the panel\n * keeps moving after the content has settled.\n *\n * `preferredWidthPx` / `minWidthPx` are constants describing the flow's\n * design envelope, so a host that wants its panel to fit the flow in both\n * axes can size the width once rather than guessing.\n */\n resize: (info: {\n heightPx: number;\n preferredWidthPx?: number;\n minWidthPx?: number;\n }) => void;\n};\n\ntype EventName = keyof EventMap;\n\n/**\n * Merchant-facing deposit SDK.\n *\n * Opens a hosted payment flow in a modal iframe, communicates with the\n * merchant's signer backend, and resolves when the user completes payment.\n *\n * The iframe has `publickey-credentials-get` and `publickey-credentials-create`\n * permissions (with explicit origin) so WebAuthn passkey ceremonies work\n * cross-origin, including in Safari.\n *\n * ```ts\n * const deposit = new Deposit({ signer: '/api/sign-payment' });\n * const result = await deposit.requestDeposit({ amount: 50, chainId: 8453, address: '0x...', token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' });\n * ```\n */\nexport class Deposit {\n private readonly config: DepositConfig;\n private iframe: IframeHandle | null = null;\n private hostedOrigin: string | null = null;\n private messageListener: ((event: MessageEvent) => void) | null = null;\n private requestId = 0;\n private destroyed = false;\n private _status: DepositStatus = 'idle';\n private _result: DepositResult | null = null;\n private _error: DepositError | null = null;\n private flowTimer: ReturnType<typeof setTimeout> | null = null;\n private lastSignerResponse: SignerResponse | null = null;\n private warmIframe: IframeHandle | null = null;\n private warmIframeReady: Promise<IframeReadyResult> | null = null;\n private warmIframeReadyCancel: (() => void) | null = null;\n /** Resolved embedded-vs-overlay decision; see {@link Deposit.isEmbedded}. */\n private embeddedResolved: boolean | null = null;\n /**\n * Settles the in-flight `requestDeposit()` as a dismissal. Non-null exactly\n * while a flow is in progress, so {@link Deposit.close} can reject the promise\n * the caller is awaiting instead of tearing the frame down under it.\n */\n private dismissActiveFlow: (() => void) | null = null;\n private listeners: { [K in EventName]: Set<EventMap[K]> } = {\n complete: new Set(),\n error: new Set(),\n close: new Set(),\n 'status-change': new Set(),\n resize: new Set(),\n };\n\n /** Current phase of the deposit flow. */\n get status(): DepositStatus {\n return this._status;\n }\n\n /** Last successful {@link DepositResult}, available when `status === 'completed'`. */\n get result(): DepositResult | null {\n return this._result;\n }\n\n /** Last {@link DepositError}, available when `status === 'error'`. */\n get error(): DepositError | null {\n return this._error;\n }\n\n /** Whether a deposit flow is currently in progress (signer loading or iframe open). */\n get isActive(): boolean {\n return this._status === 'signer-loading' || this._status === 'iframe-active';\n }\n\n /**\n * How this instance will actually present: `'embedded'` renders inline in\n * `containerElement`, `'overlay'` covers the page.\n *\n * Not simply an echo of the config — a host that asked for `'embedded'` gets\n * `'overlay'` on mobile, where a phone-sized method panel cannot hold the\n * flow (see {@link Deposit.isEmbedded}). Read it when laying out the panel:\n * on `'overlay'` no `resize` event ever fires, so a panel sized from those\n * reports would sit empty behind the overlay — collapse or skip it.\n *\n * Live until the SDK builds its first (warm-up) frame and fixed from then on,\n * so re-read it on resize rather than caching it at mount.\n */\n get presentation(): 'overlay' | 'embedded' {\n return this.isEmbedded() ? 'embedded' : 'overlay';\n }\n\n constructor(config: DepositConfig) {\n if (!config.signer || (typeof config.signer !== 'string' && typeof config.signer !== 'function')) {\n throw new DepositError('INVALID_REQUEST', 'DepositConfig.signer is required (URL string or SignerFunction).');\n }\n if (config.presentation === 'embedded') {\n // Required at construction, not at requestDeposit: the warm-up iframe is\n // created eagerly and can never be relocated afterwards — moving an\n // iframe in the DOM reloads it, throwing away the warmed document.\n if (!config.containerElement) {\n throw new DepositError(\n 'INVALID_REQUEST',\n 'DepositConfig.containerElement is required when presentation is \"embedded\".',\n );\n }\n if (config.layout === 'fixed') {\n throw new DepositError(\n 'INVALID_REQUEST',\n 'DepositConfig.layout \"fixed\" is an overlay-only escape hatch and cannot be combined with presentation \"embedded\".',\n );\n }\n }\n this.config = config;\n this.log('Deposit instance created', {\n signer: typeof config.signer === 'string' ? config.signer : '<function>',\n });\n if (config.preload !== false) {\n this.schedulePreload();\n }\n }\n\n /**\n * Warm up the hosted payment flow in a hidden iframe so `requestDeposit`\n * opens an already-loaded page (JS bundle, auth session restore, and —\n * when {@link DepositConfig.merchantId} is set — merchant config prefetch\n * all happen in the background).\n *\n * Runs automatically after construction unless `preload: false`; call it\n * manually to control the timing (e.g. on deposit-button hover). No-op\n * when a warm iframe already exists or a deposit flow is active.\n */\n preload(): void {\n if (this.destroyed || this.isActive) return;\n if (this.warmIframe && !this.warmIframe.isClosed()) return;\n if (typeof document === 'undefined' || typeof window === 'undefined') return;\n\n const webviewBaseUrl = resolveWebviewBaseUrl(this.config);\n this.hostedOrigin = this.config.hostedFlowOrigin ?? new URL(webviewBaseUrl).origin;\n\n const preloadUrl = this.buildPreloadUrl(webviewBaseUrl);\n const iframe = this.createPresentedIframe(preloadUrl, { hidden: true });\n const ready = this.waitForIframeReady(iframe, WARM_IFRAME_READY_TIMEOUT_MS);\n this.warmIframe = iframe;\n this.warmIframeReady = ready.promise;\n this.warmIframeReadyCancel = ready.cancel;\n this.log('Warm-up iframe created', { url: preloadUrl });\n }\n\n // Defer the automatic warm-up until the host page has finished its own\n // load and the main thread is idle — constructing a Deposit instance must\n // never slow the merchant page down.\n private schedulePreload(): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n\n const start = () => {\n if (!this.destroyed && !this.isActive) this.preload();\n };\n const whenIdle = () => {\n const w = window as Window & {\n requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;\n };\n if (typeof w.requestIdleCallback === 'function') {\n w.requestIdleCallback(start, { timeout: 3_000 });\n } else {\n setTimeout(start, 250);\n }\n };\n\n if (document.readyState === 'complete') {\n whenIdle();\n } else {\n window.addEventListener('load', whenIdle, { once: true });\n }\n }\n\n /**\n * Whether the flow renders inline in the host's element rather than as an\n * overlay.\n *\n * `presentation: 'embedded'` is a request, not a guarantee: **on mobile the\n * flow presents as the normal overlay** even for an embedded host. An\n * aggregator's method panel is a narrow, short column on a phone, and the\n * flow inside it is a payment journey with a keypad, wallet lists and a QR\n * code — it needs the screen. The overlay is exactly what a phone user gets\n * from every other Blink integration, and the host's own dialog stays behind\n * it. Desktop keeps the inline card, where the panel has room.\n *\n * **The decision lives with the frame.** Read live until a frame is built,\n * then committed for good ({@link Deposit.createPresentedIframe}) — `preload()`\n * warms a frame from these same predicates and the flow that later adopts it\n * must agree, because a frame warmed at `layout=embed` handed to the overlay\n * presenter (or the reverse) is a blank modal. Committing at frame creation\n * rather than at construction matters: a host that constructs `Deposit` before\n * layout settles — a widget mounting inside a transition, a background or\n * prerendered tab — reports a zero-width viewport, and `(max-width: 640px)`\n * matches at zero, so caching then would lock a desktop user into the overlay\n * over a viewport that never existed. The warm-up already waits for `load`\n * plus an idle callback, so by the time it commits the measurement is real.\n */\n private isEmbedded(): boolean {\n if (this.config.presentation !== 'embedded') return false;\n if (this.embeddedResolved !== null) return this.embeddedResolved;\n // No device signals to read (SSR, or a viewport that has not been laid out\n // yet): honour the config, and do not commit — a later call decides.\n if (typeof window === 'undefined') return true;\n const viewportWidth = window.visualViewport?.width ?? window.innerWidth;\n if (!(viewportWidth > 0)) return true;\n return !shouldUseMobileSheetLayout();\n }\n\n /**\n * The host's height budget for the inline iframe. Explicit config wins;\n * otherwise most of the host viewport, which keeps a tall flow from\n * outgrowing the page it is embedded in.\n */\n private resolveEmbedMaxHeightPx(): number | undefined {\n if (this.config.embedMaxHeightPx !== undefined) return this.config.embedMaxHeightPx;\n if (typeof window === 'undefined') return undefined;\n const derived = Math.round(window.innerHeight * DEFAULT_EMBED_MAX_HEIGHT_FRACTION);\n return derived > 0 ? derived : undefined;\n }\n\n /** Build the iframe for the configured presentation. */\n private createPresentedIframe(url: string, options: { hidden?: boolean }): IframeHandle {\n // Commit the embedded-vs-overlay decision to this instance. Everything\n // downstream — the layout URL param, the height budget, the presenter, the\n // mount target — must describe the same frame for the rest of its life.\n if (this.config.presentation === 'embedded' && this.embeddedResolved === null) {\n this.embeddedResolved = this.isEmbedded();\n if (!this.embeddedResolved) {\n this.log('Mobile device: presenting the embedded flow as an overlay');\n }\n }\n if (this.isEmbedded()) {\n return createEmbeddedIframe(url, this.config.containerElement!, {\n hidden: options.hidden,\n // A getter, not a value: the default is derived from the host\n // viewport, which changes on rotation and window resize.\n embedMaxHeightPx: () => this.resolveEmbedMaxHeightPx(),\n });\n }\n return createIframe(url, this.overlayMountTarget(), {\n hidden: options.hidden,\n fluid: this.isFluidLayout(),\n });\n }\n\n /**\n * Where the overlay mounts. `containerElement` means two different things by\n * presentation: an overlay mount point (`presentation: 'overlay'`) or the\n * aggregator's inline panel slot (`'embedded'`). When an embedded flow\n * presents as an overlay on mobile, that slot must NOT be the mount point —\n * `position: fixed` resolves against the nearest transformed/filtered/\n * contained ancestor, and an aggregator's animated dialog is exactly that, so\n * the \"full-screen\" overlay would end up positioned inside their panel.\n * Falls through to `document.body`.\n */\n private overlayMountTarget(): HTMLElement | undefined {\n return this.config.presentation === 'embedded' ? undefined : this.config.containerElement;\n }\n\n private buildPreloadUrl(webviewBaseUrl: string): string {\n const preloadUrl = new URL(webviewBaseUrl);\n preloadUrl.searchParams.set('preload', 'true');\n // Untrusted warm-up hint: lets the hosted flow prefetch the merchant\n // config and signing key before the signed payload exists. Authorization\n // still comes exclusively from the signed payload.\n if (this.config.merchantId) {\n preloadUrl.searchParams.set('merchantId', this.config.merchantId);\n }\n this.applyFullWidgetParam(preloadUrl);\n this.applyLayoutParam(preloadUrl);\n this.applyViewportParams(preloadUrl);\n return preloadUrl.toString();\n }\n\n /**\n * Detach the warm iframe for use by a starting flow. Returns null (and\n * cleans up) when there is none or it was closed in the meantime.\n */\n private takeWarmIframe(): {\n iframe: IframeHandle;\n ready: Promise<IframeReadyResult>;\n cancelReady: () => void;\n } | null {\n const iframe = this.warmIframe;\n const ready = this.warmIframeReady;\n const cancelReady = this.warmIframeReadyCancel ?? (() => {});\n this.warmIframe = null;\n this.warmIframeReady = null;\n this.warmIframeReadyCancel = null;\n\n if (!iframe || !ready) return null;\n if (iframe.isClosed()) {\n cancelReady();\n iframe.destroy();\n return null;\n }\n return { iframe, ready, cancelReady };\n }\n\n private discardWarmIframe(): void {\n this.warmIframeReadyCancel?.();\n this.warmIframeReadyCancel = null;\n this.warmIframeReady = null;\n if (this.warmIframe) {\n this.warmIframe.destroy();\n this.warmIframe = null;\n }\n }\n\n /**\n * Open the hosted payment flow for the given deposit.\n *\n * The returned Promise resolves when the user completes the payment and\n * rejects with a {@link DepositError} on failure.\n */\n requestDeposit(request: DepositRequest): Promise<DepositResult> {\n if (this.destroyed) {\n return Promise.reject(\n new DepositError('INVALID_REQUEST', 'This Deposit instance has been destroyed.'),\n );\n }\n\n validateDepositRequest(request);\n this.log('requestDeposit called', { amount: request.amount, token: request.token, chainId: request.chainId });\n\n this.requestId += 1;\n const currentRequestId = this.requestId;\n\n this.cleanup();\n\n this._result = null;\n this._error = null;\n this.setStatus('signer-loading');\n\n return new Promise<DepositResult>((resolve, reject) => {\n let settled = false;\n const settle = (fn: () => void) => {\n if (this.requestId !== currentRequestId || settled) return;\n settled = true;\n this.dismissActiveFlow = null;\n fn();\n };\n\n const onComplete = (result: DepositResult) => {\n settle(() => {\n if (this.flowTimer) {\n clearTimeout(this.flowTimer);\n this.flowTimer = null;\n }\n this._result = result;\n this._error = null;\n this.setStatus('completed');\n this.emit('complete', result);\n resolve(result);\n this.cleanup();\n });\n };\n\n const onError = (error: DepositError) => {\n settle(() => {\n this.cleanup();\n this._error = error;\n this.setStatus('error');\n this.emit('error', error);\n reject(error);\n });\n };\n\n // How `close()` settles this promise — see {@link Deposit.close}.\n //\n // A quiet dismissal: it rejects the caller's promise but does NOT emit\n // `error` or move `status` to 'error', because the HOST asked for this\n // (its own back button or dialog chrome) and does not need telling that\n // its own action ended the flow. `close()` follows with 'idle' + `close`,\n // which is what it has always reported. The flow's own close control\n // keeps the full error path: there the dismissal is news to the host.\n this.dismissActiveFlow = () => {\n settle(() => {\n this.cleanup();\n reject(dismissedError());\n });\n };\n\n if (this.config.flowTimeoutMs != null && this.config.flowTimeoutMs > 0) {\n this.flowTimer = setTimeout(() => {\n onError(\n new DepositError(\n 'FLOW_TIMEOUT',\n `The payment flow did not complete within ${this.config.flowTimeoutMs}ms.`,\n ),\n );\n }, this.config.flowTimeoutMs);\n }\n\n this.runSignerFlow(request, currentRequestId, onComplete, onError);\n });\n }\n\n /** Register an event listener. */\n on<K extends EventName>(event: K, handler: EventMap[K]): this {\n this.listeners[event].add(handler);\n return this;\n }\n\n /** Remove a previously registered event listener. */\n off<K extends EventName>(event: K, handler: EventMap[K]): this {\n this.listeners[event].delete(handler);\n return this;\n }\n\n /** No-op — retained for API compatibility with the popup-based SDK. */\n focus(): void {}\n\n /**\n * Close the deposit iframe without waiting for completion — the host's own\n * back button or dialog chrome.\n *\n * This **settles a flow in progress** by rejecting its `requestDeposit()`\n * promise with `DEPOSIT_DISMISSED`, exactly as the flow's own close control\n * does. It has to: `cleanup()` destroys the frame through `destroy()`, which\n * drops the handle's close callback on purpose, so without this the caller's\n * `await` never returns. An aggregator whose back button awaited that promise\n * to restore its method list was left showing an empty panel — the flow gone,\n * its own list still not rendered, and no error to explain why.\n *\n * The rejection code is the same `DEPOSIT_DISMISSED` the in-flow control\n * produces, so a host writes one dismissal branch rather than one per\n * affordance. What it deliberately does not do is report an error: no `error`\n * event, and `status` lands on 'idle' as it always has, because the host\n * initiated this. With no flow in progress it is a plain teardown, unchanged.\n */\n close(): void {\n this.log('close() called');\n const dismiss = this.dismissActiveFlow;\n this.dismissActiveFlow = null;\n // Rejects the pending promise and cleans up; `cleanup()` is idempotent, so\n // the shared tail below still runs the status and event side of close.\n dismiss?.();\n this.cleanup();\n this.setStatus('idle');\n this.emit('close');\n }\n\n /** Tear down the instance and release all resources. */\n destroy(): void {\n this.log('destroy() called');\n // Set before cleanup() so it doesn't schedule a fresh warm-up iframe.\n this.destroyed = true;\n this.cleanup();\n this.discardWarmIframe();\n this.setStatus('idle');\n for (const set of Object.values(this.listeners)) {\n (set as Set<unknown>).clear();\n }\n }\n\n // ── Private ──────────────────────────────────────────────────────────\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (!this.config.debug) return;\n if (data) {\n console.debug(`[BlinkDeposit] ${message}`, data);\n } else {\n console.debug(`[BlinkDeposit] ${message}`);\n }\n }\n\n /**\n * Appends `enableFullWidget=false` to the hosted-flow URL when the merchant\n * integration disables the full widget. Absence of the param means enabled\n * (the default) — the hosted flow ANDs this with the merchant's backend\n * config, so the full widget renders only when both allow it.\n */\n private applyFullWidgetParam(url: URL): void {\n if (this.config.enableFullWidget === false) {\n url.searchParams.set('enableFullWidget', 'false');\n }\n this.applyAppearanceParam(url);\n }\n\n /**\n * Appends `appearance=dark` (or `appearance=system`) to the hosted-flow URL.\n * An explicit `appearance: { theme }` config always wins — including\n * `theme: 'light'`, which pins light regardless of the merchant page. When\n * the merchant passes no theme, the default follows the merchant page's own\n * declared color scheme (see {@link detectMerchantColorScheme}) so the flow\n * doesn't render a light modal on a page that says it is dark. Absence of\n * the param means light. The hosted flow resolves `system` against the\n * user's `prefers-color-scheme`. Applied alongside the full-widget param on\n * every hosted/preload URL.\n */\n private applyAppearanceParam(url: URL): void {\n const theme = this.config.appearance?.theme ?? detectMerchantColorScheme();\n if (theme === 'dark' || theme === 'system') {\n url.searchParams.set('appearance', theme);\n }\n this.applyBrandParam(url);\n }\n\n /**\n * Appends the merchant's brand colors as `brand=p-0f62fe.bg-ffffff…`.\n *\n * On the URL rather than a message because the hosted flow's loading shell\n * paints from its entry chunk, hundreds of ms before React mounts: a palette\n * that arrived by `postMessage` would show Blink's own card color first and\n * then become the merchant's. Unreserved characters only, so the param costs\n * ~50 bytes of the URL budget rather than triple that in percent-encoding.\n *\n * Validated here purely so the merchant sees the complaint in their OWN\n * console — the hosted flow re-validates everything it decodes, since the URL\n * is host-controlled input that ends up in a stylesheet. Silence would be the\n * worst outcome: a dropped color that nobody is told about looks like the SDK\n * ignoring the config.\n */\n private applyBrandParam(url: URL): void {\n const variables = this.config.appearance?.variables;\n if (!variables) return;\n const accepted: Record<string, string> = {};\n for (const [key, value] of Object.entries(variables)) {\n if (value === undefined || value === null) continue;\n if (!BRAND_COLOR_PARAM_KEYS[key]) {\n console.error(\n `[blink] appearance.variables.${key} is not a supported brand color. `\n + `Supported: ${Object.keys(BRAND_COLOR_PARAM_KEYS).join(', ')}.`,\n );\n continue;\n }\n const hex = normalizeBrandHex(value);\n if (!hex) {\n console.error(\n `[blink] appearance.variables.${key} must be opaque hex (#rgb or #rrggbb); `\n + `received ${JSON.stringify(value)}. Ignoring it.`,\n );\n continue;\n }\n accepted[key] = hex;\n }\n const encoded = Object.keys(BRAND_COLOR_PARAM_KEYS)\n .filter((key) => accepted[key] !== undefined)\n .map((key) => `${BRAND_COLOR_PARAM_KEYS[key]}-${accepted[key].slice(1)}`)\n .join('.');\n if (encoded) url.searchParams.set('brand', encoded);\n }\n\n /**\n * Normalizes the display-only {@link DepositRequest.balance} for the wire,\n * or returns `undefined` to omit it everywhere — the `blink:signed-payload`\n * sibling field and the legacy fallback URL param alike. Additive wire\n * discipline: an unset or rejected balance leaves both channels\n * byte-for-byte what they always were, and old webviews ignore the field\n * by construction.\n *\n * Validated here purely so the merchant sees the complaint in their OWN\n * console (same rationale as {@link applyBrandParam}); the hosted flow\n * re-validates whatever arrives, since both channels are host-controlled\n * input. A rejected balance never blocks the deposit — the flow proceeds\n * without the subtitle.\n */\n private normalizeRequestBalance(balance: unknown): string | undefined {\n if (balance === undefined || balance === null) return undefined;\n const normalized = normalizeDisplayBalance(balance);\n if (normalized === null) {\n const received =\n typeof balance === 'number' ? String(balance) : JSON.stringify(balance) ?? String(balance);\n console.error(\n `[blink] balance must be a finite number >= 0 and < 1e12 (USD, display only); `\n + `received ${received}. Ignoring it.`,\n );\n return undefined;\n }\n return normalized;\n }\n\n /**\n * Fluid is the default; `layout: 'fixed'` opts back into the legacy\n * container. Embedded is a separate presentation and never fluid — the\n * constructor rejects the combination outright.\n */\n private isFluidLayout(): boolean {\n return !this.isEmbedded() && this.config.layout !== 'fixed';\n }\n\n /**\n * Marks the hosted-flow URL as fluid-layout: the iframe spans the full\n * viewport and the hosted flow renders the card/sheet chrome itself.\n * Only applied to preload URLs — the URL-param fallback path exists\n * precisely because the webview never signalled ready, so it cannot be\n * assumed to understand fluid layout and gets the fixed container.\n */\n private applyLayoutParam(url: URL): void {\n if (this.isEmbedded()) {\n url.searchParams.set('layout', 'embed');\n return;\n }\n if (this.isFluidLayout()) {\n url.searchParams.set('layout', 'fluid');\n }\n }\n\n /**\n * Seeds the merchant page's large-viewport height and safe-area bottom\n * inset onto the fluid preload URL so the hosted flow can size the sheet\n * before its JS boots. `blink:viewport` messages keep the values fresh\n * afterwards (rotation, window resize) — see iframe.ts.\n */\n private applyViewportParams(url: URL): void {\n const embedded = this.isEmbedded();\n if (!this.isFluidLayout() && !embedded) return;\n if (embedded) {\n // The height budget doubles as the sizing basis inside the flow, so it\n // has to be there before first paint — a late arrival would mean the\n // loading shell lays out against the wrong reference.\n const embedMaxHeightPx = this.resolveEmbedMaxHeightPx();\n if (embedMaxHeightPx !== undefined) {\n url.searchParams.set('embedMaxHeight', String(embedMaxHeightPx));\n }\n }\n const metrics = measureViewportMetrics();\n if (metrics.viewportLvh <= 0) return;\n url.searchParams.set('viewportLvh', String(metrics.viewportLvh));\n url.searchParams.set('safeAreaBottom', String(metrics.safeAreaBottom));\n }\n\n private setStatus(status: DepositStatus): void {\n if (this._status === status) return;\n this.log(`Status: ${this._status} → ${status}`);\n this._status = status;\n this.emit('status-change', status);\n }\n\n private async runSignerFlow(\n request: DepositRequest,\n requestId: number,\n onComplete: (result: DepositResult) => void,\n onError: (error: DepositError) => void,\n ): Promise<void> {\n try {\n const webviewBaseUrl = resolveWebviewBaseUrl(this.config);\n this.hostedOrigin = this.config.hostedFlowOrigin ?? new URL(webviewBaseUrl).origin;\n\n this.log('Calling signer', {\n signer: typeof this.config.signer === 'string' ? this.config.signer : '<function>',\n });\n const signerRequest = buildSignerRequest(request, webviewBaseUrl);\n // Display-only sibling of the signed payload. Deliberately NOT part of\n // `signerRequest`: the balance never reaches the merchant's signer and\n // is never covered by the signature — it rides out-of-band on whichever\n // delivery channel wins below.\n const displayBalance = this.normalizeRequestBalance(request.balance);\n\n // Reuse the background warm-up iframe when one exists — its document\n // (JS bundle, auth warm-up, merchant prefetches) is already loaded or\n // loading. Otherwise create the preload iframe now so the bundle at\n // least loads in parallel with the signer call.\n let preloadIframe: IframeHandle;\n let iframeReadyPromise: Promise<IframeReadyResult>;\n\n const warm = this.takeWarmIframe();\n if (warm) {\n warm.iframe.reveal();\n preloadIframe = warm.iframe;\n // The warm-up wait is generous (60s); from the moment the user acts\n // we only give it the regular 2s budget before falling back. Either\n // way, settle the underlying warm-up wait so its timer and message\n // listener are released.\n iframeReadyPromise = Promise.race([\n warm.ready,\n new Promise<IframeReadyResult>((resolve) =>\n setTimeout(() => resolve(IFRAME_NOT_READY), IFRAME_READY_TIMEOUT_MS),\n ),\n ]).then((ready) => {\n warm.cancelReady();\n return ready;\n });\n this.log('Reusing warm preload iframe');\n } else {\n preloadIframe = this.createPresentedIframe(this.buildPreloadUrl(webviewBaseUrl), {});\n iframeReadyPromise = this.waitForIframeReady(preloadIframe).promise;\n }\n this.iframe = preloadIframe;\n\n preloadIframe.onClose(() => {\n onError(dismissedError());\n this.cleanup();\n this.emit('close');\n });\n\n // Race: signer call and iframe ready signal in parallel\n const signerPromise = callSigner(\n this.config.signer,\n signerRequest,\n this.config.signerTimeoutMs,\n );\n\n const [signerResponse, iframeReady] = await Promise.all([\n signerPromise,\n iframeReadyPromise,\n ]);\n\n this.lastSignerResponse = signerResponse;\n this.log('Signer responded', { merchantId: signerResponse.merchantId });\n\n if (this.requestId !== requestId || preloadIframe.isClosed()) {\n this.log('Request superseded or iframe dismissed during signer call');\n return;\n }\n\n if (iframeReady.ready) {\n // The webview signalled ready but predates fluid layout (no\n // `layout-fluid` capability): snap the overlay back to the fixed\n // container so its fill-mode rendering looks exactly like today.\n if (this.isFluidLayout() && !iframeReady.fluidCapable) {\n preloadIframe.downgradeToFixed();\n this.log('Webview lacks layout-fluid capability — downgraded to fixed container');\n }\n // New webview supports preloading — deliver payload via postMessage\n const contentWindow = preloadIframe.contentWindow;\n if (contentWindow) {\n contentWindow.postMessage(\n buildSignedPayloadMessage(\n signerResponse.merchantId,\n signerResponse.payload,\n signerResponse.signature,\n displayBalance,\n ),\n this.hostedOrigin!,\n );\n }\n this.startMessageListener(preloadIframe, onComplete);\n this.setStatus('iframe-active');\n this.log('Payload delivered via postMessage (preload path)');\n } else {\n // Fallback: old webview did not send blink:iframe-ready.\n // Destroy preload iframe and create a new one with full URL params.\n preloadIframe.destroy();\n\n const hostedUrl = new URL(webviewBaseUrl);\n hostedUrl.searchParams.set('merchantId', signerResponse.merchantId);\n hostedUrl.searchParams.set('payload', signerResponse.payload);\n hostedUrl.searchParams.set('signature', signerResponse.signature);\n if (displayBalance !== undefined) {\n hostedUrl.searchParams.set('balance', displayBalance);\n }\n this.applyFullWidgetParam(hostedUrl);\n // The overlay's fallback deliberately omits the layout params: a\n // webview that never signalled ready predates them, so it gets the\n // legacy fixed container. Embedded has no legacy container to fall\n // back to, so it keeps its params and renders inline regardless.\n if (this.isEmbedded()) {\n this.applyLayoutParam(hostedUrl);\n this.applyViewportParams(hostedUrl);\n }\n const targetUrl = hostedUrl.toString();\n\n // Stays on the configured presenter. Embedded must never reach\n // `createIframe` here: that builds a `position: fixed` overlay, and\n // dropping a full-screen modal over an aggregator's own widget is the\n // one failure mode worse than the flow simply not starting.\n const iframeHandle = this.createPresentedIframe(targetUrl, {});\n this.iframe = iframeHandle;\n\n iframeHandle.onClose(() => {\n onError(dismissedError());\n this.cleanup();\n this.emit('close');\n });\n\n this.startMessageListener(iframeHandle, onComplete);\n this.setStatus('iframe-active');\n this.log('Iframe opened with hosted flow (fallback path)', { url: targetUrl });\n }\n } catch (err) {\n if (this.requestId !== requestId) return;\n\n this.log('Signer flow failed', { error: err instanceof Error ? err.message : String(err) });\n\n if (err instanceof DepositError) {\n onError(err);\n } else {\n onError(\n new DepositError(\n 'SIGNER_NETWORK_ERROR',\n err instanceof Error ? err.message : 'Unknown signer error.',\n ),\n );\n }\n }\n }\n\n /**\n * Resolves `{ ready: true, ... }` when the iframe posts\n * `blink:iframe-ready` (with `fluidCapable` reflecting its advertised\n * capabilities), or `{ ready: false, fluidCapable: false }` on timeout.\n * `cancel()` settles the promise as not-ready immediately and releases\n * the listener + timer — used to reap the generous warm-up wait once it no\n * longer matters (warm iframe consumed or discarded).\n */\n private waitForIframeReady(\n iframeHandle: IframeHandle,\n timeoutMs: number = IFRAME_READY_TIMEOUT_MS,\n ): { promise: Promise<IframeReadyResult>; cancel: () => void } {\n let finish: (result: IframeReadyResult) => void = () => {};\n\n const promise = new Promise<IframeReadyResult>((resolve) => {\n const handler = (event: MessageEvent) => {\n if (event.origin !== this.hostedOrigin) return;\n if (event.source !== iframeHandle.contentWindow) return;\n const readyMessage = parseIframeReady(event.data);\n if (readyMessage) {\n finish({\n ready: true,\n fluidCapable: readyMessage.capabilities.includes(LAYOUT_FLUID_CAPABILITY),\n });\n }\n };\n window.addEventListener('message', handler);\n\n const timeout = setTimeout(() => {\n this.log('Iframe ready timeout — falling back to URL params');\n finish(IFRAME_NOT_READY);\n }, timeoutMs);\n\n let settled = false;\n finish = (result: IframeReadyResult) => {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n clearTimeout(timeout);\n resolve(result);\n };\n });\n\n return { promise, cancel: () => finish(IFRAME_NOT_READY) };\n }\n\n private startMessageListener(\n iframeHandle: IframeHandle,\n onComplete: (result: DepositResult) => void,\n ): void {\n const handler = (event: MessageEvent) => {\n if (this.hostedOrigin && event.origin !== this.hostedOrigin) {\n return;\n }\n\n const contentWindow = iframeHandle.contentWindow;\n if (event.source && contentWindow && event.source !== contentWindow) {\n return;\n }\n\n if (parseCloseRequest(event.data)) {\n this.log('Close request received from hosted flow');\n iframeHandle.close();\n return;\n }\n\n const contentHeight = parseContentHeight(event.data);\n if (contentHeight) {\n // Applied without a transition on purpose: the flow animates its own\n // height, and a second animation here would fight it. Not logged —\n // this fires on every frame of that animation.\n iframeHandle.applyContentHeight(contentHeight.heightPx);\n this.emit('resize', {\n heightPx: contentHeight.heightPx,\n ...(contentHeight.preferredWidthPx === undefined\n ? {}\n : { preferredWidthPx: contentHeight.preferredWidthPx }),\n ...(contentHeight.minWidthPx === undefined\n ? {}\n : { minWidthPx: contentHeight.minWidthPx }),\n });\n return;\n }\n\n const message = parseTransferComplete(event.data);\n if (!message) {\n return;\n }\n\n this.log('Transfer complete received', { transferId: message.transfer.id, status: message.transfer.status });\n\n if (contentWindow) {\n try {\n contentWindow.postMessage(\n buildAckMessage(message.transfer.id),\n this.hostedOrigin ?? '*',\n );\n } catch {\n // Cross-origin postMessage can throw in edge cases — safe to swallow.\n }\n }\n\n const depositResult: DepositResult = { transfer: message.transfer };\n if (this.lastSignerResponse?.preview) {\n depositResult.idempotencyKey = this.lastSignerResponse.preview.idempotencyKey;\n depositResult.preview = {\n amount: this.lastSignerResponse.preview.amount,\n chainId: this.lastSignerResponse.preview.chainId,\n address: this.lastSignerResponse.preview.address,\n token: this.lastSignerResponse.preview.token,\n };\n }\n onComplete(depositResult);\n };\n\n this.messageListener = handler;\n window.addEventListener('message', handler);\n }\n\n private cleanup(): void {\n if (this.flowTimer) {\n clearTimeout(this.flowTimer);\n this.flowTimer = null;\n }\n\n if (this.messageListener) {\n window.removeEventListener('message', this.messageListener);\n this.messageListener = null;\n }\n\n if (this.iframe) {\n this.iframe.destroy();\n this.iframe = null;\n }\n\n this.hostedOrigin = null;\n this.lastSignerResponse = null;\n\n // The flow that owned the iframe is over — warm a fresh one up for the\n // next deposit. When cleanup() runs at the start of requestDeposit the\n // deferred callback sees an active flow and skips.\n if (!this.destroyed && this.config.preload !== false) {\n this.schedulePreload();\n }\n }\n\n private emit<K extends EventName>(event: K, ...args: Parameters<EventMap[K]>): void {\n for (const handler of this.listeners[event]) {\n try {\n (handler as (...a: unknown[]) => void)(...args);\n } catch {\n // Swallow listener errors to avoid breaking the SDK flow.\n }\n }\n }\n}\n\n/**\n * Detects the merchant page's declared color scheme from the used\n * `color-scheme` of the document root, mapping it to the appearance the\n * hosted flow should default to when the merchant config passes no theme:\n *\n * - `dark` (page declares itself dark, e.g. `<meta name=\"color-scheme\"\n * content=\"dark\">`) → `'dark'`\n * - `light dark` (page adapts to the OS preference) → `'system'`, so the\n * hosted flow resolves against the same `prefers-color-scheme` the page\n * itself follows\n * - anything else (`normal`, `light`, `only light`, no browser support,\n * detection failure) → `null`, keeping the light default\n *\n * Only *declared* schemes are detectable — a page that paints dark colors\n * without declaring `color-scheme` reads as light.\n */\nfunction detectMerchantColorScheme(): 'dark' | 'system' | null {\n if (typeof window === 'undefined' || typeof document === 'undefined') return null;\n const root = document.documentElement;\n if (!root || typeof window.getComputedStyle !== 'function') return null;\n let value: string;\n try {\n value = window.getComputedStyle(root).colorScheme ?? '';\n } catch {\n return null;\n }\n const tokens = value.toLowerCase().split(/\\s+/);\n const dark = tokens.includes('dark');\n const light = tokens.includes('light');\n if (dark && light) return 'system';\n if (dark) return 'dark';\n return null;\n}\n\n/** @deprecated Use {@link Deposit} instead. */\nexport const Checkout = Deposit;\n","export { Deposit, Checkout, DEFAULT_WEBVIEW_BASE_URL, SANDBOX_WEBVIEW_BASE_URL } from './checkout.ts';\nexport { DepositError, CheckoutError, getDisplayMessage } from './errors.ts';\nexport type { DepositErrorCode, CheckoutErrorCode } from './errors.ts';\nexport type {\n DepositConfig,\n CheckoutConfig,\n DepositStatus,\n CheckoutStatus,\n DepositRequest,\n DepositResult,\n SignerFunction,\n SignerRequest,\n SignerResponse,\n TransferSummary,\n} from './types.ts';\n\n// ── Wallet bridge (advanced) ──────────────────────────────────────────\n// Internal building blocks for the top-frame → iframe wallet bridge.\n// Default merchant integrations don't need these — `createIframe()` wires\n// them automatically. Re-exported so monorepo tests and any merchant\n// custom-iframe wrapper can poke at the protocol shapes.\nexport { createWalletDiscoverer } from './walletBridge/discover.ts';\nexport type { WalletDiscovererHandle, RegisteredProvider } from './walletBridge/discover.ts';\nexport { attachRpcHost } from './walletBridge/rpcHost.ts';\nexport type { RpcHostHandle, RpcHostOptions } from './walletBridge/rpcHost.ts';\nexport {\n ALLOWED_RPC_METHODS,\n BRIDGE_PROTOCOL_VERSION,\n parseBridgeMessage,\n} from './walletBridge/protocol.ts';\nexport type {\n AdvertisedWallet,\n BridgeMessage,\n BridgeHelloMessage,\n WalletsAdvertisedMessage,\n RpcRequestMessage,\n RpcResponseMessage,\n RpcEventMessage,\n EIP1193Provider as BridgeEIP1193Provider,\n EIP6963ProviderInfo,\n EIP6963ProviderDetail,\n} from './walletBridge/protocol.ts';\n\nexport const VERSION = '0.3.32';\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/messages.ts","../src/brandParam.ts","../src/balanceParam.ts","../src/minimumDepositParam.ts","../src/walletBridge/discover.ts","../src/walletBridge/protocol.ts","../src/walletBridge/rpcHost.ts","../src/viewportMetrics.ts","../src/iframeCore.ts","../src/iframe.ts","../src/embeddedIframe.ts","../src/signer.ts","../src/validation.ts","../src/checkout.ts","../src/index.ts"],"names":[],"mappings":";;;AAmBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,IAAA;AAAA,EAET,WAAA,CAAY,MAAwB,OAAA,EAAiB;AACnD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAGO,IAAM,aAAA,GAAgB;AAI7B,IAAM,gBAAA,GAAqD;AAAA,EACzD,iBAAA,EACE,0DAAA;AAAA,EACF,kBAAA,EACE,2DAAA;AAAA,EACF,qBAAA,EACE,gDAAA;AAAA,EACF,oBAAA,EACE,0EAAA;AAAA,EACF,uBAAA,EACE,qDAAA;AAAA,EACF,cAAA,EACE,gEAAA;AAAA,EACF,YAAA,EACE,+CAAA;AAAA,EACF,eAAA,EACE;AACJ,CAAA;AAQO,SAAS,kBAAkB,KAAA,EAA6B;AAC7D,EAAA,OAAO,gBAAA,CAAiB,KAAA,CAAM,IAAI,CAAA,IAAK,KAAA,CAAM,OAAA;AAC/C;;;AC3CO,SAAS,sBAAsB,IAAA,EAA+C;AACnF,EAAA,IAAI,CAAC,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACrC,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,GAAA,GAAM,IAAA;AACZ,EAAA,IAAI,GAAA,CAAI,SAAS,yBAAA,EAA2B;AAC1C,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,WAAW,GAAA,CAAI,QAAA;AACrB,EAAA,IAAI,CAAC,QAAA,IAAY,OAAO,QAAA,KAAa,QAAA,EAAU;AAC7C,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,CAAA,GAAI,QAAA;A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J,EAAA,IAAI;AACF,IAAA,KAAA,GAAQ,MAAA,CAAO,gBAAA,CAAiB,IAAI,CAAA,CAAE,WAAA,IAAe,EAAA;AAAA,EACvD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,WAAA,EAAY,CAAE,MAAM,KAAK,CAAA;AAC9C,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,QAAA,CAAS,MAAM,CAAA;AACnC,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,QAAA,CAAS,OAAO,CAAA;AACrC,EAAA,IAAI,IAAA,IAAQ,OAAO,OAAO,QAAA;AAC1B,EAAA,IAAI,MAAM,OAAO,MAAA;AACjB,EAAA,OAAO,IAAA;AACT;AAGO,IAAM,QAAA,GAAW;;;AC9iCjB,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["export type DepositErrorCode =\n | 'DEPOSIT_DISMISSED'\n | 'CHECKOUT_DISMISSED'\n | 'SIGNER_REQUEST_FAILED'\n | 'SIGNER_NETWORK_ERROR'\n | 'SIGNER_RESPONSE_INVALID'\n | 'SIGNER_TIMEOUT'\n | 'FLOW_TIMEOUT'\n | 'INVALID_REQUEST';\n\n/** @deprecated Use {@link DepositErrorCode} instead. */\nexport type CheckoutErrorCode = DepositErrorCode;\n\n/**\n * Structured error thrown by the deposit SDK.\n *\n * Every error carries a machine-readable {@link code} so merchants can\n * branch on failure mode without parsing message strings.\n */\nexport class DepositError extends Error {\n readonly code: DepositErrorCode;\n\n constructor(code: DepositErrorCode, message: string) {\n super(message);\n this.name = 'DepositError';\n this.code = code;\n }\n}\n\n/** @deprecated Use {@link DepositError} instead. */\nexport const CheckoutError = DepositError;\n/** @deprecated Use {@link DepositError} instead. */\nexport type CheckoutError = DepositError;\n\nconst DISPLAY_MESSAGES: Record<DepositErrorCode, string> = {\n DEPOSIT_DISMISSED:\n 'The deposit was dismissed before the transfer completed.',\n CHECKOUT_DISMISSED:\n 'The checkout was dismissed before the transfer completed.',\n SIGNER_REQUEST_FAILED:\n 'Unable to start the payment. Please try again.',\n SIGNER_NETWORK_ERROR:\n 'Unable to reach the payment server. Check your connection and try again.',\n SIGNER_RESPONSE_INVALID:\n 'The payment server returned an unexpected response.',\n SIGNER_TIMEOUT:\n 'The payment server took too long to respond. Please try again.',\n FLOW_TIMEOUT:\n 'The payment flow timed out. Please try again.',\n INVALID_REQUEST:\n 'Invalid payment request. Please check your input.',\n};\n\n/**\n * Return a user-friendly display string for a {@link DepositError}.\n *\n * Merchants can show this directly in their UI without maintaining their own\n * copy for each error code.\n */\nexport function getDisplayMessage(error: DepositError): string {\n return DISPLAY_MESSAGES[error.code] ?? error.message;\n}\n","import type { TransferSummary } from './types.ts';\n\n// ── Wire message shapes (internal protocol — brand-specific names are OK) ──\n\ninterface TransferCompleteMessage {\n type: 'blink:transfer-complete';\n transfer: TransferSummary;\n}\n\ninterface TransferCompleteAckMessage {\n type: 'blink:transfer-complete-ack';\n transferId: string;\n}\n\n/**\n * Parse an incoming `MessageEvent.data` value into a validated transfer\n * completion message, or return `null` if it does not match.\n */\nexport function parseTransferComplete(data: unknown): TransferCompleteMessage | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n\n const msg = data as Record<string, unknown>;\n if (msg.type !== 'blink:transfer-complete') {\n return null;\n }\n\n const transfer = msg.transfer;\n if (!transfer || typeof transfer !== 'object') {\n return null;\n }\n\n const t = transfer as Record<string, unknown>;\n if (typeof t.id !== 'string' || typeof t.status !== 'string') {\n return null;\n }\n\n return {\n type: 'blink:transfer-complete',\n transfer: {\n id: t.id,\n status: t.status,\n amount: parseAmount(t.amount),\n destinations: parseDestinations(t.destinations),\n },\n };\n}\n\nfunction parseAmount(value: unknown): TransferSummary['amount'] {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n const a = value as Record<string, unknown>;\n return {\n amount: Number(a.amount ?? 0),\n currency: String(a.currency ?? ''),\n };\n}\n\nfunction parseDestinations(value: unknown): TransferSummary['destinations'] {\n if (!Array.isArray(value)) {\n return undefined;\n }\n\n return value\n .filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === 'object')\n .map((entry) => ({\n chainId: String(entry.chainId ?? ''),\n address: String(entry.address ?? ''),\n token:\n entry.token && typeof entry.token === 'object'\n ? {\n address: String((entry.token as Record<string, unknown>).address ?? ''),\n symbol: String((entry.token as Record<string, unknown>).symbol ?? ''),\n }\n : undefined,\n }));\n}\n\n/** Build an ACK message to send back to the hosted flow. */\nexport function buildAckMessage(transferId: string): TransferCompleteAckMessage {\n return {\n type: 'blink:transfer-complete-ack',\n transferId,\n };\n}\n\n// ── Close request ─────────────────────────────────────────────────────\n\ninterface CloseRequestMessage {\n type: 'blink:close-request';\n}\n\n/**\n * Parse an incoming `MessageEvent.data` value into a close-request message,\n * or return `null` if it does not match. The hosted flow sends this when\n * the user taps the close / X button inside the iframe.\n */\nexport function parseCloseRequest(data: unknown): CloseRequestMessage | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n const msg = data as Record<string, unknown>;\n if (msg.type !== 'blink:close-request') {\n return null;\n }\n return { type: 'blink:close-request' };\n}\n\n// ── Preload handshake ─────────────────────────────────────────────────\n\ninterface IframeReadyMessage {\n type: 'blink:iframe-ready';\n /**\n * Feature capabilities advertised by the hosted flow. Older webview\n * deployments omit the field entirely — parsed as an empty list so the\n * SDK can downgrade features that need cooperation from the iframe\n * (e.g. `layout-fluid`).\n */\n capabilities: string[];\n}\n\nexport function parseIframeReady(data: unknown): IframeReadyMessage | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n const msg = data as Record<string, unknown>;\n if (msg.type !== 'blink:iframe-ready') {\n return null;\n }\n return { type: 'blink:iframe-ready', capabilities: parseCapabilities(msg.capabilities) };\n}\n\nfunction parseCapabilities(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value.filter((entry): entry is string => typeof entry === 'string');\n}\n\n// ── Reveal (fluid layout) ─────────────────────────────────────────────\n\ninterface RevealMessage {\n type: 'blink:reveal';\n}\n\n// ── Viewport metrics (fluid layout) ───────────────────────────────────\n\ninterface ViewportMessage {\n type: 'blink:viewport';\n /** Merchant page's large-viewport height (100lvh) in CSS px. */\n viewportLvh: number;\n /** Merchant page's `env(safe-area-inset-bottom)` in CSS px. */\n safeAreaBottom: number;\n /**\n * Embedded presentation only: the host's height budget for the inline\n * iframe, in CSS px. Omitted entirely on overlay/fluid loads so the wire\n * shape older webview deployments see is byte-for-byte what it always was.\n */\n embedMaxHeightPx?: number;\n}\n\n/**\n * Build the message that keeps the hosted flow's sheet geometry anchored to\n * the merchant page's *large* viewport. Inside the fluid iframe, `dvh`\n * tracks the current (chrome-dependent) viewport, so without these values\n * the sheet would resize whenever the mobile browser's URL bar collapses or\n * expands — the legacy parent-side sheet (79vh) never did.\n *\n * In embedded presentation it carries `embedMaxHeightPx` as well: there the\n * iframe's own height is a function of its content, so the flow cannot use\n * `dvh` for anything and needs a host-supplied budget to size against.\n */\nexport function buildViewportMessage(\n viewportLvh: number,\n safeAreaBottom: number,\n embedMaxHeightPx?: number,\n): ViewportMessage {\n return {\n type: 'blink:viewport',\n viewportLvh,\n safeAreaBottom,\n ...(embedMaxHeightPx === undefined ? {} : { embedMaxHeightPx }),\n };\n}\n\n// ── Content height (embedded presentation) ────────────────────────────\n\ninterface ContentHeightMessage {\n type: 'blink:content-height';\n /** Rendered height of the hosted flow's card, in CSS px. */\n heightPx: number;\n /**\n * Width the flow would like if the host has room, and the width below which\n * its fixed-width elements start to overflow. Constants from the hosted\n * flow's design envelope, not measurements — a width derived from the width\n * the host granted would just echo back, so a panel could never grow.\n * Absent from older hosted flows that only reported height.\n */\n preferredWidthPx?: number;\n minWidthPx?: number;\n}\n\n/** Upper bound on a reported height — same order as the viewport clamp. */\nconst MAX_CONTENT_HEIGHT_PX = 20_000;\n\n/**\n * Parse the hosted flow's content-height report, or return `null` if it does\n * not match. Sent continuously in embedded presentation (a ResizeObserver on\n * the card) so the host can size the inline iframe element to the flow; the\n * host is a dumb follower here, applying the value without animating it —\n * the SDK's own height transition is what the user sees.\n */\nexport function parseContentHeight(data: unknown): ContentHeightMessage | null {\n if (!data || typeof data !== 'object') {\n return null;\n }\n const msg = data as Record<string, unknown>;\n if (msg.type !== 'blink:content-height') {\n return null;\n }\n const raw = msg.heightPx;\n if (typeof raw !== 'number' || !Number.isFinite(raw)) {\n return null;\n }\n const heightPx = Math.round(raw);\n if (heightPx <= 0 || heightPx > MAX_CONTENT_HEIGHT_PX) {\n return null;\n }\n return {\n type: 'blink:content-height',\n heightPx,\n ...parseWidthHint('preferredWidthPx', msg.preferredWidthPx),\n ...parseWidthHint('minWidthPx', msg.minWidthPx),\n };\n}\n\n/** A width hint is optional: drop anything unusable rather than failing the report. */\nfunction parseWidthHint(key: 'preferredWidthPx' | 'minWidthPx', value: unknown) {\n if (typeof value !== 'number' || !Number.isFinite(value)) return {};\n const px = Math.round(value);\n if (px <= 0 || px > MAX_CONTENT_HEIGHT_PX) return {};\n return { [key]: px } as Record<string, number>;\n}\n\n/**\n * Build the message that tells the hosted flow its overlay just became (or\n * already is) visible, so it plays the card entry animation. Only meaningful\n * in fluid layout, where the card chrome lives inside the iframe; other\n * webviews ignore it.\n */\nexport function buildRevealMessage(): RevealMessage {\n return { type: 'blink:reveal' };\n}\n\ninterface SignedPayloadMessage {\n type: 'blink:signed-payload';\n merchantId: string;\n payload: string;\n signature: string;\n /**\n * Display-only merchant balance in USD, already normalized by the host SDK\n * (`balanceParam.ts`: floored to cents, always two fraction digits —\n * `\"20.70\"`). An UNSIGNED sibling of the payload: it is not covered by the\n * signature and the hosted flow re-validates it before display. Omitted\n * entirely when the merchant passed nothing usable, so the wire shape older\n * webview deployments see is byte-for-byte what it always was.\n */\n balance?: string;\n /**\n * Merchant minimum deposit in USD, already normalized by the host SDK\n * (`minimumDepositParam.ts`: ceiled to cents, always two fraction digits —\n * `\"10.00\"`). An UNSIGNED sibling of the payload, like `balance`: not\n * covered by the signature, re-validated by the hosted flow, and omitted\n * entirely when the merchant passed nothing usable so the wire shape older\n * webview deployments see is byte-for-byte what it always was.\n */\n minimumDeposit?: string;\n}\n\nexport function buildSignedPayloadMessage(\n merchantId: string,\n payload: string,\n signature: string,\n balance?: string,\n minimumDeposit?: string,\n): SignedPayloadMessage {\n return {\n type: 'blink:signed-payload',\n merchantId,\n payload,\n signature,\n ...(balance === undefined ? {} : { balance }),\n ...(minimumDeposit === undefined ? {} : { minimumDeposit }),\n };\n}\n","// ── Brand color param (host side) ─────────────────────────────────────\n//\n// The encoder half of the `brand` URL param. The decoder, the palette\n// derivation and the contrast gate all live in the hosted flow\n// (`swype-sdk/src/brandColors.ts`) — that is where the colors are actually\n// used, and it re-validates everything it decodes because the URL is\n// host-controlled input on its way into a stylesheet.\n//\n// So the key map below is one table in two packages. Deliberate: this SDK ships\n// to merchants with zero dependencies and cannot import the hosted flow's\n// module, and duplicating five short strings is a better trade than a shared\n// package for them. They ship together with the webview, and the round trip is\n// covered by tests on both sides — but if you add a key here, add it there.\n\n/** Config key → param key. Mirrors `BRAND_PARAM_KEYS` in swype-sdk. */\nexport const BRAND_COLOR_PARAM_KEYS: Record<string, string> = {\n colorPrimary: 'p',\n colorBackground: 'bg',\n colorText: 't',\n colorDanger: 'd',\n colorBorder: 'b',\n};\n\n/**\n * Normalizes `#rgb` / `#rrggbb` (any case) to lowercase `#rrggbb`. Returns null\n * for anything else, including 8-digit hex: Blink's card is a solid surface, so\n * alpha has no meaning and is rejected rather than silently flattened.\n */\nexport function normalizeBrandHex(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const hex = value.trim().toLowerCase();\n if (!/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/.test(hex)) return null;\n const digits = hex.slice(1);\n if (digits.length === 6) return `#${digits}`;\n return `#${digits[0]}${digits[0]}${digits[1]}${digits[1]}${digits[2]}${digits[2]}`;\n}\n","// ── Merchant balance param (host side) ────────────────────────────────\n//\n// The encoder half of the display-only merchant balance. The decoder lives\n// in the hosted flow (webview-app), which re-validates everything it\n// receives — the postMessage sibling field and the `balance` URL param are\n// both host-controlled input on their way into the deposit header.\n//\n// Validated here as well purely so the merchant sees the complaint in their\n// OWN console (same rationale as `brandParam.ts`): a balance that silently\n// vanishes looks like the SDK ignoring the request. Never forward the\n// merchant's raw value — parse, floor, re-serialize.\n\n/**\n * Exclusive upper bound on an accepted balance, in USD. Mirrors the\n * `MAX_CONTENT_HEIGHT_PX` clamp philosophy in `messages.ts`: a hard cap on\n * merchant-supplied magnitudes, generous enough for any real balance.\n */\nconst MAX_BALANCE_USD = 1e12;\n\n/**\n * Normalizes a merchant-supplied display balance to its canonical wire form,\n * or returns `null` for anything unusable (the caller drops the field).\n *\n * Accepts only a finite number `>= 0` and `< 1e12`. The value is floored to\n * whole cents — a balance never rounds up — and serialized as a plain decimal\n * string with exactly two fraction digits: `20.7` → `\"20.70\"`, `0` → `\"0.00\"`.\n *\n * Flooring detail: `Math.floor(value * 100)` alone is wrong for values whose\n * float64 form sits just under the cent boundary (`0.29 * 100 ===\n * 28.999999999999996`). `toPrecision(15)` strips that representation noise —\n * it lives at significant digit 16–17 — before flooring, so only genuine\n * sub-cent digits are dropped. The cents guard afterwards rejects the one\n * pathological corner where noise-stripping rounds a value within float64\n * noise of the cap up through it (e.g. `999999999999.9999`): dropping it beats\n * emitting a balance at or above the cap.\n */\nexport function normalizeDisplayBalance(value: unknown): string | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) return null;\n if (value < 0 || value >= MAX_BALANCE_USD) return null;\n const cents = Math.floor(Number((value * 100).toPrecision(15)));\n if (cents < 0 || cents >= MAX_BALANCE_USD * 100) return null;\n return (cents / 100).toFixed(2);\n}\n","// ── Merchant minimum-deposit param (host side) ────────────────────────\n//\n// The encoder half of the merchant-supplied deposit floor. The decoder lives\n// in the hosted flow (webview-app), which re-validates everything it receives\n// — the postMessage sibling field and the `minDeposit` URL param are both\n// host-controlled input on their way into the amount screen's validation.\n//\n// Validated here as well purely so the merchant sees the complaint in their\n// OWN console (same rationale as `brandParam.ts` / `balanceParam.ts`): a\n// minimum that silently vanishes looks like the SDK ignoring the request.\n// Never forward the merchant's raw value — parse, round, re-serialize.\n//\n// This is a MERCHANT business rule, not a security boundary. It is unsigned\n// (like `balance`), so a determined user can strip it; what they cannot strip\n// is Blink's own per-route floor, which the hosted flow enforces underneath\n// and the server enforces again at quote time. The two compose as a max —\n// see the hosted flow's `resolveMinimumDepositUsd`.\n\n/**\n * Exclusive upper bound on an accepted minimum, in USD. Mirrors the\n * `MAX_BALANCE_USD` clamp philosophy: a hard cap on merchant-supplied\n * magnitudes, generous enough for any real floor and small enough that a\n * fat-fingered `1e18` cannot lock every user out of depositing.\n */\nconst MAX_MINIMUM_DEPOSIT_USD = 1e6;\n\n/**\n * Normalizes a merchant-supplied minimum deposit to its canonical wire form,\n * or returns `null` for anything unusable (the caller drops the field).\n *\n * Accepts only a finite number `> 0` and `< 1e6`, serialized as a plain\n * decimal string with exactly two fraction digits: `10` → `\"10.00\"`, `9.5` →\n * `\"9.50\"`.\n *\n * Sub-cent values round UP, the opposite of `normalizeDisplayBalance`. Each\n * rounds in the direction that cannot misrepresent: a balance floors because\n * it must never advertise money the user does not have, and a minimum ceils\n * because it must never advertise a floor lower than the one being enforced.\n * A `9.991` minimum shown as `$9.99` would reject a $9.99 deposit the screen\n * had just called acceptable.\n *\n * Ceiling detail: `Math.ceil(value * 100)` alone is wrong for values whose\n * float64 form sits just above a cent boundary (`10.00 * 100 ===\n * 1000.0000000000001` for some inputs). `toPrecision(15)` strips that\n * representation noise — it lives at significant digit 16–17 — before\n * ceiling, so only genuine sub-cent digits round up. The cents guard\n * afterwards rejects the corner where noise-stripping pushes a value within\n * float64 noise of the cap up through it.\n */\nexport function normalizeMinimumDeposit(value: unknown): string | null {\n if (typeof value !== 'number' || !Number.isFinite(value)) return null;\n if (value <= 0 || value >= MAX_MINIMUM_DEPOSIT_USD) return null;\n const cents = Math.ceil(Number((value * 100).toPrecision(15)));\n if (cents <= 0 || cents >= MAX_MINIMUM_DEPOSIT_USD * 100) return null;\n return (cents / 100).toFixed(2);\n}\n","// ── EIP-6963 Wallet Discoverer (parent-frame) ──────────────────────────\n//\n// Some browser-extension wallets (notably Uniswap and Rainbow) inject\n// `window.ethereum` and dispatch EIP-6963 announcements only into the\n// top-level frame. Inside our cross-origin payment iframe, wagmi's MIPD\n// scan never sees them.\n//\n// This module runs in the parent frame (the merchant page that loads\n// `@swype-org/deposit`). It listens for EIP-6963 announcements, builds a\n// registry of installed providers keyed by their EIP-6963 `info.uuid`,\n// and exposes it for the `rpcHost` to advertise into the iframe.\n//\n// Hand-off contract with the iframe lives in `messages.ts` /\n// `walletBridge/protocol.ts`.\n\nimport type {\n EIP1193Provider,\n EIP6963ProviderDetail,\n EIP6963ProviderInfo,\n} from './protocol.ts';\n\nexport interface RegisteredProvider {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\nexport interface WalletDiscovererHandle {\n /** Snapshot of currently-registered providers. */\n list(): RegisteredProvider[];\n /** Look up a single provider by EIP-6963 uuid. */\n get(uuid: string): EIP1193Provider | undefined;\n /** Subscribe to registry changes. Returns an unsubscribe callback. */\n subscribe(listener: (snapshot: RegisteredProvider[]) => void): () => void;\n /**\n * Re-dispatch `eip6963:requestProvider`. Wallets that wired up after\n * page load (or after the initial sweep) will re-announce in response.\n */\n requestProviders(): void;\n /** Tear down listeners. After this, `list()` returns `[]`. */\n destroy(): void;\n}\n\ninterface AnnounceEvent extends Event {\n detail?: EIP6963ProviderDetail;\n}\n\n/**\n * Start discovering EIP-6963 providers in the current (top-level) frame.\n *\n * Safe to call multiple times — each handle owns its own listeners and\n * registry; calling `destroy()` releases both. In practice, `createIframe`\n * spins one handle per modal open.\n */\nexport function createWalletDiscoverer(): WalletDiscovererHandle {\n if (typeof window === 'undefined') {\n return makeNoopHandle();\n }\n\n const registry = new Map<string, RegisteredProvider>();\n const listeners = new Set<(snapshot: RegisteredProvider[]) => void>();\n let destroyed = false;\n\n const onAnnounce = (event: Event) => {\n if (destroyed) return;\n const detail = (event as AnnounceEvent).detail;\n if (!isValidProviderDetail(detail)) {\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] dropping malformed EIP-6963 announcement', {\n rawInfo: (event as AnnounceEvent).detail\n && ((event as AnnounceEvent).detail as { info?: unknown }).info,\n });\n return;\n }\n\n const existing = registry.get(detail.info.uuid);\n if (existing && existing.provider === detail.provider) {\n return;\n }\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] EIP-6963 announceProvider', {\n rdns: detail.info.rdns,\n name: detail.info.name,\n uuid: detail.info.uuid,\n });\n registry.set(detail.info.uuid, {\n info: { ...detail.info },\n provider: detail.provider,\n });\n notify();\n };\n\n // EIP-6963 requires the page to listen for announcements *first*, then\n // dispatch the request. Wallets respond synchronously with their\n // provider details. Wallets that load late (slow content scripts) will\n // also auto-announce on their own once they're ready.\n window.addEventListener('eip6963:announceProvider', onAnnounce);\n requestProviders();\n\n // Mirror wagmi's `unstable_shimAsyncInject: 2_000` — a few content\n // scripts (Uniswap is one) finish wiring up after `DOMContentLoaded`,\n // so a single sweep can miss them. Re-request a handful of times in\n // the first few seconds, then stop. Each re-request is cheap (one\n // CustomEvent dispatch).\n const RESWEEP_INTERVALS_MS = [500, 1500, 3000, 6000];\n const reSweepTimers: ReturnType<typeof setTimeout>[] = [];\n for (const ms of RESWEEP_INTERVALS_MS) {\n reSweepTimers.push(\n setTimeout(() => {\n if (!destroyed) requestProviders();\n }, ms),\n );\n }\n\n function requestProviders(): void {\n try {\n window.dispatchEvent(new Event('eip6963:requestProvider'));\n } catch {\n // jsdom older than v22 throws on `new Event()` in some setups —\n // safe to swallow; real browsers always succeed here.\n }\n }\n\n function notify(): void {\n const snapshot = list();\n for (const listener of listeners) {\n try {\n listener(snapshot);\n } catch {\n // Listener errors must not break the discoverer.\n }\n }\n }\n\n function list(): RegisteredProvider[] {\n return [...registry.values()];\n }\n\n return {\n list,\n get(uuid: string): EIP1193Provider | undefined {\n return registry.get(uuid)?.provider;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n requestProviders,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n window.removeEventListener('eip6963:announceProvider', onAnnounce);\n for (const t of reSweepTimers) clearTimeout(t);\n registry.clear();\n listeners.clear();\n },\n };\n}\n\nfunction makeNoopHandle(): WalletDiscovererHandle {\n return {\n list: () => [],\n get: () => undefined,\n subscribe: () => () => {},\n requestProviders: () => {},\n destroy: () => {},\n };\n}\n\nfunction isValidProviderDetail(value: unknown): value is EIP6963ProviderDetail {\n if (!value || typeof value !== 'object') return false;\n const detail = value as Record<string, unknown>;\n const info = detail.info as Record<string, unknown> | undefined;\n const provider = detail.provider as Record<string, unknown> | undefined;\n if (!info || !provider) return false;\n if (typeof info.uuid !== 'string' || info.uuid.length === 0) return false;\n if (typeof info.name !== 'string') return false;\n if (typeof info.rdns !== 'string') return false;\n if (typeof provider.request !== 'function') return false;\n return true;\n}\n","// ── Wallet Bridge Wire Protocol ────────────────────────────────────────\n//\n// Shared between parent (`deposit-sdk`) and iframe (`swype-sdk`). Both\n// sides define the same shapes locally — there is no runtime import\n// across the postMessage boundary, only structural conformance via\n// `protocolVersion: 1`. Bumping the version to 2 is a breaking change\n// receivers must opt into; v1 receivers silently drop v2 messages and\n// fall through to legacy behavior.\n//\n// New `type` values are additive within the same `protocolVersion`: any\n// peer that doesn't recognize them returns `null` from\n// `parseBridgeMessage` and the sender falls through to its own\n// timeout/fallback path. Only bump the version when we change the wire\n// shape of an existing message.\n\n/** Current wire-protocol version. Bump on breaking changes. */\nexport const BRIDGE_PROTOCOL_VERSION = 1;\n\n// ── EIP-6963 / EIP-1193 (subset we touch) ──────────────────────────────\n\nexport interface EIP6963ProviderInfo {\n uuid: string;\n name: string;\n icon: string;\n rdns: string;\n}\n\nexport interface EIP1193RequestArgs {\n method: string;\n params?: unknown[] | Record<string, unknown>;\n}\n\nexport interface EIP1193Provider {\n request(args: EIP1193RequestArgs): Promise<unknown>;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n removeListener?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n}\n\nexport interface EIP6963ProviderDetail {\n info: EIP6963ProviderInfo;\n provider: EIP1193Provider;\n}\n\n// ── Wire messages (both directions tagged with `type`) ─────────────────\n\n/** Iframe → Parent: handshake, sent once on mount. */\nexport interface BridgeHelloMessage {\n type: 'blink:bridge-hello';\n protocolVersion: number;\n}\n\n/** Parent → Iframe: list of installed wallets the iframe can borrow. */\nexport interface WalletsAdvertisedMessage {\n type: 'blink:wallets-advertised';\n protocolVersion: number;\n wallets: AdvertisedWallet[];\n}\n\nexport interface AdvertisedWallet {\n uuid: string;\n rdns: string;\n name: string;\n icon: string;\n}\n\n/** Iframe → Parent: invoke a JSON-RPC method on a top-frame wallet. */\nexport interface RpcRequestMessage {\n type: 'blink:rpc-request';\n protocolVersion: number;\n uuid: string;\n id: string;\n method: string;\n params?: unknown[] | Record<string, unknown>;\n}\n\n/** Parent → Iframe: result of a previous `RpcRequestMessage`. */\nexport interface RpcResponseMessage {\n type: 'blink:rpc-response';\n protocolVersion: number;\n id: string;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n}\n\n/** Parent → Iframe: forwarded EIP-1193 event from a top-frame wallet. */\nexport interface RpcEventMessage {\n type: 'blink:rpc-event';\n protocolVersion: number;\n uuid: string;\n event: string;\n args: unknown[];\n}\n\n/**\n * Iframe → Parent: ask \"which advertised wallet has any of these flags\n * (e.g. `isUniswapWallet`) set as a truthy property on its provider?\".\n * Used to disambiguate Reown registry entries that lack `rdns` (e.g.\n * Uniswap, where Reown only ships `injected[].injectedId:\n * 'isUniswapWallet'`). The parent reads `provider[flag]` defensively\n * for each advertised provider and returns the first hit, or null.\n *\n * The parent answers each request once; the response is matched by\n * `id`. Cost is local property reads on already-discovered providers —\n * no network and no cross-frame I/O beyond the postMessage round-trip.\n */\nexport interface ResolveByFlagRequestMessage {\n type: 'blink:resolve-by-flag';\n protocolVersion: number;\n /** Request id, mirrored on the response so the iframe can route it. */\n id: string;\n /** Flag names to test in order; first truthy property wins. */\n flags: string[];\n}\n\n/** Parent → Iframe: result of a previous `ResolveByFlagRequestMessage`. */\nexport interface ResolveByFlagResponseMessage {\n type: 'blink:resolve-by-flag-response';\n protocolVersion: number;\n id: string;\n /** `null` when no advertised provider had any flag set. */\n match: ResolveByFlagMatch | null;\n}\n\nexport interface ResolveByFlagMatch {\n /** EIP-6963 `rdns` of the matched provider. */\n rdns: string;\n /** EIP-6963 `uuid` of the matched provider. */\n uuid: string;\n /** Which flag matched first (lets the caller log/telemeter). */\n flag: string;\n}\n\nexport type BridgeMessage =\n | BridgeHelloMessage\n | WalletsAdvertisedMessage\n | RpcRequestMessage\n | RpcResponseMessage\n | RpcEventMessage\n | ResolveByFlagRequestMessage\n | ResolveByFlagResponseMessage;\n\n// ── JSON-RPC method allowlist ──────────────────────────────────────────\n//\n// Only methods on this list are forwarded to the top-frame provider.\n// Anything else gets a `-32601 Method not allowed` rejection, mirroring\n// the JSON-RPC 2.0 \"Method not found\" error code.\n\nexport const ALLOWED_RPC_METHODS = new Set<string>([\n // Read\n 'eth_accounts',\n 'eth_blockNumber',\n 'eth_call',\n 'eth_chainId',\n 'eth_estimateGas',\n 'eth_gasPrice',\n 'eth_getBalance',\n 'eth_getCode',\n 'eth_getStorageAt',\n 'eth_getTransactionByHash',\n 'eth_getTransactionCount',\n 'eth_getTransactionReceipt',\n 'net_version',\n 'wallet_getCapabilities',\n 'wallet_getCallsStatus',\n // Write / sign\n 'eth_requestAccounts',\n 'eth_sendTransaction',\n 'eth_sendRawTransaction',\n 'eth_sign',\n 'personal_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_sendCalls',\n 'wallet_watchAsset',\n // EIP-2255: lets the SDK revoke the dApp's `eth_accounts` grant before\n // re-prompting on \"+ Add wallet\" / back-from-setup, so MetaMask shows the\n // account picker instead of silently reusing the previously-permitted\n // account. Wallets that don't implement it return method-not-supported,\n // which the SDK swallows.\n 'wallet_revokePermissions',\n]);\n\n// ── Forwarded EIP-1193 events ──────────────────────────────────────────\n\nexport const FORWARDED_PROVIDER_EVENTS = [\n 'accountsChanged',\n 'chainChanged',\n 'connect',\n 'disconnect',\n 'message',\n] as const;\n\nexport type ForwardedProviderEvent = (typeof FORWARDED_PROVIDER_EVENTS)[number];\n\n// ── Parsers (used by both sides) ───────────────────────────────────────\n\nexport function parseBridgeMessage(data: unknown): BridgeMessage | null {\n if (!data || typeof data !== 'object') return null;\n const msg = data as Record<string, unknown>;\n if (msg.protocolVersion !== BRIDGE_PROTOCOL_VERSION) return null;\n switch (msg.type) {\n case 'blink:bridge-hello':\n return msg as unknown as BridgeHelloMessage;\n case 'blink:wallets-advertised':\n return Array.isArray(msg.wallets) ? (msg as unknown as WalletsAdvertisedMessage) : null;\n case 'blink:rpc-request':\n if (typeof msg.uuid !== 'string' || typeof msg.id !== 'string' || typeof msg.method !== 'string') {\n return null;\n }\n return msg as unknown as RpcRequestMessage;\n case 'blink:rpc-response':\n if (typeof msg.id !== 'string') return null;\n return msg as unknown as RpcResponseMessage;\n case 'blink:rpc-event':\n if (typeof msg.uuid !== 'string' || typeof msg.event !== 'string' || !Array.isArray(msg.args)) {\n return null;\n }\n return msg as unknown as RpcEventMessage;\n case 'blink:resolve-by-flag':\n if (typeof msg.id !== 'string' || !Array.isArray(msg.flags)) return null;\n // Defensive: every flag must be a non-empty string. Reject the\n // whole message rather than silently filtering to keep the\n // request/response semantics honest.\n if (!msg.flags.every((f) => typeof f === 'string' && f.length > 0)) return null;\n return msg as unknown as ResolveByFlagRequestMessage;\n case 'blink:resolve-by-flag-response':\n if (typeof msg.id !== 'string') return null;\n // `match` may be null or an object with rdns/uuid/flag; the\n // caller validates the inner shape.\n if (msg.match !== null && (typeof msg.match !== 'object' || !msg.match)) return null;\n return msg as unknown as ResolveByFlagResponseMessage;\n default:\n return null;\n }\n}\n","// ── Wallet Bridge RPC Host (parent-frame) ──────────────────────────────\n//\n// Exposes top-frame EIP-1193 providers to the cross-origin iframe over\n// `postMessage`. Built on top of `WalletDiscovererHandle` (the EIP-6963\n// registry) and the wire protocol in `protocol.ts`.\n//\n// Security model:\n// - Origin-pinned: only `event.origin === iframeOrigin` is honored.\n// - Source-pinned: only messages whose `event.source === iframeWindow`\n// are honored (defends against rogue iframes on the same page).\n// - Method allowlist: anything outside `ALLOWED_RPC_METHODS` rejects\n// with JSON-RPC `-32601 Method not allowed`. Defense in depth — the\n// iframe SDK is trusted, but we don't want a future SDK regression\n// to expose, say, `eth_signTransaction` (offline signing) by accident.\n//\n// Backwards-compat: this host responds to `blink:bridge-hello` with the\n// current advertisement. Old iframes never send the hello and never send\n// `blink:rpc-request`, so the host is silent for them.\n\nimport type { WalletDiscovererHandle, RegisteredProvider } from './discover.ts';\nimport {\n ALLOWED_RPC_METHODS,\n BRIDGE_PROTOCOL_VERSION,\n FORWARDED_PROVIDER_EVENTS,\n parseBridgeMessage,\n type AdvertisedWallet,\n type EIP1193Provider,\n type ResolveByFlagMatch,\n type ResolveByFlagResponseMessage,\n type RpcEventMessage,\n type RpcResponseMessage,\n type WalletsAdvertisedMessage,\n type ForwardedProviderEvent,\n} from './protocol.ts';\n\nexport interface RpcHostHandle {\n /** Tear down listeners and unsubscribe from all bridged providers. */\n detach(): void;\n}\n\nexport interface RpcHostOptions {\n /** Cross-origin iframe window we're talking to. */\n iframeWindow: Window;\n /** Origin of the iframe — origin-pin all postMessage send/receive. */\n iframeOrigin: string;\n /** Discoverer providing the EIP-6963 provider registry. */\n discoverer: WalletDiscovererHandle;\n /** Optional debug logger; defaults to a no-op. */\n log?: (message: string, data?: Record<string, unknown>) => void;\n}\n\ninterface SubscriptionRecord {\n provider: EIP1193Provider;\n listeners: Map<ForwardedProviderEvent, (...args: unknown[]) => void>;\n}\n\n/**\n * Attach an RPC host to the given iframe. Listens on `window` for\n * messages from the iframe and routes allowlisted JSON-RPC calls to the\n * matching top-frame EIP-1193 provider.\n */\nexport function attachRpcHost(options: RpcHostOptions): RpcHostHandle {\n const { iframeWindow, iframeOrigin, discoverer } = options;\n const log = options.log ?? noopLog;\n\n if (typeof window === 'undefined') {\n return { detach: () => {} };\n }\n\n let detached = false;\n const subscriptions = new Map<string, SubscriptionRecord>();\n const unsubscribeFromDiscoverer = discoverer.subscribe((snapshot) => {\n if (detached) return;\n advertiseWallets(snapshot);\n });\n\n function postToIframe(message: object): void {\n if (detached) return;\n try {\n iframeWindow.postMessage(message, iframeOrigin);\n } catch (err) {\n log('postMessage to iframe failed', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n // Advertised-list fingerprint of the last `blink:wallets-advertised`\n // post. Wallets re-announce fresh provider instances on EIP-6963\n // resweeps, which changes the discoverer registry (RPC routing must use\n // the newest instance) without changing the advertised POJO list — those\n // must not be re-broadcast, since each one rebuilds the iframe's wagmi\n // config and can orphan an in-flight connect.\n let lastAdvertisedKey: string | null = null;\n\n function advertiseWallets(snapshot: RegisteredProvider[], opts?: { force?: boolean }): void {\n const wallets: AdvertisedWallet[] = snapshot.map((entry) => ({\n uuid: entry.info.uuid,\n rdns: entry.info.rdns,\n name: entry.info.name,\n icon: entry.info.icon,\n }));\n const key = JSON.stringify(wallets.map((w) => [w.uuid, w.rdns, w.name, w.icon]));\n // `force` is the bridge-hello handshake ack — the iframe's\n // `bridgeAvailable` flag depends on it, so it always posts.\n if (!opts?.force && key === lastAdvertisedKey) {\n log('skipping identical re-advertisement', { count: wallets.length });\n return;\n }\n lastAdvertisedKey = key;\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] advertising wallets', wallets.map((w) => ({\n rdns: w.rdns,\n name: w.name,\n })));\n const message: WalletsAdvertisedMessage = {\n type: 'blink:wallets-advertised',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n wallets,\n };\n postToIframe(message);\n }\n\n function ensureSubscription(uuid: string, provider: EIP1193Provider): void {\n if (subscriptions.has(uuid)) return;\n if (typeof provider.on !== 'function') {\n // No event support — record an empty subscription so we don't keep\n // re-checking on every request.\n subscriptions.set(uuid, { provider, listeners: new Map() });\n return;\n }\n const record: SubscriptionRecord = { provider, listeners: new Map() };\n for (const event of FORWARDED_PROVIDER_EVENTS) {\n const listener = (...args: unknown[]) => {\n const eventMessage: RpcEventMessage = {\n type: 'blink:rpc-event',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n uuid,\n event,\n args,\n };\n postToIframe(eventMessage);\n };\n try {\n provider.on(event, listener);\n record.listeners.set(event, listener);\n } catch (err) {\n log(`provider.on('${event}') threw — skipping that event`, {\n uuid,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n subscriptions.set(uuid, record);\n }\n\n function unsubscribeAll(): void {\n for (const [, record] of subscriptions) {\n const provider = record.provider;\n if (typeof provider.removeListener !== 'function') continue;\n for (const [event, listener] of record.listeners) {\n try {\n provider.removeListener(event, listener);\n } catch {\n // Provider close may have already cleaned up — safe to ignore.\n }\n }\n }\n subscriptions.clear();\n }\n\n function sendError(id: string, code: number, message: string, data?: unknown): void {\n const response: RpcResponseMessage = {\n type: 'blink:rpc-response',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n };\n postToIframe(response);\n }\n\n function sendResult(id: string, result: unknown): void {\n const response: RpcResponseMessage = {\n type: 'blink:rpc-response',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n id,\n result,\n };\n postToIframe(response);\n }\n\n const onMessage = (event: MessageEvent) => {\n if (detached) return;\n if (event.source !== iframeWindow) return;\n if (event.origin !== iframeOrigin) return;\n const message = parseBridgeMessage(event.data);\n if (!message) return;\n\n switch (message.type) {\n case 'blink:bridge-hello': {\n // New-protocol iframe is asking \"are you there?\" Reply with the\n // current registry, even if empty. The iframe uses this to flip\n // its `bridgeAvailable` flag.\n advertiseWallets(discoverer.list(), { force: true });\n // Some wallets only finish wiring up after page load — re-request\n // EIP-6963 announcements once the iframe is alive too.\n discoverer.requestProviders();\n return;\n }\n case 'blink:rpc-request': {\n const { id, uuid, method, params } = message;\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] rpc-request', { uuid, method });\n if (!ALLOWED_RPC_METHODS.has(method)) {\n log('rejecting non-allowlisted method', { uuid, method });\n sendError(id, -32601, `Method not allowed: ${method}`);\n return;\n }\n const provider = discoverer.get(uuid);\n if (!provider) {\n log('no provider for uuid', { uuid, method });\n sendError(id, -32602, `Unknown wallet: ${uuid}`);\n return;\n }\n ensureSubscription(uuid, provider);\n provider\n .request({ method, params })\n .then((result) => {\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] rpc-result', { uuid, method, ok: true });\n sendResult(id, result);\n })\n .catch((err: unknown) => {\n const { code, message: errMessage, data } = normalizeProviderError(err);\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] rpc-error', { uuid, method, code, message: errMessage });\n sendError(id, code, errMessage, data);\n });\n return;\n }\n case 'blink:resolve-by-flag': {\n const match = resolveByFlag(discoverer.list(), message.flags, log);\n // eslint-disable-next-line no-console\n console.info('[blink-bridge:parent] resolveByFlag', {\n flags: message.flags,\n match: match ? { rdns: match.rdns, flag: match.flag } : null,\n });\n const response: ResolveByFlagResponseMessage = {\n type: 'blink:resolve-by-flag-response',\n protocolVersion: BRIDGE_PROTOCOL_VERSION,\n id: message.id,\n match,\n };\n postToIframe(response);\n return;\n }\n case 'blink:wallets-advertised':\n case 'blink:rpc-response':\n case 'blink:rpc-event':\n case 'blink:resolve-by-flag-response':\n // These are parent → iframe messages. If we receive them, the\n // peer is misconfigured — ignore.\n return;\n }\n };\n\n window.addEventListener('message', onMessage);\n\n return {\n detach() {\n if (detached) return;\n detached = true;\n window.removeEventListener('message', onMessage);\n unsubscribeFromDiscoverer();\n unsubscribeAll();\n },\n };\n}\n\nfunction noopLog(): void {}\n\n/**\n * Walk the registered providers and return the first that has any of\n * the requested flags set as a truthy property (e.g. `isUniswapWallet`,\n * `isRainbow`). Used by the iframe to resolve Reown registry entries\n * that lack `rdns` but ship an `injectedId` flag.\n *\n * Per-provider reads are wrapped in try/catch because some wallets\n * proxy `window.ethereum` and throw on unknown property access.\n */\nfunction resolveByFlag(\n snapshot: RegisteredProvider[],\n flags: string[],\n log: (message: string, data?: Record<string, unknown>) => void,\n): ResolveByFlagMatch | null {\n for (const flag of flags) {\n for (const entry of snapshot) {\n let value: unknown;\n try {\n value = (entry.provider as unknown as Record<string, unknown>)[flag];\n } catch (err) {\n log('provider threw on flag read — skipping', {\n rdns: entry.info.rdns,\n flag,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n if (value) {\n return { rdns: entry.info.rdns, uuid: entry.info.uuid, flag };\n }\n }\n }\n return null;\n}\n\ninterface NormalizedProviderError {\n code: number;\n message: string;\n data?: unknown;\n}\n\n/**\n * Coerce whatever an EIP-1193 provider threw into a JSON-RPC-shaped\n * error. Most wallets already throw `{ code, message, data? }`; we just\n * shape it. Anything else gets a generic -32603 (internal error).\n */\nfunction normalizeProviderError(err: unknown): NormalizedProviderError {\n if (err && typeof err === 'object') {\n const e = err as Record<string, unknown>;\n const code = typeof e.code === 'number' ? e.code : -32603;\n const message =\n typeof e.message === 'string'\n ? e.message\n : err instanceof Error\n ? err.message\n : 'Provider error';\n const data = 'data' in e ? e.data : undefined;\n return data === undefined ? { code, message } : { code, message, data };\n }\n return { code: -32603, message: typeof err === 'string' ? err : 'Provider error' };\n}\n","// ── Merchant-page viewport metrics for the fluid layout ──────────────\n//\n// The fluid iframe fills the overlay (`position: fixed; inset: 0`), which on\n// iOS tracks the *current* viewport — it shrinks and grows as the browser's\n// collapsible chrome (URL bar) shows and hides. Inside the iframe, `dvh`\n// therefore resolves against that moving target, while the legacy\n// parent-side sheet was sized with `79vh` = 79% of the *large* viewport\n// (chrome hidden) — a constant. Only the merchant page can measure the\n// large viewport and its safe-area inset, so the SDK probes them here and\n// ships them to the hosted flow (URL params at creation, `blink:viewport`\n// messages on resize/orientation change).\n\nexport interface ViewportMetrics {\n /** Merchant page's large-viewport height (100lvh) in CSS px, rounded. */\n viewportLvh: number;\n /** Merchant page's `env(safe-area-inset-bottom)` in CSS px, rounded. */\n safeAreaBottom: number;\n}\n\n/**\n * Measure via a hidden fixed probe. `100lvh` needs iOS 15.4+/Chrome 108+;\n * on older browsers the declaration is dropped and the probe collapses to\n * zero height, so `window.innerHeight` (the current viewport) is used\n * instead — a degraded but sane basis. Returns zeros outside a DOM.\n */\nexport function measureViewportMetrics(): ViewportMetrics {\n const unavailable: ViewportMetrics = { viewportLvh: 0, safeAreaBottom: 0 };\n if (\n typeof document === 'undefined' ||\n typeof window === 'undefined' ||\n typeof window.getComputedStyle !== 'function' ||\n !document.body\n ) {\n return unavailable;\n }\n\n // Measurement is a nicety — it must never break the payment flow. Any\n // DOM surprise (exotic embeds, sandboxed contexts) degrades to zeros,\n // which callers treat as \"metrics unavailable\".\n try {\n const probe = document.createElement('div');\n probe.style.cssText =\n 'position:fixed;top:0;left:0;width:0;visibility:hidden;pointer-events:none;' +\n 'height:100lvh;padding-bottom:env(safe-area-inset-bottom,0px)';\n document.body.appendChild(probe);\n\n let viewportLvh = 0;\n let safeAreaBottom = 0;\n try {\n const computed = window.getComputedStyle(probe);\n viewportLvh = Math.round(Number.parseFloat(computed.height) || 0);\n safeAreaBottom = Math.round(Number.parseFloat(computed.paddingBottom) || 0);\n } finally {\n probe.remove();\n }\n\n if (viewportLvh <= 0) {\n // `100lvh` needs iOS 15.4+/Chrome 108+; older browsers drop the\n // declaration and the probe collapses. The current viewport is a\n // degraded but sane basis there.\n viewportLvh = Math.round(window.innerHeight || 0);\n }\n\n return { viewportLvh, safeAreaBottom };\n } catch {\n return unavailable;\n }\n}\n","// ── Shared frame plumbing (presentation-independent) ──────────────────\n//\n// Everything here is common to every way the hosted flow can be presented:\n// the overlay modal (iframe.ts) and the inline embed (embeddedIframe.ts).\n// It deliberately owns the two things that must never be duplicated:\n//\n// 1. The `allow` attribute. Passkey ceremonies are a WebAuthn correctness\n// and security invariant — a presenter that forgot a delegation, or\n// spelled an origin differently, would fail silently at the credential\n// call. One definition, one place.\n// 2. The wallet-bridge attach/detach lifecycle, whose ordering is not\n// obvious (attach eagerly for browsers that populate `contentWindow`\n// synchronously, then again on `load` for the cross-origin case).\n//\n// What is NOT here is presentation: backdrops, scroll locks, dismissal,\n// animations, geometry. Those share nothing between the two modes, which is\n// why this is a shared core with thin presenters rather than one function\n// with a mode flag.\n\nimport { createWalletDiscoverer } from './walletBridge/discover.ts';\nimport { attachRpcHost, type RpcHostHandle } from './walletBridge/rpcHost.ts';\nimport { buildRevealMessage, buildViewportMessage } from './messages.ts';\nimport { measureViewportMetrics } from './viewportMetrics.ts';\n\n/** The iframe element plus the origin every message to it must target. */\nexport interface FrameElement {\n iframe: HTMLIFrameElement;\n iframeOrigin: string;\n}\n\n/**\n * Create the hosted-flow iframe with the Permissions-Policy delegations the\n * flow needs. `publickey-credentials-*` are required for passkey signup and\n * login; `clipboard-write` for copying deposit addresses; `web-share` for\n * handing a Blink Boost card to the OS share sheet.\n *\n * `web-share` defaults to `self`, so without the delegation the hosted flow's\n * `navigator.canShare({ files })` answers false inside this frame — not because\n * the device cannot share, but because we never asked. On mobile that silently\n * routed the Boost share down the DESKTOP path: no share sheet, no image, just\n * X's web composer in a new tab. There is no way for the hosted flow to detect\n * the difference, which is why the delegation belongs here rather than a\n * fallback there.\n */\nexport function createFrameElement(url: string): FrameElement {\n const iframe = document.createElement('iframe');\n iframe.src = url;\n\n const iframeOrigin = new URL(url).origin;\n iframe.allow =\n `publickey-credentials-get ${iframeOrigin}; publickey-credentials-create ${iframeOrigin}; clipboard-write ${iframeOrigin}; web-share ${iframeOrigin}`;\n\n return { iframe, iframeOrigin };\n}\n\nexport interface FrameBridges {\n /**\n * Post `blink:reveal` so the hosted flow plays its entry animation. Safe\n * before load — the hosted page buffers the signal — and idempotent.\n */\n postReveal(): void;\n /**\n * Post the host page's viewport metrics (and, in embedded presentation,\n * the height budget). No-op when the presenter opted out.\n */\n postViewportMetrics(): void;\n detach(): void;\n}\n\nexport interface AttachFrameBridgesOptions extends FrameElement {\n /**\n * Whether this presentation needs viewport metrics at all. The legacy\n * fixed overlay sizes the iframe itself and ignores them; fluid and\n * embedded both depend on them.\n */\n postViewport: boolean;\n /**\n * Embedded presentation: the current height budget, read at post time so a\n * host that changes it mid-flow is picked up by the next resize.\n */\n getEmbedMaxHeightPx?: () => number | undefined;\n /**\n * Whether a freshly loaded document should be revealed immediately. A\n * visible-from-birth frame is \"revealed\" as soon as its document exists; a\n * hidden warm-up waits for an explicit `reveal()`.\n */\n shouldRevealOnLoad: () => boolean;\n}\n\n/**\n * Wire up the top-frame wallet bridge, the reveal/viewport message channel,\n * and the host-viewport listeners for one frame.\n *\n * Wallet bridge: discovers EIP-6963 wallets in this frame (Uniswap, Rainbow,\n * and any other extension that doesn't inject into iframes) and exposes them\n * to the hosted flow over postMessage. Old iframes that don't know about the\n * bridge never send a hello; the host stays silent for them — strictly\n * additive behavior.\n */\nexport function attachFrameBridges(options: AttachFrameBridgesOptions): FrameBridges {\n const { iframe, iframeOrigin, postViewport, getEmbedMaxHeightPx, shouldRevealOnLoad } = options;\n\n let detached = false;\n\n const discoverer = createWalletDiscoverer();\n let rpcHostHandle: RpcHostHandle | null = null;\n\n const attachBridge = () => {\n if (rpcHostHandle) return;\n if (!iframe.contentWindow) return;\n rpcHostHandle = attachRpcHost({\n iframeWindow: iframe.contentWindow,\n iframeOrigin,\n discoverer,\n });\n };\n // Try once now (some browsers populate contentWindow eagerly) and again on\n // `load` for the cross-origin case.\n attachBridge();\n iframe.addEventListener('load', attachBridge);\n\n function postReveal(): void {\n if (detached) return;\n iframe.contentWindow?.postMessage(buildRevealMessage(), iframeOrigin);\n }\n\n function postViewportMetrics(): void {\n if (detached || !postViewport) return;\n const metrics = measureViewportMetrics();\n if (metrics.viewportLvh <= 0) return;\n iframe.contentWindow?.postMessage(\n buildViewportMessage(\n metrics.viewportLvh,\n metrics.safeAreaBottom,\n getEmbedMaxHeightPx?.(),\n ),\n iframeOrigin,\n );\n }\n\n // Keep the hosted flow's geometry anchored to the host page's large\n // viewport across rotations and window resizes. rAF-coalesced — iOS fires\n // resize storms while the browser chrome animates.\n let viewportPostScheduled = false;\n const onViewportChange = () => {\n if (viewportPostScheduled) return;\n viewportPostScheduled = true;\n requestAnimationFrame(() => {\n viewportPostScheduled = false;\n postViewportMetrics();\n });\n };\n if (postViewport) {\n window.addEventListener('resize', onViewportChange);\n window.addEventListener('orientationchange', onViewportChange);\n }\n\n // A visible-from-birth frame (no warm-up) is revealed as soon as its\n // document exists: post the reveal on load so the hosted flow plays its\n // entry animation without waiting for an explicit reveal() call. The\n // hosted page treats blink:reveal as idempotent. Viewport metrics ride\n // along so geometry is settled before first paint even if the URL-param\n // seed went stale during a slow load.\n const onLoadReveal = () => {\n postViewportMetrics();\n if (shouldRevealOnLoad()) postReveal();\n };\n iframe.addEventListener('load', onLoadReveal);\n\n return {\n postReveal,\n postViewportMetrics,\n detach(): void {\n if (detached) return;\n detached = true;\n iframe.removeEventListener('load', attachBridge);\n iframe.removeEventListener('load', onLoadReveal);\n window.removeEventListener('resize', onViewportChange);\n window.removeEventListener('orientationchange', onViewportChange);\n if (rpcHostHandle) {\n rpcHostHandle.detach();\n rpcHostHandle = null;\n }\n discoverer.destroy();\n },\n };\n}\n","import { attachFrameBridges, createFrameElement, type FrameBridges } from './iframeCore.ts';\n\nconst STYLE_ID = 'blink-deposit-styles';\n\nconst CLOSE_DURATION_MS = 280;\nconst MOBILE_SHEET_MAX_VIEWPORT_PX = 640;\nconst MOBILE_SHEET_MAX_SCREEN_PX = 900;\n\n// The iframe's color-scheme must be an explicit `light`, not `normal`: normal\n// resolves to the merchant page's default scheme, so a merchant-declared\n// color-scheme:dark makes Chromium see a scheme mismatch with the light hosted\n// document and paint the cross-origin iframe on an opaque white backplate —\n// solid white over the whole viewport instead of the dim showing the page.\nconst STYLES = `\n@keyframes blink-fade-in{from{opacity:0}to{opacity:1}}\n@keyframes blink-fade-out{from{opacity:1}to{opacity:0}}\n@keyframes blink-slide-up{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}\n@keyframes blink-slide-up-full{from{transform:translateY(100%)}to{transform:translateY(0)}}\n@keyframes blink-slide-down-full{from{transform:translateY(0)}to{transform:translateY(100%)}}\n[data-blink-overlay]{position:fixed;inset:0;background:rgba(0,0,0,.6);display:flex;align-items:center;justify-content:center;z-index:2147483647;animation:blink-fade-in .2s ease-out;backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px)}\n[data-blink-overlay][data-blink-closing]{animation:blink-fade-out ${CLOSE_DURATION_MS}ms ease-in forwards;pointer-events:none}\n[data-blink-overlay][data-blink-mobile-sheet]{align-items:flex-end;touch-action:none;overscroll-behavior:contain}\n[data-blink-container]{width:min(420px,92vw);height:min(600px,85vh);border-radius:24px;overflow:hidden;box-shadow:0 24px 80px rgba(0,0,0,.4);animation:blink-slide-up .25s ease-out;display:flex;flex-direction:column;background:transparent}\n[data-blink-overlay][data-blink-closing] [data-blink-container]{opacity:0;transition:opacity ${CLOSE_DURATION_MS}ms ease-in}\n[data-blink-container] iframe{width:100%;flex:1;border:none;display:block;background:transparent;color-scheme:light;border-radius:inherit}\n[data-blink-overlay][data-blink-mobile-sheet] [data-blink-container]{width:100%;max-width:100%;height:79vh;border-radius:24px 24px 0 0;box-shadow:0 -8px 40px rgba(0,0,0,.25);animation:blink-slide-up-full .35s cubic-bezier(.32,.72,0,1);padding-bottom:env(safe-area-inset-bottom,0px)}\n[data-blink-overlay][data-blink-mobile-sheet][data-blink-closing] [data-blink-container]{opacity:1;animation:blink-slide-down-full ${CLOSE_DURATION_MS}ms ease-in forwards}\n@media(max-width:${MOBILE_SHEET_MAX_VIEWPORT_PX}px){[data-blink-overlay]{align-items:flex-end;touch-action:none;overscroll-behavior:contain}[data-blink-container]{width:100%;max-width:100%;height:79vh;border-radius:24px 24px 0 0;box-shadow:0 -8px 40px rgba(0,0,0,.25);animation:blink-slide-up-full .35s cubic-bezier(.32,.72,0,1);padding-bottom:env(safe-area-inset-bottom,0px)}[data-blink-overlay][data-blink-closing] [data-blink-container]{opacity:1;animation:blink-slide-down-full ${CLOSE_DURATION_MS}ms ease-in forwards}}\n[data-blink-overlay][data-blink-fluid] [data-blink-container],[data-blink-overlay][data-blink-fluid][data-blink-mobile-sheet] [data-blink-container]{width:100%;max-width:100%;height:100%;max-height:100%;border-radius:0;box-shadow:none;animation:none;background:transparent;padding-bottom:0}\n[data-blink-overlay][data-blink-fluid][data-blink-closing] [data-blink-container]{animation:none;transition:none;opacity:1}\n`;\n\nexport interface IframeHandle {\n readonly contentWindow: Window | null;\n close(): void;\n isClosed(): boolean;\n isHidden(): boolean;\n /**\n * Make a `hidden: true` overlay visible: re-evaluates the mobile-sheet\n * layout for the current viewport, locks body scroll, and attaches the\n * backdrop/Escape dismissal listeners. No-op when already visible or\n * closed. The iframe element is never reparented — moving an iframe in the\n * DOM reloads it, which would throw away the warmed-up document.\n */\n reveal(): void;\n /**\n * Post `blink:reveal` to the hosted flow so it plays its entry animation\n * (fluid mode renders the card chrome inside the iframe). Safe to call\n * before the iframe has loaded — the hosted page buffers the signal, and\n * `createIframe` re-posts on the iframe `load` event while visible.\n */\n postReveal(): void;\n /**\n * Revert a fluid overlay to the legacy fixed-size container by removing\n * `data-blink-fluid` — pure CSS, the iframe is never reparented (moving an\n * iframe in the DOM reloads it). Used when the hosted flow's ready message\n * does not advertise the `layout-fluid` capability (an older webview\n * deployment), so it renders fill-mode into the fixed container as today.\n */\n downgradeToFixed(): void;\n /**\n * Embedded presentation only: size the inline iframe element to the height\n * the hosted flow just reported. No-op for the overlay, whose geometry is\n * viewport-derived and owned by CSS.\n */\n applyContentHeight(heightPx: number): void;\n onClose(callback: () => void): void;\n destroy(): void;\n}\n\nexport interface CreateIframeOptions {\n /**\n * Create the overlay invisible (`display: none`) for background warm-up:\n * the iframe document loads normally, but there is no backdrop, no body\n * scroll-lock, and no dismissal listeners until `reveal()` is called.\n */\n hidden?: boolean;\n /**\n * Full-viewport transparent container: the card/sheet chrome (size, radius,\n * shadow, entry/exit animations) is rendered by the hosted flow inside the\n * iframe instead of by this overlay. The dim + blur backdrop stays on the\n * overlay — an iframe cannot `backdrop-filter` the page behind itself.\n * Requires a webview that understands `layout=fluid`; pair with\n * `downgradeToFixed()` when the ready handshake lacks the capability.\n */\n fluid?: boolean;\n}\n\n/**\n * Create a modal overlay with a cross-origin iframe pointing to the hosted\n * checkout flow. The iframe has the Permissions-Policy attributes required\n * for WebAuthn passkey ceremonies.\n *\n * The overlay is dismissed when the user clicks the backdrop, presses\n * Escape, or the hosted flow sends a `blink:close-request` postMessage.\n */\nexport function createIframe(\n url: string,\n containerElement?: HTMLElement,\n options?: CreateIframeOptions,\n): IframeHandle {\n ensureStyles();\n\n let closed = false;\n let hidden = options?.hidden === true;\n let closeCallback: (() => void) | null = null;\n\n const overlay = document.createElement('div');\n overlay.setAttribute('data-blink-overlay', '');\n if (shouldUseMobileSheetLayout()) {\n overlay.setAttribute('data-blink-mobile-sheet', '');\n }\n if (options?.fluid) {\n overlay.setAttribute('data-blink-fluid', '');\n }\n if (hidden) {\n overlay.style.display = 'none';\n }\n\n const container = document.createElement('div');\n container.setAttribute('data-blink-container', '');\n\n const { iframe, iframeOrigin } = createFrameElement(url);\n\n const handle = document.createElement('div');\n\n container.appendChild(handle);\n container.appendChild(iframe);\n overlay.appendChild(container);\n\n const mountTarget = containerElement ?? document.body;\n mountTarget.appendChild(overlay);\n\n const bridges: FrameBridges = attachFrameBridges({\n iframe,\n iframeOrigin,\n // Only fluid needs them: the legacy fixed overlay sizes the iframe itself.\n postViewport: options?.fluid === true,\n shouldRevealOnLoad: () => !hidden,\n });\n\n let savedOverflow = '';\n let scrollLocked = false;\n\n const onBackdropClick = (event: MouseEvent) => {\n if (event.target === overlay) triggerClose();\n };\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') triggerClose();\n };\n\n const onTouchMove = (event: TouchEvent) => {\n if (event.target === overlay) event.preventDefault();\n };\n\n function lockScroll(): void {\n if (scrollLocked) return;\n scrollLocked = true;\n savedOverflow = document.body.style.overflow;\n document.body.style.overflow = 'hidden';\n }\n\n function attachDismissalListeners(): void {\n overlay.addEventListener('click', onBackdropClick);\n overlay.addEventListener('touchmove', onTouchMove, { passive: false });\n document.addEventListener('keydown', onKeyDown);\n }\n\n // Hidden warm-up overlays must not trap Escape/scroll while invisible —\n // the host page doesn't know they exist yet.\n if (!hidden) {\n lockScroll();\n attachDismissalListeners();\n }\n\n function removeListeners(): void {\n overlay.removeEventListener('click', onBackdropClick);\n overlay.removeEventListener('touchmove', onTouchMove);\n document.removeEventListener('keydown', onKeyDown);\n }\n\n function unlockScroll(): void {\n if (!scrollLocked) return;\n scrollLocked = false;\n document.body.style.overflow = savedOverflow;\n }\n\n function triggerClose(): void {\n if (closed) return;\n closed = true;\n removeListeners();\n bridges.detach();\n\n overlay.setAttribute('data-blink-closing', '');\n\n let removed = false;\n const removeOverlay = () => {\n if (removed) return;\n removed = true;\n overlay.remove();\n unlockScroll();\n closeCallback?.();\n };\n\n container.addEventListener('animationend', removeOverlay, { once: true });\n setTimeout(removeOverlay, CLOSE_DURATION_MS + 50);\n }\n\n return {\n get contentWindow(): Window | null {\n return iframe.contentWindow;\n },\n\n close(): void {\n triggerClose();\n },\n\n isClosed(): boolean {\n return closed;\n },\n\n isHidden(): boolean {\n return hidden;\n },\n\n reveal(): void {\n if (closed || !hidden) return;\n hidden = false;\n // The viewport may have changed (resize/rotation) since the hidden\n // warm-up overlay was created — re-evaluate the sheet layout now.\n if (shouldUseMobileSheetLayout()) {\n overlay.setAttribute('data-blink-mobile-sheet', '');\n } else {\n overlay.removeAttribute('data-blink-mobile-sheet');\n }\n overlay.style.display = '';\n lockScroll();\n attachDismissalListeners();\n bridges.postViewportMetrics();\n bridges.postReveal();\n },\n\n postReveal(): void {\n bridges.postReveal();\n },\n\n downgradeToFixed(): void {\n overlay.removeAttribute('data-blink-fluid');\n },\n\n applyContentHeight(): void {\n // The overlay's card is sized by CSS against the viewport; content\n // height reports are an embedded-only channel and never arrive here.\n },\n\n onClose(callback: () => void): void {\n closeCallback = callback;\n },\n\n destroy(): void {\n closeCallback = null;\n if (!closed) {\n closed = true;\n removeListeners();\n bridges.detach();\n overlay.remove();\n unlockScroll();\n }\n },\n };\n}\n\nfunction ensureStyles(): void {\n const existingStyle = document.getElementById(STYLE_ID);\n if (existingStyle) {\n if (existingStyle.textContent !== STYLES) {\n existingStyle.textContent = STYLES;\n }\n return;\n }\n const style = document.createElement('style');\n style.id = STYLE_ID;\n style.textContent = STYLES;\n document.head.appendChild(style);\n}\n\n/**\n * Whether this device should get the mobile bottom sheet rather than the\n * centered desktop card. Narrow viewport, or a coarse pointer on a\n * phone-sized screen.\n *\n * Also the predicate `checkout.ts` uses to decide that an *embedded* flow\n * presents as a normal overlay on mobile — one rule for \"this is a phone\", so\n * the presentation and the sheet chrome inside it can never disagree.\n */\nexport function shouldUseMobileSheetLayout(): boolean {\n if (typeof window === 'undefined') return false;\n\n if (window.matchMedia?.(`(max-width: ${MOBILE_SHEET_MAX_VIEWPORT_PX}px)`).matches) {\n return true;\n }\n\n const viewportWidth = window.visualViewport?.width ?? window.innerWidth;\n if (viewportWidth > 0 && viewportWidth <= MOBILE_SHEET_MAX_VIEWPORT_PX) {\n return true;\n }\n\n const hasCoarsePointer = window.matchMedia?.('(pointer: coarse)').matches ?? false;\n if (!hasCoarsePointer) {\n return false;\n }\n\n const shortestScreenSide = Math.min(window.screen.width, window.screen.height);\n return shortestScreenSide > 0 && shortestScreenSide <= MOBILE_SHEET_MAX_SCREEN_PX;\n}\n","// ── Embedded presentation ─────────────────────────────────────────────\n//\n// Mounts the hosted flow INLINE inside a host widget — a payment-method\n// aggregator listing Blink beside Card / Bank / Wallet — instead of as a\n// full-viewport modal.\n//\n// What this deliberately does NOT do, and why:\n//\n// • No overlay, backdrop, blur, or z-index. There is nothing to dim; the\n// host's own panel is the surface.\n// • No body scroll lock. The host already owns page scroll (an aggregator\n// opening its widget in a dialog has typically locked it), and a second\n// lock would fight theirs on teardown.\n// • No backdrop-click or document-level Escape dismissal. Inline, \"the user\n// pressed Escape\" is the host's event to interpret, not ours — stealing\n// it would close Blink out from under a host that meant to close its own\n// dialog. The in-flow close control still posts `blink:close-request`.\n// • No close animation. There is no card flying out; the host removes the\n// element or animates its own panel.\n// • No mobile-sheet heuristic. Inside a host widget the device signals\n// describe the device, not the slot — a narrow embed on a wide desktop\n// would otherwise present as a swipeable bottom sheet.\n//\n// Height is the one thing this presenter actively manages: the hosted flow\n// reports its rendered card height and we size the iframe element to match.\n\nimport { attachFrameBridges, createFrameElement, type FrameBridges } from './iframeCore.ts';\nimport type { IframeHandle } from './iframe.ts';\n\nconst EMBED_STYLE_ID = 'blink-deposit-embed-styles';\n\n// Scoped to `[data-blink-embed]` and injected only by this presenter, so a\n// merchant using the overlay never receives embed CSS and an aggregator never\n// receives a `position: fixed; z-index: 2147483647` rule for an overlay that\n// will never exist on their page.\n//\n// `color-scheme: light` is pinned for the same reason as the overlay: left at\n// `normal` it resolves to the host page's scheme, and a host declaring\n// `color-scheme: dark` makes Chromium see a mismatch against the light hosted\n// document and paint an opaque backplate behind the cross-origin iframe.\n//\n// The hidden warm-up state is `visibility: hidden` + a clipped zero-height\n// wrapper, NOT `display: none`: a display:none subtree has no layout at all,\n// so the flow inside could not measure itself and would report a height of\n// zero the moment it was revealed.\nconst EMBED_STYLES = `\n[data-blink-embed]{display:block;width:100%;position:relative}\n[data-blink-embed][data-blink-embed-hidden]{height:0;overflow:hidden;visibility:hidden;pointer-events:none}\n[data-blink-embed] iframe{display:block;width:100%;height:0;border:none;background:transparent;color-scheme:light}\n`;\n\nexport interface CreateEmbeddedIframeOptions {\n /**\n * Create the frame invisible for background warm-up: the document loads\n * normally but occupies no space in the host's layout and cannot be\n * interacted with until `reveal()`.\n */\n hidden?: boolean;\n /**\n * Hard cap on the iframe element's height, in CSS px. Reported content\n * heights are clamped to it, and it rides along on the viewport message as\n * the basis the flow sizes against.\n *\n * A function is re-read on every post, so a budget derived from the host\n * viewport stays correct across rotation and window resizes. A plain number\n * is fixed for the life of the frame.\n */\n embedMaxHeightPx?: number | (() => number | undefined);\n}\n\n/**\n * Create an inline cross-origin iframe pointing at the hosted flow, mounted\n * into the host's element. Returns the same {@link IframeHandle} shape as the\n * overlay presenter so the `Deposit` lifecycle is presentation-agnostic.\n */\nexport function createEmbeddedIframe(\n url: string,\n containerElement: HTMLElement,\n options?: CreateEmbeddedIframeOptions,\n): IframeHandle {\n ensureEmbedStyles();\n\n // The instance holds this node for its whole life and re-warms a fresh\n // hidden iframe into it after every close. If the host unmounted it (a\n // `{open && …}` around the slot is the usual cause), everything from here on\n // renders into an orphan: the first flow works, every later one is blank,\n // and nothing throws. Say so — a silent blank panel is close to\n // undiagnosable from the outside.\n if (!containerElement.isConnected) {\n console.warn(\n '[blink] The containerElement passed to Deposit is not in the document. '\n + 'Embedded mode renders into it for the life of the instance, so it must '\n + 'be a stable node — render the slot once and hide it with '\n + '`visibility: hidden` (NOT `display: none`, which removes its layout and '\n + 'leaves the warming flow unable to measure itself) instead of unmounting '\n + 'it, or construct a new Deposit against the new node.',\n );\n }\n\n let closed = false;\n let hidden = options?.hidden === true;\n let closeCallback: (() => void) | null = null;\n const readEmbedMaxHeightPx = (): number | undefined =>\n typeof options?.embedMaxHeightPx === 'function'\n ? options.embedMaxHeightPx()\n : options?.embedMaxHeightPx;\n\n const wrapper = document.createElement('div');\n wrapper.setAttribute('data-blink-embed', '');\n if (hidden) {\n wrapper.setAttribute('data-blink-embed-hidden', '');\n }\n\n const { iframe, iframeOrigin } = createFrameElement(url);\n // The card owns its own internal scroll, and the frame is sized to the\n // card, so the frame itself must never scroll. Without this a growth\n // transient (content briefly taller than the last applied height) puts a\n // root scrollbar in the frame; on Windows/Linux that is ~15px of\n // layout-consuming width, which rewraps the card and changes the very\n // height we are converging on. Stripe's embedded checkout sets the same\n // attribute for the same reason.\n iframe.setAttribute('scrolling', 'no');\n // Start at the host's budget rather than the stylesheet's 0. The flow\n // reports its real height as soon as it paints and this shrinks to fit, but\n // starting at zero would mean a visible collapsed frame for however long\n // the document takes to boot — and if a deployment never reports at all,\n // the budget is a correct, usable height rather than an invisible widget.\n const initialBudget = readEmbedMaxHeightPx();\n if (initialBudget !== undefined) {\n iframe.style.height = `${initialBudget}px`;\n }\n wrapper.appendChild(iframe);\n containerElement.appendChild(wrapper);\n\n const bridges: FrameBridges = attachFrameBridges({\n iframe,\n iframeOrigin,\n // Embedded always needs them: the flow has no usable viewport of its own,\n // so the basis it sizes against can only come from here.\n postViewport: true,\n getEmbedMaxHeightPx: readEmbedMaxHeightPx,\n shouldRevealOnLoad: () => !hidden,\n });\n\n function teardown(): void {\n closed = true;\n bridges.detach();\n wrapper.remove();\n }\n\n return {\n get contentWindow(): Window | null {\n return iframe.contentWindow;\n },\n\n close(): void {\n if (closed) return;\n teardown();\n closeCallback?.();\n },\n\n isClosed(): boolean {\n return closed;\n },\n\n isHidden(): boolean {\n return hidden;\n },\n\n reveal(): void {\n if (closed || !hidden) return;\n hidden = false;\n wrapper.removeAttribute('data-blink-embed-hidden');\n warnIfContainerNotRendered(containerElement);\n bridges.postViewportMetrics();\n bridges.postReveal();\n // Deliberately no focus() call. Focusing an element inside a\n // cross-origin iframe makes the outer browser scroll it into view,\n // which yanks the host's page — and inside a focus-trapped dialog it\n // fights the host's own focus guards.\n },\n\n postReveal(): void {\n bridges.postReveal();\n },\n\n downgradeToFixed(): void {\n // No-op: the fixed container is overlay geometry. There is nothing for\n // an inline frame to snap back to, and reintroducing a fixed-size card\n // here would fight the host's own panel.\n },\n\n applyContentHeight(heightPx: number): void {\n if (closed) return;\n const budget = readEmbedMaxHeightPx();\n const capped = budget === undefined ? heightPx : Math.min(heightPx, budget);\n iframe.style.height = `${Math.max(0, Math.round(capped))}px`;\n },\n\n onClose(callback: () => void): void {\n closeCallback = callback;\n },\n\n destroy(): void {\n closeCallback = null;\n if (!closed) teardown();\n },\n };\n}\n\n/**\n * Warns when the flow is being revealed into a container that has no layout —\n * almost always a host hiding its slot with `display: none` between opens.\n *\n * That subtree has no layout at all, so the flow warming inside it cannot\n * measure itself, and the height it reports on reveal is whatever the browser\n * has: nothing. Whether it recovers comes down to whether the host's own display\n * flip lands before this reveal reaches the frame — closing an entire dialog\n * usually wins that race, a panel's own back button usually loses it, and the\n * loser is a blank box at the budget height with nothing in the host's console.\n *\n * Checked at reveal rather than at mount: warming inside a hidden container is\n * fine and expected (the SDK hides its own wrapper with `visibility`), it is\n * being *revealed* while still unrendered that cannot work.\n *\n * `offsetParent` is null for a `display: none` subtree and for `position: fixed`\n * elements, so the zero-rect check carries the verdict and `offsetParent` only\n * distinguishes the cause.\n */\nfunction warnIfContainerNotRendered(containerElement: HTMLElement): void {\n // Never let a diagnostic break a reveal: a host may hand us something that is\n // element-like without being a full HTMLElement, and there is nothing to\n // measure in a non-DOM environment either.\n if (typeof containerElement.getBoundingClientRect !== 'function') return;\n const rect = containerElement.getBoundingClientRect();\n if (rect.width > 0 || rect.height > 0) return;\n const display = typeof getComputedStyle === 'function'\n ? getComputedStyle(containerElement).display\n : '';\n console.warn(\n '[blink] The containerElement has no layout at the moment the flow is '\n + `revealed${display === 'none' ? ' (display: none)' : ''}. A display:none `\n + 'subtree cannot be measured, so the flow may report no height and the '\n + 'panel stays blank at its budget height. Hide the slot with '\n + '`visibility: hidden` (plus `height: 0; overflow: hidden`) instead of '\n + '`display: none`, so it keeps its box while it warms up.',\n );\n}\n\nfunction ensureEmbedStyles(): void {\n const existingStyle = document.getElementById(EMBED_STYLE_ID);\n if (existingStyle) {\n if (existingStyle.textContent !== EMBED_STYLES) {\n existingStyle.textContent = EMBED_STYLES;\n }\n return;\n }\n const style = document.createElement('style');\n style.id = EMBED_STYLE_ID;\n style.textContent = EMBED_STYLES;\n document.head.appendChild(style);\n}\n","import { DepositError } from './errors.ts';\nimport type { SignerFunction, SignerRequest, SignerResponse } from './types.ts';\n\nconst DEFAULT_SIGNER_TIMEOUT_MS = 15_000;\n\n/**\n * Invoke the merchant signer and return the validated response.\n *\n * When `signer` is a URL string the SDK performs a `POST` with a JSON body.\n * When `signer` is a function the SDK delegates entirely to it.\n * In both cases a timeout wrapper is applied via `timeoutMs`.\n */\nexport async function callSigner(\n signer: string | SignerFunction,\n request: SignerRequest,\n timeoutMs?: number,\n): Promise<SignerResponse> {\n const timeout = timeoutMs ?? DEFAULT_SIGNER_TIMEOUT_MS;\n\n const body: SignerResponse =\n typeof signer === 'function'\n ? await invokeSignerFunction(signer, request, timeout)\n : await invokeSignerUrl(signer, request, timeout);\n\n validateSignerResponse(body);\n return body;\n}\n\nasync function invokeSignerUrl(\n signerUrl: string,\n request: SignerRequest,\n timeoutMs: number,\n): Promise<SignerResponse> {\n let response: Response;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n response = await fetch(signerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n } catch (err) {\n if (controller.signal.aborted) {\n throw new DepositError(\n 'SIGNER_TIMEOUT',\n `Signer did not respond within ${timeoutMs}ms.`,\n );\n }\n throw new DepositError(\n 'SIGNER_NETWORK_ERROR',\n 'Unable to reach the merchant signer. Check the signer URL and network connectivity.',\n );\n } finally {\n clearTimeout(timer);\n }\n\n const body = await response.json().catch(() => null) as\n | (Partial<SignerResponse> & { error?: string })\n | null;\n\n if (!response.ok) {\n const detail = body?.error ?? `Signer returned HTTP ${response.status}.`;\n throw new DepositError('SIGNER_REQUEST_FAILED', detail);\n }\n\n return body as SignerResponse;\n}\n\nasync function invokeSignerFunction(\n signer: SignerFunction,\n request: SignerRequest,\n timeoutMs: number,\n): Promise<SignerResponse> {\n return new Promise<SignerResponse>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new DepositError('SIGNER_TIMEOUT', `Signer did not respond within ${timeoutMs}ms.`)),\n timeoutMs,\n );\n\n signer(request).then(\n (result) => { clearTimeout(timer); resolve(result); },\n (err) => {\n clearTimeout(timer);\n if (err instanceof DepositError) {\n reject(err);\n } else {\n reject(new DepositError(\n 'SIGNER_REQUEST_FAILED',\n err instanceof Error ? err.message : 'Signer function threw an error.',\n ));\n }\n },\n );\n });\n}\n\nfunction validateSignerResponse(body: unknown): asserts body is SignerResponse {\n const obj = body as Partial<SignerResponse> | null | undefined;\n if (\n !obj ||\n typeof obj.merchantId !== 'string' ||\n typeof obj.payload !== 'string' ||\n typeof obj.signature !== 'string' ||\n !obj.preview ||\n typeof obj.preview !== 'object'\n ) {\n throw new DepositError(\n 'SIGNER_RESPONSE_INVALID',\n 'Signer response is missing required fields (merchantId, payload, signature, preview).',\n );\n }\n}\n","import { DepositError } from './errors.ts';\nimport type { DepositRequest, SignerRequest } from './types.ts';\n\nconst EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;\nconst TOKEN_ADDRESS_RE = /^0x[a-fA-F0-9]{1,40}$/;\nconst SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\nfunction isValidAddress(value: string): boolean {\n return EVM_ADDRESS_RE.test(value) || SOLANA_ADDRESS_RE.test(value);\n}\n\nfunction isValidTokenAddress(value: string): boolean {\n return TOKEN_ADDRESS_RE.test(value) || SOLANA_ADDRESS_RE.test(value);\n}\n\nexport function validateDepositRequest(request: DepositRequest): void {\n if (request.amount !== null) {\n if (typeof request.amount !== 'number' || !Number.isFinite(request.amount) || request.amount <= 0) {\n throw new DepositError('INVALID_REQUEST', 'amount must be a positive number or null.');\n }\n }\n\n if (!Number.isInteger(request.chainId) || request.chainId <= 0) {\n throw new DepositError('INVALID_REQUEST', 'chainId must be a positive integer.');\n }\n\n if (!isValidAddress(request.address)) {\n throw new DepositError(\n 'INVALID_REQUEST',\n 'address must be a valid EVM (0x-prefixed, 40 hex chars) or Solana (Base58, 32-44 chars) address.',\n );\n }\n\n if (typeof request.token !== 'string' || !isValidTokenAddress(request.token)) {\n throw new DepositError(\n 'INVALID_REQUEST',\n 'token must be a valid EVM (0x-prefixed hex) or Solana (Base58) token address.',\n );\n }\n}\n\nexport function buildSignerRequest(request: DepositRequest, webviewBaseUrl: string): SignerRequest {\n const base: SignerRequest = {\n amount: request.amount,\n chainId: request.chainId,\n address: request.address,\n token: request.token,\n callbackScheme: request.callbackScheme ?? null,\n url: webviewBaseUrl,\n version: 'v1',\n };\n\n if (request.reference) base.reference = request.reference;\n if (request.metadata && Object.keys(request.metadata).length > 0) {\n base.metadata = request.metadata;\n }\n\n return base;\n}\n","import { DepositError } from './errors.ts';\nimport {\n parseTransferComplete,\n parseCloseRequest,\n parseContentHeight,\n parseIframeReady,\n buildAckMessage,\n buildSignedPayloadMessage,\n} from './messages.ts';\nimport { BRAND_COLOR_PARAM_KEYS, normalizeBrandHex } from './brandParam.ts';\nimport { normalizeDisplayBalance } from './balanceParam.ts';\nimport { normalizeMinimumDeposit } from './minimumDepositParam.ts';\nimport { createIframe, shouldUseMobileSheetLayout, type IframeHandle } from './iframe.ts';\nimport { createEmbeddedIframe } from './embeddedIframe.ts';\nimport { measureViewportMetrics } from './viewportMetrics.ts';\nimport { callSigner } from './signer.ts';\nimport { validateDepositRequest, buildSignerRequest } from './validation.ts';\nimport type { DepositConfig, DepositStatus, DepositRequest, DepositResult, SignerResponse } from './types.ts';\n\nexport const DEFAULT_WEBVIEW_BASE_URL = 'https://pay.blink.cash';\nexport const SANDBOX_WEBVIEW_BASE_URL = 'https://pay-sandbox.blink.cash';\n\n/** How long `requestDeposit` waits for `blink:iframe-ready` before falling back to URL params. */\nconst IFRAME_READY_TIMEOUT_MS = 2_000;\n\n/**\n * How long a background warm-up iframe may take to signal ready. Generous on\n * purpose: the warm-up happens while the user hasn't acted yet, so a slow\n * connection finishing at 10s still produces a fully warmed flow. The strict\n * 2s budget only applies once `requestDeposit` is actually waiting.\n */\nconst WARM_IFRAME_READY_TIMEOUT_MS = 60_000;\n\n/**\n * Capability the hosted flow must advertise on `blink:iframe-ready` for the\n * full-viewport fluid layout (card chrome rendered inside the iframe). A\n * ready message without it means an older webview deployment — the overlay\n * is downgraded to the legacy fixed-size container before payload delivery.\n */\nconst LAYOUT_FLUID_CAPABILITY = 'layout-fluid';\n\n/** Fraction of the host viewport used as the default embedded height budget. */\nconst DEFAULT_EMBED_MAX_HEIGHT_FRACTION = 0.9;\n\ninterface IframeReadyResult {\n ready: boolean;\n fluidCapable: boolean;\n}\n\n/**\n * The one dismissal error. Every route out of a flow that isn't completion or a\n * failure produces this: the flow's own close control, the overlay backdrop,\n * Escape, and the host calling {@link Deposit.close} — so an integrator writes a\n * single `DEPOSIT_DISMISSED` branch rather than one per affordance.\n */\nfunction dismissedError(): DepositError {\n return new DepositError(\n 'DEPOSIT_DISMISSED',\n 'The deposit was dismissed before the transfer completed.',\n );\n}\n\nconst IFRAME_NOT_READY: IframeReadyResult = { ready: false, fluidCapable: false };\n\n/**\n * Resolves the hosted-flow base URL from config.\n *\n * Precedence: explicit `webviewBaseUrl` > `environment: 'sandbox'` > production default.\n */\nexport function resolveWebviewBaseUrl(\n config: Pick<DepositConfig, 'webviewBaseUrl' | 'environment'>,\n): string {\n if (config.webviewBaseUrl) return config.webviewBaseUrl;\n return config.environment === 'sandbox' ? SANDBOX_WEBVIEW_BASE_URL : DEFAULT_WEBVIEW_BASE_URL;\n}\n\ntype EventMap = {\n complete: (result: DepositResult) => void;\n error: (error: DepositError) => void;\n close: () => void;\n 'status-change': (status: DepositStatus) => void;\n /**\n * Embedded presentation only: the hosted flow's rendered height changed and\n * the inline iframe has already been resized to match. Hosts that size their\n * own panel around the iframe follow it from here.\n *\n * `heightPx` fires on every frame of the flow's own height transition —\n * apply it directly, with NO CSS transition on the host side, or two\n * independent animations of the same quantity fight each other and the panel\n * keeps moving after the content has settled.\n *\n * `preferredWidthPx` / `minWidthPx` are constants describing the flow's\n * design envelope, so a host that wants its panel to fit the flow in both\n * axes can size the width once rather than guessing.\n */\n resize: (info: {\n heightPx: number;\n preferredWidthPx?: number;\n minWidthPx?: number;\n }) => void;\n};\n\ntype EventName = keyof EventMap;\n\n/**\n * Merchant-facing deposit SDK.\n *\n * Opens a hosted payment flow in a modal iframe, communicates with the\n * merchant's signer backend, and resolves when the user completes payment.\n *\n * The iframe has `publickey-credentials-get` and `publickey-credentials-create`\n * permissions (with explicit origin) so WebAuthn passkey ceremonies work\n * cross-origin, including in Safari.\n *\n * ```ts\n * const deposit = new Deposit({ signer: '/api/sign-payment' });\n * const result = await deposit.requestDeposit({ amount: 50, chainId: 8453, address: '0x...', token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' });\n * ```\n */\nexport class Deposit {\n private readonly config: DepositConfig;\n private iframe: IframeHandle | null = null;\n private hostedOrigin: string | null = null;\n private messageListener: ((event: MessageEvent) => void) | null = null;\n private requestId = 0;\n private destroyed = false;\n private _status: DepositStatus = 'idle';\n private _result: DepositResult | null = null;\n private _error: DepositError | null = null;\n private flowTimer: ReturnType<typeof setTimeout> | null = null;\n private lastSignerResponse: SignerResponse | null = null;\n private warmIframe: IframeHandle | null = null;\n private warmIframeReady: Promise<IframeReadyResult> | null = null;\n private warmIframeReadyCancel: (() => void) | null = null;\n /** Resolved embedded-vs-overlay decision; see {@link Deposit.isEmbedded}. */\n private embeddedResolved: boolean | null = null;\n /**\n * Settles the in-flight `requestDeposit()` as a dismissal. Non-null exactly\n * while a flow is in progress, so {@link Deposit.close} can reject the promise\n * the caller is awaiting instead of tearing the frame down under it.\n */\n private dismissActiveFlow: (() => void) | null = null;\n private listeners: { [K in EventName]: Set<EventMap[K]> } = {\n complete: new Set(),\n error: new Set(),\n close: new Set(),\n 'status-change': new Set(),\n resize: new Set(),\n };\n\n /** Current phase of the deposit flow. */\n get status(): DepositStatus {\n return this._status;\n }\n\n /** Last successful {@link DepositResult}, available when `status === 'completed'`. */\n get result(): DepositResult | null {\n return this._result;\n }\n\n /** Last {@link DepositError}, available when `status === 'error'`. */\n get error(): DepositError | null {\n return this._error;\n }\n\n /** Whether a deposit flow is currently in progress (signer loading or iframe open). */\n get isActive(): boolean {\n return this._status === 'signer-loading' || this._status === 'iframe-active';\n }\n\n /**\n * How this instance will actually present: `'embedded'` renders inline in\n * `containerElement`, `'overlay'` covers the page.\n *\n * Not simply an echo of the config — a host that asked for `'embedded'` gets\n * `'overlay'` on mobile, where a phone-sized method panel cannot hold the\n * flow (see {@link Deposit.isEmbedded}). Read it when laying out the panel:\n * on `'overlay'` no `resize` event ever fires, so a panel sized from those\n * reports would sit empty behind the overlay — collapse or skip it.\n *\n * Live until the SDK builds its first (warm-up) frame and fixed from then on,\n * so re-read it on resize rather than caching it at mount.\n */\n get presentation(): 'overlay' | 'embedded' {\n return this.isEmbedded() ? 'embedded' : 'overlay';\n }\n\n constructor(config: DepositConfig) {\n if (!config.signer || (typeof config.signer !== 'string' && typeof config.signer !== 'function')) {\n throw new DepositError('INVALID_REQUEST', 'DepositConfig.signer is required (URL string or SignerFunction).');\n }\n if (config.presentation === 'embedded') {\n // Required at construction, not at requestDeposit: the warm-up iframe is\n // created eagerly and can never be relocated afterwards — moving an\n // iframe in the DOM reloads it, throwing away the warmed document.\n if (!config.containerElement) {\n throw new DepositError(\n 'INVALID_REQUEST',\n 'DepositConfig.containerElement is required when presentation is \"embedded\".',\n );\n }\n if (config.layout === 'fixed') {\n throw new DepositError(\n 'INVALID_REQUEST',\n 'DepositConfig.layout \"fixed\" is an overlay-only escape hatch and cannot be combined with presentation \"embedded\".',\n );\n }\n }\n this.config = config;\n this.log('Deposit instance created', {\n signer: typeof config.signer === 'string' ? config.signer : '<function>',\n });\n if (config.preload !== false) {\n this.schedulePreload();\n }\n }\n\n /**\n * Warm up the hosted payment flow in a hidden iframe so `requestDeposit`\n * opens an already-loaded page (JS bundle, auth session restore, and —\n * when {@link DepositConfig.merchantId} is set — merchant config prefetch\n * all happen in the background).\n *\n * Runs automatically after construction unless `preload: false`; call it\n * manually to control the timing (e.g. on deposit-button hover). No-op\n * when a warm iframe already exists or a deposit flow is active.\n */\n preload(): void {\n if (this.destroyed || this.isActive) return;\n if (this.warmIframe && !this.warmIframe.isClosed()) return;\n if (typeof document === 'undefined' || typeof window === 'undefined') return;\n\n const webviewBaseUrl = resolveWebviewBaseUrl(this.config);\n this.hostedOrigin = this.config.hostedFlowOrigin ?? new URL(webviewBaseUrl).origin;\n\n const preloadUrl = this.buildPreloadUrl(webviewBaseUrl);\n const iframe = this.createPresentedIframe(preloadUrl, { hidden: true });\n const ready = this.waitForIframeReady(iframe, WARM_IFRAME_READY_TIMEOUT_MS);\n this.warmIframe = iframe;\n this.warmIframeReady = ready.promise;\n this.warmIframeReadyCancel = ready.cancel;\n this.log('Warm-up iframe created', { url: preloadUrl });\n }\n\n // Defer the automatic warm-up until the host page has finished its own\n // load and the main thread is idle — constructing a Deposit instance must\n // never slow the merchant page down.\n private schedulePreload(): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n\n const start = () => {\n if (!this.destroyed && !this.isActive) this.preload();\n };\n const whenIdle = () => {\n const w = window as Window & {\n requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;\n };\n if (typeof w.requestIdleCallback === 'function') {\n w.requestIdleCallback(start, { timeout: 3_000 });\n } else {\n setTimeout(start, 250);\n }\n };\n\n if (document.readyState === 'complete') {\n whenIdle();\n } else {\n window.addEventListener('load', whenIdle, { once: true });\n }\n }\n\n /**\n * Whether the flow renders inline in the host's element rather than as an\n * overlay.\n *\n * `presentation: 'embedded'` is a request, not a guarantee: **on mobile the\n * flow presents as the normal overlay** even for an embedded host. An\n * aggregator's method panel is a narrow, short column on a phone, and the\n * flow inside it is a payment journey with a keypad, wallet lists and a QR\n * code — it needs the screen. The overlay is exactly what a phone user gets\n * from every other Blink integration, and the host's own dialog stays behind\n * it. Desktop keeps the inline card, where the panel has room.\n *\n * **The decision lives with the frame.** Read live until a frame is built,\n * then committed for good ({@link Deposit.createPresentedIframe}) — `preload()`\n * warms a frame from these same predicates and the flow that later adopts it\n * must agree, because a frame warmed at `layout=embed` handed to the overlay\n * presenter (or the reverse) is a blank modal. Committing at frame creation\n * rather than at construction matters: a host that constructs `Deposit` before\n * layout settles — a widget mounting inside a transition, a background or\n * prerendered tab — reports a zero-width viewport, and `(max-width: 640px)`\n * matches at zero, so caching then would lock a desktop user into the overlay\n * over a viewport that never existed. The warm-up already waits for `load`\n * plus an idle callback, so by the time it commits the measurement is real.\n */\n private isEmbedded(): boolean {\n if (this.config.presentation !== 'embedded') return false;\n if (this.embeddedResolved !== null) return this.embeddedResolved;\n // No device signals to read (SSR, or a viewport that has not been laid out\n // yet): honour the config, and do not commit — a later call decides.\n if (typeof window === 'undefined') return true;\n const viewportWidth = window.visualViewport?.width ?? window.innerWidth;\n if (!(viewportWidth > 0)) return true;\n return !shouldUseMobileSheetLayout();\n }\n\n /**\n * The host's height budget for the inline iframe. Explicit config wins;\n * otherwise most of the host viewport, which keeps a tall flow from\n * outgrowing the page it is embedded in.\n */\n private resolveEmbedMaxHeightPx(): number | undefined {\n if (this.config.embedMaxHeightPx !== undefined) return this.config.embedMaxHeightPx;\n if (typeof window === 'undefined') return undefined;\n const derived = Math.round(window.innerHeight * DEFAULT_EMBED_MAX_HEIGHT_FRACTION);\n return derived > 0 ? derived : undefined;\n }\n\n /** Build the iframe for the configured presentation. */\n private createPresentedIframe(url: string, options: { hidden?: boolean }): IframeHandle {\n // Commit the embedded-vs-overlay decision to this instance. Everything\n // downstream — the layout URL param, the height budget, the presenter, the\n // mount target — must describe the same frame for the rest of its life.\n if (this.config.presentation === 'embedded' && this.embeddedResolved === null) {\n this.embeddedResolved = this.isEmbedded();\n if (!this.embeddedResolved) {\n this.log('Mobile device: presenting the embedded flow as an overlay');\n }\n }\n if (this.isEmbedded()) {\n return createEmbeddedIframe(url, this.config.containerElement!, {\n hidden: options.hidden,\n // A getter, not a value: the default is derived from the host\n // viewport, which changes on rotation and window resize.\n embedMaxHeightPx: () => this.resolveEmbedMaxHeightPx(),\n });\n }\n return createIframe(url, this.overlayMountTarget(), {\n hidden: options.hidden,\n fluid: this.isFluidLayout(),\n });\n }\n\n /**\n * Where the overlay mounts. `containerElement` means two different things by\n * presentation: an overlay mount point (`presentation: 'overlay'`) or the\n * aggregator's inline panel slot (`'embedded'`). When an embedded flow\n * presents as an overlay on mobile, that slot must NOT be the mount point —\n * `position: fixed` resolves against the nearest transformed/filtered/\n * contained ancestor, and an aggregator's animated dialog is exactly that, so\n * the \"full-screen\" overlay would end up positioned inside their panel.\n * Falls through to `document.body`.\n */\n private overlayMountTarget(): HTMLElement | undefined {\n return this.config.presentation === 'embedded' ? undefined : this.config.containerElement;\n }\n\n private buildPreloadUrl(webviewBaseUrl: string): string {\n const preloadUrl = new URL(webviewBaseUrl);\n preloadUrl.searchParams.set('preload', 'true');\n // Untrusted warm-up hint: lets the hosted flow prefetch the merchant\n // config and signing key before the signed payload exists. Authorization\n // still comes exclusively from the signed payload.\n if (this.config.merchantId) {\n preloadUrl.searchParams.set('merchantId', this.config.merchantId);\n }\n this.applyFullWidgetParam(preloadUrl);\n this.applyLayoutParam(preloadUrl);\n this.applyViewportParams(preloadUrl);\n return preloadUrl.toString();\n }\n\n /**\n * Detach the warm iframe for use by a starting flow. Returns null (and\n * cleans up) when there is none or it was closed in the meantime.\n */\n private takeWarmIframe(): {\n iframe: IframeHandle;\n ready: Promise<IframeReadyResult>;\n cancelReady: () => void;\n } | null {\n const iframe = this.warmIframe;\n const ready = this.warmIframeReady;\n const cancelReady = this.warmIframeReadyCancel ?? (() => {});\n this.warmIframe = null;\n this.warmIframeReady = null;\n this.warmIframeReadyCancel = null;\n\n if (!iframe || !ready) return null;\n if (iframe.isClosed()) {\n cancelReady();\n iframe.destroy();\n return null;\n }\n return { iframe, ready, cancelReady };\n }\n\n private discardWarmIframe(): void {\n this.warmIframeReadyCancel?.();\n this.warmIframeReadyCancel = null;\n this.warmIframeReady = null;\n if (this.warmIframe) {\n this.warmIframe.destroy();\n this.warmIframe = null;\n }\n }\n\n /**\n * Open the hosted payment flow for the given deposit.\n *\n * The returned Promise resolves when the user completes the payment and\n * rejects with a {@link DepositError} on failure.\n */\n requestDeposit(request: DepositRequest): Promise<DepositResult> {\n if (this.destroyed) {\n return Promise.reject(\n new DepositError('INVALID_REQUEST', 'This Deposit instance has been destroyed.'),\n );\n }\n\n validateDepositRequest(request);\n this.log('requestDeposit called', { amount: request.amount, token: request.token, chainId: request.chainId });\n\n this.requestId += 1;\n const currentRequestId = this.requestId;\n\n this.cleanup();\n\n this._result = null;\n this._error = null;\n this.setStatus('signer-loading');\n\n return new Promise<DepositResult>((resolve, reject) => {\n let settled = false;\n const settle = (fn: () => void) => {\n if (this.requestId !== currentRequestId || settled) return;\n settled = true;\n this.dismissActiveFlow = null;\n fn();\n };\n\n const onComplete = (result: DepositResult) => {\n settle(() => {\n if (this.flowTimer) {\n clearTimeout(this.flowTimer);\n this.flowTimer = null;\n }\n this._result = result;\n this._error = null;\n this.setStatus('completed');\n this.emit('complete', result);\n resolve(result);\n this.cleanup();\n });\n };\n\n const onError = (error: DepositError) => {\n settle(() => {\n this.cleanup();\n this._error = error;\n this.setStatus('error');\n this.emit('error', error);\n reject(error);\n });\n };\n\n // How `close()` settles this promise — see {@link Deposit.close}.\n //\n // A quiet dismissal: it rejects the caller's promise but does NOT emit\n // `error` or move `status` to 'error', because the HOST asked for this\n // (its own back button or dialog chrome) and does not need telling that\n // its own action ended the flow. `close()` follows with 'idle' + `close`,\n // which is what it has always reported. The flow's own close control\n // keeps the full error path: there the dismissal is news to the host.\n this.dismissActiveFlow = () => {\n settle(() => {\n this.cleanup();\n reject(dismissedError());\n });\n };\n\n if (this.config.flowTimeoutMs != null && this.config.flowTimeoutMs > 0) {\n this.flowTimer = setTimeout(() => {\n onError(\n new DepositError(\n 'FLOW_TIMEOUT',\n `The payment flow did not complete within ${this.config.flowTimeoutMs}ms.`,\n ),\n );\n }, this.config.flowTimeoutMs);\n }\n\n this.runSignerFlow(request, currentRequestId, onComplete, onError);\n });\n }\n\n /** Register an event listener. */\n on<K extends EventName>(event: K, handler: EventMap[K]): this {\n this.listeners[event].add(handler);\n return this;\n }\n\n /** Remove a previously registered event listener. */\n off<K extends EventName>(event: K, handler: EventMap[K]): this {\n this.listeners[event].delete(handler);\n return this;\n }\n\n /** No-op — retained for API compatibility with the popup-based SDK. */\n focus(): void {}\n\n /**\n * Close the deposit iframe without waiting for completion — the host's own\n * back button or dialog chrome.\n *\n * This **settles a flow in progress** by rejecting its `requestDeposit()`\n * promise with `DEPOSIT_DISMISSED`, exactly as the flow's own close control\n * does. It has to: `cleanup()` destroys the frame through `destroy()`, which\n * drops the handle's close callback on purpose, so without this the caller's\n * `await` never returns. An aggregator whose back button awaited that promise\n * to restore its method list was left showing an empty panel — the flow gone,\n * its own list still not rendered, and no error to explain why.\n *\n * The rejection code is the same `DEPOSIT_DISMISSED` the in-flow control\n * produces, so a host writes one dismissal branch rather than one per\n * affordance. What it deliberately does not do is report an error: no `error`\n * event, and `status` lands on 'idle' as it always has, because the host\n * initiated this. With no flow in progress it is a plain teardown, unchanged.\n */\n close(): void {\n this.log('close() called');\n const dismiss = this.dismissActiveFlow;\n this.dismissActiveFlow = null;\n // Rejects the pending promise and cleans up; `cleanup()` is idempotent, so\n // the shared tail below still runs the status and event side of close.\n dismiss?.();\n this.cleanup();\n this.setStatus('idle');\n this.emit('close');\n }\n\n /** Tear down the instance and release all resources. */\n destroy(): void {\n this.log('destroy() called');\n // Set before cleanup() so it doesn't schedule a fresh warm-up iframe.\n this.destroyed = true;\n this.cleanup();\n this.discardWarmIframe();\n this.setStatus('idle');\n for (const set of Object.values(this.listeners)) {\n (set as Set<unknown>).clear();\n }\n }\n\n // ── Private ──────────────────────────────────────────────────────────\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (!this.config.debug) return;\n if (data) {\n console.debug(`[BlinkDeposit] ${message}`, data);\n } else {\n console.debug(`[BlinkDeposit] ${message}`);\n }\n }\n\n /**\n * Appends `enableFullWidget=false` to the hosted-flow URL when the merchant\n * integration disables the full widget. Absence of the param means enabled\n * (the default) — the hosted flow ANDs this with the merchant's backend\n * config, so the full widget renders only when both allow it.\n */\n private applyFullWidgetParam(url: URL): void {\n if (this.config.enableFullWidget === false) {\n url.searchParams.set('enableFullWidget', 'false');\n }\n this.applyAppearanceParam(url);\n }\n\n /**\n * Appends `appearance=dark` (or `appearance=system`) to the hosted-flow URL.\n * An explicit `appearance: { theme }` config always wins — including\n * `theme: 'light'`, which pins light regardless of the merchant page. When\n * the merchant passes no theme, the default follows the merchant page's own\n * declared color scheme (see {@link detectMerchantColorScheme}) so the flow\n * doesn't render a light modal on a page that says it is dark. Absence of\n * the param means light. The hosted flow resolves `system` against the\n * user's `prefers-color-scheme`. Applied alongside the full-widget param on\n * every hosted/preload URL.\n */\n private applyAppearanceParam(url: URL): void {\n const theme = this.config.appearance?.theme ?? detectMerchantColorScheme();\n if (theme === 'dark' || theme === 'system') {\n url.searchParams.set('appearance', theme);\n }\n this.applyBrandParam(url);\n }\n\n /**\n * Appends the merchant's brand colors as `brand=p-0f62fe.bg-ffffff…`.\n *\n * On the URL rather than a message because the hosted flow's loading shell\n * paints from its entry chunk, hundreds of ms before React mounts: a palette\n * that arrived by `postMessage` would show Blink's own card color first and\n * then become the merchant's. Unreserved characters only, so the param costs\n * ~50 bytes of the URL budget rather than triple that in percent-encoding.\n *\n * Validated here purely so the merchant sees the complaint in their OWN\n * console — the hosted flow re-validates everything it decodes, since the URL\n * is host-controlled input that ends up in a stylesheet. Silence would be the\n * worst outcome: a dropped color that nobody is told about looks like the SDK\n * ignoring the config.\n */\n private applyBrandParam(url: URL): void {\n const variables = this.config.appearance?.variables;\n if (!variables) return;\n const accepted: Record<string, string> = {};\n for (const [key, value] of Object.entries(variables)) {\n if (value === undefined || value === null) continue;\n if (!BRAND_COLOR_PARAM_KEYS[key]) {\n console.error(\n `[blink] appearance.variables.${key} is not a supported brand color. `\n + `Supported: ${Object.keys(BRAND_COLOR_PARAM_KEYS).join(', ')}.`,\n );\n continue;\n }\n const hex = normalizeBrandHex(value);\n if (!hex) {\n console.error(\n `[blink] appearance.variables.${key} must be opaque hex (#rgb or #rrggbb); `\n + `received ${JSON.stringify(value)}. Ignoring it.`,\n );\n continue;\n }\n accepted[key] = hex;\n }\n const encoded = Object.keys(BRAND_COLOR_PARAM_KEYS)\n .filter((key) => accepted[key] !== undefined)\n .map((key) => `${BRAND_COLOR_PARAM_KEYS[key]}-${accepted[key].slice(1)}`)\n .join('.');\n if (encoded) url.searchParams.set('brand', encoded);\n }\n\n /**\n * Normalizes the display-only {@link DepositRequest.balance} for the wire,\n * or returns `undefined` to omit it everywhere — the `blink:signed-payload`\n * sibling field and the legacy fallback URL param alike. Additive wire\n * discipline: an unset or rejected balance leaves both channels\n * byte-for-byte what they always were, and old webviews ignore the field\n * by construction.\n *\n * Validated here purely so the merchant sees the complaint in their OWN\n * console (same rationale as {@link applyBrandParam}); the hosted flow\n * re-validates whatever arrives, since both channels are host-controlled\n * input. A rejected balance never blocks the deposit — the flow proceeds\n * without the subtitle.\n */\n private normalizeRequestBalance(balance: unknown): string | undefined {\n if (balance === undefined || balance === null) return undefined;\n const normalized = normalizeDisplayBalance(balance);\n if (normalized === null) {\n const received =\n typeof balance === 'number' ? String(balance) : JSON.stringify(balance) ?? String(balance);\n console.error(\n `[blink] balance must be a finite number >= 0 and < 1e12 (USD, display only); `\n + `received ${received}. Ignoring it.`,\n );\n return undefined;\n }\n return normalized;\n }\n\n /**\n * Normalizes {@link DepositRequest.minimumDeposit} for the wire, or returns\n * `undefined` to omit it everywhere. Same additive discipline and same\n * console-complaint rationale as {@link normalizeRequestBalance}.\n *\n * A rejected minimum never blocks the deposit — the flow proceeds on\n * Blink's own per-route floor, which is the safe direction to fail: the\n * merchant loses their higher floor, nobody is locked out of depositing.\n */\n private normalizeRequestMinimumDeposit(minimumDeposit: unknown): string | undefined {\n if (minimumDeposit === undefined || minimumDeposit === null) return undefined;\n const normalized = normalizeMinimumDeposit(minimumDeposit);\n if (normalized === null) {\n const received =\n typeof minimumDeposit === 'number'\n ? String(minimumDeposit)\n : JSON.stringify(minimumDeposit) ?? String(minimumDeposit);\n console.error(\n `[blink] minimumDeposit must be a finite number > 0 and < 1e6 (USD); `\n + `received ${received}. Ignoring it.`,\n );\n return undefined;\n }\n return normalized;\n }\n\n /**\n * Fluid is the default; `layout: 'fixed'` opts back into the legacy\n * container. Embedded is a separate presentation and never fluid — the\n * constructor rejects the combination outright.\n */\n private isFluidLayout(): boolean {\n return !this.isEmbedded() && this.config.layout !== 'fixed';\n }\n\n /**\n * Marks the hosted-flow URL as fluid-layout: the iframe spans the full\n * viewport and the hosted flow renders the card/sheet chrome itself.\n * Only applied to preload URLs — the URL-param fallback path exists\n * precisely because the webview never signalled ready, so it cannot be\n * assumed to understand fluid layout and gets the fixed container.\n */\n private applyLayoutParam(url: URL): void {\n if (this.isEmbedded()) {\n url.searchParams.set('layout', 'embed');\n return;\n }\n if (this.isFluidLayout()) {\n url.searchParams.set('layout', 'fluid');\n }\n }\n\n /**\n * Seeds the merchant page's large-viewport height and safe-area bottom\n * inset onto the fluid preload URL so the hosted flow can size the sheet\n * before its JS boots. `blink:viewport` messages keep the values fresh\n * afterwards (rotation, window resize) — see iframe.ts.\n */\n private applyViewportParams(url: URL): void {\n const embedded = this.isEmbedded();\n if (!this.isFluidLayout() && !embedded) return;\n if (embedded) {\n // The height budget doubles as the sizing basis inside the flow, so it\n // has to be there before first paint — a late arrival would mean the\n // loading shell lays out against the wrong reference.\n const embedMaxHeightPx = this.resolveEmbedMaxHeightPx();\n if (embedMaxHeightPx !== undefined) {\n url.searchParams.set('embedMaxHeight', String(embedMaxHeightPx));\n }\n }\n const metrics = measureViewportMetrics();\n if (metrics.viewportLvh <= 0) return;\n url.searchParams.set('viewportLvh', String(metrics.viewportLvh));\n url.searchParams.set('safeAreaBottom', String(metrics.safeAreaBottom));\n }\n\n private setStatus(status: DepositStatus): void {\n if (this._status === status) return;\n this.log(`Status: ${this._status} → ${status}`);\n this._status = status;\n this.emit('status-change', status);\n }\n\n private async runSignerFlow(\n request: DepositRequest,\n requestId: number,\n onComplete: (result: DepositResult) => void,\n onError: (error: DepositError) => void,\n ): Promise<void> {\n try {\n const webviewBaseUrl = resolveWebviewBaseUrl(this.config);\n this.hostedOrigin = this.config.hostedFlowOrigin ?? new URL(webviewBaseUrl).origin;\n\n this.log('Calling signer', {\n signer: typeof this.config.signer === 'string' ? this.config.signer : '<function>',\n });\n const signerRequest = buildSignerRequest(request, webviewBaseUrl);\n // Display-only sibling of the signed payload. Deliberately NOT part of\n // `signerRequest`: the balance never reaches the merchant's signer and\n // is never covered by the signature — it rides out-of-band on whichever\n // delivery channel wins below.\n const displayBalance = this.normalizeRequestBalance(request.balance);\n // Same out-of-band treatment as the balance: a merchant business rule,\n // unsigned, re-validated by the hosted flow, and never sent to the\n // merchant's signer.\n const minimumDeposit = this.normalizeRequestMinimumDeposit(request.minimumDeposit);\n\n // Reuse the background warm-up iframe when one exists — its document\n // (JS bundle, auth warm-up, merchant prefetches) is already loaded or\n // loading. Otherwise create the preload iframe now so the bundle at\n // least loads in parallel with the signer call.\n let preloadIframe: IframeHandle;\n let iframeReadyPromise: Promise<IframeReadyResult>;\n\n const warm = this.takeWarmIframe();\n if (warm) {\n warm.iframe.reveal();\n preloadIframe = warm.iframe;\n // The warm-up wait is generous (60s); from the moment the user acts\n // we only give it the regular 2s budget before falling back. Either\n // way, settle the underlying warm-up wait so its timer and message\n // listener are released.\n iframeReadyPromise = Promise.race([\n warm.ready,\n new Promise<IframeReadyResult>((resolve) =>\n setTimeout(() => resolve(IFRAME_NOT_READY), IFRAME_READY_TIMEOUT_MS),\n ),\n ]).then((ready) => {\n warm.cancelReady();\n return ready;\n });\n this.log('Reusing warm preload iframe');\n } else {\n preloadIframe = this.createPresentedIframe(this.buildPreloadUrl(webviewBaseUrl), {});\n iframeReadyPromise = this.waitForIframeReady(preloadIframe).promise;\n }\n this.iframe = preloadIframe;\n\n preloadIframe.onClose(() => {\n onError(dismissedError());\n this.cleanup();\n this.emit('close');\n });\n\n // Race: signer call and iframe ready signal in parallel\n const signerPromise = callSigner(\n this.config.signer,\n signerRequest,\n this.config.signerTimeoutMs,\n );\n\n const [signerResponse, iframeReady] = await Promise.all([\n signerPromise,\n iframeReadyPromise,\n ]);\n\n this.lastSignerResponse = signerResponse;\n this.log('Signer responded', { merchantId: signerResponse.merchantId });\n\n if (this.requestId !== requestId || preloadIframe.isClosed()) {\n this.log('Request superseded or iframe dismissed during signer call');\n return;\n }\n\n if (iframeReady.ready) {\n // The webview signalled ready but predates fluid layout (no\n // `layout-fluid` capability): snap the overlay back to the fixed\n // container so its fill-mode rendering looks exactly like today.\n if (this.isFluidLayout() && !iframeReady.fluidCapable) {\n preloadIframe.downgradeToFixed();\n this.log('Webview lacks layout-fluid capability — downgraded to fixed container');\n }\n // New webview supports preloading — deliver payload via postMessage\n const contentWindow = preloadIframe.contentWindow;\n if (contentWindow) {\n contentWindow.postMessage(\n buildSignedPayloadMessage(\n signerResponse.merchantId,\n signerResponse.payload,\n signerResponse.signature,\n displayBalance,\n minimumDeposit,\n ),\n this.hostedOrigin!,\n );\n }\n this.startMessageListener(preloadIframe, onComplete);\n this.setStatus('iframe-active');\n this.log('Payload delivered via postMessage (preload path)');\n } else {\n // Fallback: old webview did not send blink:iframe-ready.\n // Destroy preload iframe and create a new one with full URL params.\n preloadIframe.destroy();\n\n const hostedUrl = new URL(webviewBaseUrl);\n hostedUrl.searchParams.set('merchantId', signerResponse.merchantId);\n hostedUrl.searchParams.set('payload', signerResponse.payload);\n hostedUrl.searchParams.set('signature', signerResponse.signature);\n if (displayBalance !== undefined) {\n hostedUrl.searchParams.set('balance', displayBalance);\n }\n if (minimumDeposit !== undefined) {\n hostedUrl.searchParams.set('minDeposit', minimumDeposit);\n }\n this.applyFullWidgetParam(hostedUrl);\n // The overlay's fallback deliberately omits the layout params: a\n // webview that never signalled ready predates them, so it gets the\n // legacy fixed container. Embedded has no legacy container to fall\n // back to, so it keeps its params and renders inline regardless.\n if (this.isEmbedded()) {\n this.applyLayoutParam(hostedUrl);\n this.applyViewportParams(hostedUrl);\n }\n const targetUrl = hostedUrl.toString();\n\n // Stays on the configured presenter. Embedded must never reach\n // `createIframe` here: that builds a `position: fixed` overlay, and\n // dropping a full-screen modal over an aggregator's own widget is the\n // one failure mode worse than the flow simply not starting.\n const iframeHandle = this.createPresentedIframe(targetUrl, {});\n this.iframe = iframeHandle;\n\n iframeHandle.onClose(() => {\n onError(dismissedError());\n this.cleanup();\n this.emit('close');\n });\n\n this.startMessageListener(iframeHandle, onComplete);\n this.setStatus('iframe-active');\n this.log('Iframe opened with hosted flow (fallback path)', { url: targetUrl });\n }\n } catch (err) {\n if (this.requestId !== requestId) return;\n\n this.log('Signer flow failed', { error: err instanceof Error ? err.message : String(err) });\n\n if (err instanceof DepositError) {\n onError(err);\n } else {\n onError(\n new DepositError(\n 'SIGNER_NETWORK_ERROR',\n err instanceof Error ? err.message : 'Unknown signer error.',\n ),\n );\n }\n }\n }\n\n /**\n * Resolves `{ ready: true, ... }` when the iframe posts\n * `blink:iframe-ready` (with `fluidCapable` reflecting its advertised\n * capabilities), or `{ ready: false, fluidCapable: false }` on timeout.\n * `cancel()` settles the promise as not-ready immediately and releases\n * the listener + timer — used to reap the generous warm-up wait once it no\n * longer matters (warm iframe consumed or discarded).\n */\n private waitForIframeReady(\n iframeHandle: IframeHandle,\n timeoutMs: number = IFRAME_READY_TIMEOUT_MS,\n ): { promise: Promise<IframeReadyResult>; cancel: () => void } {\n let finish: (result: IframeReadyResult) => void = () => {};\n\n const promise = new Promise<IframeReadyResult>((resolve) => {\n const handler = (event: MessageEvent) => {\n if (event.origin !== this.hostedOrigin) return;\n if (event.source !== iframeHandle.contentWindow) return;\n const readyMessage = parseIframeReady(event.data);\n if (readyMessage) {\n finish({\n ready: true,\n fluidCapable: readyMessage.capabilities.includes(LAYOUT_FLUID_CAPABILITY),\n });\n }\n };\n window.addEventListener('message', handler);\n\n const timeout = setTimeout(() => {\n this.log('Iframe ready timeout — falling back to URL params');\n finish(IFRAME_NOT_READY);\n }, timeoutMs);\n\n let settled = false;\n finish = (result: IframeReadyResult) => {\n if (settled) return;\n settled = true;\n window.removeEventListener('message', handler);\n clearTimeout(timeout);\n resolve(result);\n };\n });\n\n return { promise, cancel: () => finish(IFRAME_NOT_READY) };\n }\n\n private startMessageListener(\n iframeHandle: IframeHandle,\n onComplete: (result: DepositResult) => void,\n ): void {\n const handler = (event: MessageEvent) => {\n if (this.hostedOrigin && event.origin !== this.hostedOrigin) {\n return;\n }\n\n const contentWindow = iframeHandle.contentWindow;\n if (event.source && contentWindow && event.source !== contentWindow) {\n return;\n }\n\n if (parseCloseRequest(event.data)) {\n this.log('Close request received from hosted flow');\n iframeHandle.close();\n return;\n }\n\n const contentHeight = parseContentHeight(event.data);\n if (contentHeight) {\n // Applied without a transition on purpose: the flow animates its own\n // height, and a second animation here would fight it. Not logged —\n // this fires on every frame of that animation.\n iframeHandle.applyContentHeight(contentHeight.heightPx);\n this.emit('resize', {\n heightPx: contentHeight.heightPx,\n ...(contentHeight.preferredWidthPx === undefined\n ? {}\n : { preferredWidthPx: contentHeight.preferredWidthPx }),\n ...(contentHeight.minWidthPx === undefined\n ? {}\n : { minWidthPx: contentHeight.minWidthPx }),\n });\n return;\n }\n\n const message = parseTransferComplete(event.data);\n if (!message) {\n return;\n }\n\n this.log('Transfer complete received', { transferId: message.transfer.id, status: message.transfer.status });\n\n if (contentWindow) {\n try {\n contentWindow.postMessage(\n buildAckMessage(message.transfer.id),\n this.hostedOrigin ?? '*',\n );\n } catch {\n // Cross-origin postMessage can throw in edge cases — safe to swallow.\n }\n }\n\n const depositResult: DepositResult = { transfer: message.transfer };\n if (this.lastSignerResponse?.preview) {\n depositResult.idempotencyKey = this.lastSignerResponse.preview.idempotencyKey;\n depositResult.preview = {\n amount: this.lastSignerResponse.preview.amount,\n chainId: this.lastSignerResponse.preview.chainId,\n address: this.lastSignerResponse.preview.address,\n token: this.lastSignerResponse.preview.token,\n };\n }\n onComplete(depositResult);\n };\n\n this.messageListener = handler;\n window.addEventListener('message', handler);\n }\n\n private cleanup(): void {\n if (this.flowTimer) {\n clearTimeout(this.flowTimer);\n this.flowTimer = null;\n }\n\n if (this.messageListener) {\n window.removeEventListener('message', this.messageListener);\n this.messageListener = null;\n }\n\n if (this.iframe) {\n this.iframe.destroy();\n this.iframe = null;\n }\n\n this.hostedOrigin = null;\n this.lastSignerResponse = null;\n\n // The flow that owned the iframe is over — warm a fresh one up for the\n // next deposit. When cleanup() runs at the start of requestDeposit the\n // deferred callback sees an active flow and skips.\n if (!this.destroyed && this.config.preload !== false) {\n this.schedulePreload();\n }\n }\n\n private emit<K extends EventName>(event: K, ...args: Parameters<EventMap[K]>): void {\n for (const handler of this.listeners[event]) {\n try {\n (handler as (...a: unknown[]) => void)(...args);\n } catch {\n // Swallow listener errors to avoid breaking the SDK flow.\n }\n }\n }\n}\n\n/**\n * Detects the merchant page's declared color scheme from the used\n * `color-scheme` of the document root, mapping it to the appearance the\n * hosted flow should default to when the merchant config passes no theme:\n *\n * - `dark` (page declares itself dark, e.g. `<meta name=\"color-scheme\"\n * content=\"dark\">`) → `'dark'`\n * - `light dark` (page adapts to the OS preference) → `'system'`, so the\n * hosted flow resolves against the same `prefers-color-scheme` the page\n * itself follows\n * - anything else (`normal`, `light`, `only light`, no browser support,\n * detection failure) → `null`, keeping the light default\n *\n * Only *declared* schemes are detectable — a page that paints dark colors\n * without declaring `color-scheme` reads as light.\n */\nfunction detectMerchantColorScheme(): 'dark' | 'system' | null {\n if (typeof window === 'undefined' || typeof document === 'undefined') return null;\n const root = document.documentElement;\n if (!root || typeof window.getComputedStyle !== 'function') return null;\n let value: string;\n try {\n value = window.getComputedStyle(root).colorScheme ?? '';\n } catch {\n return null;\n }\n const tokens = value.toLowerCase().split(/\\s+/);\n const dark = tokens.includes('dark');\n const light = tokens.includes('light');\n if (dark && light) return 'system';\n if (dark) return 'dark';\n return null;\n}\n\n/** @deprecated Use {@link Deposit} instead. */\nexport const Checkout = Deposit;\n","export { Deposit, Checkout, DEFAULT_WEBVIEW_BASE_URL, SANDBOX_WEBVIEW_BASE_URL } from './checkout.ts';\nexport { DepositError, CheckoutError, getDisplayMessage } from './errors.ts';\nexport type { DepositErrorCode, CheckoutErrorCode } from './errors.ts';\nexport type {\n DepositConfig,\n CheckoutConfig,\n DepositStatus,\n CheckoutStatus,\n DepositRequest,\n DepositResult,\n SignerFunction,\n SignerRequest,\n SignerResponse,\n TransferSummary,\n} from './types.ts';\n\n// ── Wallet bridge (advanced) ──────────────────────────────────────────\n// Internal building blocks for the top-frame → iframe wallet bridge.\n// Default merchant integrations don't need these — `createIframe()` wires\n// them automatically. Re-exported so monorepo tests and any merchant\n// custom-iframe wrapper can poke at the protocol shapes.\nexport { createWalletDiscoverer } from './walletBridge/discover.ts';\nexport type { WalletDiscovererHandle, RegisteredProvider } from './walletBridge/discover.ts';\nexport { attachRpcHost } from './walletBridge/rpcHost.ts';\nexport type { RpcHostHandle, RpcHostOptions } from './walletBridge/rpcHost.ts';\nexport {\n ALLOWED_RPC_METHODS,\n BRIDGE_PROTOCOL_VERSION,\n parseBridgeMessage,\n} from './walletBridge/protocol.ts';\nexport type {\n AdvertisedWallet,\n BridgeMessage,\n BridgeHelloMessage,\n WalletsAdvertisedMessage,\n RpcRequestMessage,\n RpcResponseMessage,\n RpcEventMessage,\n EIP1193Provider as BridgeEIP1193Provider,\n EIP6963ProviderInfo,\n EIP6963ProviderDetail,\n} from './walletBridge/protocol.ts';\n\nexport const VERSION = '0.3.32';\n"]}