@sunbay/checkout-sdk-js 0.1.0 → 0.2.0

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/index.ts","../../protocol/src/envelope.ts","../../protocol/src/errors.ts","../../protocol/src/commands.ts","../../protocol/src/events.ts","../../protocol/src/iframeLayout.ts","../src/config/env.ts","../src/transport/hello.ts","../src/transport/MainFrameTransport.ts","../src/Element.ts","../src/CheckoutInstance.ts","../src/createCheckout.ts"],"sourcesContent":["/**\n * @sunbay/checkout-js public entry (source of truth).\n *\n * Exports the `createCheckout` entry, the `CheckoutInstance` / `CheckoutElement` handle types,\n * and the public protocol types (for TS consumers).\n * In the IIFE build, additionally exposes `{ createCheckout }` on `window.SunbayCheckout`.\n */\n\nexport { createCheckout } from './createCheckout';\nexport type {\n CreateCheckoutOptions,\n TransportFactory,\n} from './createCheckout';\n\nexport { CheckoutInstance } from './CheckoutInstance';\nexport type {\n CheckoutInstanceOptions,\n ConfirmOptions,\n InstanceTransport,\n} from './CheckoutInstance';\n\nexport { CheckoutElement } from './Element';\nexport type { CheckoutElementOptions, ElementTransport, MountOptions } from './Element';\n\nexport type { Env } from './config/env';\n\n// Public protocol types (the contract for TS consumers).\nexport {\n ErrorCode,\n WARNING_CODES,\n type ErrorCodeValue,\n type CheckoutError,\n type CheckoutErrorCategory,\n type PaymentOutcome,\n type PublicSessionView,\n type PublicPaymentMethod,\n type PublicProductLine,\n type PaymentMethod,\n type PaymentMethodFilter,\n type Appearance,\n type AddressInfo,\n type TxnStatus,\n type SessionStatus,\n type ElementType,\n type ElementOptions,\n type ElementStatus,\n type CardElementOptions,\n type CardFieldElementOptions,\n type AddressElementOptions,\n type AddressFormStyle,\n type ExpressCheckoutElementOptions,\n type AvailableWallets,\n type ApplePayOptions,\n type GooglePayOptions,\n type ApplePayButtonTheme,\n type GooglePayButtonTheme,\n type ApplePayButtonType,\n type GooglePayButtonType,\n type PaymentAction,\n type WalletErrorStage,\n type EventName,\n type EventPayloadMap,\n type ErrorEvent,\n type WarningEvent,\n type WarningCode,\n type PaymentResultEvent,\n type PaymentStateChangeEvent,\n type ExpressAvailabilityChangeEvent,\n type ElementReadyEvent,\n type ChangeEvent,\n type LoadErrorEvent,\n type ReadyEvent,\n type FocusEvent,\n type BlurEvent,\n type AppearanceVariables,\n type AppearanceRuleTarget,\n type AppearanceRuleStyle,\n} from '@sunbay/checkout-sdk-protocol';\n\nimport { createCheckout } from './createCheckout';\n\n/**\n * IIFE / browser global: mount `window.SunbayCheckout = { createCheckout }`.\n *\n * The tsup IIFE build already exposes the module exports via `globalName: 'SunbayCheckout'`;\n * this explicitly ensures `window.SunbayCheckout.createCheckout` is available (while staying\n * compatible with re-exporting more entries in the future).\n */\nif (typeof window !== 'undefined') {\n const w = window as typeof window & {\n SunbayCheckout?: { createCheckout: typeof createCheckout };\n };\n w.SunbayCheckout = { ...(w.SunbayCheckout ?? {}), createCheckout };\n}\n\n/**\n * Package version. Injected at build time by tsup's `define` from `package.json` as\n * `__SDK_VERSION__` (see tsup.config.ts), so the code's version always stays in sync with\n * package.json. Environments without a build (e.g. vitest running src directly) have no such\n * define and fall back to `'0.0.0'`.\n */\ndeclare const __SDK_VERSION__: string;\nexport const version: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : '0.0.0';\n","/**\n * Envelope and handshake contract (spec 5.1, source of truth).\n *\n * Protocol name `sunbay-checkout`, `major = 1`. This is a different protocol from the existing\n * Native Bridge `{v:1,type,...}`; identical numbers do not imply compatibility.\n *\n * `encodeEnvelope`/`decodeEnvelope`: JSON serialization + minimal runtime structural validation\n * (validates protocol/major/kind/required fields), throwing on invalid input. The decoder does\n * **not** validate whether request.name is a known CommandName — an unknown name is still decoded\n * as kind==='request' and rejected by the caller.\n */\n\nimport type { CheckoutError } from './types';\n\n/** Protocol name constant. */\nexport const PROTOCOL_NAME = 'sunbay-checkout' as const;\n/** Current major version. */\nexport const PROTOCOL_MAJOR = 1 as const;\n\n/**\n * Handshake message (spec 5.1). Broadcast first after the main iframe loads, when there is no\n * checkoutId yet.\n */\nexport type RuntimeHello = {\n protocol: 'sunbay-checkout';\n kind: 'hello';\n runtimeId: string;\n supportedMajorVersions: number[];\n /** First phase: ['card','splitCard','address','express','paymentMethodFilter']. */\n capabilities: string[];\n};\n\n/**\n * Public envelope after initialization (spec 5.1).\n */\nexport type Envelope = {\n protocol: 'sunbay-checkout';\n major: 1;\n runtimeId: string;\n checkoutId: string;\n elementId?: string;\n} & (\n | { kind: 'request'; requestId: string; name: string; payload: unknown }\n | { kind: 'response'; requestId: string; ok: true; data: unknown }\n | { kind: 'response'; requestId: string; ok: false; error: CheckoutError }\n | { kind: 'event'; eventId: string; name: string; operationId?: string; payload: unknown }\n);\n\n/** Set of valid kinds. */\nconst ENVELOPE_KINDS = ['request', 'response', 'event'] as const;\n\n/** Protocol validation failure error. */\nexport class EnvelopeDecodeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'EnvelopeDecodeError';\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction assertString(obj: Record<string, unknown>, key: string): void {\n if (typeof obj[key] !== 'string') {\n throw new EnvelopeDecodeError(`Envelope field \"${key}\" is missing or not a string`);\n }\n}\n\n/**\n * Serialize an envelope into a wire string (JSON).\n *\n * @param envelope The envelope to send\n * @returns JSON string\n * @example\n * const wire = encodeEnvelope({ protocol: 'sunbay-checkout', major: 1, ... });\n */\nexport function encodeEnvelope(envelope: Envelope): string {\n return JSON.stringify(envelope);\n}\n\n/**\n * Parse and minimally structurally validate an envelope. Invalid input (missing protocol, wrong\n * major, invalid kind, missing required fields, non-JSON) always throws {@link EnvelopeDecodeError}.\n *\n * Note: the decoder does not validate whether request.name is a known command — an unknown name is\n * still decoded as kind==='request' and left for the caller (e.g. the Orchestrator) to reject.\n *\n * @param wire The wire string\n * @returns The structurally validated envelope\n * @example\n * const env = decodeEnvelope(wire);\n * if (env.kind === 'request') { ... }\n */\nexport function decodeEnvelope(wire: string): Envelope {\n let parsed: unknown;\n try {\n parsed = JSON.parse(wire);\n } catch {\n throw new EnvelopeDecodeError('Envelope is not valid JSON');\n }\n\n if (!isRecord(parsed)) {\n throw new EnvelopeDecodeError('Envelope must be an object');\n }\n\n if (parsed.protocol !== PROTOCOL_NAME) {\n throw new EnvelopeDecodeError(\n `protocol must be \"${PROTOCOL_NAME}\", received ${JSON.stringify(parsed.protocol)}`\n );\n }\n if (parsed.major !== PROTOCOL_MAJOR) {\n throw new EnvelopeDecodeError(\n `major must be ${PROTOCOL_MAJOR}, received ${JSON.stringify(parsed.major)}`\n );\n }\n\n assertString(parsed, 'runtimeId');\n assertString(parsed, 'checkoutId');\n if (parsed.elementId !== undefined && typeof parsed.elementId !== 'string') {\n throw new EnvelopeDecodeError('elementId must be a string when present');\n }\n\n const kind = parsed.kind;\n if (typeof kind !== 'string' || !(ENVELOPE_KINDS as readonly string[]).includes(kind)) {\n throw new EnvelopeDecodeError(`Invalid kind: ${JSON.stringify(kind)}`);\n }\n\n switch (kind) {\n case 'request': {\n assertString(parsed, 'requestId');\n assertString(parsed, 'name');\n if (!('payload' in parsed)) {\n throw new EnvelopeDecodeError('request envelope is missing payload');\n }\n break;\n }\n case 'response': {\n assertString(parsed, 'requestId');\n if (typeof parsed.ok !== 'boolean') {\n throw new EnvelopeDecodeError('response envelope is missing boolean ok');\n }\n if (parsed.ok === true) {\n if (!('data' in parsed)) {\n throw new EnvelopeDecodeError('successful response is missing data');\n }\n } else if (!isRecord(parsed.error)) {\n throw new EnvelopeDecodeError('failed response is missing error object');\n }\n break;\n }\n case 'event': {\n assertString(parsed, 'eventId');\n assertString(parsed, 'name');\n if (!('payload' in parsed)) {\n throw new EnvelopeDecodeError('event envelope is missing payload');\n }\n if (\n 'operationId' in parsed &&\n parsed.operationId !== undefined &&\n typeof parsed.operationId !== 'string'\n ) {\n throw new EnvelopeDecodeError('operationId must be a string when present');\n }\n break;\n }\n }\n\n // Structure validated; confirmed to be an Envelope shape.\n return parsed as unknown as Envelope;\n}\n","/**\n * Protocol error code constants (single source of truth, spec 5.4).\n *\n * Does not provide a generic `retryable` boolean that could mislead into duplicate payments.\n * Only keeps error codes that are actually produced; new codes must have a production point.\n */\n\nexport const ErrorCode = {\n INVALID_OPTIONS: 'INVALID_OPTIONS',\n ELEMENT_CONFLICT: 'ELEMENT_CONFLICT',\n INSTANCE_DESTROYED: 'INSTANCE_DESTROYED',\n CHECKOUT_BUSY: 'CHECKOUT_BUSY',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n SESSION_LOAD_FAILED: 'SESSION_LOAD_FAILED',\n RUNTIME_LOAD_FAILED: 'RUNTIME_LOAD_FAILED',\n PROTOCOL_UNSUPPORTED: 'PROTOCOL_UNSUPPORTED',\n REQUEST_TIMEOUT: 'REQUEST_TIMEOUT',\n PAYMENT_FLOW_ERROR: 'PAYMENT_FLOW_ERROR',\n UNSUPPORTED_CAPABILITY: 'UNSUPPORTED_CAPABILITY',\n} as const;\n\n/** Error code literal union type. */\nexport type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];\n","/**\n * Command contract (merchant SDK → main, spec 5.2 table, source of truth).\n *\n * The request/response types for each command are defined here; only JSON-serializable data is sent\n * across the channel.\n */\n\nimport type {\n Appearance,\n AddressInfo,\n ElementOptions,\n ElementType,\n PaymentMethodFilter,\n PublicSessionView,\n SessionStatus,\n TxnStatus,\n} from './types';\nimport type { WarningEvent } from './events';\n\n/** All command names (spec 5.2). */\nexport type CommandName =\n | 'initialize'\n | 'createElement'\n | 'updateElement'\n | 'destroyElement'\n | 'focus'\n | 'blur'\n | 'clear'\n | 'updateCheckout'\n | 'getSession'\n | 'refresh'\n | 'getPaymentStatus'\n | 'confirm'\n | 'destroy';\n\n/** Set of known command names (for callers to validate whether request.name is supported). */\nexport const COMMAND_NAMES: readonly CommandName[] = [\n 'initialize',\n 'createElement',\n 'updateElement',\n 'destroyElement',\n 'focus',\n 'blur',\n 'clear',\n 'updateCheckout',\n 'getSession',\n 'refresh',\n 'getPaymentStatus',\n 'confirm',\n 'destroy',\n];\n\n/** Determine whether a string is a known command name. */\nexport function isCommandName(name: string): name is CommandName {\n return (COMMAND_NAMES as readonly string[]).includes(name);\n}\n\n// --- initialize ---\nexport interface InitializeReq {\n sessionId: string;\n locale?: string;\n appearance?: Appearance;\n paymentMethods?: PaymentMethodFilter;\n /** Host-collected billing address; when complete, wallets do not ask for it again. */\n billingAddress?: AddressInfo;\n /** Host-collected shipping address; when complete, wallets do not ask for it again. */\n shippingAddress?: AddressInfo;\n /**\n * Sensitive per-session secret (optional at the protocol level; the JS SDK enforces it).\n * Returned by the merchant backend's\n * `create-session` call when `sessionType` is `embedded`. Never log it or put it in a URL.\n */\n checkoutClientSecret?: string;\n}\nexport interface InitializeResp {\n capabilities: string[];\n session: PublicSessionView;\n /**\n * Non-fatal warnings produced while handling `initialize` (e.g. unknown `paymentMethods`\n * filter identifiers). Events emitted during `initialize` cannot reach listeners (the instance\n * does not exist yet), so they are carried here and replayed by the SDK to the first\n * `warning` listener.\n */\n warnings?: WarningEvent[];\n}\n\n// --- createElement ---\nexport interface CreateElementReq {\n elementId: string;\n type: ElementType;\n options?: ElementOptions;\n}\nexport interface CreateElementResp {\n elementId: string;\n registered: true;\n}\n\n// --- updateElement ---\nexport interface UpdateElementReq {\n elementId: string;\n patch: Partial<ElementOptions>;\n}\nexport interface UpdateElementResp {\n elementId: string;\n options: ElementOptions;\n}\n\n// --- destroyElement ---\nexport interface DestroyElementReq {\n elementId: string;\n}\nexport interface DestroyElementResp {\n elementId: string;\n released: true;\n}\n\n// --- focus / blur / clear (input-type Elements only) ---\nexport interface ElementActionReq {\n elementId: string;\n}\nexport interface ElementActionResp {\n elementId: string;\n done: true;\n}\n\n// --- updateCheckout (does not change session/amount) ---\nexport interface UpdateCheckoutReq {\n locale?: string;\n appearance?: Appearance;\n /** Replace the host-provided billing address (send `{}` to clear; `undefined` leaves it unchanged). */\n billingAddress?: AddressInfo;\n /** Replace the host-provided shipping address. */\n shippingAddress?: AddressInfo;\n}\nexport interface UpdateCheckoutResp {\n updated: true;\n}\n\n// --- getSession / refresh ---\nexport type GetSessionReq = Record<string, never>;\nexport type GetSessionResp = PublicSessionView;\n\n// --- getPaymentStatus (returns TxnStatus verbatim, no translation) ---\nexport type GetPaymentStatusReq = Record<string, never>;\nexport interface GetPaymentStatusResp {\n /**\n * Latest transaction status. May be absent when the session is `EXPIRED` and the backend\n * has no transaction to report.\n */\n txnStatus?: TxnStatus;\n /** Status of the session itself. Absent on backends that do not report it. */\n sessionStatus?: SessionStatus;\n txnId?: string;\n}\n\n// --- confirm (only indicates that execution has started) ---\nexport interface ConfirmReq {\n operationId: string;\n billingAddress?: AddressInfo;\n shippingAddress?: AddressInfo;\n customerName?: string;\n email?: string;\n returnUrl?: string;\n}\nexport interface ConfirmResp {\n accepted: true;\n}\n\n// --- destroy ---\nexport type DestroyReq = Record<string, never>;\nexport interface DestroyResp {\n released: true;\n}\n\n/** Command name → request payload mapping. */\nexport interface CommandRequestMap {\n initialize: InitializeReq;\n createElement: CreateElementReq;\n updateElement: UpdateElementReq;\n destroyElement: DestroyElementReq;\n focus: ElementActionReq;\n blur: ElementActionReq;\n clear: ElementActionReq;\n updateCheckout: UpdateCheckoutReq;\n getSession: GetSessionReq;\n refresh: GetSessionReq;\n getPaymentStatus: GetPaymentStatusReq;\n confirm: ConfirmReq;\n destroy: DestroyReq;\n}\n\n/** Command name → success response payload mapping. */\nexport interface CommandResponseMap {\n initialize: InitializeResp;\n createElement: CreateElementResp;\n updateElement: UpdateElementResp;\n destroyElement: DestroyElementResp;\n focus: ElementActionResp;\n blur: ElementActionResp;\n clear: ElementActionResp;\n updateCheckout: UpdateCheckoutResp;\n getSession: GetSessionResp;\n refresh: GetSessionResp;\n getPaymentStatus: GetPaymentStatusResp;\n confirm: ConfirmResp;\n destroy: DestroyResp;\n}\n","/**\n * Event contract (main → merchant SDK, spec 5.3 table, source of truth).\n *\n * Public events only expose allowed states such as empty/complete/brand/error, and **never contain\n * card values**; no card-data getValue is provided. After `on` registration, historical events are\n * not replayed.\n */\n\nimport type {\n AvailableWallets,\n CheckoutError,\n PaymentAction,\n WalletErrorStage,\n PaymentMethod,\n PaymentOutcome,\n} from './types';\n\n/** All event names (spec 5.3). */\nexport type EventName =\n | 'ready'\n | 'change'\n | 'focus'\n | 'blur'\n | 'loadError'\n | 'elementReady'\n | 'expressAvailabilityChange'\n | 'paymentStateChange'\n | 'paymentResult'\n | 'error'\n | 'warning';\n\n/** Set of known event names. */\nexport const EVENT_NAMES: readonly EventName[] = [\n 'ready',\n 'change',\n 'focus',\n 'blur',\n 'loadError',\n 'elementReady',\n 'expressAvailabilityChange',\n 'paymentStateChange',\n 'paymentResult',\n 'error',\n 'warning',\n];\n\n/** Determine whether a string is a known event name. */\nexport function isEventName(name: string): name is EventName {\n return (EVENT_NAMES as readonly string[]).includes(name);\n}\n\n// --- Input Element events ---\nexport interface ReadyEvent {\n elementId: string;\n}\nexport interface ElementReadyEvent {\n elementId: string;\n /** Only carried when the expressCheckout Element is ready: per-wallet availability. */\n availableWallets?: AvailableWallets;\n}\nexport interface ChangeEvent {\n elementId: string;\n empty: boolean;\n complete: boolean;\n error?: CheckoutError;\n /** Only the card number field may carry brand; never contains card values. */\n brand?: string;\n}\nexport interface FocusEvent {\n elementId: string;\n}\nexport interface BlurEvent {\n elementId: string;\n}\nexport interface LoadErrorEvent {\n elementId: string;\n error: CheckoutError;\n}\n\n// --- Express events ---\n/**\n * Express available-wallets change event (spec 6).\n * Dedicated to expressCheckout: uses AvailableWallets to express the availability of each wallet\n * (Apple/Google Pay).\n */\nexport interface ExpressAvailabilityChangeEvent {\n availableWallets: AvailableWallets;\n}\n\n// --- Checkout-level events ---\nexport interface PaymentStateChangeEvent {\n operationId: string;\n method: PaymentMethod;\n /** Intermediate state; carries action info when requiresAction. */\n state: string;\n action?: PaymentAction;\n}\nexport interface PaymentResultEvent {\n operationId: string;\n method: PaymentMethod;\n outcome: PaymentOutcome;\n}\nexport interface ErrorEvent {\n /** Error in an asynchronous proactive flow; may include operationId (if already created). */\n operationId?: string;\n /** Payment method the error relates to, if any. */\n method?: PaymentMethod;\n /** Payment flow stage in which the error occurred, if applicable (wallet and card flows). */\n stage?: WalletErrorStage;\n error: CheckoutError;\n}\n\n/**\n * Cross-platform registry of `warning` event codes (single source of truth for Web, iOS, Android).\n * Warnings are non-fatal: the offending input was ignored. A platform that needs a new code adds it\n * here (and to the docs table) so every SDK shares one vocabulary.\n */\nexport const WARNING_CODES = {\n /** A `paymentMethods` filter identifier matched nothing (unknown / not offered). */\n PAYMENT_METHOD_FILTER_IGNORED: 'PAYMENT_METHOD_FILTER_IGNORED',\n /** An expressCheckout option was not whitelisted or had an invalid value. */\n EXPRESS_OPTION_IGNORED: 'EXPRESS_OPTION_IGNORED',\n /** A host-provided billing/shipping address was incomplete, so it was treated as not provided. */\n ADDRESS_INCOMPLETE: 'ADDRESS_INCOMPLETE',\n /** A host-provided address was ignored because our Address Element owns that mode. */\n ADDRESS_ENTRY_IGNORED: 'ADDRESS_ENTRY_IGNORED',\n /**\n * The wallet (Apple Pay / Google Pay) payment parameters delivered by the session were missing\n * or invalid, so that wallet is not offered. Registered for the native SDKs (iOS first); the Web\n * runtime currently only logs this condition and does not emit the event.\n */\n WALLET_PARAMS_INVALID: 'WALLET_PARAMS_INVALID',\n} as const;\n\n/** Warning code (non-fatal; the offending input was ignored). */\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Non-fatal warning: some merchant-supplied input was ignored instead of failing the call\n * (e.g. an unknown `paymentMethods` filter identifier, or a non-whitelisted Express option).\n */\nexport interface WarningEvent {\n code: WarningCode;\n /** The ignored identifiers / option paths. */\n ignored: string[];\n /** Human-readable reason (may list the accepted values). */\n reason: string;\n}\n\n/** Event name → payload mapping. */\nexport interface EventPayloadMap {\n ready: ReadyEvent;\n change: ChangeEvent;\n focus: FocusEvent;\n blur: BlurEvent;\n loadError: LoadErrorEvent;\n elementReady: ElementReadyEvent;\n expressAvailabilityChange: ExpressAvailabilityChangeEvent;\n paymentStateChange: PaymentStateChangeEvent;\n paymentResult: PaymentResultEvent;\n error: ErrorEvent;\n warning: WarningEvent;\n}\n","/**\n * iframe layout protocol: the **direct postMessage** contract from the hosted iframe (checkout,\n * child) → parent window (merchant SDK, parent), used for iframe auto-height.\n *\n * Distinct from both the outer Envelope (merchant SDK ↔ main iframe) and the inner point-to-point\n * port (element ↔ main): this message is posted directly by each visible field / element iframe to\n * its `window.parent` (the merchant page), and the merchant SDK's Element handle listens for it and\n * adjusts the outer iframe height to the real content height (width stays 100%).\n *\n * Security constraint (AGENTS/spec): this message **never contains any card value** (plaintext or\n * ciphertext); it only carries height and elementId. The parent-window side must validate the\n * source (`event.source === iframe.contentWindow` and `event.origin === hostOrigin`) before\n * trusting it, to prevent cross-origin forgery.\n */\n\n/** Discriminant literal for the iframe auto-height message (namespaced to avoid colliding with other postMessages). */\nexport const IFRAME_RESIZE_MESSAGE_TYPE = 'sunbay:checkout:iframe-resize' as const;\n\n/**\n * Content height change notification from the iframe (child) → parent window (SDK).\n *\n * The child observes content height with a `ResizeObserver` and sends on change (deduplicated); the\n * parent sets `iframe.style.height` accordingly. Never contains card values.\n */\nexport interface IframeResizeMessage {\n /** Discriminant field, fixed to {@link IFRAME_RESIZE_MESSAGE_TYPE}. */\n type: typeof IFRAME_RESIZE_MESSAGE_TYPE;\n /**\n * The unique id of the target Element. Passed down by the merchant SDK via the iframe src's\n * `&elementId=`, echoed back verbatim by the child, so the parent window can dispatch by handle\n * among multiple iframes on the same page.\n */\n elementId: string;\n /** Content height (CSS px, already `Math.ceil`-ed; finite and non-negative). */\n height: number;\n}\n\n/**\n * Whether the value is a valid {@link IframeResizeMessage}.\n *\n * Validates: non-null object + type literal match + elementId is a non-empty string + height is a\n * finite non-negative number.\n *\n * @param data - Data from any source (typically `MessageEvent.data`).\n * @returns Whether data is a valid iframe-resize message.\n */\nexport function isIframeResizeMessage(data: unknown): data is IframeResizeMessage {\n if (typeof data !== 'object' || data === null) {\n return false;\n }\n const msg = data as Partial<IframeResizeMessage>;\n return (\n msg.type === IFRAME_RESIZE_MESSAGE_TYPE &&\n typeof msg.elementId === 'string' &&\n msg.elementId.length > 0 &&\n typeof msg.height === 'number' &&\n Number.isFinite(msg.height) &&\n msg.height >= 0\n );\n}\n","/**\n * Runtime environment identifier.\n * - `dev`: development hosted page.\n * - `test`: UAT/test hosted page.\n * - `prod`: production hosted page.\n */\nexport type Env = 'dev' | 'test' | 'prod';\n\n/**\n * Built-in hosted page origins (consistently without a trailing slash).\n */\nconst HOST_ORIGINS: Record<Env, string> = {\n dev: 'https://checkout.sunbay-dev.com',\n test: 'https://checkout.sunbay-uat.us',\n prod: 'https://checkout.sunbay.us',\n};\n\n/**\n * Resolve the hosted page origin.\n *\n * @param env - Runtime environment, defaults to `'prod'`.\n * @param override - Override origin (for env vars/tests); takes precedence when non-empty.\n * @returns Hosted page origin (without a trailing slash).\n * @example\n * resolveHostOrigin(); // 'https://checkout.sunbay.us'\n * resolveHostOrigin('dev'); // 'https://checkout.sunbay-dev.com'\n * resolveHostOrigin('test'); // 'https://checkout.sunbay-uat.us'\n * resolveHostOrigin('dev', 'http://localhost:3000'); // 'http://localhost:3000'\n */\nexport function resolveHostOrigin(env: Env = 'prod', override?: string): string {\n if (override) {\n return override.replace(/\\/+$/, '');\n }\n return HOST_ORIGINS[env];\n}\n\n/**\n * Base path under which the hosted runtime serves its pages (`main`, `field/*`, `element/*`).\n * Requires a hosted runtime that serves `/embed/sdk/*` (SDK >= 0.0.7).\n */\nexport const RUNTIME_BASE_PATH = '/embed/sdk';\n\n/**\n * Build a hosted-runtime page URL (without a query string; callers append their own).\n *\n * @param hostOrigin - Hosted page origin; trailing slashes are stripped.\n * @param segment - `'main'` (hidden main frame), `'field'` (split field) or `'element'`.\n * @param type - Field/element type; required for `'field'` and `'element'`.\n * @returns Absolute URL such as `https://host/embed/sdk/field/cardNumber`.\n * @example\n * runtimeUrl('https://checkout.sunbay.us', 'main'); // '.../embed/sdk/main'\n * runtimeUrl('https://checkout.sunbay.us/', 'field', 'cardNumber'); // '.../embed/sdk/field/cardNumber'\n */\nexport function runtimeUrl(\n hostOrigin: string,\n segment: 'main' | 'field' | 'element',\n type?: string\n): string {\n const origin = hostOrigin.replace(/\\/+$/, '');\n const path = type ? `${segment}/${type}` : segment;\n return `${origin}${RUNTIME_BASE_PATH}/${path}`;\n}\n","/**\n * RuntimeHello shape validation shared by the transport and the createCheckout handshake.\n *\n * A hello that fails validation is ignored (never throws), so a malformed or hostile message can\n * neither crash the handshake with a raw TypeError nor consume the one-shot hello slot.\n */\n\nimport { PROTOCOL_NAME, type RuntimeHello } from '@sunbay/checkout-sdk-protocol';\n\n/**\n * Check that a value is a well-formed RuntimeHello.\n *\n * Requires `runtimeId` to be a non-empty string and `supportedMajorVersions` to be an array of\n * finite numbers. `capabilities` is optional, but when present it must be an array of strings.\n *\n * @param value - Unknown parsed message.\n * @returns Whether the value is a valid RuntimeHello.\n */\nexport function isValidRuntimeHello(value: unknown): value is RuntimeHello {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const r = value as Record<string, unknown>;\n if (r.protocol !== PROTOCOL_NAME || r.kind !== 'hello') {\n return false;\n }\n if (typeof r.runtimeId !== 'string' || r.runtimeId.length === 0) {\n return false;\n }\n if (\n !Array.isArray(r.supportedMajorVersions) ||\n !r.supportedMajorVersions.every((v) => typeof v === 'number' && Number.isFinite(v))\n ) {\n return false;\n }\n if (\n r.capabilities !== undefined &&\n (!Array.isArray(r.capabilities) || !r.capabilities.every((c) => typeof c === 'string'))\n ) {\n return false;\n }\n return true;\n}\n","/**\n * MainFrameTransport — the transport layer between the merchant SDK and the hosted main iframe (spec 5).\n *\n * Responsibilities:\n * - Create a hidden, 0-size main iframe (`${hostOrigin}/embed/sdk/main?checkoutId=...`).\n * - Send request envelopes and pair responses by `requestId` (resolve/reject).\n * - Dispatch `kind:'event'` envelopes to handlers registered via `on`.\n * - Enforce the security boundary: only accept messages whose `event.origin === hostOrigin`,\n * whose `event.source` is this transport's own main iframe window, whose envelope `checkoutId`\n * matches and (after the handshake) whose `runtimeId` matches the negotiated one.\n * - `destroy()` cleans up the iframe/listener and rejects all pending requests with INSTANCE_DESTROYED.\n *\n * Security constraint (AGENTS/spec): envelopes **never contain card values**; this layer only\n * carries protocol envelopes and never touches card data.\n * RuntimeHello (`kind:'hello'`) has no checkoutId yet during the handshake phase, so it is\n * recognized and handled **separately** by this layer rather than passed to `decodeEnvelope`\n * (which requires checkoutId).\n */\n\nimport {\n decodeEnvelope,\n encodeEnvelope,\n PROTOCOL_MAJOR,\n PROTOCOL_NAME,\n type CheckoutError,\n type CommandName,\n type Envelope,\n type EventName,\n type RuntimeHello,\n} from '@sunbay/checkout-sdk-protocol';\nimport { ErrorCode } from '@sunbay/checkout-sdk-protocol';\nimport { runtimeUrl } from '../config/env';\nimport { isValidRuntimeHello } from './hello';\n\n/** Constructor parameters. */\nexport interface MainFrameTransportOptions {\n checkoutId: string;\n hostOrigin: string;\n}\n\n/** Configurable timeouts (ms). */\nexport interface RequestTimeoutConfig {\n /** Default timeout for regular commands. */\n default: number;\n /** Timeout for the initialize command. */\n initialize: number;\n /** Handshake (hello) timeout. */\n handshake: number;\n}\n\n/** Default timeouts: regular 10s, initialize 30s, handshake 15s. */\nexport const DEFAULT_REQUEST_TIMEOUTS: RequestTimeoutConfig = {\n default: 10_000,\n initialize: 30_000,\n handshake: 15_000,\n};\n\n/**\n * Rethrow an error from a handler asynchronously: the current dispatch loop keeps running, while\n * the error still reaches the host page's console / `window.onerror` instead of being swallowed.\n */\nfunction rethrowAsync(err: unknown): void {\n setTimeout(() => {\n throw err;\n }, 0);\n}\n\n/** Event handler signature (payload is of unknown shape, refined by the caller per EventName). */\nexport type EventHandler = (payload: unknown) => void;\n\n/** Pairing record for a pending request. */\ninterface PendingRequest {\n resolve: (value: unknown) => void;\n reject: (reason: CheckoutError) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/** Generate a unique id (requestId / errorId). */\nfunction genId(prefix: string): string {\n const rand = Math.random().toString(36).slice(2);\n return `${prefix}_${Date.now().toString(36)}_${rand}`;\n}\n\n/** Construct a structured CheckoutError (runtime category). */\nfunction makeError(code: string, message: string): CheckoutError {\n return {\n code,\n message,\n category: 'runtime',\n errorId: genId('err'),\n };\n}\n\n/**\n * Determine whether an unknown object is a RuntimeHello (handshake phase, no checkoutId).\n *\n * Does not rely on decodeEnvelope — hello is not part of the Envelope union.\n */\nfunction isRuntimeHello(value: unknown): value is RuntimeHello {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const record = value as Record<string, unknown>;\n return record.protocol === PROTOCOL_NAME && record.kind === 'hello';\n}\n\nexport class MainFrameTransport {\n private readonly checkoutId: string;\n private readonly hostOrigin: string;\n private readonly timeouts: RequestTimeoutConfig;\n\n private iframe: HTMLIFrameElement | null = null;\n private readonly pending = new Map<string, PendingRequest>();\n private readonly eventHandlers = new Map<EventName, Set<EventHandler>>();\n private helloHandler: ((hello: RuntimeHello) => void) | null = null;\n /**\n * Runtime id negotiated during the handshake; empty string before injection. Outbound request\n * envelopes are filled from it; the main endpoint only processes requests whose runtimeId\n * matches its own, and an empty string is silently dropped.\n */\n private runtimeId = '';\n\n private readonly messageListener: (event: MessageEvent) => void;\n private destroyed = false;\n\n constructor(\n options: MainFrameTransportOptions,\n timeouts: RequestTimeoutConfig = DEFAULT_REQUEST_TIMEOUTS\n ) {\n this.checkoutId = options.checkoutId;\n this.hostOrigin = options.hostOrigin;\n this.timeouts = timeouts;\n this.messageListener = (event: MessageEvent): void => {\n this.handleMessage(event);\n };\n window.addEventListener('message', this.messageListener);\n }\n\n /**\n * Create the hidden, 0-size main iframe and append it to document.body.\n *\n * @returns The mounted iframe element.\n * @example\n * const iframe = transport.createHiddenIframe();\n */\n createHiddenIframe(): HTMLIFrameElement {\n if (this.iframe) {\n return this.iframe;\n }\n const iframe = document.createElement('iframe');\n iframe.src = `${runtimeUrl(this.hostOrigin, 'main')}?checkoutId=${this.checkoutId}`;\n iframe.setAttribute('aria-hidden', 'true');\n iframe.title = 'sunbay-checkout-main';\n iframe.style.position = 'absolute';\n iframe.style.width = '0';\n iframe.style.height = '0';\n iframe.style.border = '0';\n iframe.style.visibility = 'hidden';\n document.body.appendChild(iframe);\n this.iframe = iframe;\n return iframe;\n }\n\n /**\n * Send one request envelope and pair the response by requestId.\n *\n * @param name - Command name.\n * @param payload - Command payload (JSON-serializable).\n * @returns The response data; on failure (ok:false / timeout / destroy) rejects with a CheckoutError.\n * @example\n * const session = await transport.request('getSession', {});\n */\n request(name: CommandName, payload: unknown): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n if (this.destroyed) {\n reject(makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed'));\n return;\n }\n const contentWindow = this.iframe?.contentWindow;\n if (!contentWindow) {\n reject(\n makeError(\n ErrorCode.RUNTIME_LOAD_FAILED,\n 'main iframe not created or contentWindow unavailable'\n )\n );\n return;\n }\n\n const requestId = genId('req');\n const envelope: Envelope = {\n protocol: PROTOCOL_NAME,\n major: PROTOCOL_MAJOR,\n runtimeId: this.runtimeId,\n checkoutId: this.checkoutId,\n kind: 'request',\n requestId,\n name,\n payload,\n };\n\n const timeoutMs = this.resolveTimeout(name);\n const timer = setTimeout(() => {\n this.pending.delete(requestId);\n reject(makeError(ErrorCode.REQUEST_TIMEOUT, `Command ${name} timed out`));\n }, timeoutMs);\n\n this.pending.set(requestId, { resolve, reject, timer });\n contentWindow.postMessage(encodeEnvelope(envelope), this.hostOrigin);\n });\n }\n\n /**\n * Register an event handler (dispatches the payload of kind:'event' envelopes).\n *\n * @param event - Event name.\n * @param handler - Callback.\n */\n on(event: EventName, handler: EventHandler): void {\n let set = this.eventHandlers.get(event);\n if (!set) {\n set = new Set<EventHandler>();\n this.eventHandlers.set(event, set);\n }\n set.add(handler);\n }\n\n /**\n * Unregister an event handler.\n *\n * @param event - Event name.\n * @param handler - The previously registered callback.\n */\n off(event: EventName, handler: EventHandler): void {\n const set = this.eventHandlers.get(event);\n if (set) {\n set.delete(handler);\n if (set.size === 0) {\n this.eventHandlers.delete(event);\n }\n }\n }\n\n /**\n * Register the handshake (RuntimeHello) callback. The hello phase has no checkoutId yet and is\n * handled separately. The callback is one-shot: it is cleared after the first valid hello from\n * this transport's own iframe; malformed hellos are ignored.\n *\n * @param handler - Called when a hello is received.\n */\n onHello(handler: (hello: RuntimeHello) => void): void {\n this.helloHandler = handler;\n }\n\n /**\n * Inject the runtime id negotiated during the handshake. Must be called before sending the first\n * request (initialize), otherwise the outbound envelope's runtimeId is an empty string, gets\n * silently dropped by the main endpoint, and the request times out.\n *\n * @param runtimeId - The runtimeId from RuntimeHello.\n */\n setRuntimeId(runtimeId: string): void {\n this.runtimeId = runtimeId;\n }\n\n /**\n * Destroy: remove the iframe, clear listeners, and reject pending requests with INSTANCE_DESTROYED.\n */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n window.removeEventListener('message', this.messageListener);\n\n for (const [, entry] of this.pending) {\n clearTimeout(entry.timer);\n entry.reject(makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed'));\n }\n this.pending.clear();\n this.eventHandlers.clear();\n this.helloHandler = null;\n\n if (this.iframe && this.iframe.parentNode) {\n this.iframe.parentNode.removeChild(this.iframe);\n }\n this.iframe = null;\n }\n\n /** Resolve the timeout by command name. */\n private resolveTimeout(name: CommandName): number {\n if (name === 'initialize') {\n return this.timeouts.initialize;\n }\n return this.timeouts.default;\n }\n\n /**\n * Point-to-point port relay (parent-window relay, Stripe controller model).\n *\n * Sibling iframes (main and the various Element iframes) cannot obtain each other's window\n * references, so they cannot transfer a MessagePort directly. This layer (the merchant page,\n * the only party that can reach both ends and knows their origin) does the following when it\n * receives an `element-online` from some Element iframe:\n * 1. Create a `MessageChannel`;\n * 2. `port1` → main iframe (`relay-port`, targetOrigin=hostOrigin);\n * 3. `port2` → the originating Element iframe (i.e. `event.source`, targetOrigin=hostOrigin).\n *\n * Both ends' origin is hostOrigin, so targetOrigin is always correct (and not dropped across\n * origins). This layer only carries **empty ports** and never touches card values (which are\n * transmitted end-to-end after the port is established).\n *\n * @param event Inbound message (origin already verified as hostOrigin)\n * @returns Whether it was handled as element-online (if so, the caller should return)\n */\n private tryHandleElementOnline(event: MessageEvent): boolean {\n const data = event.data as unknown;\n if (typeof data !== 'object' || data === null) {\n return false;\n }\n const msg = data as Record<string, unknown>;\n if (msg.kind !== 'element-online') {\n return false;\n }\n // Validate: checkoutId matches, fieldType is valid, source window exists.\n if (msg.checkoutId !== this.checkoutId || typeof msg.fieldType !== 'string') {\n return true;\n }\n const mainWin = this.iframe?.contentWindow;\n const elementWin = event.source as Window | null;\n if (!mainWin || !elementWin) {\n return true;\n }\n\n const channel = new MessageChannel();\n const relayMsg = {\n kind: 'relay-port' as const,\n checkoutId: this.checkoutId,\n fieldType: msg.fieldType,\n };\n // port1 → main iframe; port2 → the originating Element iframe.\n mainWin.postMessage(relayMsg, this.hostOrigin, [channel.port1]);\n elementWin.postMessage(relayMsg, this.hostOrigin, [channel.port2]);\n return true;\n }\n\n /** Handle an inbound message: filter origin, recognize relay / hello / Envelope and dispatch. */\n private handleMessage(event: MessageEvent): void {\n if (this.destroyed) {\n return;\n }\n // Security boundary: only accept messages from the hosted page origin.\n if (event.origin !== this.hostOrigin) {\n return;\n }\n\n // Point-to-point port relay: an Element iframe comes online → this layer (parent window)\n // creates a channel and transfers the two ports to the main iframe and that Element iframe\n // respectively (see below). The relay message is an object (not a string envelope) and must\n // be recognized before the string check.\n if (this.tryHandleElementOnline(event)) {\n return;\n }\n\n if (typeof event.data !== 'string') {\n return;\n }\n\n // Security boundary: hello and envelopes must come from this instance's own main iframe\n // window. This keeps concurrent checkout instances (each with its own iframe) from\n // adopting each other's hello/runtimeId, and rejects same-origin lookalike windows.\n const mainWindow = this.iframe?.contentWindow;\n if (!mainWindow || event.source !== mainWindow) {\n return;\n }\n\n // The handshake hello is parsed separately (not via the Envelope union; no checkoutId at this phase).\n let raw: unknown;\n try {\n raw = JSON.parse(event.data);\n } catch {\n return;\n }\n if (isRuntimeHello(raw)) {\n // A malformed hello is ignored (it neither throws nor consumes the one-shot handler).\n if (!isValidRuntimeHello(raw)) {\n return;\n }\n // One-shot: the first valid hello is consumed; later hellos (e.g. a dev double mount\n // or a reloaded runtime) are ignored so the negotiated runtimeId cannot be swapped.\n const handler = this.helloHandler;\n this.helloHandler = null;\n if (handler) {\n try {\n handler(raw);\n } catch (err) {\n rethrowAsync(err);\n }\n }\n return;\n }\n\n // Everything else is validated and decoded as an Envelope.\n let envelope: Envelope;\n try {\n envelope = decodeEnvelope(event.data);\n } catch {\n return;\n }\n\n // Security boundary: the envelope checkoutId must match this instance.\n if (envelope.checkoutId !== this.checkoutId) {\n return;\n }\n\n // Once a runtimeId is negotiated, drop response/event envelopes from any other runtime\n // instance (the runtime stamps every response and event with its own runtimeId).\n if (this.runtimeId !== '' && envelope.runtimeId !== this.runtimeId) {\n return;\n }\n\n if (envelope.kind === 'response') {\n this.handleResponse(envelope);\n } else if (envelope.kind === 'event') {\n this.handleEvent(envelope);\n }\n // kind:'request' from main → SDK should not occur; ignore.\n }\n\n /** Dispatch a response to the paired pending request. */\n private handleResponse(envelope: Extract<Envelope, { kind: 'response' }>): void {\n const entry = this.pending.get(envelope.requestId);\n if (!entry) {\n return;\n }\n this.pending.delete(envelope.requestId);\n clearTimeout(entry.timer);\n if (envelope.ok) {\n entry.resolve(envelope.data);\n } else {\n entry.reject(envelope.error);\n }\n }\n\n /** Dispatch an event to the registered handlers. */\n private handleEvent(envelope: Extract<Envelope, { kind: 'event' }>): void {\n const set = this.eventHandlers.get(envelope.name as EventName);\n if (!set) {\n return;\n }\n // Iterate a snapshot so handlers that call on/off during dispatch cannot affect this pass.\n for (const handler of [...set]) {\n try {\n handler(envelope.payload);\n } catch (err) {\n rethrowAsync(err);\n }\n }\n }\n}\n","/**\n * CheckoutElement — the merchant-side Element handle (spec 6).\n *\n * Responsibilities:\n * - Constructed by `CheckoutInstance.create` (in unit tests, injected via a mock transport +\n * constructor args).\n * - Mount a **visible** iframe at the merchant DOM target and forward Element commands through the\n * transport.\n * - Maintain the state machine `created → loading → ready → destroyed` (with `loadError` as a side branch).\n * - Subscribe to the transport's `elementReady` / `loadError` events, filter by **its own elementId**,\n * and drive the resolve / reject of `mount()`.\n *\n * Security constraint (AGENTS/spec): this layer only does DOM mounting and protocol command\n * forwarding and **never touches card values**. Card data exists only inside the hosted iframe and\n * is never transmitted via this handle or the transport.\n */\n\nimport {\n ErrorCode,\n isIframeResizeMessage,\n type Appearance,\n type AvailableWallets,\n type CheckoutError,\n type CommandName,\n type ElementOptions,\n type ElementStatus,\n type ElementType,\n type EventName,\n type EventPayloadMap,\n type ExpressAvailabilityChangeEvent,\n type ExpressCheckoutElementOptions,\n} from '@sunbay/checkout-sdk-protocol';\nimport { runtimeUrl } from './config/env';\n\n/**\n * The minimal interface the transport depends on (satisfied by MainFrameTransport).\n *\n * Only declares the methods the Element handle needs, to make mock injection in unit tests easy.\n */\nexport interface ElementTransport {\n request(name: CommandName, payload: unknown): Promise<unknown>;\n on(event: EventName, handler: (payload: unknown) => void): void;\n off(event: EventName, handler: (payload: unknown) => void): void;\n}\n\n/** CheckoutElement constructor parameters (assembled by CheckoutInstance.create). */\nexport interface CheckoutElementOptions {\n /** Unique Element id (generated by the instance, used to pair commands/events). */\n elementId: string;\n /** Element type (determines the iframe path and available actions). */\n type: ElementType;\n /** Hosted page origin (without a trailing slash). */\n hostOrigin: string;\n /**\n * The current checkout session id. Sent with the iframe src as `?checkoutId=`, so that hosted\n * fields/element iframes join the correct same-origin signaling channel\n * (`sunbay-checkout:<checkoutId>`) and pair with main; missing it causes the field channel name\n * to mismatch and never become ready.\n */\n checkoutId: string;\n /** The transport layer. */\n transport: ElementTransport;\n /** Initial Element configuration (sent with createElement). */\n initialOptions?: ElementOptions;\n /**\n * Handle destruction callback (injected by CheckoutInstance). Called with this elementId when\n * `destroy()` successfully destroys the handle, so the instance removes itself from the\n * mutual-exclusion registry (elements Map), thereby allowing a mutually-exclusive Element of the\n * same kind to be recreated after destruction (e.g. switching expressCheckout's\n * buttonType/buttonHeight requires recreating the iframe). Not called by `unmount()` (which\n * keeps the handle, still occupies the slot, and can remount).\n */\n onDestroy?: (elementId: string) => void;\n /**\n * Initial color scheme (from createCheckout's appearance.colorScheme).\n * Only when provided is it appended to the iframe src's `&colorScheme=<value>`, so the hosted\n * iframe renders with that scheme on the first frame (no flash). When absent it is not appended\n * and the hosted side handles the default (light). Runtime switching goes through the\n * updateCheckout command, not here.\n */\n colorScheme?: 'light' | 'dark' | 'auto';\n /**\n * Initial appearance customization (from createCheckout's appearance).\n * Only when it contains `variables` or `rules` is it serialized into the iframe src's\n * `&appearance=<encodeURIComponent(JSON)>`, so the hosted iframe renders with that appearance on\n * the first frame (no flash). When it contains only `colorScheme` (no variables/rules) it is not\n * appended, to avoid an empty appearance string; colorScheme goes via the separate\n * `&colorScheme=`. Runtime switching goes through the updateCheckout command, not here.\n */\n appearance?: Appearance;\n}\n\n/** Default time (ms) `mount()` waits for the hosted Element to become ready. */\nexport const DEFAULT_MOUNT_TIMEOUT_MS = 30_000;\n\n/** Options for {@link CheckoutElement.mount}. */\nexport interface MountOptions {\n /**\n * Maximum time (ms) to wait for the Element to become ready. Defaults to 30000. On expiry the\n * iframe is removed, the status becomes `loadError` and the promise rejects with\n * `RUNTIME_LOAD_FAILED`.\n */\n timeoutMs?: number;\n}\n\n/** A merchant handler as stored internally (loosely typed; typing lives on the public methods). */\ntype UserHandler = (payload: unknown) => void;\n\n/** The common structure of an event payload (contains elementId, used to filter by the own handle). */\ninterface WithElementId {\n elementId?: string;\n}\n\n/** The loadError event payload structure. */\ninterface LoadErrorPayload extends WithElementId {\n error: CheckoutError;\n}\n\n/** The elementReady event payload structure (expressCheckout additionally carries availableWallets). */\ninterface ElementReadyPayload extends WithElementId {\n availableWallets?: AvailableWallets;\n}\n\n/** The split field types (routed to /embed/sdk/field/<type>). */\nconst FIELD_TYPES: readonly ElementType[] = ['cardNumber', 'cardExpiry', 'cardCvc'];\n\n/** The input classes that provide focus/blur/clear (expressCheckout excluded). */\nconst INPUT_TYPES: readonly ElementType[] = [\n 'cardNumber',\n 'cardExpiry',\n 'cardCvc',\n 'card',\n 'address',\n];\n\n/** Build a structured CheckoutError (configuration category, for the handle's local errors). */\nfunction makeError(code: string, message: string, elementId?: string): CheckoutError {\n const rand = Math.random().toString(36).slice(2);\n return {\n code,\n message,\n category: 'configuration',\n errorId: `err_${Date.now().toString(36)}_${rand}`,\n elementId,\n };\n}\n\n/**\n * Determine whether the payload targets this elementId (**strict match**).\n *\n * Only when `payload.elementId === elementId` is it considered this Element's elementReady/loadError.\n * Missing elementId or inequality both fail to match, avoiding event cross-talk when multiple\n * Elements (T6) share the same transport.\n * (The protocol guarantees elementReady/loadError always carry an elementId.)\n */\nfunction matchesElement(payload: unknown, elementId: string): boolean {\n if (typeof payload !== 'object' || payload === null) {\n return false;\n }\n return (payload as WithElementId).elementId === elementId;\n}\n\nexport class CheckoutElement {\n /** Unique Element id. */\n readonly elementId: string;\n /** Element type. */\n readonly type: ElementType;\n /** The address Element's mode (billing/shipping; only meaningful for address), used by the instance to judge mutual exclusion by mode. */\n readonly mode: string | undefined;\n\n private readonly hostOrigin: string;\n private readonly checkoutId: string;\n private readonly transport: ElementTransport;\n private options: ElementOptions | undefined;\n /** Initial color scheme (appended to the iframe src; not appended when absent). */\n private readonly colorScheme: 'light' | 'dark' | 'auto' | undefined;\n /** Initial appearance customization (appended to the iframe src when it contains variables/rules; not appended when absent or colorScheme-only). */\n private readonly appearance: Appearance | undefined;\n /** Destruction callback (injected by the instance): called at the end of destroy() so the instance removes itself from the mutual-exclusion registry to free the slot. */\n private readonly onDestroy: ((elementId: string) => void) | undefined;\n\n private status: ElementStatus = 'created';\n private container: HTMLElement | null = null;\n private iframe: HTMLIFrameElement | null = null;\n\n /** Event handlers temporarily subscribed during mount (unbound after resolve/reject). */\n private readyHandler: ((payload: unknown) => void) | null = null;\n private loadErrorHandler: ((payload: unknown) => void) | null = null;\n /**\n * Cancels the in-flight mount (clears its timer/listeners and rejects its promise). Null when no\n * mount is in flight. Used by `unmount()` / `destroy()` while the Element is still loading.\n */\n private abortMount: ((reason: CheckoutError) => void) | null = null;\n\n /**\n * expressCheckout only: a snapshot of each wallet's availability.\n * Initially from elementReady.availableWallets, then updated by expressAvailabilityChange.\n */\n private availableWallets: AvailableWallets | undefined;\n /** expressCheckout only: the persistently subscribed expressAvailabilityChange handler (unbound on destroy). */\n private availabilityHandler: ((payload: unknown) => void) | null = null;\n\n /** Merchant listeners registered via `on`: event → (original handler → transport wrapper). Cleared on destroy. */\n private readonly userListeners = new Map<EventName, Map<UserHandler, UserHandler>>();\n\n /**\n * iframe auto-height: the window 'message' listener that stays resident during mount (unbound\n * when the iframe disappears/is destroyed). Keeps a reference so removeEventListener can be\n * called; null means not listening.\n */\n private resizeHandler: ((e: MessageEvent) => void) | null = null;\n /** The most recently applied iframe height (px), used for deduplication to avoid redundant style writes; null means not yet set. */\n private lastHeight: number | null = null;\n\n constructor(opts: CheckoutElementOptions) {\n this.elementId = opts.elementId;\n this.type = opts.type;\n this.hostOrigin = opts.hostOrigin;\n this.checkoutId = opts.checkoutId;\n this.transport = opts.transport;\n this.options = opts.initialOptions;\n this.colorScheme = opts.colorScheme;\n this.appearance = opts.appearance;\n this.mode = (opts.initialOptions as { mode?: string } | undefined)?.mode;\n this.onDestroy = opts.onDestroy;\n this.installInputActions();\n this.installExpressAvailability();\n }\n\n /** The current status (read-only snapshot, for external/test observation). */\n getStatus(): ElementStatus {\n return this.status;\n }\n\n /**\n * expressCheckout only: return the current snapshot of each wallet's availability (always\n * undefined for other types).\n *\n * The initial value comes from elementReady's availableWallets, then is updated by\n * expressAvailabilityChange.\n *\n * @returns The availability snapshot; undefined when not yet ready or non-express.\n */\n getAvailableWallets(): AvailableWallets | undefined {\n return this.availableWallets;\n }\n\n /**\n * Mount at the merchant DOM target: insert a visible iframe, send createElement, await elementReady.\n *\n * Failure modes: a hosted `loadError` / command failure rejects with that error; waiting longer\n * than `opts.timeoutMs` (default 30000ms) removes the iframe and rejects `RUNTIME_LOAD_FAILED`;\n * calling `unmount()` while loading rejects with `RUNTIME_LOAD_FAILED` (\"mount cancelled\");\n * calling `destroy()` (or destroying the instance) while loading rejects `INSTANCE_DESTROYED`.\n * A late `elementReady` after any of these is ignored and never flips the status to ready.\n *\n * @param selectorOrEl - A CSS selector or an HTMLElement container; the container must be unique and empty.\n * @param opts - Optional mount options (`timeoutMs`).\n * @returns Resolves after elementReady; on failure removes the node and rejects (loadError / INVALID_OPTIONS).\n * @throws INSTANCE_DESTROYED when already destroyed.\n * @example\n * await element.mount('#card-field', { timeoutMs: 20000 });\n */\n mount(selectorOrEl: string | HTMLElement, opts?: MountOptions): Promise<void> {\n this.assertAlive();\n\n if (this.status === 'loading' || this.status === 'ready') {\n return Promise.reject(\n makeError(\n ErrorCode.ELEMENT_CONFLICT,\n 'This Element is already mounted; mount cannot be called twice',\n this.elementId\n )\n );\n }\n\n const container = this.resolveContainer(selectorOrEl);\n if (!container) {\n return Promise.reject(\n makeError(\n ErrorCode.INVALID_OPTIONS,\n 'Target container not found or not uniquely resolvable',\n this.elementId\n )\n );\n }\n if (container.childElementCount > 0) {\n return Promise.reject(\n makeError(ErrorCode.INVALID_OPTIONS, 'Target container is not empty', this.elementId)\n );\n }\n\n this.status = 'loading';\n this.container = container;\n\n const iframe = document.createElement('iframe');\n iframe.src = this.resolveSrc();\n iframe.title = `sunbay-checkout-${this.type}`;\n iframe.setAttribute('data-element-id', this.elementId);\n // Grant the Permissions Policy features the hosted iframe needs for cross-origin payment\n // flows, each scoped to 'self' and the hostOrigin (not opened to any other origin):\n // - `payment`: the Payment Request API used by Apple Pay / Google Pay. Without it the\n // browser denies the API inside this cross-origin iframe (\"payment is not allowed in\n // this document\"); Safari 17+ specifically requires allow=\"payment\" for cross-origin\n // Apple Pay.\n // - `publickey-credentials-get`: WebAuthn get(), used by passkey / biometric payment\n // verification (e.g. 3DS/SCA). Cross-origin iframes need it explicitly granted.\n // All element types carry the same allowlist so the SDK works uniformly regardless of\n // which element drives a wallet / WebAuthn flow.\n iframe.setAttribute(\n 'allow',\n `payment 'self' ${this.hostOrigin}; publickey-credentials-get 'self' ${this.hostOrigin}`\n );\n iframe.style.border = '0';\n iframe.style.width = '100%';\n iframe.style.display = 'block';\n // Height is fully driven by the iframe auto-resize protocol (child reports a ceil()'d\n // height via postMessage; see installResizeListener). Disable the iframe's own scrollbar\n // so sub-pixel content height differences on high-DPR browsers never surface a spurious\n // scrollbar (observed on the express button at devicePixelRatio=2).\n iframe.setAttribute('scrolling', 'no');\n container.appendChild(iframe);\n this.iframe = iframe;\n this.installResizeListener();\n\n const requested = opts?.timeoutMs;\n const timeoutMs =\n typeof requested === 'number' && Number.isFinite(requested) && requested > 0\n ? requested\n : DEFAULT_MOUNT_TIMEOUT_MS;\n\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const cleanup = (): void => {\n settled = true;\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n this.abortMount = null;\n if (this.readyHandler) {\n this.transport.off('elementReady', this.readyHandler);\n this.readyHandler = null;\n }\n if (this.loadErrorHandler) {\n this.transport.off('loadError', this.loadErrorHandler);\n this.loadErrorHandler = null;\n }\n };\n\n const onReady = (payload: unknown): void => {\n if (settled || !matchesElement(payload, this.elementId)) {\n return;\n }\n cleanup();\n // expressCheckout: capture the initial wallet availability carried by ready.\n const wallets = (payload as ElementReadyPayload).availableWallets;\n if (wallets) {\n this.availableWallets = wallets;\n }\n this.status = 'ready';\n resolve();\n };\n\n const onLoadError = (payload: unknown): void => {\n if (settled || !matchesElement(payload, this.elementId)) {\n return;\n }\n cleanup();\n this.status = 'loadError';\n this.removeIframe();\n // Release even if the createElement response has not arrived yet: the hosted side may\n // already have registered the element, and destroyElement is idempotent there.\n this.releaseHostedElement();\n const err = (payload as LoadErrorPayload)?.error;\n reject(\n err ??\n makeError(\n ErrorCode.RUNTIME_LOAD_FAILED,\n 'Failed to load Element',\n this.elementId\n )\n );\n };\n\n this.readyHandler = onReady;\n this.loadErrorHandler = onLoadError;\n this.transport.on('elementReady', onReady);\n this.transport.on('loadError', onLoadError);\n\n // Cancellation by unmount()/destroy(): the caller owns status/iframe handling.\n this.abortMount = (reason: CheckoutError): void => {\n if (settled) {\n return;\n }\n cleanup();\n reject(reason);\n };\n\n timer = setTimeout(() => {\n if (settled) {\n return;\n }\n cleanup();\n this.status = 'loadError';\n this.removeIframe();\n // Release the hosted registration so a retry mount() does not hit ELEMENT_CONFLICT.\n this.releaseHostedElement();\n reject(\n makeError(\n ErrorCode.RUNTIME_LOAD_FAILED,\n `Element did not become ready within ${timeoutMs}ms`,\n this.elementId\n )\n );\n }, timeoutMs);\n\n // Send the createElement command; a command-level failure also goes through the loadError side branch.\n this.transport\n .request('createElement', {\n elementId: this.elementId,\n type: this.type,\n options: this.options,\n })\n .then(\n () => undefined,\n (cmdErr: unknown) => {\n if (settled) {\n return;\n }\n cleanup();\n this.status = 'loadError';\n this.removeIframe();\n reject(cmdErr as CheckoutError);\n }\n );\n });\n }\n\n /** Best-effort, fire-and-forget release of the hosted element registration; never throws. */\n private releaseHostedElement(): void {\n try {\n void Promise.resolve(\n this.transport.request('destroyElement', { elementId: this.elementId })\n ).catch(() => undefined);\n } catch {\n // Ignore: release is best-effort.\n }\n }\n\n /**\n * Unmount: send destroyElement, remove the iframe; idempotent; keeps the handle and configuration.\n *\n * @returns Resolves on completion (resolves directly when not mounted).\n * @throws INSTANCE_DESTROYED when already destroyed.\n */\n async unmount(): Promise<void> {\n this.assertAlive();\n if (this.status !== 'ready' && this.status !== 'loading') {\n // Not mounted: idempotent no-op.\n return;\n }\n // Cancel an in-flight mount first so its promise rejects and a late elementReady is ignored.\n this.abortMount?.(\n makeError(\n ErrorCode.RUNTIME_LOAD_FAILED,\n 'Mount cancelled: the Element was unmounted while loading',\n this.elementId\n )\n );\n try {\n await this.transport.request('destroyElement', { elementId: this.elementId });\n } finally {\n this.removeIframe();\n this.container = null;\n this.status = 'created';\n }\n }\n\n /**\n * Destroy the handle: idempotent; remove the iframe; afterwards any non-destroy/off call throws INSTANCE_DESTROYED.\n */\n destroy(): void {\n if (this.status === 'destroyed') {\n return;\n }\n const wasHosted = this.status === 'loading' || this.status === 'ready';\n // Reject an in-flight mount (also clears its timer and listeners).\n this.abortMount?.(\n makeError(\n ErrorCode.INSTANCE_DESTROYED,\n 'Mount cancelled: the Element was destroyed while loading',\n this.elementId\n )\n );\n if (this.readyHandler) {\n this.transport.off('elementReady', this.readyHandler);\n this.readyHandler = null;\n }\n if (this.loadErrorHandler) {\n this.transport.off('loadError', this.loadErrorHandler);\n this.loadErrorHandler = null;\n }\n if (this.availabilityHandler) {\n this.transport.off('expressAvailabilityChange', this.availabilityHandler);\n this.availabilityHandler = null;\n }\n for (const [event, wrappers] of this.userListeners) {\n for (const wrapper of wrappers.values()) {\n this.transport.off(event, wrapper);\n }\n }\n this.userListeners.clear();\n this.removeIframe();\n this.container = null;\n this.status = 'destroyed';\n if (wasHosted) {\n // Release the hosted registration; best effort (the transport may already be gone).\n try {\n void Promise.resolve(\n this.transport.request('destroyElement', { elementId: this.elementId })\n ).catch(() => undefined);\n } catch {\n // Ignore: destroy() must never throw.\n }\n }\n // Notify the instance to remove itself from the mutual-exclusion registry, freeing the slot to allow recreating a mutually-exclusive Element of the same kind after destruction.\n this.onDestroy?.(this.elementId);\n }\n\n /**\n * Update the Element configuration: send updateElement; illegal fields are rejected wholesale by the hosted side.\n *\n * @param patch - Configuration delta.\n * @returns Resolves after successfully writing back the local options.\n * @throws INSTANCE_DESTROYED when already destroyed.\n */\n async update(patch: Partial<ElementOptions>): Promise<void> {\n this.assertAlive();\n const resp = await this.transport.request('updateElement', {\n elementId: this.elementId,\n patch,\n });\n const next = (resp as { options?: ElementOptions } | undefined)?.options;\n if (next) {\n this.options = next;\n }\n }\n\n /**\n * Register an event handler (passed through to the transport, dispatched by event name).\n *\n * @param event - Event name.\n * @param handler - Callback.\n * @throws INSTANCE_DESTROYED when already destroyed.\n */\n on<E extends EventName>(event: E, handler: (payload: EventPayloadMap[E]) => void): void {\n this.assertAlive();\n let wrappers = this.userListeners.get(event);\n if (!wrappers) {\n wrappers = new Map();\n this.userListeners.set(event, wrappers);\n }\n if (wrappers.has(handler as UserHandler)) {\n return;\n }\n // The only typed→loose cast: the transport is loosely typed and the protocol guarantees the\n // payload shape per event name. The wrapper scopes delivery to this element: payloads that\n // carry a different elementId are dropped, payloads without one pass through unchanged.\n const typed = handler as UserHandler;\n const wrapper = (payload: unknown): void => {\n const target = (payload as WithElementId | null | undefined)?.elementId;\n if (target !== undefined && target !== this.elementId) {\n return;\n }\n typed(payload);\n };\n wrappers.set(typed, wrapper);\n this.transport.on(event, wrapper);\n }\n\n /**\n * Unregister an event handler (still safe to call after destruction).\n *\n * @param event - Event name.\n * @param handler - The previously registered callback.\n */\n off<E extends EventName>(event: E, handler: (payload: EventPayloadMap[E]) => void): void {\n const wrappers = this.userListeners.get(event);\n const wrapper = wrappers?.get(handler as UserHandler);\n if (!wrappers || !wrapper) {\n return;\n }\n wrappers.delete(handler as UserHandler);\n this.transport.off(event, wrapper);\n }\n\n /** Focus (input classes only, not provided by expressCheckout). */\n focus?: () => Promise<void>;\n /** Blur (input classes only, not provided by expressCheckout). */\n blur?: () => Promise<void>;\n /** Clear (input classes only, not provided by expressCheckout). */\n clear?: () => Promise<void>;\n\n /** Install input-class action methods (automatically called after construction). */\n private installInputActions(): void {\n if (!INPUT_TYPES.includes(this.type)) {\n return;\n }\n this.focus = (): Promise<void> => this.sendAction('focus');\n this.blur = (): Promise<void> => this.sendAction('blur');\n this.clear = (): Promise<void> => this.sendAction('clear');\n }\n\n /**\n * expressCheckout only: persistently subscribe to expressAvailabilityChange and update the local availability snapshot.\n *\n * This event payload has no elementId; express is a singleton (guaranteed by CheckoutInstance),\n * so there is no need to filter by elementId. Non-express types do not subscribe.\n */\n private installExpressAvailability(): void {\n if (this.type !== 'expressCheckout') {\n return;\n }\n const handler = (payload: unknown): void => {\n if (typeof payload !== 'object' || payload === null) {\n return;\n }\n const wallets = (payload as ExpressAvailabilityChangeEvent).availableWallets;\n if (wallets) {\n this.availableWallets = wallets;\n }\n };\n this.availabilityHandler = handler;\n this.transport.on('expressAvailabilityChange', handler);\n }\n\n /** Send one input-class action command (synchronously throws INSTANCE_DESTROYED after destruction). */\n private sendAction(name: 'focus' | 'blur' | 'clear'): Promise<void> {\n this.assertAlive();\n return this.transport.request(name, { elementId: this.elementId }).then(() => undefined);\n }\n\n /** Throw INSTANCE_DESTROYED if already destroyed. */\n private assertAlive(): void {\n if (this.status === 'destroyed') {\n throw makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed', this.elementId);\n }\n }\n\n /** Resolve the mount container (the selector must uniquely match a single element). */\n private resolveContainer(selectorOrEl: string | HTMLElement): HTMLElement | null {\n if (typeof selectorOrEl !== 'string') {\n return selectorOrEl;\n }\n const nodes = document.querySelectorAll(selectorOrEl);\n if (nodes.length !== 1) {\n return null;\n }\n const node = nodes[0];\n return node instanceof HTMLElement ? node : null;\n }\n\n /**\n * Resolve the iframe src: split fields go to /embed/sdk/field/, the rest to /embed/sdk/element/, with\n * checkoutId and elementId; if an initial colorScheme is provided, append `&colorScheme=<value>`\n * (no flash on the first frame); if the initial appearance contains variables or rules, append\n * `&appearance=<encodeURIComponent(JSON.stringify(appearance))>` (takes effect on the first\n * frame, no flash). An appearance containing only colorScheme (no variables/rules) is not\n * appended, to avoid an empty appearance string. For expressCheckout, additionally append the\n * wallet toggles / per-wallet buttonType / global buttonHeight (see {@link resolveExpressQuery}).\n *\n * elementId is sent with the src so the hosted child echoes it verbatim in iframe-resize\n * messages, letting the parent window dispatch the height per handle among multiple iframes on\n * the same page.\n */\n private resolveSrc(): string {\n const segment = FIELD_TYPES.includes(this.type) ? 'field' : 'element';\n let query = `?checkoutId=${encodeURIComponent(this.checkoutId)}`;\n query += `&elementId=${encodeURIComponent(this.elementId)}`;\n // address: pass the mode (billing/shipping) through so the hosted page binds the\n // correct same-origin field channel (address:<mode>). Without it, both address\n // Elements fall back to the default mode and the second never pairs/readies.\n if (this.type === 'address') {\n const { mode, style } = (this.options as { mode?: string; style?: unknown } | undefined) ?? {};\n if (mode) {\n query += `&mode=${encodeURIComponent(mode)}`;\n }\n // style: only the known values travel; anything else falls back to the default\n // full form on the hosted side, so it is simply not sent.\n if (style === 'simple' || style === 'full') {\n query += `&style=${style}`;\n }\n }\n if (this.colorScheme) {\n query += `&colorScheme=${encodeURIComponent(this.colorScheme)}`;\n }\n // Effective appearance for the first frame: a per-element appearance (from\n // create(type, { appearance })) takes precedence over the instance-level appearance\n // (from createCheckout). Serialize only when it contains variables or rules (avoid an\n // empty appearance string; colorScheme is passed through separately).\n const effectiveAppearance = this.perElementAppearance() ?? this.appearance;\n if (effectiveAppearance && (effectiveAppearance.variables || effectiveAppearance.rules)) {\n query += `&appearance=${encodeURIComponent(JSON.stringify(effectiveAppearance))}`;\n }\n // expressCheckout: pass the express options from create's second argument (wallet toggles /\n // buttonType / buttonHeight) through to the hosted iframe, so the merchant's configuration\n // takes effect on the first frame (C1 broken-link fix).\n if (this.type === 'expressCheckout') {\n query += this.resolveExpressQuery();\n }\n return `${runtimeUrl(this.hostOrigin, segment, this.type)}${query}`;\n }\n\n /**\n * Extract a per-element appearance (from the Element's own options, i.e. the second\n * argument of create(type, options)). Returns undefined when absent. Used so per-element\n * customization (e.g. CardFieldElementOptions.appearance) is honored on the first frame.\n */\n private perElementAppearance(): Appearance | undefined {\n const opts = this.options as { appearance?: Appearance } | undefined;\n return opts?.appearance;\n }\n\n /**\n * Build the expressCheckout-specific query fragment (only called for expressCheckout):\n * - a wallet explicitly set to `false` → `&applePay=false` / `&googlePay=false` (force hidden,\n * preserving the existing toggle semantics; `true` / absent → automatic, no toggle appended);\n * - a wallet configured in object form containing `buttonType` → `&applePayButtonType=<v>` /\n * `&googlePayButtonType=<v>` (boolean toggle / absent → not appended);\n * - global `buttonHeight` (a finite number) → `&buttonHeight=<n>`.\n *\n * Appended only when there is a value; empty strings are not appended. This fragment never\n * touches card values and only carries display configuration.\n *\n * @returns A query fragment starting with `&` (returns an empty string when nothing is appendable).\n */\n private resolveExpressQuery(): string {\n const options = this.options as ExpressCheckoutElementOptions | undefined;\n if (!options) {\n return '';\n }\n let query = '';\n const applePay = options.paymentMethods?.applePay;\n const googlePay = options.paymentMethods?.googlePay;\n // Wallet toggle: only an explicit false (force hidden) is sent, preserving the existing toggle semantics.\n if (applePay === false) {\n query += `&applePay=false`;\n }\n if (googlePay === false) {\n query += `&googlePay=false`;\n }\n // Per-wallet buttonType: sent only when in object form and containing buttonType.\n if (typeof applePay === 'object' && applePay.buttonType) {\n query += `&applePayButtonType=${encodeURIComponent(applePay.buttonType)}`;\n }\n if (typeof googlePay === 'object' && googlePay.buttonType) {\n query += `&googlePayButtonType=${encodeURIComponent(googlePay.buttonType)}`;\n }\n // Global button height: sent only when a finite number (the hosted side then clamps to [30,64]).\n if (typeof options.buttonHeight === 'number' && Number.isFinite(options.buttonHeight)) {\n query += `&buttonHeight=${encodeURIComponent(String(options.buttonHeight))}`;\n }\n return query;\n }\n\n /**\n * Install the iframe auto-height listener: subscribe to window 'message', only trust a valid\n * {@link IframeResizeMessage} from this iframe's `contentWindow` with origin === hostOrigin, and\n * when the elementId matches this handle, adjust the outer iframe's height to the content's real\n * height (width stays 100%).\n *\n * Security: first verify `event.source === iframe.contentWindow` (the key source check), then\n * verify `event.origin === hostOrigin` (a stricter same-origin check), to prevent cross-origin forgery.\n * Height deduplication: skip if identical to the last one, to avoid redundant style writes.\n */\n private installResizeListener(): void {\n const handler = (event: MessageEvent): void => {\n if (!this.iframe) {\n return;\n }\n if (event.source !== this.iframe.contentWindow) {\n return;\n }\n if (event.origin !== this.hostOrigin) {\n return;\n }\n if (!isIframeResizeMessage(event.data)) {\n return;\n }\n if (event.data.elementId !== this.elementId) {\n return;\n }\n const { height } = event.data;\n if (height === this.lastHeight) {\n return;\n }\n this.lastHeight = height;\n this.iframe.style.height = `${height}px`;\n };\n this.resizeHandler = handler;\n window.addEventListener('message', handler);\n }\n\n /** Unbind the iframe auto-height listener and reset the deduplication state (idempotent). */\n private teardownResizeListener(): void {\n if (this.resizeHandler) {\n window.removeEventListener('message', this.resizeHandler);\n this.resizeHandler = null;\n }\n this.lastHeight = null;\n }\n\n /** Remove the iframe DOM node (if present) and unbind the auto-height listener. */\n private removeIframe(): void {\n this.teardownResizeListener();\n if (this.iframe && this.iframe.parentNode) {\n this.iframe.parentNode.removeChild(this.iframe);\n }\n this.iframe = null;\n }\n\n /** Factory: equivalent to `new CheckoutElement(opts)` (a unified entry for CheckoutInstance). */\n static create(opts: CheckoutElementOptions): CheckoutElement {\n return new CheckoutElement(opts);\n }\n}\n","/**\n * CheckoutInstance — the merchant-side checkout instance handle (spec 4 / 7 / 8).\n *\n * Responsibilities:\n * - Constructed by `createCheckout` after a successful handshake + initialize (holds the ready\n * transport, runtimeId, capabilities, and the initial PublicSessionView).\n * - `create` assembles and returns a {@link CheckoutElement}, maintaining a **mutual-exclusion\n * registry** (card and split fields are mutually exclusive, same-mode addresses are mutually\n * exclusive, expressCheckout is a singleton → `ELEMENT_CONFLICT`).\n * - `confirm` generates an operationId, sends the confirm command to obtain accepted, and the\n * Promise is fulfilled by a later `paymentResult` event with the same operationId; calling\n * confirm again while in progress → `CHECKOUT_BUSY`.\n * - `getSession/refresh/getPaymentStatus/updateCheckout` pass through to the corresponding commands.\n * - `destroy` is idempotent: releases Elements, unbinds listeners, rejects the pending confirm with\n * INSTANCE_DESTROYED, sends the destroy command and destroys the transport; any late\n * `paymentResult` afterwards is ignored.\n *\n * Security constraint (AGENTS/spec): this layer only ferries protocol commands/events and\n * **never touches card values**.\n */\n\nimport { CheckoutElement, type CheckoutElementOptions } from './Element';\nimport {\n ErrorCode,\n type Appearance,\n type AddressInfo,\n type CheckoutError,\n type CommandName,\n type ConfirmReq,\n type ElementOptions,\n type ElementType,\n type EventName,\n type EventPayloadMap,\n type WarningEvent,\n type GetPaymentStatusResp,\n type PaymentOutcome,\n type PaymentResultEvent,\n type PublicSessionView,\n type UpdateCheckoutReq,\n} from '@sunbay/checkout-sdk-protocol';\n\n/**\n * The minimal transport interface CheckoutInstance depends on (satisfied by MainFrameTransport).\n *\n * Adds `onHello/createHiddenIframe/destroy` beyond ElementTransport, used by createCheckout for\n * handshake wiring and for instance destruction. Tests can inject a mock.\n */\nexport interface InstanceTransport {\n request(name: CommandName, payload: unknown): Promise<unknown>;\n on(event: EventName, handler: (payload: unknown) => void): void;\n off(event: EventName, handler: (payload: unknown) => void): void;\n onHello(handler: (hello: unknown) => void): void;\n setRuntimeId(runtimeId: string): void;\n createHiddenIframe(): unknown;\n destroy(): void;\n}\n\n/** CheckoutInstance constructor parameters (assembled by createCheckout). */\nexport interface CheckoutInstanceOptions {\n /** Unique checkout id. */\n checkoutId: string;\n /** Negotiated runtime id (from RuntimeHello). */\n runtimeId: string;\n /** Hosted page origin (without a trailing slash). */\n hostOrigin: string;\n /** The ready transport. */\n transport: InstanceTransport;\n /** The capabilities returned by initialize. */\n capabilities: string[];\n /** The initial session view returned by initialize. */\n session: PublicSessionView;\n /**\n * Warnings produced during initialize (the instance did not exist yet, so they could not be\n * delivered as events). Replayed once to the first `warning` listener.\n */\n initialWarnings?: WarningEvent[];\n /**\n * Initial appearance customization (from createCheckout's appearance).\n * Passed through to every created Element and serialized into its iframe src (no flash on the\n * first frame):\n * - colorScheme appended as `&colorScheme=`;\n * - variables/rules appended as `&appearance=` (only when non-empty).\n * Not appended when absent. Runtime switching goes through the updateCheckout command.\n */\n appearance?: Appearance;\n}\n\n/** Default time (ms) `confirm()` waits for a terminal outcome before resolving `pending`. */\nexport const CONFIRM_RESULT_DEADLINE_MS = 120_000;\n\n/**\n * Optional confirm parameters (aligned with ConfirmReq, minus the instance-generated operationId,\n * plus two SDK-only options that are never sent to the runtime).\n */\nexport type ConfirmOptions = Omit<ConfirmReq, 'operationId'> & {\n /**\n * Called synchronously with the generated operationId, before the `confirm` command is sent.\n * Lets the merchant persist the id early (e.g. to reconcile after a timeout or page reload).\n */\n onOperation?: (operationId: string) => void;\n /**\n * Per-call override of the result watchdog in milliseconds (default\n * {@link CONFIRM_RESULT_DEADLINE_MS}). Must be a positive finite number, otherwise the default\n * applies.\n */\n resultTimeoutMs?: number;\n};\n\n/** Pairing record for a pending confirm. */\ninterface PendingConfirm {\n operationId: string;\n /** Whether the merchant-facing Promise has already settled (the slot may still be held). */\n settled: boolean;\n resolve: (outcome: PaymentOutcome) => void;\n reject: (reason: CheckoutError) => void;\n /** Result watchdog timer. */\n watchdog: ReturnType<typeof setTimeout> | null;\n /** txnId of the most recent non-terminal `pending` outcome, if any. */\n lastPendingTxnId: string | undefined;\n}\n\n/** The set of split card field types. */\nconst CARD_FIELD_TYPES: readonly ElementType[] = ['cardNumber', 'cardExpiry', 'cardCvc'];\n\n/** Generate a unique id. */\nfunction genId(prefix: string): string {\n const rand = Math.random().toString(36).slice(2);\n return `${prefix}_${Date.now().toString(36)}_${rand}`;\n}\n\n/** Construct a structured CheckoutError. */\nfunction makeError(\n code: string,\n message: string,\n category: CheckoutError['category'] = 'configuration'\n): CheckoutError {\n return {\n code,\n message,\n category,\n errorId: genId('err'),\n };\n}\n\nexport class CheckoutInstance {\n /** Unique checkout id. */\n readonly checkoutId: string;\n /** Negotiated runtime id. */\n readonly runtimeId: string;\n /** Negotiated capability set. */\n readonly capabilities: readonly string[];\n\n private readonly hostOrigin: string;\n private readonly transport: InstanceTransport;\n private session: PublicSessionView;\n /** Initial appearance customization (passed through to each created Element's iframe src). */\n private readonly appearance: Appearance | undefined;\n\n /** Created Elements (indexed by elementId). */\n /**\n * The **single source of truth** for the mutual-exclusion registry: elementId → the created\n * CheckoutElement. Mutual-exclusion decisions are derived live from this Map (see\n * {@link assertNoConflict}); an element's `destroy()` removes itself from this Map via\n * {@link releaseElement} to free the slot (allowing a mutually-exclusive Element of the same\n * kind to be recreated after destruction).\n */\n private readonly elements = new Map<string, CheckoutElement>();\n\n /** The current pending confirm (at most one at a time). */\n private pendingConfirm: PendingConfirm | null = null;\n /** The paymentResult event subscription handler (unbound on destroy). */\n private readonly paymentResultHandler: (payload: unknown) => void;\n\n private destroyed = false;\n\n /** Warnings from initialize not yet delivered to any `warning` listener. */\n private pendingWarnings: WarningEvent[];\n\n constructor(opts: CheckoutInstanceOptions) {\n this.pendingWarnings = opts.initialWarnings ? [...opts.initialWarnings] : [];\n this.checkoutId = opts.checkoutId;\n this.runtimeId = opts.runtimeId;\n this.capabilities = opts.capabilities;\n this.hostOrigin = opts.hostOrigin;\n this.transport = opts.transport;\n this.session = opts.session;\n this.appearance = opts.appearance;\n\n this.paymentResultHandler = (payload: unknown): void => {\n this.handlePaymentResult(payload);\n };\n this.transport.on('paymentResult', this.paymentResultHandler);\n }\n\n /**\n * Create an Element handle (not auto-mounted; a mutual-exclusion conflict throws ELEMENT_CONFLICT).\n *\n * Mutual-exclusion rules (spec 6):\n * - The combined `card` and any split field (cardNumber/cardExpiry/cardCvc) are mutually exclusive.\n * - An address with the same `mode` (billing/shipping) cannot be duplicated.\n * - `expressCheckout` is a singleton.\n *\n * @param type - Element type.\n * @param options - Initial Element configuration.\n * @returns The newly created CheckoutElement.\n * @throws INSTANCE_DESTROYED when already destroyed; ELEMENT_CONFLICT on a mutual-exclusion conflict.\n */\n create(type: ElementType, options?: ElementOptions): CheckoutElement {\n this.assertAlive();\n this.assertNoConflict(type, options);\n\n const elementId = genId('el');\n const elementOpts: CheckoutElementOptions = {\n elementId,\n type,\n hostOrigin: this.hostOrigin,\n checkoutId: this.checkoutId,\n transport: this.transport,\n initialOptions: options,\n colorScheme: this.appearance?.colorScheme,\n appearance: this.appearance,\n onDestroy: (id: string) => this.releaseElement(id),\n };\n const element = CheckoutElement.create(elementOpts);\n this.elements.set(elementId, element);\n return element;\n }\n\n /**\n * Initiate a payment confirmation. Generates an operationId, sends the `confirm` command, and\n * returns a Promise fulfilled by `paymentResult` events with the same operationId.\n *\n * Behavior changes in 0.0.7: previously the Promise resolved on the first `paymentResult`,\n * including a non-final `pending` outcome. Now it resolves ONLY on a terminal outcome\n * (`succeeded` | `failed` | `canceled`); a `pending` outcome keeps it waiting.\n *\n * Watchdog: if no terminal outcome arrives within `resultTimeoutMs` (default\n * {@link CONFIRM_RESULT_DEADLINE_MS} = 120000ms) the Promise resolves\n * `{ status: 'pending', operationId, txnId? }`. This is NOT a failure: the payment may still\n * complete, so never treat it as failed and never retry blindly. Reconcile with\n * `getPaymentStatus()` or the `paymentResult` event.\n *\n * Slot semantics (duplicate-submit protection): the confirm slot stays occupied until a\n * terminal outcome arrives or `destroy()` is called. While it is occupied another `confirm()`\n * rejects with `CHECKOUT_BUSY`; this also holds after the watchdog resolved `pending`, and later\n * terminal outcomes are still delivered through `on('paymentResult', ...)`.\n *\n * If the `confirm` command is rejected by the runtime the payment was not started: the Promise\n * rejects with that error and the slot is freed. If the command itself times out\n * (`REQUEST_TIMEOUT`) the runtime may have started the payment: the Promise rejects with the\n * error augmented with `paymentStateKnown: false`, the slot stays occupied and a later terminal\n * `paymentResult` for this operation frees it. Do not retry; reconcile with `getPaymentStatus()`.\n *\n * `error` events with `paymentStateKnown === false` are informational and do not settle the\n * Promise.\n *\n * @param opts - Optional billing/shipping address, name, email, returnUrl, plus `onOperation`\n * and `resultTimeoutMs`.\n * @returns The terminal PaymentOutcome, or `{ status: 'pending' }` when the watchdog fires.\n * @throws rejects INSTANCE_DESTROYED when destroyed; rejects CHECKOUT_BUSY when in progress.\n */\n confirm(opts?: ConfirmOptions): Promise<PaymentOutcome> {\n if (this.destroyed) {\n return Promise.reject(\n makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed', 'runtime')\n );\n }\n if (this.pendingConfirm) {\n return Promise.reject(\n makeError(ErrorCode.CHECKOUT_BUSY, 'A payment confirmation is already in progress', 'runtime')\n );\n }\n\n // SDK-only options never go on the wire.\n const { onOperation, resultTimeoutMs, ...rest } = opts ?? {};\n const operationId = genId('op');\n const payload: ConfirmReq = { ...rest, operationId };\n const deadline =\n typeof resultTimeoutMs === 'number' && Number.isFinite(resultTimeoutMs) && resultTimeoutMs > 0\n ? resultTimeoutMs\n : CONFIRM_RESULT_DEADLINE_MS;\n\n return new Promise<PaymentOutcome>((resolve, reject) => {\n // Reserve the slot first, to prevent a concurrent confirm before accepted.\n const entry: PendingConfirm = {\n operationId,\n settled: false,\n resolve,\n reject,\n watchdog: null,\n lastPendingTxnId: undefined,\n };\n this.pendingConfirm = entry;\n\n entry.watchdog = setTimeout(() => {\n entry.watchdog = null;\n if (entry.settled) {\n return;\n }\n entry.settled = true;\n // Not a failure and not a rejection: the state is unknown. The slot stays held.\n const outcome: PaymentOutcome =\n entry.lastPendingTxnId !== undefined\n ? { status: 'pending', operationId, txnId: entry.lastPendingTxnId }\n : { status: 'pending', operationId };\n resolve(outcome);\n }, deadline);\n\n // Expose the operation id before the command leaves; a throwing callback must not break\n // the payment flow, so surface its error asynchronously.\n if (typeof onOperation === 'function') {\n try {\n onOperation(operationId);\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n\n this.transport.request('confirm', payload).catch((err: unknown) => {\n if (this.pendingConfirm !== entry) {\n return;\n }\n const error = err as CheckoutError;\n if (error && error.code === ErrorCode.REQUEST_TIMEOUT) {\n // The runtime may have started the payment: keep the slot, mark state unknown.\n if (!entry.settled) {\n entry.settled = true;\n this.clearWatchdog(entry);\n reject({ ...error, paymentStateKnown: false });\n }\n return;\n }\n // The runtime did not accept the command: free the slot and reject.\n this.pendingConfirm = null;\n this.clearWatchdog(entry);\n if (!entry.settled) {\n entry.settled = true;\n reject(error);\n }\n });\n });\n }\n\n /**\n * Get the latest session view (passes through the getSession command and writes back the local snapshot).\n *\n * @returns The latest PublicSessionView.\n * @throws rejects INSTANCE_DESTROYED when destroyed.\n */\n async getSession(): Promise<PublicSessionView> {\n this.assertAlive();\n const resp = (await this.transport.request('getSession', {})) as PublicSessionView;\n this.session = resp;\n return resp;\n }\n\n /**\n * Refresh the session (passes through the refresh command and writes back the local snapshot).\n *\n * @returns The refreshed PublicSessionView.\n * @throws rejects INSTANCE_DESTROYED when destroyed.\n */\n async refresh(): Promise<PublicSessionView> {\n this.assertAlive();\n const resp = (await this.transport.request('refresh', {})) as PublicSessionView;\n this.session = resp;\n return resp;\n }\n\n /**\n * Query the payment status (returns TxnStatus as-is, no transformation).\n *\n * @returns txnStatus (may be absent when the session is expired), sessionStatus and txnId.\n * @throws rejects INSTANCE_DESTROYED when destroyed.\n */\n async getPaymentStatus(): Promise<GetPaymentStatusResp> {\n this.assertAlive();\n return (await this.transport.request('getPaymentStatus', {})) as GetPaymentStatusResp;\n }\n\n /**\n * Update the checkout appearance/locale (does not change the session or the amount).\n *\n * @param patch - locale / appearance delta.\n * @throws rejects INSTANCE_DESTROYED when destroyed.\n */\n async updateCheckout(patch: {\n locale?: string;\n appearance?: Appearance;\n billingAddress?: AddressInfo;\n shippingAddress?: AddressInfo;\n }): Promise<void> {\n this.assertAlive();\n const payload: UpdateCheckoutReq = patch;\n await this.transport.request('updateCheckout', payload);\n }\n\n /**\n * Register a Checkout-level event handler (passes through the transport).\n *\n * @param event - Event name.\n * @param handler - Callback.\n * @throws INSTANCE_DESTROYED when destroyed.\n */\n on<E extends EventName>(event: E, handler: (payload: EventPayloadMap[E]) => void): void {\n this.assertAlive();\n // The only typed→loose cast: the transport is loosely typed and the protocol guarantees the\n // payload shape per event name. The same function identity is passed, so `off` works as is.\n this.transport.on(event, handler as (payload: unknown) => void);\n // Replay warnings raised during initialize to the first `warning` listener (once), async so\n // the caller finishes its setup before the handler runs.\n if (event === 'warning' && this.pendingWarnings.length > 0) {\n const pending = this.pendingWarnings;\n this.pendingWarnings = [];\n queueMicrotask(() => {\n if (this.destroyed) {\n return;\n }\n for (const w of pending) {\n (handler as (payload: WarningEvent) => void)(w);\n }\n });\n }\n }\n\n /**\n * Unregister an event handler (safe to call after destruction).\n *\n * @param event - Event name.\n * @param handler - The previously registered callback.\n */\n off<E extends EventName>(event: E, handler: (payload: EventPayloadMap[E]) => void): void {\n this.transport.off(event, handler as (payload: unknown) => void);\n }\n\n /**\n * Destroy the instance: idempotent. Releases all Elements, unbinds the paymentResult listener,\n * rejects the pending confirm with INSTANCE_DESTROYED, sends the destroy command and destroys\n * the transport. Any late paymentResult afterwards is ignored and does not overwrite an already\n * settled Promise.\n */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n\n // Release all Element handles.\n for (const element of this.elements.values()) {\n element.destroy();\n }\n this.elements.clear();\n\n // Unbind the paymentResult listener (no handler can be reached by a late result afterwards).\n this.transport.off('paymentResult', this.paymentResultHandler);\n\n // Reject the pending confirm with INSTANCE_DESTROYED.\n if (this.pendingConfirm) {\n const entry = this.pendingConfirm;\n this.pendingConfirm = null;\n this.clearWatchdog(entry);\n if (!entry.settled) {\n entry.settled = true;\n entry.reject(\n makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed', 'runtime')\n );\n }\n }\n\n // Notify the hosted side and destroy the transport (request after destroy is rejected by the transport itself).\n void Promise.resolve(this.transport.request('destroy', {})).catch(() => undefined);\n this.transport.destroy();\n }\n\n /** Throw INSTANCE_DESTROYED if already destroyed. */\n private assertAlive(): void {\n if (this.destroyed) {\n throw makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed', 'runtime');\n }\n }\n\n /** Mutual-exclusion check: throws ELEMENT_CONFLICT on conflict (derived live from the elements Map, does not mutate the registry). */\n private assertNoConflict(type: ElementType, options?: ElementOptions): void {\n const existing = [...this.elements.values()];\n const has = (t: ElementType): boolean => existing.some((e) => e.type === t);\n const hasCardField = (): boolean => existing.some((e) => CARD_FIELD_TYPES.includes(e.type));\n\n if (type === 'card') {\n if (has('card')) {\n throw makeError(ErrorCode.ELEMENT_CONFLICT, 'A combined card Element already exists');\n }\n if (hasCardField()) {\n throw makeError(\n ErrorCode.ELEMENT_CONFLICT,\n 'Combined card and split card fields are mutually exclusive; split card fields already exist'\n );\n }\n return;\n }\n if (CARD_FIELD_TYPES.includes(type)) {\n if (has('card')) {\n throw makeError(\n ErrorCode.ELEMENT_CONFLICT,\n 'Split card fields and combined card are mutually exclusive; a combined card already exists'\n );\n }\n // The same split field type cannot be duplicated.\n if (has(type)) {\n throw makeError(\n ErrorCode.ELEMENT_CONFLICT,\n `A split card field of type ${type} already exists`\n );\n }\n return;\n }\n if (type === 'address') {\n const mode = (options as { mode?: string } | undefined)?.mode;\n if (mode && existing.some((e) => e.type === 'address' && e.mode === mode)) {\n throw makeError(\n ErrorCode.ELEMENT_CONFLICT,\n `An address Element with mode=${mode} already exists`\n );\n }\n return;\n }\n if (type === 'expressCheckout') {\n if (has('expressCheckout')) {\n throw makeError(ErrorCode.ELEMENT_CONFLICT, 'An expressCheckout Element already exists');\n }\n return;\n }\n }\n\n /**\n * Element `destroy()` callback: remove this elementId from the mutual-exclusion registry (the\n * elements Map) to free the slot. Idempotent; when the whole instance is destroyed (destroyed\n * already set) it goes through the unified `elements.clear()` path, so this is a no-op here,\n * avoiding concurrent modification while iterating elements to call element.destroy().\n */\n private releaseElement(elementId: string): void {\n if (this.destroyed) {\n return;\n }\n this.elements.delete(elementId);\n }\n\n /** Handle the paymentResult event: fulfill the pending confirm by operationId; late/mismatched ones are ignored. */\n private handlePaymentResult(payload: unknown): void {\n if (this.destroyed) {\n return;\n }\n if (typeof payload !== 'object' || payload === null) {\n return;\n }\n const evt = payload as Partial<PaymentResultEvent>;\n const pending = this.pendingConfirm;\n if (!pending) {\n return;\n }\n if (evt.operationId !== pending.operationId) {\n return;\n }\n const outcome = evt.outcome;\n if (!outcome) {\n return;\n }\n if (outcome.status === 'pending') {\n // Non-terminal: keep waiting (and keep the slot) for the final outcome.\n pending.lastPendingTxnId = outcome.txnId ?? pending.lastPendingTxnId;\n return;\n }\n if (\n outcome.status !== 'succeeded' &&\n outcome.status !== 'failed' &&\n outcome.status !== 'canceled'\n ) {\n return;\n }\n // Terminal: free the slot; settle the Promise unless the watchdog/timeout already did.\n this.pendingConfirm = null;\n this.clearWatchdog(pending);\n if (!pending.settled) {\n pending.settled = true;\n pending.resolve(outcome);\n }\n }\n\n /** Clear a pending confirm's watchdog timer (idempotent). */\n private clearWatchdog(entry: PendingConfirm): void {\n if (entry.watchdog !== null) {\n clearTimeout(entry.watchdog);\n entry.watchdog = null;\n }\n }\n}\n","/**\n * createCheckout — the merchant SDK's single async entry (spec 4).\n *\n * Flow:\n * 1. Generate `checkoutId`, derive the hosted origin via `resolveHostOrigin(env, hostOrigin)`.\n * 2. Build the transport, `createHiddenIframe()` to load the hosted main iframe.\n * 3. Register onHello; wait for RuntimeHello (timeout 15s → reject RUNTIME_LOAD_FAILED).\n * 4. Pick a common major version (no intersection → reject PROTOCOL_UNSUPPORTED).\n * 5. Send `initialize` (sessionId/locale/appearance/paymentMethods) to obtain\n * capabilities + PublicSessionView; any step failing rejects and destroys the transport.\n * 6. Inject the handshake runtimeId into the transport, construct and resolve {@link CheckoutInstance}.\n *\n * Security constraint (AGENTS/spec): this layer only orchestrates handshake/initialization and\n * **never touches card values**.\n */\n\nimport { MainFrameTransport } from './transport/MainFrameTransport';\nimport { CheckoutInstance, type InstanceTransport } from './CheckoutInstance';\nimport { isValidRuntimeHello } from './transport/hello';\nimport { resolveHostOrigin, type Env } from './config/env';\nimport {\n ErrorCode,\n PROTOCOL_MAJOR,\n type Appearance,\n type AddressInfo,\n type CheckoutError,\n type InitializeReq,\n type InitializeResp,\n type PaymentMethodFilter,\n type RuntimeHello,\n} from '@sunbay/checkout-sdk-protocol';\n\n/** Handshake timeout (ms): matches the transport handshake timeout (15s). */\nconst HANDSHAKE_TIMEOUT_MS = 15_000;\n\n/**\n * Internal transport factory injectable when creating a CheckoutInstance (test/advanced use only).\n *\n * Real scenarios use the built-in MainFrameTransport; tests may inject a mock to drive hello/events.\n */\nexport type TransportFactory = (args: {\n checkoutId: string;\n hostOrigin: string;\n}) => InstanceTransport;\n\n/** createCheckout parameters. */\nexport interface CreateCheckoutOptions {\n /** Checkout session id created by the backend (required). */\n sessionId: string;\n /**\n * Client secret of the session (required). Returned by the merchant backend's `create-session`\n * call when `sessionType` is `embedded`. Hand it to the browser over an authenticated HTTPS\n * response; never put it in a URL or write it to logs.\n */\n checkoutClientSecret: string;\n /** Runtime environment (dev/test/prod), defaults to prod. */\n env?: Env;\n /** Override the hosted origin (takes precedence over env). */\n hostOrigin?: string;\n /** Locale. */\n locale?: string;\n /** Appearance customization. */\n appearance?: Appearance;\n /** Payment method filter (subtractive/reordering only). */\n paymentMethods?: PaymentMethodFilter;\n /**\n * Host-collected billing address. When complete, Apple Pay / Google Pay do not ask the user for\n * it again, and it is used as the default for card `confirm()`.\n */\n billingAddress?: AddressInfo;\n /** Host-collected shipping address (complete = address + name + phone). Same rules as above. */\n shippingAddress?: AddressInfo;\n /** Internal injection point: custom transport factory (test use; not part of the public API contract). */\n __transportFactory?: TransportFactory;\n}\n\n/** Generate a unique id. */\nfunction genId(prefix: string): string {\n const rand = Math.random().toString(36).slice(2);\n return `${prefix}_${Date.now().toString(36)}_${rand}`;\n}\n\n/** Construct a structured CheckoutError (runtime category). */\nfunction makeError(code: string, message: string): CheckoutError {\n return {\n code,\n message,\n category: 'runtime',\n errorId: genId('err'),\n };\n}\n\n/** Default transport factory: the built-in MainFrameTransport. */\nconst defaultTransportFactory: TransportFactory = ({ checkoutId, hostOrigin }) =>\n new MainFrameTransport({ checkoutId, hostOrigin });\n\n/**\n * Create a checkout instance: resolves after a successful handshake + initialization.\n *\n * @param opts - Checkout parameters.\n * @returns A ready CheckoutInstance.\n * @throws reject INVALID_OPTIONS (missing/blank/non-string checkoutClientSecret, before any iframe\n * is created) / RUNTIME_LOAD_FAILED (handshake timeout) / PROTOCOL_UNSUPPORTED (no common major\n * version) / or the initialize business error.\n * @example\n * const checkout = await createCheckout({\n * sessionId: 'sess_x',\n * checkoutClientSecret: 'ccs_x', // from your backend's create-session (sessionType: embedded)\n * env: 'prod',\n * });\n */\nexport async function createCheckout(opts: CreateCheckoutOptions): Promise<CheckoutInstance> {\n // Validate first so a rejected call creates no iframe. Never echo the supplied value.\n if (typeof opts.checkoutClientSecret !== 'string' || opts.checkoutClientSecret.trim() === '') {\n throw makeError(ErrorCode.INVALID_OPTIONS, 'checkoutClientSecret is required');\n }\n const checkoutId = genId('co');\n const hostOrigin = resolveHostOrigin(opts.env, opts.hostOrigin);\n const factory = opts.__transportFactory ?? defaultTransportFactory;\n const transport = factory({ checkoutId, hostOrigin });\n\n // Start the hosted main iframe (hidden, 0 size).\n transport.createHiddenIframe();\n\n let hello: RuntimeHello;\n try {\n hello = await waitForHello(transport);\n } catch (err) {\n transport.destroy();\n throw err;\n }\n\n // Pick a common major version.\n if (!hello.supportedMajorVersions.includes(PROTOCOL_MAJOR)) {\n transport.destroy();\n throw makeError(\n ErrorCode.PROTOCOL_UNSUPPORTED,\n `No common major protocol version: SDK=${PROTOCOL_MAJOR}, runtime=${JSON.stringify(hello.supportedMajorVersions)}`\n );\n }\n\n // Inject the negotiated runtimeId: must happen before sending initialize, otherwise the\n // outbound envelope's runtimeId is an empty string, gets silently dropped by the main\n // endpoint, and causes initialize to time out.\n transport.setRuntimeId(hello.runtimeId);\n\n // Send initialize.\n const initReq: InitializeReq = {\n sessionId: opts.sessionId,\n checkoutClientSecret: opts.checkoutClientSecret,\n locale: opts.locale,\n appearance: opts.appearance,\n paymentMethods: opts.paymentMethods,\n billingAddress: opts.billingAddress,\n shippingAddress: opts.shippingAddress,\n };\n let initResp: InitializeResp;\n try {\n initResp = (await transport.request('initialize', initReq)) as InitializeResp;\n } catch (err) {\n transport.destroy();\n throw err as CheckoutError;\n }\n\n return new CheckoutInstance({\n checkoutId,\n runtimeId: hello.runtimeId,\n hostOrigin,\n transport,\n capabilities: initResp.capabilities,\n session: initResp.session,\n initialWarnings: initResp.warnings,\n appearance: opts.appearance,\n });\n}\n\n/** Wait for RuntimeHello; reject RUNTIME_LOAD_FAILED on timeout. */\nfunction waitForHello(transport: InstanceTransport): Promise<RuntimeHello> {\n return new Promise<RuntimeHello>((resolve, reject) => {\n let settled = false;\n const timer = setTimeout(() => {\n if (settled) {\n return;\n }\n settled = true;\n reject(makeError(ErrorCode.RUNTIME_LOAD_FAILED, 'Timed out waiting for hosted runtime handshake'));\n }, HANDSHAKE_TIMEOUT_MS);\n\n transport.onHello((raw: unknown) => {\n if (settled || !isValidRuntimeHello(raw)) {\n // Malformed hello: ignore and keep waiting (the handshake timeout still applies).\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolve(raw);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,MAAM,gBAAgB;AAEtB,MAAM,iBAAiB;AAgC9B,MAAM,iBAAiB,CAAC,WAAW,YAAY,OAAO;AAG/C,MAAM,sBAAN,cAAkC,MAAM;IAC3C,YAAY,SAAiB;AACzB,YAAM,OAAO;AACb,WAAK,OAAO;IAChB;EACJ;AAEA,WAAS,SAAS,OAAkD;AAChE,WAAO,OAAO,UAAU,YAAY,UAAU;EAClD;AAEA,WAAS,aAAa,KAA8B,KAAmB;AACnE,QAAI,OAAO,IAAI,GAAG,MAAM,UAAU;AAC9B,YAAM,IAAI,oBAAoB,mBAAmB,GAAG,8BAA8B;IACtF;EACJ;AAUO,WAAS,eAAe,UAA4B;AACvD,WAAO,KAAK,UAAU,QAAQ;EAClC;AAeO,WAAS,eAAe,MAAwB;AACnD,QAAI;AACJ,QAAI;AACA,eAAS,KAAK,MAAM,IAAI;IAC5B,QAAQ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AAAA,MACf,CAAC;AAAA,IACL,CAAC;AAAA,EACL;;;AX9GA,MAAI,OAAO,WAAW,aAAa;AAC/B,UAAM,IAAI;AAGV,MAAE,iBAAiB,EAAE,GAAI,EAAE,kBAAkB,CAAC,GAAI,eAAe;AAAA,EACrE;AASO,MAAM,UACT,OAAyC,UAAkB;","names":["makeError","genId","makeError","genId","makeError"]}
1
+ {"version":3,"sources":["../src/index.ts","../../protocol/src/envelope.ts","../../protocol/src/errors.ts","../../protocol/src/commands.ts","../../protocol/src/events.ts","../../protocol/src/iframeLayout.ts","../src/config/env.ts","../src/transport/hello.ts","../src/transport/MainFrameTransport.ts","../src/Element.ts","../src/CheckoutInstance.ts","../src/createCheckout.ts"],"sourcesContent":["/**\n * @sunbay/checkout-js public entry (source of truth).\n *\n * Exports the `createCheckout` entry, the `CheckoutInstance` / `CheckoutElement` handle types,\n * and the public protocol types (for TS consumers).\n * In the IIFE build, additionally exposes `{ createCheckout }` on `window.SunbayCheckout`.\n */\n\nexport { createCheckout } from './createCheckout';\nexport type {\n CreateCheckoutOptions,\n TransportFactory,\n} from './createCheckout';\n\nexport { CheckoutInstance } from './CheckoutInstance';\nexport type {\n CheckoutInstanceOptions,\n ConfirmOptions,\n InstanceTransport,\n} from './CheckoutInstance';\n\nexport { CheckoutElement } from './Element';\nexport type { CheckoutElementOptions, ElementTransport, MountOptions } from './Element';\n\nexport type { Env } from './config/env';\n\n// Public protocol types (the contract for TS consumers).\nexport {\n ErrorCode,\n WARNING_CODES,\n type ErrorCodeValue,\n type CheckoutError,\n type CheckoutErrorCategory,\n type PaymentOutcome,\n type PublicSessionView,\n type PublicPaymentMethod,\n type ExpressMethodView,\n type PaymentMethodsView,\n type ElementState,\n type PublicProductLine,\n type PaymentMethod,\n type PaymentMethodFilter,\n type Appearance,\n type AddressInfo,\n type TxnStatus,\n type SessionStatus,\n type ElementType,\n type ElementOptions,\n type ElementStatus,\n type CardElementOptions,\n type CardFieldElementOptions,\n type AddressElementOptions,\n type AddressFormStyle,\n type ExpressCheckoutElementOptions,\n type AvailableWallets,\n type ApplePayOptions,\n type GooglePayOptions,\n type ApplePayButtonTheme,\n type GooglePayButtonTheme,\n type ApplePayButtonType,\n type GooglePayButtonType,\n type PaymentAction,\n type WalletErrorStage,\n type EventName,\n type EventPayloadMap,\n type ErrorEvent,\n type WarningEvent,\n type WarningCode,\n type PaymentResultEvent,\n type PaymentStateChangeEvent,\n type ExpressAvailabilityChangeEvent,\n type ElementReadyEvent,\n type ChangeEvent,\n type LoadErrorEvent,\n type ReadyEvent,\n type FocusEvent,\n type BlurEvent,\n type AppearanceVariables,\n type AppearanceRuleTarget,\n type AppearanceRuleStyle,\n} from '@sunbay/checkout-sdk-protocol';\n\nimport { createCheckout } from './createCheckout';\n\n/**\n * IIFE / browser global: mount `window.SunbayCheckout = { createCheckout }`.\n *\n * The tsup IIFE build already exposes the module exports via `globalName: 'SunbayCheckout'`;\n * this explicitly ensures `window.SunbayCheckout.createCheckout` is available (while staying\n * compatible with re-exporting more entries in the future).\n */\nif (typeof window !== 'undefined') {\n const w = window as typeof window & {\n SunbayCheckout?: { createCheckout: typeof createCheckout };\n };\n w.SunbayCheckout = { ...(w.SunbayCheckout ?? {}), createCheckout };\n}\n\n/**\n * Package version. Injected at build time by tsup's `define` from `package.json` as\n * `__SDK_VERSION__` (see tsup.config.ts), so the code's version always stays in sync with\n * package.json. Environments without a build (e.g. vitest running src directly) have no such\n * define and fall back to `'0.0.0'`.\n */\ndeclare const __SDK_VERSION__: string;\nexport const version: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : '0.0.0';\n","/**\n * Envelope and handshake contract (spec 5.1, source of truth).\n *\n * Protocol name `sunbay-checkout`, `major = 1`. This is a different protocol from the existing\n * Native Bridge `{v:1,type,...}`; identical numbers do not imply compatibility.\n *\n * `encodeEnvelope`/`decodeEnvelope`: JSON serialization + minimal runtime structural validation\n * (validates protocol/major/kind/required fields), throwing on invalid input. The decoder does\n * **not** validate whether request.name is a known CommandName — an unknown name is still decoded\n * as kind==='request' and rejected by the caller.\n */\n\nimport type { CheckoutError } from './types';\n\n/** Protocol name constant. */\nexport const PROTOCOL_NAME = 'sunbay-checkout' as const;\n/** Current major version. */\nexport const PROTOCOL_MAJOR = 1 as const;\n\n/**\n * Handshake message (spec 5.1). Broadcast first after the main iframe loads, when there is no\n * checkoutId yet.\n */\nexport type RuntimeHello = {\n protocol: 'sunbay-checkout';\n kind: 'hello';\n runtimeId: string;\n supportedMajorVersions: number[];\n /** First phase: ['card','splitCard','address','express','paymentMethodFilter']. */\n capabilities: string[];\n};\n\n/**\n * Public envelope after initialization (spec 5.1).\n */\nexport type Envelope = {\n protocol: 'sunbay-checkout';\n major: 1;\n runtimeId: string;\n checkoutId: string;\n elementId?: string;\n} & (\n | { kind: 'request'; requestId: string; name: string; payload: unknown }\n | { kind: 'response'; requestId: string; ok: true; data: unknown }\n | { kind: 'response'; requestId: string; ok: false; error: CheckoutError }\n | { kind: 'event'; eventId: string; name: string; operationId?: string; payload: unknown }\n);\n\n/** Set of valid kinds. */\nconst ENVELOPE_KINDS = ['request', 'response', 'event'] as const;\n\n/** Protocol validation failure error. */\nexport class EnvelopeDecodeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'EnvelopeDecodeError';\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction assertString(obj: Record<string, unknown>, key: string): void {\n if (typeof obj[key] !== 'string') {\n throw new EnvelopeDecodeError(`Envelope field \"${key}\" is missing or not a string`);\n }\n}\n\n/**\n * Serialize an envelope into a wire string (JSON).\n *\n * @param envelope The envelope to send\n * @returns JSON string\n * @example\n * const wire = encodeEnvelope({ protocol: 'sunbay-checkout', major: 1, ... });\n */\nexport function encodeEnvelope(envelope: Envelope): string {\n return JSON.stringify(envelope);\n}\n\n/**\n * Parse and minimally structurally validate an envelope. Invalid input (missing protocol, wrong\n * major, invalid kind, missing required fields, non-JSON) always throws {@link EnvelopeDecodeError}.\n *\n * Note: the decoder does not validate whether request.name is a known command — an unknown name is\n * still decoded as kind==='request' and left for the caller (e.g. the Orchestrator) to reject.\n *\n * @param wire The wire string\n * @returns The structurally validated envelope\n * @example\n * const env = decodeEnvelope(wire);\n * if (env.kind === 'request') { ... }\n */\nexport function decodeEnvelope(wire: string): Envelope {\n let parsed: unknown;\n try {\n parsed = JSON.parse(wire);\n } catch {\n throw new EnvelopeDecodeError('Envelope is not valid JSON');\n }\n\n if (!isRecord(parsed)) {\n throw new EnvelopeDecodeError('Envelope must be an object');\n }\n\n if (parsed.protocol !== PROTOCOL_NAME) {\n throw new EnvelopeDecodeError(\n `protocol must be \"${PROTOCOL_NAME}\", received ${JSON.stringify(parsed.protocol)}`\n );\n }\n if (parsed.major !== PROTOCOL_MAJOR) {\n throw new EnvelopeDecodeError(\n `major must be ${PROTOCOL_MAJOR}, received ${JSON.stringify(parsed.major)}`\n );\n }\n\n assertString(parsed, 'runtimeId');\n assertString(parsed, 'checkoutId');\n if (parsed.elementId !== undefined && typeof parsed.elementId !== 'string') {\n throw new EnvelopeDecodeError('elementId must be a string when present');\n }\n\n const kind = parsed.kind;\n if (typeof kind !== 'string' || !(ENVELOPE_KINDS as readonly string[]).includes(kind)) {\n throw new EnvelopeDecodeError(`Invalid kind: ${JSON.stringify(kind)}`);\n }\n\n switch (kind) {\n case 'request': {\n assertString(parsed, 'requestId');\n assertString(parsed, 'name');\n if (!('payload' in parsed)) {\n throw new EnvelopeDecodeError('request envelope is missing payload');\n }\n break;\n }\n case 'response': {\n assertString(parsed, 'requestId');\n if (typeof parsed.ok !== 'boolean') {\n throw new EnvelopeDecodeError('response envelope is missing boolean ok');\n }\n if (parsed.ok === true) {\n if (!('data' in parsed)) {\n throw new EnvelopeDecodeError('successful response is missing data');\n }\n } else if (!isRecord(parsed.error)) {\n throw new EnvelopeDecodeError('failed response is missing error object');\n }\n break;\n }\n case 'event': {\n assertString(parsed, 'eventId');\n assertString(parsed, 'name');\n if (!('payload' in parsed)) {\n throw new EnvelopeDecodeError('event envelope is missing payload');\n }\n if (\n 'operationId' in parsed &&\n parsed.operationId !== undefined &&\n typeof parsed.operationId !== 'string'\n ) {\n throw new EnvelopeDecodeError('operationId must be a string when present');\n }\n break;\n }\n }\n\n // Structure validated; confirmed to be an Envelope shape.\n return parsed as unknown as Envelope;\n}\n","/**\n * Protocol error code constants (single source of truth, spec 5.4).\n *\n * Does not provide a generic `retryable` boolean that could mislead into duplicate payments.\n * Only keeps error codes that are actually produced; new codes must have a production point.\n */\n\nexport const ErrorCode = {\n INVALID_OPTIONS: 'INVALID_OPTIONS',\n ELEMENT_CONFLICT: 'ELEMENT_CONFLICT',\n INSTANCE_DESTROYED: 'INSTANCE_DESTROYED',\n CHECKOUT_BUSY: 'CHECKOUT_BUSY',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n SESSION_LOAD_FAILED: 'SESSION_LOAD_FAILED',\n RUNTIME_LOAD_FAILED: 'RUNTIME_LOAD_FAILED',\n PROTOCOL_UNSUPPORTED: 'PROTOCOL_UNSUPPORTED',\n REQUEST_TIMEOUT: 'REQUEST_TIMEOUT',\n PAYMENT_FLOW_ERROR: 'PAYMENT_FLOW_ERROR',\n UNSUPPORTED_CAPABILITY: 'UNSUPPORTED_CAPABILITY',\n} as const;\n\n/** Error code literal union type. */\nexport type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];\n","/**\n * Command contract (merchant SDK → main, spec 5.2 table, source of truth).\n *\n * The request/response types for each command are defined here; only JSON-serializable data is sent\n * across the channel.\n */\n\nimport type {\n Appearance,\n AddressInfo,\n ElementOptions,\n ElementType,\n PaymentMethodFilter,\n PublicSessionView,\n SessionStatus,\n TxnStatus,\n} from './types';\nimport type { WarningEvent } from './events';\n\n/** All command names (spec 5.2). */\nexport type CommandName =\n | 'initialize'\n | 'createElement'\n | 'updateElement'\n | 'destroyElement'\n | 'focus'\n | 'blur'\n | 'clear'\n | 'updateCheckout'\n | 'getSession'\n | 'refresh'\n | 'getPaymentStatus'\n | 'confirm'\n | 'destroy';\n\n/** Set of known command names (for callers to validate whether request.name is supported). */\nexport const COMMAND_NAMES: readonly CommandName[] = [\n 'initialize',\n 'createElement',\n 'updateElement',\n 'destroyElement',\n 'focus',\n 'blur',\n 'clear',\n 'updateCheckout',\n 'getSession',\n 'refresh',\n 'getPaymentStatus',\n 'confirm',\n 'destroy',\n];\n\n/** Determine whether a string is a known command name. */\nexport function isCommandName(name: string): name is CommandName {\n return (COMMAND_NAMES as readonly string[]).includes(name);\n}\n\n// --- initialize ---\nexport interface InitializeReq {\n sessionId: string;\n locale?: string;\n appearance?: Appearance;\n paymentMethods?: PaymentMethodFilter;\n /** Host-collected billing address; when complete, wallets do not ask for it again. */\n billingAddress?: AddressInfo;\n /** Host-collected shipping address; when complete, wallets do not ask for it again. */\n shippingAddress?: AddressInfo;\n /**\n * Sensitive per-session secret (optional at the protocol level; the JS SDK enforces it).\n * Returned by the merchant backend's\n * `create-session` call when `sessionType` is `embedded`. Never log it or put it in a URL.\n */\n checkoutClientSecret?: string;\n}\nexport interface InitializeResp {\n capabilities: string[];\n session: PublicSessionView;\n /**\n * Non-fatal warnings produced while handling `initialize` (e.g. unknown `paymentMethods`\n * filter identifiers). Events emitted during `initialize` cannot reach listeners (the instance\n * does not exist yet), so they are carried here and replayed by the SDK to the first\n * `warning` listener.\n */\n warnings?: WarningEvent[];\n}\n\n// --- createElement ---\nexport interface CreateElementReq {\n elementId: string;\n type: ElementType;\n options?: ElementOptions;\n}\nexport interface CreateElementResp {\n elementId: string;\n registered: true;\n}\n\n// --- updateElement ---\nexport interface UpdateElementReq {\n elementId: string;\n patch: Partial<ElementOptions>;\n}\nexport interface UpdateElementResp {\n elementId: string;\n options: ElementOptions;\n}\n\n// --- destroyElement ---\nexport interface DestroyElementReq {\n elementId: string;\n}\nexport interface DestroyElementResp {\n elementId: string;\n released: true;\n}\n\n// --- focus / blur / clear (input-type Elements only) ---\nexport interface ElementActionReq {\n elementId: string;\n}\nexport interface ElementActionResp {\n elementId: string;\n done: true;\n}\n\n// --- updateCheckout (does not change session/amount) ---\nexport interface UpdateCheckoutReq {\n locale?: string;\n appearance?: Appearance;\n /** Replace the host-provided billing address (send `{}` to clear; `undefined` leaves it unchanged). */\n billingAddress?: AddressInfo;\n /** Replace the host-provided shipping address. */\n shippingAddress?: AddressInfo;\n}\nexport interface UpdateCheckoutResp {\n updated: true;\n}\n\n// --- getSession / refresh ---\nexport type GetSessionReq = Record<string, never>;\nexport type GetSessionResp = PublicSessionView;\n\n// --- getPaymentStatus (returns TxnStatus verbatim, no translation) ---\nexport type GetPaymentStatusReq = Record<string, never>;\nexport interface GetPaymentStatusResp {\n /**\n * Latest transaction status. May be absent when the session is `EXPIRED` and the backend\n * has no transaction to report.\n */\n txnStatus?: TxnStatus;\n /** Status of the session itself. Absent on backends that do not report it. */\n sessionStatus?: SessionStatus;\n txnId?: string;\n}\n\n// --- confirm (only indicates that execution has started) ---\nexport interface ConfirmReq {\n operationId: string;\n billingAddress?: AddressInfo;\n shippingAddress?: AddressInfo;\n customerName?: string;\n email?: string;\n returnUrl?: string;\n}\nexport interface ConfirmResp {\n accepted: true;\n}\n\n// --- destroy ---\nexport type DestroyReq = Record<string, never>;\nexport interface DestroyResp {\n released: true;\n}\n\n/** Command name → request payload mapping. */\nexport interface CommandRequestMap {\n initialize: InitializeReq;\n createElement: CreateElementReq;\n updateElement: UpdateElementReq;\n destroyElement: DestroyElementReq;\n focus: ElementActionReq;\n blur: ElementActionReq;\n clear: ElementActionReq;\n updateCheckout: UpdateCheckoutReq;\n getSession: GetSessionReq;\n refresh: GetSessionReq;\n getPaymentStatus: GetPaymentStatusReq;\n confirm: ConfirmReq;\n destroy: DestroyReq;\n}\n\n/** Command name → success response payload mapping. */\nexport interface CommandResponseMap {\n initialize: InitializeResp;\n createElement: CreateElementResp;\n updateElement: UpdateElementResp;\n destroyElement: DestroyElementResp;\n focus: ElementActionResp;\n blur: ElementActionResp;\n clear: ElementActionResp;\n updateCheckout: UpdateCheckoutResp;\n getSession: GetSessionResp;\n refresh: GetSessionResp;\n getPaymentStatus: GetPaymentStatusResp;\n confirm: ConfirmResp;\n destroy: DestroyResp;\n}\n","/**\n * Event contract (main → merchant SDK, spec 5.3 table, source of truth).\n *\n * Public events only expose allowed states such as empty/complete/brand/error, and **never contain\n * card values**; no card-data getValue is provided. After `on` registration, historical events are\n * not replayed.\n */\n\nimport type {\n AvailableWallets,\n CheckoutError,\n PaymentAction,\n WalletErrorStage,\n PaymentMethod,\n PaymentOutcome,\n} from './types';\n\n/** All event names (spec 5.3). */\nexport type EventName =\n | 'ready'\n | 'change'\n | 'focus'\n | 'blur'\n | 'loadError'\n | 'elementReady'\n | 'expressAvailabilityChange'\n | 'paymentStateChange'\n | 'paymentResult'\n | 'error'\n | 'warning';\n\n/** Set of known event names. */\nexport const EVENT_NAMES: readonly EventName[] = [\n 'ready',\n 'change',\n 'focus',\n 'blur',\n 'loadError',\n 'elementReady',\n 'expressAvailabilityChange',\n 'paymentStateChange',\n 'paymentResult',\n 'error',\n 'warning',\n];\n\n/** Determine whether a string is a known event name. */\nexport function isEventName(name: string): name is EventName {\n return (EVENT_NAMES as readonly string[]).includes(name);\n}\n\n// --- Input Element events ---\nexport interface ReadyEvent {\n elementId: string;\n}\nexport interface ElementReadyEvent {\n elementId: string;\n /** Only carried when the expressCheckout Element is ready: per-wallet availability. */\n availableWallets?: AvailableWallets;\n}\nexport interface ChangeEvent {\n elementId: string;\n empty: boolean;\n complete: boolean;\n error?: CheckoutError;\n /** Only the card number field may carry brand; never contains card values. */\n brand?: string;\n}\nexport interface FocusEvent {\n elementId: string;\n}\nexport interface BlurEvent {\n elementId: string;\n}\nexport interface LoadErrorEvent {\n elementId: string;\n error: CheckoutError;\n}\n\n// --- Express events ---\n/**\n * Express available-wallets change event (spec 6).\n * Dedicated to expressCheckout: uses AvailableWallets to express the availability of each wallet\n * (Apple/Google Pay).\n */\nexport interface ExpressAvailabilityChangeEvent {\n availableWallets: AvailableWallets;\n}\n\n// --- Checkout-level events ---\nexport interface PaymentStateChangeEvent {\n operationId: string;\n method: PaymentMethod;\n /** Intermediate state; carries action info when requiresAction. */\n state: string;\n action?: PaymentAction;\n}\nexport interface PaymentResultEvent {\n operationId: string;\n method: PaymentMethod;\n outcome: PaymentOutcome;\n}\nexport interface ErrorEvent {\n /** Error in an asynchronous proactive flow; may include operationId (if already created). */\n operationId?: string;\n /** Payment method the error relates to, if any. */\n method?: PaymentMethod;\n /** Payment flow stage in which the error occurred, if applicable (wallet and card flows). */\n stage?: WalletErrorStage;\n error: CheckoutError;\n}\n\n/**\n * Cross-platform registry of `warning` event codes (single source of truth for Web, iOS, Android).\n * Warnings are non-fatal: the offending input was ignored. A platform that needs a new code adds it\n * here (and to the docs table) so every SDK shares one vocabulary.\n */\nexport const WARNING_CODES = {\n /** A `paymentMethods` filter identifier matched nothing (unknown / not offered). */\n PAYMENT_METHOD_FILTER_IGNORED: 'PAYMENT_METHOD_FILTER_IGNORED',\n /** An expressCheckout option was not whitelisted or had an invalid value. */\n EXPRESS_OPTION_IGNORED: 'EXPRESS_OPTION_IGNORED',\n /** A host-provided billing/shipping address was incomplete, so it was treated as not provided. */\n ADDRESS_INCOMPLETE: 'ADDRESS_INCOMPLETE',\n /** A host-provided address was ignored because our Address Element owns that mode. */\n ADDRESS_ENTRY_IGNORED: 'ADDRESS_ENTRY_IGNORED',\n /**\n * The wallet (Apple Pay / Google Pay) payment parameters delivered by the session were missing\n * or invalid, so that wallet is not offered. Registered for the native SDKs (iOS first); the Web\n * runtime currently only logs this condition and does not emit the event.\n */\n WALLET_PARAMS_INVALID: 'WALLET_PARAMS_INVALID',\n} as const;\n\n/** Warning code (non-fatal; the offending input was ignored). */\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Non-fatal warning: some merchant-supplied input was ignored instead of failing the call\n * (e.g. an unknown `paymentMethods` filter identifier, or a non-whitelisted Express option).\n */\nexport interface WarningEvent {\n code: WarningCode;\n /** The ignored identifiers / option paths. */\n ignored: string[];\n /** Human-readable reason (may list the accepted values). */\n reason: string;\n}\n\n/** Event name → payload mapping. */\nexport interface EventPayloadMap {\n ready: ReadyEvent;\n change: ChangeEvent;\n focus: FocusEvent;\n blur: BlurEvent;\n loadError: LoadErrorEvent;\n elementReady: ElementReadyEvent;\n expressAvailabilityChange: ExpressAvailabilityChangeEvent;\n paymentStateChange: PaymentStateChangeEvent;\n paymentResult: PaymentResultEvent;\n error: ErrorEvent;\n warning: WarningEvent;\n}\n","/**\n * iframe layout protocol: the **direct postMessage** contract from the hosted iframe (checkout,\n * child) → parent window (merchant SDK, parent), used for iframe auto-height.\n *\n * Distinct from both the outer Envelope (merchant SDK ↔ main iframe) and the inner point-to-point\n * port (element ↔ main): this message is posted directly by each visible field / element iframe to\n * its `window.parent` (the merchant page), and the merchant SDK's Element handle listens for it and\n * adjusts the outer iframe height to the real content height (width stays 100%).\n *\n * Security constraint (AGENTS/spec): this message **never contains any card value** (plaintext or\n * ciphertext); it only carries height and elementId. The parent-window side must validate the\n * source (`event.source === iframe.contentWindow` and `event.origin === hostOrigin`) before\n * trusting it, to prevent cross-origin forgery.\n */\n\n/** Discriminant literal for the iframe auto-height message (namespaced to avoid colliding with other postMessages). */\nexport const IFRAME_RESIZE_MESSAGE_TYPE = 'sunbay:checkout:iframe-resize' as const;\n\n/**\n * Content height change notification from the iframe (child) → parent window (SDK).\n *\n * The child observes content height with a `ResizeObserver` and sends on change (deduplicated); the\n * parent sets `iframe.style.height` accordingly. Never contains card values.\n */\nexport interface IframeResizeMessage {\n /** Discriminant field, fixed to {@link IFRAME_RESIZE_MESSAGE_TYPE}. */\n type: typeof IFRAME_RESIZE_MESSAGE_TYPE;\n /**\n * The unique id of the target Element. Passed down by the merchant SDK via the iframe src's\n * `&elementId=`, echoed back verbatim by the child, so the parent window can dispatch by handle\n * among multiple iframes on the same page.\n */\n elementId: string;\n /** Content height (CSS px, already `Math.ceil`-ed; finite and non-negative). */\n height: number;\n}\n\n/**\n * Whether the value is a valid {@link IframeResizeMessage}.\n *\n * Validates: non-null object + type literal match + elementId is a non-empty string + height is a\n * finite non-negative number.\n *\n * @param data - Data from any source (typically `MessageEvent.data`).\n * @returns Whether data is a valid iframe-resize message.\n */\nexport function isIframeResizeMessage(data: unknown): data is IframeResizeMessage {\n if (typeof data !== 'object' || data === null) {\n return false;\n }\n const msg = data as Partial<IframeResizeMessage>;\n return (\n msg.type === IFRAME_RESIZE_MESSAGE_TYPE &&\n typeof msg.elementId === 'string' &&\n msg.elementId.length > 0 &&\n typeof msg.height === 'number' &&\n Number.isFinite(msg.height) &&\n msg.height >= 0\n );\n}\n","/**\n * Runtime environment identifier.\n * - `dev`: development hosted page.\n * - `test`: UAT/test hosted page.\n * - `prod`: production hosted page.\n */\nexport type Env = 'dev' | 'test' | 'prod';\n\n/**\n * Built-in hosted page origins (consistently without a trailing slash).\n */\nconst HOST_ORIGINS: Record<Env, string> = {\n dev: 'https://checkout.sunbay-dev.com',\n test: 'https://checkout.sunbay-uat.us',\n prod: 'https://checkout.sunbay.us',\n};\n\n/**\n * Resolve the hosted page origin.\n *\n * @param env - Runtime environment, defaults to `'prod'`.\n * @param override - Override origin (for env vars/tests); takes precedence when non-empty.\n * @returns Hosted page origin (without a trailing slash).\n * @example\n * resolveHostOrigin(); // 'https://checkout.sunbay.us'\n * resolveHostOrigin('dev'); // 'https://checkout.sunbay-dev.com'\n * resolveHostOrigin('test'); // 'https://checkout.sunbay-uat.us'\n * resolveHostOrigin('dev', 'http://localhost:3000'); // 'http://localhost:3000'\n */\nexport function resolveHostOrigin(env: Env = 'prod', override?: string): string {\n if (override) {\n return override.replace(/\\/+$/, '');\n }\n return HOST_ORIGINS[env];\n}\n\n/**\n * Base path under which the hosted runtime serves its pages (`main`, `field/*`, `element/*`).\n * Requires a hosted runtime that serves `/embed/sdk/*` (SDK >= 0.0.7).\n */\nexport const RUNTIME_BASE_PATH = '/embed/sdk';\n\n/**\n * Build a hosted-runtime page URL (without a query string; callers append their own).\n *\n * @param hostOrigin - Hosted page origin; trailing slashes are stripped.\n * @param segment - `'main'` (hidden main frame), `'field'` (split field) or `'element'`.\n * @param type - Field/element type; required for `'field'` and `'element'`.\n * @returns Absolute URL such as `https://host/embed/sdk/field/cardNumber`.\n * @example\n * runtimeUrl('https://checkout.sunbay.us', 'main'); // '.../embed/sdk/main'\n * runtimeUrl('https://checkout.sunbay.us/', 'field', 'cardNumber'); // '.../embed/sdk/field/cardNumber'\n */\nexport function runtimeUrl(\n hostOrigin: string,\n segment: 'main' | 'field' | 'element',\n type?: string\n): string {\n const origin = hostOrigin.replace(/\\/+$/, '');\n const path = type ? `${segment}/${type}` : segment;\n return `${origin}${RUNTIME_BASE_PATH}/${path}`;\n}\n","/**\n * RuntimeHello shape validation shared by the transport and the createCheckout handshake.\n *\n * A hello that fails validation is ignored (never throws), so a malformed or hostile message can\n * neither crash the handshake with a raw TypeError nor consume the one-shot hello slot.\n */\n\nimport { PROTOCOL_NAME, type RuntimeHello } from '@sunbay/checkout-sdk-protocol';\n\n/**\n * Check that a value is a well-formed RuntimeHello.\n *\n * Requires `runtimeId` to be a non-empty string and `supportedMajorVersions` to be an array of\n * finite numbers. `capabilities` is optional, but when present it must be an array of strings.\n *\n * @param value - Unknown parsed message.\n * @returns Whether the value is a valid RuntimeHello.\n */\nexport function isValidRuntimeHello(value: unknown): value is RuntimeHello {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const r = value as Record<string, unknown>;\n if (r.protocol !== PROTOCOL_NAME || r.kind !== 'hello') {\n return false;\n }\n if (typeof r.runtimeId !== 'string' || r.runtimeId.length === 0) {\n return false;\n }\n if (\n !Array.isArray(r.supportedMajorVersions) ||\n !r.supportedMajorVersions.every((v) => typeof v === 'number' && Number.isFinite(v))\n ) {\n return false;\n }\n if (\n r.capabilities !== undefined &&\n (!Array.isArray(r.capabilities) || !r.capabilities.every((c) => typeof c === 'string'))\n ) {\n return false;\n }\n return true;\n}\n","/**\n * MainFrameTransport — the transport layer between the merchant SDK and the hosted main iframe (spec 5).\n *\n * Responsibilities:\n * - Create a hidden, 0-size main iframe (`${hostOrigin}/embed/sdk/main?checkoutId=...`).\n * - Send request envelopes and pair responses by `requestId` (resolve/reject).\n * - Dispatch `kind:'event'` envelopes to handlers registered via `on`.\n * - Enforce the security boundary: only accept messages whose `event.origin === hostOrigin`,\n * whose `event.source` is this transport's own main iframe window, whose envelope `checkoutId`\n * matches and (after the handshake) whose `runtimeId` matches the negotiated one.\n * - `destroy()` cleans up the iframe/listener and rejects all pending requests with INSTANCE_DESTROYED.\n *\n * Security constraint (AGENTS/spec): envelopes **never contain card values**; this layer only\n * carries protocol envelopes and never touches card data.\n * RuntimeHello (`kind:'hello'`) has no checkoutId yet during the handshake phase, so it is\n * recognized and handled **separately** by this layer rather than passed to `decodeEnvelope`\n * (which requires checkoutId).\n */\n\nimport {\n decodeEnvelope,\n encodeEnvelope,\n PROTOCOL_MAJOR,\n PROTOCOL_NAME,\n type CheckoutError,\n type CommandName,\n type Envelope,\n type EventName,\n type RuntimeHello,\n} from '@sunbay/checkout-sdk-protocol';\nimport { ErrorCode } from '@sunbay/checkout-sdk-protocol';\nimport { runtimeUrl } from '../config/env';\nimport { isValidRuntimeHello } from './hello';\n\n/** Constructor parameters. */\nexport interface MainFrameTransportOptions {\n checkoutId: string;\n hostOrigin: string;\n}\n\n/** Configurable timeouts (ms). */\nexport interface RequestTimeoutConfig {\n /** Default timeout for regular commands. */\n default: number;\n /** Timeout for the initialize command. */\n initialize: number;\n /** Handshake (hello) timeout. */\n handshake: number;\n}\n\n/** Default timeouts: regular 10s, initialize 30s, handshake 15s. */\nexport const DEFAULT_REQUEST_TIMEOUTS: RequestTimeoutConfig = {\n default: 10_000,\n initialize: 30_000,\n handshake: 15_000,\n};\n\n/**\n * Rethrow an error from a handler asynchronously: the current dispatch loop keeps running, while\n * the error still reaches the host page's console / `window.onerror` instead of being swallowed.\n */\nfunction rethrowAsync(err: unknown): void {\n setTimeout(() => {\n throw err;\n }, 0);\n}\n\n/** Event handler signature (payload is of unknown shape, refined by the caller per EventName). */\nexport type EventHandler = (payload: unknown) => void;\n\n/** Pairing record for a pending request. */\ninterface PendingRequest {\n resolve: (value: unknown) => void;\n reject: (reason: CheckoutError) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/** Generate a unique id (requestId / errorId). */\nfunction genId(prefix: string): string {\n const rand = Math.random().toString(36).slice(2);\n return `${prefix}_${Date.now().toString(36)}_${rand}`;\n}\n\n/** Construct a structured CheckoutError (runtime category). */\nfunction makeError(code: string, message: string): CheckoutError {\n return {\n code,\n message,\n category: 'runtime',\n errorId: genId('err'),\n };\n}\n\n/**\n * Determine whether an unknown object is a RuntimeHello (handshake phase, no checkoutId).\n *\n * Does not rely on decodeEnvelope — hello is not part of the Envelope union.\n */\nfunction isRuntimeHello(value: unknown): value is RuntimeHello {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n const record = value as Record<string, unknown>;\n return record.protocol === PROTOCOL_NAME && record.kind === 'hello';\n}\n\nexport class MainFrameTransport {\n private readonly checkoutId: string;\n private readonly hostOrigin: string;\n private readonly timeouts: RequestTimeoutConfig;\n\n private iframe: HTMLIFrameElement | null = null;\n private readonly pending = new Map<string, PendingRequest>();\n private readonly eventHandlers = new Map<EventName, Set<EventHandler>>();\n private helloHandler: ((hello: RuntimeHello) => void) | null = null;\n /**\n * Runtime id negotiated during the handshake; empty string before injection. Outbound request\n * envelopes are filled from it; the main endpoint only processes requests whose runtimeId\n * matches its own, and an empty string is silently dropped.\n */\n private runtimeId = '';\n\n private readonly messageListener: (event: MessageEvent) => void;\n private destroyed = false;\n\n constructor(\n options: MainFrameTransportOptions,\n timeouts: RequestTimeoutConfig = DEFAULT_REQUEST_TIMEOUTS\n ) {\n this.checkoutId = options.checkoutId;\n this.hostOrigin = options.hostOrigin;\n this.timeouts = timeouts;\n this.messageListener = (event: MessageEvent): void => {\n this.handleMessage(event);\n };\n window.addEventListener('message', this.messageListener);\n }\n\n /**\n * Create the hidden, 0-size main iframe and append it to document.body.\n *\n * @returns The mounted iframe element.\n * @example\n * const iframe = transport.createHiddenIframe();\n */\n createHiddenIframe(): HTMLIFrameElement {\n if (this.iframe) {\n return this.iframe;\n }\n const iframe = document.createElement('iframe');\n iframe.src = `${runtimeUrl(this.hostOrigin, 'main')}?checkoutId=${this.checkoutId}`;\n iframe.setAttribute('aria-hidden', 'true');\n iframe.title = 'sunbay-checkout-main';\n iframe.style.position = 'absolute';\n iframe.style.width = '0';\n iframe.style.height = '0';\n iframe.style.border = '0';\n iframe.style.visibility = 'hidden';\n document.body.appendChild(iframe);\n this.iframe = iframe;\n return iframe;\n }\n\n /**\n * Send one request envelope and pair the response by requestId.\n *\n * @param name - Command name.\n * @param payload - Command payload (JSON-serializable).\n * @returns The response data; on failure (ok:false / timeout / destroy) rejects with a CheckoutError.\n * @example\n * const session = await transport.request('getSession', {});\n */\n request(name: CommandName, payload: unknown): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n if (this.destroyed) {\n reject(makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed'));\n return;\n }\n const contentWindow = this.iframe?.contentWindow;\n if (!contentWindow) {\n reject(\n makeError(\n ErrorCode.RUNTIME_LOAD_FAILED,\n 'main iframe not created or contentWindow unavailable'\n )\n );\n return;\n }\n\n const requestId = genId('req');\n const envelope: Envelope = {\n protocol: PROTOCOL_NAME,\n major: PROTOCOL_MAJOR,\n runtimeId: this.runtimeId,\n checkoutId: this.checkoutId,\n kind: 'request',\n requestId,\n name,\n payload,\n };\n\n const timeoutMs = this.resolveTimeout(name);\n const timer = setTimeout(() => {\n this.pending.delete(requestId);\n reject(makeError(ErrorCode.REQUEST_TIMEOUT, `Command ${name} timed out`));\n }, timeoutMs);\n\n this.pending.set(requestId, { resolve, reject, timer });\n contentWindow.postMessage(encodeEnvelope(envelope), this.hostOrigin);\n });\n }\n\n /**\n * Register an event handler (dispatches the payload of kind:'event' envelopes).\n *\n * @param event - Event name.\n * @param handler - Callback.\n */\n on(event: EventName, handler: EventHandler): void {\n let set = this.eventHandlers.get(event);\n if (!set) {\n set = new Set<EventHandler>();\n this.eventHandlers.set(event, set);\n }\n set.add(handler);\n }\n\n /**\n * Unregister an event handler.\n *\n * @param event - Event name.\n * @param handler - The previously registered callback.\n */\n off(event: EventName, handler: EventHandler): void {\n const set = this.eventHandlers.get(event);\n if (set) {\n set.delete(handler);\n if (set.size === 0) {\n this.eventHandlers.delete(event);\n }\n }\n }\n\n /**\n * Register the handshake (RuntimeHello) callback. The hello phase has no checkoutId yet and is\n * handled separately. The callback is one-shot: it is cleared after the first valid hello from\n * this transport's own iframe; malformed hellos are ignored.\n *\n * @param handler - Called when a hello is received.\n */\n onHello(handler: (hello: RuntimeHello) => void): void {\n this.helloHandler = handler;\n }\n\n /**\n * Inject the runtime id negotiated during the handshake. Must be called before sending the first\n * request (initialize), otherwise the outbound envelope's runtimeId is an empty string, gets\n * silently dropped by the main endpoint, and the request times out.\n *\n * @param runtimeId - The runtimeId from RuntimeHello.\n */\n setRuntimeId(runtimeId: string): void {\n this.runtimeId = runtimeId;\n }\n\n /**\n * Destroy: remove the iframe, clear listeners, and reject pending requests with INSTANCE_DESTROYED.\n */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n window.removeEventListener('message', this.messageListener);\n\n for (const [, entry] of this.pending) {\n clearTimeout(entry.timer);\n entry.reject(makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed'));\n }\n this.pending.clear();\n this.eventHandlers.clear();\n this.helloHandler = null;\n\n if (this.iframe && this.iframe.parentNode) {\n this.iframe.parentNode.removeChild(this.iframe);\n }\n this.iframe = null;\n }\n\n /** Resolve the timeout by command name. */\n private resolveTimeout(name: CommandName): number {\n if (name === 'initialize') {\n return this.timeouts.initialize;\n }\n return this.timeouts.default;\n }\n\n /**\n * Point-to-point port relay (parent-window relay, Stripe controller model).\n *\n * Sibling iframes (main and the various Element iframes) cannot obtain each other's window\n * references, so they cannot transfer a MessagePort directly. This layer (the merchant page,\n * the only party that can reach both ends and knows their origin) does the following when it\n * receives an `element-online` from some Element iframe:\n * 1. Create a `MessageChannel`;\n * 2. `port1` → main iframe (`relay-port`, targetOrigin=hostOrigin);\n * 3. `port2` → the originating Element iframe (i.e. `event.source`, targetOrigin=hostOrigin).\n *\n * Both ends' origin is hostOrigin, so targetOrigin is always correct (and not dropped across\n * origins). This layer only carries **empty ports** and never touches card values (which are\n * transmitted end-to-end after the port is established).\n *\n * @param event Inbound message (origin already verified as hostOrigin)\n * @returns Whether it was handled as element-online (if so, the caller should return)\n */\n private tryHandleElementOnline(event: MessageEvent): boolean {\n const data = event.data as unknown;\n if (typeof data !== 'object' || data === null) {\n return false;\n }\n const msg = data as Record<string, unknown>;\n if (msg.kind !== 'element-online') {\n return false;\n }\n // Validate: checkoutId matches, fieldType is valid, source window exists.\n if (msg.checkoutId !== this.checkoutId || typeof msg.fieldType !== 'string') {\n return true;\n }\n const mainWin = this.iframe?.contentWindow;\n const elementWin = event.source as Window | null;\n if (!mainWin || !elementWin) {\n return true;\n }\n\n const channel = new MessageChannel();\n const relayMsg = {\n kind: 'relay-port' as const,\n checkoutId: this.checkoutId,\n fieldType: msg.fieldType,\n };\n // port1 → main iframe; port2 → the originating Element iframe.\n mainWin.postMessage(relayMsg, this.hostOrigin, [channel.port1]);\n elementWin.postMessage(relayMsg, this.hostOrigin, [channel.port2]);\n return true;\n }\n\n /** Handle an inbound message: filter origin, recognize relay / hello / Envelope and dispatch. */\n private handleMessage(event: MessageEvent): void {\n if (this.destroyed) {\n return;\n }\n // Security boundary: only accept messages from the hosted page origin.\n if (event.origin !== this.hostOrigin) {\n return;\n }\n\n // Point-to-point port relay: an Element iframe comes online → this layer (parent window)\n // creates a channel and transfers the two ports to the main iframe and that Element iframe\n // respectively (see below). The relay message is an object (not a string envelope) and must\n // be recognized before the string check.\n if (this.tryHandleElementOnline(event)) {\n return;\n }\n\n if (typeof event.data !== 'string') {\n return;\n }\n\n // Security boundary: hello and envelopes must come from this instance's own main iframe\n // window. This keeps concurrent checkout instances (each with its own iframe) from\n // adopting each other's hello/runtimeId, and rejects same-origin lookalike windows.\n const mainWindow = this.iframe?.contentWindow;\n if (!mainWindow || event.source !== mainWindow) {\n return;\n }\n\n // The handshake hello is parsed separately (not via the Envelope union; no checkoutId at this phase).\n let raw: unknown;\n try {\n raw = JSON.parse(event.data);\n } catch {\n return;\n }\n if (isRuntimeHello(raw)) {\n // A malformed hello is ignored (it neither throws nor consumes the one-shot handler).\n if (!isValidRuntimeHello(raw)) {\n return;\n }\n // One-shot: the first valid hello is consumed; later hellos (e.g. a dev double mount\n // or a reloaded runtime) are ignored so the negotiated runtimeId cannot be swapped.\n const handler = this.helloHandler;\n this.helloHandler = null;\n if (handler) {\n try {\n handler(raw);\n } catch (err) {\n rethrowAsync(err);\n }\n }\n return;\n }\n\n // Everything else is validated and decoded as an Envelope.\n let envelope: Envelope;\n try {\n envelope = decodeEnvelope(event.data);\n } catch {\n return;\n }\n\n // Security boundary: the envelope checkoutId must match this instance.\n if (envelope.checkoutId !== this.checkoutId) {\n return;\n }\n\n // Once a runtimeId is negotiated, drop response/event envelopes from any other runtime\n // instance (the runtime stamps every response and event with its own runtimeId).\n if (this.runtimeId !== '' && envelope.runtimeId !== this.runtimeId) {\n return;\n }\n\n if (envelope.kind === 'response') {\n this.handleResponse(envelope);\n } else if (envelope.kind === 'event') {\n this.handleEvent(envelope);\n }\n // kind:'request' from main → SDK should not occur; ignore.\n }\n\n /** Dispatch a response to the paired pending request. */\n private handleResponse(envelope: Extract<Envelope, { kind: 'response' }>): void {\n const entry = this.pending.get(envelope.requestId);\n if (!entry) {\n return;\n }\n this.pending.delete(envelope.requestId);\n clearTimeout(entry.timer);\n if (envelope.ok) {\n entry.resolve(envelope.data);\n } else {\n entry.reject(envelope.error);\n }\n }\n\n /** Dispatch an event to the registered handlers. */\n private handleEvent(envelope: Extract<Envelope, { kind: 'event' }>): void {\n const set = this.eventHandlers.get(envelope.name as EventName);\n if (!set) {\n return;\n }\n // Iterate a snapshot so handlers that call on/off during dispatch cannot affect this pass.\n for (const handler of [...set]) {\n try {\n handler(envelope.payload);\n } catch (err) {\n rethrowAsync(err);\n }\n }\n }\n}\n","/**\n * CheckoutElement — the merchant-side Element handle (spec 6).\n *\n * Responsibilities:\n * - Constructed by `CheckoutInstance.create` (in unit tests, injected via a mock transport +\n * constructor args).\n * - Mount a **visible** iframe at the merchant DOM target and forward Element commands through the\n * transport.\n * - Maintain the state machine `created → loading → ready → destroyed` (with `loadError` as a side branch).\n * - Subscribe to the transport's `elementReady` / `loadError` events, filter by **its own elementId**,\n * and drive the resolve / reject of `mount()`.\n *\n * Security constraint (AGENTS/spec): this layer only does DOM mounting and protocol command\n * forwarding and **never touches card values**. Card data exists only inside the hosted iframe and\n * is never transmitted via this handle or the transport.\n */\n\nimport {\n ErrorCode,\n isIframeResizeMessage,\n type Appearance,\n type AvailableWallets,\n type ChangeEvent,\n type CheckoutError,\n type CommandName,\n type ElementOptions,\n type ElementState,\n type ElementStatus,\n type ElementType,\n type EventName,\n type EventPayloadMap,\n type ExpressAvailabilityChangeEvent,\n type ExpressCheckoutElementOptions,\n} from '@sunbay/checkout-sdk-protocol';\nimport { runtimeUrl } from './config/env';\n\n/**\n * The minimal interface the transport depends on (satisfied by MainFrameTransport).\n *\n * Only declares the methods the Element handle needs, to make mock injection in unit tests easy.\n */\nexport interface ElementTransport {\n request(name: CommandName, payload: unknown): Promise<unknown>;\n on(event: EventName, handler: (payload: unknown) => void): void;\n off(event: EventName, handler: (payload: unknown) => void): void;\n}\n\n/** CheckoutElement constructor parameters (assembled by CheckoutInstance.create). */\nexport interface CheckoutElementOptions {\n /** Unique Element id (generated by the instance, used to pair commands/events). */\n elementId: string;\n /** Element type (determines the iframe path and available actions). */\n type: ElementType;\n /** Hosted page origin (without a trailing slash). */\n hostOrigin: string;\n /**\n * The current checkout session id. Sent with the iframe src as `?checkoutId=`, so that hosted\n * fields/element iframes join the correct same-origin signaling channel\n * (`sunbay-checkout:<checkoutId>`) and pair with main; missing it causes the field channel name\n * to mismatch and never become ready.\n */\n checkoutId: string;\n /** The transport layer. */\n transport: ElementTransport;\n /** Initial Element configuration (sent with createElement). */\n initialOptions?: ElementOptions;\n /**\n * Handle destruction callback (injected by CheckoutInstance). Called with this elementId when\n * `destroy()` successfully destroys the handle, so the instance removes itself from the\n * mutual-exclusion registry (elements Map), thereby allowing a mutually-exclusive Element of the\n * same kind to be recreated after destruction (e.g. switching expressCheckout's\n * buttonType/buttonHeight requires recreating the iframe). Not called by `unmount()` (which\n * keeps the handle, still occupies the slot, and can remount).\n */\n onDestroy?: (elementId: string) => void;\n /**\n * Initial color scheme (from createCheckout's appearance.colorScheme).\n * Only when provided is it appended to the iframe src's `&colorScheme=<value>`, so the hosted\n * iframe renders with that scheme on the first frame (no flash). When absent it is not appended\n * and the hosted side handles the default (light). Runtime switching goes through the\n * updateCheckout command, not here.\n */\n colorScheme?: 'light' | 'dark' | 'auto';\n /**\n * Initial appearance customization (from createCheckout's appearance).\n * Only when it contains `variables` or `rules` is it serialized into the iframe src's\n * `&appearance=<encodeURIComponent(JSON)>`, so the hosted iframe renders with that appearance on\n * the first frame (no flash). When it contains only `colorScheme` (no variables/rules) it is not\n * appended, to avoid an empty appearance string; colorScheme goes via the separate\n * `&colorScheme=`. Runtime switching goes through the updateCheckout command, not here.\n */\n appearance?: Appearance;\n /**\n * Initial locale (from createCheckout's `locale`). When provided and non-empty it is appended\n * to the iframe src as `&locale=<value>`, so the hosted iframe renders in that language on the\n * first frame (no flash). The hosted side resolves it to a supported language and ignores\n * unknown values. Runtime switching goes through the updateCheckout command, not here.\n */\n locale?: string;\n}\n\n/** Default time (ms) `mount()` waits for the hosted Element to become ready. */\nexport const DEFAULT_MOUNT_TIMEOUT_MS = 30_000;\n\n/** Options for {@link CheckoutElement.mount}. */\nexport interface MountOptions {\n /**\n * Maximum time (ms) to wait for the Element to become ready. Defaults to 30000. On expiry the\n * iframe is removed, the status becomes `loadError` and the promise rejects with\n * `RUNTIME_LOAD_FAILED`.\n */\n timeoutMs?: number;\n}\n\n/** A merchant handler as stored internally (loosely typed; typing lives on the public methods). */\ntype UserHandler = (payload: unknown) => void;\n\n/** The common structure of an event payload (contains elementId, used to filter by the own handle). */\ninterface WithElementId {\n elementId?: string;\n}\n\n/** The loadError event payload structure. */\ninterface LoadErrorPayload extends WithElementId {\n error: CheckoutError;\n}\n\n/** The elementReady event payload structure (expressCheckout additionally carries availableWallets). */\ninterface ElementReadyPayload extends WithElementId {\n availableWallets?: AvailableWallets;\n}\n\n/** The split field types (routed to /embed/sdk/field/<type>). */\nconst FIELD_TYPES: readonly ElementType[] = ['cardNumber', 'cardExpiry', 'cardCvc'];\n\n/** The input classes that provide focus/blur/clear (expressCheckout excluded). */\nconst INPUT_TYPES: readonly ElementType[] = [\n 'cardNumber',\n 'cardExpiry',\n 'cardCvc',\n 'card',\n 'address',\n];\n\n/** Build a structured CheckoutError (configuration category, for the handle's local errors). */\nfunction makeError(code: string, message: string, elementId?: string): CheckoutError {\n const rand = Math.random().toString(36).slice(2);\n return {\n code,\n message,\n category: 'configuration',\n errorId: `err_${Date.now().toString(36)}_${rand}`,\n elementId,\n };\n}\n\n/**\n * Determine whether the payload targets this elementId (**strict match**).\n *\n * Only when `payload.elementId === elementId` is it considered this Element's elementReady/loadError.\n * Missing elementId or inequality both fail to match, avoiding event cross-talk when multiple\n * Elements (T6) share the same transport.\n * (The protocol guarantees elementReady/loadError always carry an elementId.)\n */\nfunction matchesElement(payload: unknown, elementId: string): boolean {\n if (typeof payload !== 'object' || payload === null) {\n return false;\n }\n return (payload as WithElementId).elementId === elementId;\n}\n\nexport class CheckoutElement {\n /** Unique Element id. */\n readonly elementId: string;\n /** Element type. */\n readonly type: ElementType;\n /** The address Element's mode (billing/shipping; only meaningful for address), used by the instance to judge mutual exclusion by mode. */\n readonly mode: string | undefined;\n\n private readonly hostOrigin: string;\n private readonly checkoutId: string;\n private readonly transport: ElementTransport;\n private options: ElementOptions | undefined;\n /** Initial color scheme (appended to the iframe src; not appended when absent). */\n private readonly colorScheme: 'light' | 'dark' | 'auto' | undefined;\n /** Initial appearance customization (appended to the iframe src when it contains variables/rules; not appended when absent or colorScheme-only). */\n private readonly appearance: Appearance | undefined;\n /** Initial locale (appended to the iframe src; not appended when absent or empty). */\n private readonly locale: string | undefined;\n /** Destruction callback (injected by the instance): called at the end of destroy() so the instance removes itself from the mutual-exclusion registry to free the slot. */\n private readonly onDestroy: ((elementId: string) => void) | undefined;\n\n private status: ElementStatus = 'created';\n private container: HTMLElement | null = null;\n private iframe: HTMLIFrameElement | null = null;\n\n /** Event handlers temporarily subscribed during mount (unbound after resolve/reject). */\n private readyHandler: ((payload: unknown) => void) | null = null;\n private loadErrorHandler: ((payload: unknown) => void) | null = null;\n /**\n * Cancels the in-flight mount (clears its timer/listeners and rejects its promise). Null when no\n * mount is in flight. Used by `unmount()` / `destroy()` while the Element is still loading.\n */\n private abortMount: ((reason: CheckoutError) => void) | null = null;\n\n /**\n * expressCheckout only: a snapshot of each wallet's availability.\n * Initially from elementReady.availableWallets, then updated by expressAvailabilityChange.\n */\n private availableWallets: AvailableWallets | undefined;\n /** expressCheckout only: the persistently subscribed expressAvailabilityChange handler (unbound on destroy). */\n private availabilityHandler: ((payload: unknown) => void) | null = null;\n\n /** Input Elements only: the last `change` snapshot, tracked from construction (never replayed to `on`). */\n private state: ElementState = { empty: true, complete: false };\n /** Input Elements only: the persistently subscribed `change` handler (unbound on destroy). */\n private stateHandler: ((payload: unknown) => void) | null = null;\n\n /** Merchant listeners registered via `on`: event → (original handler → transport wrapper). Cleared on destroy. */\n private readonly userListeners = new Map<EventName, Map<UserHandler, UserHandler>>();\n\n /**\n * iframe auto-height: the window 'message' listener that stays resident during mount (unbound\n * when the iframe disappears/is destroyed). Keeps a reference so removeEventListener can be\n * called; null means not listening.\n */\n private resizeHandler: ((e: MessageEvent) => void) | null = null;\n /** The most recently applied iframe height (px), used for deduplication to avoid redundant style writes; null means not yet set. */\n private lastHeight: number | null = null;\n\n constructor(opts: CheckoutElementOptions) {\n this.elementId = opts.elementId;\n this.type = opts.type;\n this.hostOrigin = opts.hostOrigin;\n this.checkoutId = opts.checkoutId;\n this.transport = opts.transport;\n this.options = opts.initialOptions;\n this.colorScheme = opts.colorScheme;\n this.appearance = opts.appearance;\n this.locale = opts.locale;\n this.mode = (opts.initialOptions as { mode?: string } | undefined)?.mode;\n this.onDestroy = opts.onDestroy;\n this.installInputActions();\n this.installExpressAvailability();\n this.installInputState();\n }\n\n /** The current status (read-only snapshot, for external/test observation). */\n getStatus(): ElementStatus {\n return this.status;\n }\n\n /**\n * expressCheckout only: return the current snapshot of each wallet's availability (always\n * undefined for other types).\n *\n * The initial value comes from elementReady's availableWallets, then is updated by\n * expressAvailabilityChange.\n *\n * @returns The availability snapshot; undefined when not yet ready or non-express.\n */\n getAvailableWallets(): AvailableWallets | undefined {\n return this.availableWallets;\n }\n\n /**\n * Input Elements only: the last known `change` state (`empty`, `complete`, `brand?`, `error?`).\n *\n * `change` events are not replayed, so a handler registered after `mount()` resolves can miss\n * changes (e.g. browser autofill). Read this to get the current value instead; it is tracked from\n * construction. Starts as `{ empty: true, complete: false }`. Never contains values.\n *\n * @returns A copy of the snapshot; undefined for `expressCheckout`. Still readable after destroy.\n */\n getState(): ElementState | undefined {\n if (!INPUT_TYPES.includes(this.type)) {\n return undefined;\n }\n return { ...this.state };\n }\n\n /**\n * Mount at the merchant DOM target: insert a visible iframe, send createElement, await elementReady.\n *\n * Failure modes: a hosted `loadError` / command failure rejects with that error; waiting longer\n * than `opts.timeoutMs` (default 30000ms) removes the iframe and rejects `RUNTIME_LOAD_FAILED`;\n * calling `unmount()` while loading rejects with `RUNTIME_LOAD_FAILED` (\"mount cancelled\");\n * calling `destroy()` (or destroying the instance) while loading rejects `INSTANCE_DESTROYED`.\n * A late `elementReady` after any of these is ignored and never flips the status to ready.\n *\n * @param selectorOrEl - A CSS selector or an HTMLElement container; the container must be unique and empty.\n * @param opts - Optional mount options (`timeoutMs`).\n * @returns Resolves after elementReady; on failure removes the node and rejects (loadError / INVALID_OPTIONS).\n * @throws INSTANCE_DESTROYED when already destroyed.\n * @example\n * await element.mount('#card-field', { timeoutMs: 20000 });\n */\n mount(selectorOrEl: string | HTMLElement, opts?: MountOptions): Promise<void> {\n this.assertAlive();\n\n if (this.status === 'loading' || this.status === 'ready') {\n return Promise.reject(\n makeError(\n ErrorCode.ELEMENT_CONFLICT,\n 'This Element is already mounted; mount cannot be called twice',\n this.elementId\n )\n );\n }\n\n const container = this.resolveContainer(selectorOrEl);\n if (!container) {\n return Promise.reject(\n makeError(\n ErrorCode.INVALID_OPTIONS,\n 'Target container not found or not uniquely resolvable',\n this.elementId\n )\n );\n }\n if (container.childElementCount > 0) {\n return Promise.reject(\n makeError(ErrorCode.INVALID_OPTIONS, 'Target container is not empty', this.elementId)\n );\n }\n\n this.status = 'loading';\n this.container = container;\n\n const iframe = document.createElement('iframe');\n iframe.src = this.resolveSrc();\n iframe.title = `sunbay-checkout-${this.type}`;\n iframe.setAttribute('data-element-id', this.elementId);\n // Grant the Permissions Policy features the hosted iframe needs for cross-origin payment\n // flows, each scoped to 'self' and the hostOrigin (not opened to any other origin):\n // - `payment`: the Payment Request API used by Apple Pay / Google Pay. Without it the\n // browser denies the API inside this cross-origin iframe (\"payment is not allowed in\n // this document\"); Safari 17+ specifically requires allow=\"payment\" for cross-origin\n // Apple Pay.\n // - `publickey-credentials-get`: WebAuthn get(), used by passkey / biometric payment\n // verification (e.g. 3DS/SCA). Cross-origin iframes need it explicitly granted.\n // All element types carry the same allowlist so the SDK works uniformly regardless of\n // which element drives a wallet / WebAuthn flow.\n iframe.setAttribute(\n 'allow',\n `payment 'self' ${this.hostOrigin}; publickey-credentials-get 'self' ${this.hostOrigin}`\n );\n iframe.style.border = '0';\n iframe.style.width = '100%';\n iframe.style.display = 'block';\n // Height is fully driven by the iframe auto-resize protocol (child reports a ceil()'d\n // height via postMessage; see installResizeListener). Disable the iframe's own scrollbar\n // so sub-pixel content height differences on high-DPR browsers never surface a spurious\n // scrollbar (observed on the express button at devicePixelRatio=2).\n iframe.setAttribute('scrolling', 'no');\n container.appendChild(iframe);\n this.iframe = iframe;\n this.installResizeListener();\n\n const requested = opts?.timeoutMs;\n const timeoutMs =\n typeof requested === 'number' && Number.isFinite(requested) && requested > 0\n ? requested\n : DEFAULT_MOUNT_TIMEOUT_MS;\n\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const cleanup = (): void => {\n settled = true;\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n this.abortMount = null;\n if (this.readyHandler) {\n this.transport.off('elementReady', this.readyHandler);\n this.readyHandler = null;\n }\n if (this.loadErrorHandler) {\n this.transport.off('loadError', this.loadErrorHandler);\n this.loadErrorHandler = null;\n }\n };\n\n const onReady = (payload: unknown): void => {\n if (settled || !matchesElement(payload, this.elementId)) {\n return;\n }\n cleanup();\n // expressCheckout: capture the initial wallet availability carried by ready.\n const wallets = (payload as ElementReadyPayload).availableWallets;\n if (wallets) {\n this.availableWallets = wallets;\n }\n this.status = 'ready';\n resolve();\n };\n\n const onLoadError = (payload: unknown): void => {\n if (settled || !matchesElement(payload, this.elementId)) {\n return;\n }\n cleanup();\n this.status = 'loadError';\n this.removeIframe();\n // Release even if the createElement response has not arrived yet: the hosted side may\n // already have registered the element, and destroyElement is idempotent there.\n this.releaseHostedElement();\n const err = (payload as LoadErrorPayload)?.error;\n reject(\n err ??\n makeError(\n ErrorCode.RUNTIME_LOAD_FAILED,\n 'Failed to load Element',\n this.elementId\n )\n );\n };\n\n this.readyHandler = onReady;\n this.loadErrorHandler = onLoadError;\n this.transport.on('elementReady', onReady);\n this.transport.on('loadError', onLoadError);\n\n // Cancellation by unmount()/destroy(): the caller owns status/iframe handling.\n this.abortMount = (reason: CheckoutError): void => {\n if (settled) {\n return;\n }\n cleanup();\n reject(reason);\n };\n\n timer = setTimeout(() => {\n if (settled) {\n return;\n }\n cleanup();\n this.status = 'loadError';\n this.removeIframe();\n // Release the hosted registration so a retry mount() does not hit ELEMENT_CONFLICT.\n this.releaseHostedElement();\n reject(\n makeError(\n ErrorCode.RUNTIME_LOAD_FAILED,\n `Element did not become ready within ${timeoutMs}ms`,\n this.elementId\n )\n );\n }, timeoutMs);\n\n // Send the createElement command; a command-level failure also goes through the loadError side branch.\n this.transport\n .request('createElement', {\n elementId: this.elementId,\n type: this.type,\n options: this.options,\n })\n .then(\n () => undefined,\n (cmdErr: unknown) => {\n if (settled) {\n return;\n }\n cleanup();\n this.status = 'loadError';\n this.removeIframe();\n reject(cmdErr as CheckoutError);\n }\n );\n });\n }\n\n /** Best-effort, fire-and-forget release of the hosted element registration; never throws. */\n private releaseHostedElement(): void {\n try {\n void Promise.resolve(\n this.transport.request('destroyElement', { elementId: this.elementId })\n ).catch(() => undefined);\n } catch {\n // Ignore: release is best-effort.\n }\n }\n\n /**\n * Unmount: send destroyElement, remove the iframe; idempotent; keeps the handle and configuration.\n *\n * @returns Resolves on completion (resolves directly when not mounted).\n * @throws INSTANCE_DESTROYED when already destroyed.\n */\n async unmount(): Promise<void> {\n this.assertAlive();\n if (this.status !== 'ready' && this.status !== 'loading') {\n // Not mounted: idempotent no-op.\n return;\n }\n // Cancel an in-flight mount first so its promise rejects and a late elementReady is ignored.\n this.abortMount?.(\n makeError(\n ErrorCode.RUNTIME_LOAD_FAILED,\n 'Mount cancelled: the Element was unmounted while loading',\n this.elementId\n )\n );\n try {\n await this.transport.request('destroyElement', { elementId: this.elementId });\n } finally {\n this.removeIframe();\n this.container = null;\n this.status = 'created';\n }\n }\n\n /**\n * Destroy the handle: idempotent; remove the iframe; afterwards any non-destroy/off call throws INSTANCE_DESTROYED.\n */\n destroy(): void {\n if (this.status === 'destroyed') {\n return;\n }\n const wasHosted = this.status === 'loading' || this.status === 'ready';\n // Reject an in-flight mount (also clears its timer and listeners).\n this.abortMount?.(\n makeError(\n ErrorCode.INSTANCE_DESTROYED,\n 'Mount cancelled: the Element was destroyed while loading',\n this.elementId\n )\n );\n if (this.readyHandler) {\n this.transport.off('elementReady', this.readyHandler);\n this.readyHandler = null;\n }\n if (this.loadErrorHandler) {\n this.transport.off('loadError', this.loadErrorHandler);\n this.loadErrorHandler = null;\n }\n if (this.availabilityHandler) {\n this.transport.off('expressAvailabilityChange', this.availabilityHandler);\n this.availabilityHandler = null;\n }\n if (this.stateHandler) {\n this.transport.off('change', this.stateHandler);\n this.stateHandler = null;\n }\n for (const [event, wrappers] of this.userListeners) {\n for (const wrapper of wrappers.values()) {\n this.transport.off(event, wrapper);\n }\n }\n this.userListeners.clear();\n this.removeIframe();\n this.container = null;\n this.status = 'destroyed';\n if (wasHosted) {\n // Release the hosted registration; best effort (the transport may already be gone).\n try {\n void Promise.resolve(\n this.transport.request('destroyElement', { elementId: this.elementId })\n ).catch(() => undefined);\n } catch {\n // Ignore: destroy() must never throw.\n }\n }\n // Notify the instance to remove itself from the mutual-exclusion registry, freeing the slot to allow recreating a mutually-exclusive Element of the same kind after destruction.\n this.onDestroy?.(this.elementId);\n }\n\n /**\n * Update the Element configuration: send updateElement; illegal fields are rejected wholesale by the hosted side.\n *\n * @param patch - Configuration delta.\n * @returns Resolves after successfully writing back the local options.\n * @throws INSTANCE_DESTROYED when already destroyed.\n */\n async update(patch: Partial<ElementOptions>): Promise<void> {\n this.assertAlive();\n const resp = await this.transport.request('updateElement', {\n elementId: this.elementId,\n patch,\n });\n const next = (resp as { options?: ElementOptions } | undefined)?.options;\n if (next) {\n this.options = next;\n }\n }\n\n /**\n * Register an event handler (passed through to the transport, dispatched by event name).\n *\n * @param event - Event name.\n * @param handler - Callback.\n * @throws INSTANCE_DESTROYED when already destroyed.\n */\n on<E extends EventName>(event: E, handler: (payload: EventPayloadMap[E]) => void): void {\n this.assertAlive();\n let wrappers = this.userListeners.get(event);\n if (!wrappers) {\n wrappers = new Map();\n this.userListeners.set(event, wrappers);\n }\n if (wrappers.has(handler as UserHandler)) {\n return;\n }\n // The only typed→loose cast: the transport is loosely typed and the protocol guarantees the\n // payload shape per event name. The wrapper scopes delivery to this element: payloads that\n // carry a different elementId are dropped, payloads without one pass through unchanged.\n const typed = handler as UserHandler;\n const wrapper = (payload: unknown): void => {\n const target = (payload as WithElementId | null | undefined)?.elementId;\n if (target !== undefined && target !== this.elementId) {\n return;\n }\n typed(payload);\n };\n wrappers.set(typed, wrapper);\n this.transport.on(event, wrapper);\n }\n\n /**\n * Unregister an event handler (still safe to call after destruction).\n *\n * @param event - Event name.\n * @param handler - The previously registered callback.\n */\n off<E extends EventName>(event: E, handler: (payload: EventPayloadMap[E]) => void): void {\n const wrappers = this.userListeners.get(event);\n const wrapper = wrappers?.get(handler as UserHandler);\n if (!wrappers || !wrapper) {\n return;\n }\n wrappers.delete(handler as UserHandler);\n this.transport.off(event, wrapper);\n }\n\n /** Focus (input classes only, not provided by expressCheckout). */\n focus?: () => Promise<void>;\n /** Blur (input classes only, not provided by expressCheckout). */\n blur?: () => Promise<void>;\n /** Clear (input classes only, not provided by expressCheckout). */\n clear?: () => Promise<void>;\n\n /** Install input-class action methods (automatically called after construction). */\n private installInputActions(): void {\n if (!INPUT_TYPES.includes(this.type)) {\n return;\n }\n this.focus = (): Promise<void> => this.sendAction('focus');\n this.blur = (): Promise<void> => this.sendAction('blur');\n this.clear = (): Promise<void> => this.sendAction('clear');\n }\n\n /**\n * expressCheckout only: persistently subscribe to expressAvailabilityChange and update the local availability snapshot.\n *\n * This event payload has no elementId; express is a singleton (guaranteed by CheckoutInstance),\n * so there is no need to filter by elementId. Non-express types do not subscribe.\n */\n private installExpressAvailability(): void {\n if (this.type !== 'expressCheckout') {\n return;\n }\n const handler = (payload: unknown): void => {\n if (typeof payload !== 'object' || payload === null) {\n return;\n }\n const wallets = (payload as ExpressAvailabilityChangeEvent).availableWallets;\n if (wallets) {\n this.availableWallets = wallets;\n }\n };\n this.availabilityHandler = handler;\n this.transport.on('expressAvailabilityChange', handler);\n }\n\n /** Input Elements only: keep the `change` snapshot current so `getState()` works without a listener. */\n private installInputState(): void {\n if (!INPUT_TYPES.includes(this.type)) {\n return;\n }\n const handler = (payload: unknown): void => {\n const change = payload as Partial<ChangeEvent> | null | undefined;\n if (!change || change.elementId !== this.elementId) {\n return;\n }\n const next: ElementState = {\n empty: change.empty === true,\n complete: change.complete === true,\n };\n if (change.brand !== undefined) {\n next.brand = change.brand;\n }\n if (change.error !== undefined) {\n next.error = change.error;\n }\n this.state = next;\n };\n this.stateHandler = handler;\n this.transport.on('change', handler);\n }\n\n /** Send one input-class action command (synchronously throws INSTANCE_DESTROYED after destruction). */\n private sendAction(name: 'focus' | 'blur' | 'clear'): Promise<void> {\n this.assertAlive();\n return this.transport.request(name, { elementId: this.elementId }).then(() => undefined);\n }\n\n /** Throw INSTANCE_DESTROYED if already destroyed. */\n private assertAlive(): void {\n if (this.status === 'destroyed') {\n throw makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed', this.elementId);\n }\n }\n\n /** Resolve the mount container (the selector must uniquely match a single element). */\n private resolveContainer(selectorOrEl: string | HTMLElement): HTMLElement | null {\n if (typeof selectorOrEl !== 'string') {\n return selectorOrEl;\n }\n const nodes = document.querySelectorAll(selectorOrEl);\n if (nodes.length !== 1) {\n return null;\n }\n const node = nodes[0];\n return node instanceof HTMLElement ? node : null;\n }\n\n /**\n * Resolve the iframe src: split fields go to /embed/sdk/field/, the rest to /embed/sdk/element/, with\n * checkoutId and elementId; if an initial colorScheme is provided, append `&colorScheme=<value>`\n * (no flash on the first frame); if the initial appearance contains variables or rules, append\n * `&appearance=<encodeURIComponent(JSON.stringify(appearance))>` (takes effect on the first\n * frame, no flash). An appearance containing only colorScheme (no variables/rules) is not\n * appended, to avoid an empty appearance string. If an initial locale is provided, append\n * `&locale=<value>` (first frame renders in that language). For expressCheckout, additionally append the\n * wallet toggles / per-wallet buttonType / global buttonHeight (see {@link resolveExpressQuery}).\n *\n * elementId is sent with the src so the hosted child echoes it verbatim in iframe-resize\n * messages, letting the parent window dispatch the height per handle among multiple iframes on\n * the same page.\n */\n private resolveSrc(): string {\n const segment = FIELD_TYPES.includes(this.type) ? 'field' : 'element';\n let query = `?checkoutId=${encodeURIComponent(this.checkoutId)}`;\n query += `&elementId=${encodeURIComponent(this.elementId)}`;\n // address: pass the mode (billing/shipping) through so the hosted page binds the\n // correct same-origin field channel (address:<mode>). Without it, both address\n // Elements fall back to the default mode and the second never pairs/readies.\n if (this.type === 'address') {\n const { mode, style } = (this.options as { mode?: string; style?: unknown } | undefined) ?? {};\n if (mode) {\n query += `&mode=${encodeURIComponent(mode)}`;\n }\n // style: only the known values travel; anything else falls back to the default\n // full form on the hosted side, so it is simply not sent.\n if (style === 'simple' || style === 'full') {\n query += `&style=${style}`;\n }\n }\n if (this.colorScheme) {\n query += `&colorScheme=${encodeURIComponent(this.colorScheme)}`;\n }\n // Initial locale for the first frame (the hosted side validates it).\n if (this.locale) {\n query += `&locale=${encodeURIComponent(this.locale)}`;\n }\n // Effective appearance for the first frame: a per-element appearance (from\n // create(type, { appearance })) takes precedence over the instance-level appearance\n // (from createCheckout). Serialize only when it contains variables or rules (avoid an\n // empty appearance string; colorScheme is passed through separately).\n const effectiveAppearance = this.perElementAppearance() ?? this.appearance;\n if (effectiveAppearance && (effectiveAppearance.variables || effectiveAppearance.rules)) {\n query += `&appearance=${encodeURIComponent(JSON.stringify(effectiveAppearance))}`;\n }\n // expressCheckout: pass the express options from create's second argument (wallet toggles /\n // buttonType / buttonHeight) through to the hosted iframe, so the merchant's configuration\n // takes effect on the first frame (C1 broken-link fix).\n if (this.type === 'expressCheckout') {\n query += this.resolveExpressQuery();\n }\n return `${runtimeUrl(this.hostOrigin, segment, this.type)}${query}`;\n }\n\n /**\n * Extract a per-element appearance (from the Element's own options, i.e. the second\n * argument of create(type, options)). Returns undefined when absent. Used so per-element\n * customization (e.g. CardFieldElementOptions.appearance) is honored on the first frame.\n */\n private perElementAppearance(): Appearance | undefined {\n const opts = this.options as { appearance?: Appearance } | undefined;\n return opts?.appearance;\n }\n\n /**\n * Build the expressCheckout-specific query fragment (only called for expressCheckout):\n * - a wallet explicitly set to `false` → `&applePay=false` / `&googlePay=false` (force hidden,\n * preserving the existing toggle semantics; `true` / absent → automatic, no toggle appended);\n * - a wallet configured in object form containing `buttonType` → `&applePayButtonType=<v>` /\n * `&googlePayButtonType=<v>` (boolean toggle / absent → not appended);\n * - global `buttonHeight` (a finite number) → `&buttonHeight=<n>`.\n *\n * Appended only when there is a value; empty strings are not appended. This fragment never\n * touches card values and only carries display configuration.\n *\n * @returns A query fragment starting with `&` (returns an empty string when nothing is appendable).\n */\n private resolveExpressQuery(): string {\n const options = this.options as ExpressCheckoutElementOptions | undefined;\n if (!options) {\n return '';\n }\n let query = '';\n const applePay = options.paymentMethods?.applePay;\n const googlePay = options.paymentMethods?.googlePay;\n // Wallet toggle: only an explicit false (force hidden) is sent, preserving the existing toggle semantics.\n if (applePay === false) {\n query += `&applePay=false`;\n }\n if (googlePay === false) {\n query += `&googlePay=false`;\n }\n // Per-wallet buttonType: sent only when in object form and containing buttonType.\n if (typeof applePay === 'object' && applePay.buttonType) {\n query += `&applePayButtonType=${encodeURIComponent(applePay.buttonType)}`;\n }\n if (typeof googlePay === 'object' && googlePay.buttonType) {\n query += `&googlePayButtonType=${encodeURIComponent(googlePay.buttonType)}`;\n }\n // Global button height: sent only when a finite number (the hosted side then clamps to [30,64]).\n if (typeof options.buttonHeight === 'number' && Number.isFinite(options.buttonHeight)) {\n query += `&buttonHeight=${encodeURIComponent(String(options.buttonHeight))}`;\n }\n return query;\n }\n\n /**\n * Install the iframe auto-height listener: subscribe to window 'message', only trust a valid\n * {@link IframeResizeMessage} from this iframe's `contentWindow` with origin === hostOrigin, and\n * when the elementId matches this handle, adjust the outer iframe's height to the content's real\n * height (width stays 100%).\n *\n * Security: first verify `event.source === iframe.contentWindow` (the key source check), then\n * verify `event.origin === hostOrigin` (a stricter same-origin check), to prevent cross-origin forgery.\n * Height deduplication: skip if identical to the last one, to avoid redundant style writes.\n */\n private installResizeListener(): void {\n const handler = (event: MessageEvent): void => {\n if (!this.iframe) {\n return;\n }\n if (event.source !== this.iframe.contentWindow) {\n return;\n }\n if (event.origin !== this.hostOrigin) {\n return;\n }\n if (!isIframeResizeMessage(event.data)) {\n return;\n }\n if (event.data.elementId !== this.elementId) {\n return;\n }\n const { height } = event.data;\n if (height === this.lastHeight) {\n return;\n }\n this.lastHeight = height;\n this.iframe.style.height = `${height}px`;\n };\n this.resizeHandler = handler;\n window.addEventListener('message', handler);\n }\n\n /** Unbind the iframe auto-height listener and reset the deduplication state (idempotent). */\n private teardownResizeListener(): void {\n if (this.resizeHandler) {\n window.removeEventListener('message', this.resizeHandler);\n this.resizeHandler = null;\n }\n this.lastHeight = null;\n }\n\n /** Remove the iframe DOM node (if present) and unbind the auto-height listener. */\n private removeIframe(): void {\n this.teardownResizeListener();\n if (this.iframe && this.iframe.parentNode) {\n this.iframe.parentNode.removeChild(this.iframe);\n }\n this.iframe = null;\n }\n\n /** Factory: equivalent to `new CheckoutElement(opts)` (a unified entry for CheckoutInstance). */\n static create(opts: CheckoutElementOptions): CheckoutElement {\n return new CheckoutElement(opts);\n }\n}\n","/**\n * CheckoutInstance — the merchant-side checkout instance handle (spec 4 / 7 / 8).\n *\n * Responsibilities:\n * - Constructed by `createCheckout` after a successful handshake + initialize (holds the ready\n * transport, runtimeId, capabilities, and the initial PublicSessionView).\n * - `create` assembles and returns a {@link CheckoutElement}, maintaining a **mutual-exclusion\n * registry** (card and split fields are mutually exclusive, same-mode addresses are mutually\n * exclusive, expressCheckout is a singleton → `ELEMENT_CONFLICT`).\n * - `confirm` generates an operationId, sends the confirm command to obtain accepted, and the\n * Promise is fulfilled by a later `paymentResult` event with the same operationId; calling\n * confirm again while in progress → `CHECKOUT_BUSY`.\n * - `getSession/refresh/getPaymentStatus/updateCheckout` pass through to the corresponding commands.\n * - `destroy` is idempotent: releases Elements, unbinds listeners, rejects the pending confirm with\n * INSTANCE_DESTROYED, sends the destroy command and destroys the transport; any late\n * `paymentResult` afterwards is ignored.\n *\n * Security constraint (AGENTS/spec): this layer only ferries protocol commands/events and\n * **never touches card values**.\n */\n\nimport { CheckoutElement, type CheckoutElementOptions } from './Element';\nimport {\n ErrorCode,\n type Appearance,\n type AddressInfo,\n type AvailableWallets,\n type CheckoutError,\n type CommandName,\n type ConfirmReq,\n type ElementOptions,\n type ElementType,\n type EventName,\n type EventPayloadMap,\n type WarningEvent,\n type GetPaymentStatusResp,\n type PaymentOutcome,\n type PaymentMethodsView,\n type PaymentResultEvent,\n type PublicSessionView,\n type UpdateCheckoutReq,\n} from '@sunbay/checkout-sdk-protocol';\n\n/**\n * The minimal transport interface CheckoutInstance depends on (satisfied by MainFrameTransport).\n *\n * Adds `onHello/createHiddenIframe/destroy` beyond ElementTransport, used by createCheckout for\n * handshake wiring and for instance destruction. Tests can inject a mock.\n */\nexport interface InstanceTransport {\n request(name: CommandName, payload: unknown): Promise<unknown>;\n on(event: EventName, handler: (payload: unknown) => void): void;\n off(event: EventName, handler: (payload: unknown) => void): void;\n onHello(handler: (hello: unknown) => void): void;\n setRuntimeId(runtimeId: string): void;\n createHiddenIframe(): unknown;\n destroy(): void;\n}\n\n/** CheckoutInstance constructor parameters (assembled by createCheckout). */\nexport interface CheckoutInstanceOptions {\n /** Unique checkout id. */\n checkoutId: string;\n /** Negotiated runtime id (from RuntimeHello). */\n runtimeId: string;\n /** Hosted page origin (without a trailing slash). */\n hostOrigin: string;\n /** The ready transport. */\n transport: InstanceTransport;\n /** The capabilities returned by initialize. */\n capabilities: string[];\n /** The initial session view returned by initialize. */\n session: PublicSessionView;\n /**\n * Warnings produced during initialize (the instance did not exist yet, so they could not be\n * delivered as events). Replayed once to the first `warning` listener.\n */\n initialWarnings?: WarningEvent[];\n /**\n * Initial appearance customization (from createCheckout's appearance).\n * Passed through to every created Element and serialized into its iframe src (no flash on the\n * first frame):\n * - colorScheme appended as `&colorScheme=`;\n * - variables/rules appended as `&appearance=` (only when non-empty).\n * Not appended when absent. Runtime switching goes through the updateCheckout command.\n */\n appearance?: Appearance;\n /**\n * Initial locale (from createCheckout's `locale`). Passed through to every created Element and\n * appended to its iframe src as `&locale=`, so the first frame renders in that language.\n */\n locale?: string;\n}\n\n/** Default time (ms) `confirm()` waits for a terminal outcome before resolving `pending`. */\nexport const CONFIRM_RESULT_DEADLINE_MS = 120_000;\n\n/**\n * Optional confirm parameters (aligned with ConfirmReq, minus the instance-generated operationId,\n * plus two SDK-only options that are never sent to the runtime).\n */\nexport type ConfirmOptions = Omit<ConfirmReq, 'operationId'> & {\n /**\n * Called synchronously with the generated operationId, before the `confirm` command is sent.\n * Lets the merchant persist the id early (e.g. to reconcile after a timeout or page reload).\n */\n onOperation?: (operationId: string) => void;\n /**\n * Per-call override of the result watchdog in milliseconds (default\n * {@link CONFIRM_RESULT_DEADLINE_MS}). Must be a positive finite number, otherwise the default\n * applies.\n */\n resultTimeoutMs?: number;\n};\n\n/** Pairing record for a pending confirm. */\ninterface PendingConfirm {\n operationId: string;\n /** Whether the merchant-facing Promise has already settled (the slot may still be held). */\n settled: boolean;\n resolve: (outcome: PaymentOutcome) => void;\n reject: (reason: CheckoutError) => void;\n /** Result watchdog timer. */\n watchdog: ReturnType<typeof setTimeout> | null;\n /** txnId of the most recent non-terminal `pending` outcome, if any. */\n lastPendingTxnId: string | undefined;\n}\n\n/** The set of split card field types. */\nconst CARD_FIELD_TYPES: readonly ElementType[] = ['cardNumber', 'cardExpiry', 'cardCvc'];\n\n/** Generate a unique id. */\nfunction genId(prefix: string): string {\n const rand = Math.random().toString(36).slice(2);\n return `${prefix}_${Date.now().toString(36)}_${rand}`;\n}\n\n/** Construct a structured CheckoutError. */\nfunction makeError(\n code: string,\n message: string,\n category: CheckoutError['category'] = 'configuration'\n): CheckoutError {\n return {\n code,\n message,\n category,\n errorId: genId('err'),\n };\n}\n\nexport class CheckoutInstance {\n /** Unique checkout id. */\n readonly checkoutId: string;\n /** Negotiated runtime id. */\n readonly runtimeId: string;\n /** Negotiated capability set. */\n readonly capabilities: readonly string[];\n\n private readonly hostOrigin: string;\n private readonly transport: InstanceTransport;\n private session: PublicSessionView;\n /** Initial appearance customization (passed through to each created Element's iframe src). */\n private readonly appearance: Appearance | undefined;\n /** Initial locale (passed through to each created Element's iframe src). */\n private readonly locale: string | undefined;\n\n /** Created Elements (indexed by elementId). */\n /**\n * The **single source of truth** for the mutual-exclusion registry: elementId → the created\n * CheckoutElement. Mutual-exclusion decisions are derived live from this Map (see\n * {@link assertNoConflict}); an element's `destroy()` removes itself from this Map via\n * {@link releaseElement} to free the slot (allowing a mutually-exclusive Element of the same\n * kind to be recreated after destruction).\n */\n private readonly elements = new Map<string, CheckoutElement>();\n\n /** The current pending confirm (at most one at a time). */\n private pendingConfirm: PendingConfirm | null = null;\n /** The paymentResult event subscription handler (unbound on destroy). */\n private readonly paymentResultHandler: (payload: unknown) => void;\n\n private destroyed = false;\n\n /** Warnings from initialize not yet delivered to any `warning` listener. */\n private pendingWarnings: WarningEvent[];\n\n constructor(opts: CheckoutInstanceOptions) {\n this.pendingWarnings = opts.initialWarnings ? [...opts.initialWarnings] : [];\n this.checkoutId = opts.checkoutId;\n this.runtimeId = opts.runtimeId;\n this.capabilities = opts.capabilities;\n this.hostOrigin = opts.hostOrigin;\n this.transport = opts.transport;\n this.session = opts.session;\n this.appearance = opts.appearance;\n this.locale = opts.locale;\n\n this.paymentResultHandler = (payload: unknown): void => {\n this.handlePaymentResult(payload);\n };\n this.transport.on('paymentResult', this.paymentResultHandler);\n }\n\n /**\n * Create an Element handle (not auto-mounted; a mutual-exclusion conflict throws ELEMENT_CONFLICT).\n *\n * Mutual-exclusion rules (spec 6):\n * - The combined `card` and any split field (cardNumber/cardExpiry/cardCvc) are mutually exclusive.\n * - An address with the same `mode` (billing/shipping) cannot be duplicated.\n * - `expressCheckout` is a singleton.\n *\n * @param type - Element type.\n * @param options - Initial Element configuration.\n * @returns The newly created CheckoutElement.\n * @throws INSTANCE_DESTROYED when already destroyed; ELEMENT_CONFLICT on a mutual-exclusion conflict.\n */\n create(type: ElementType, options?: ElementOptions): CheckoutElement {\n this.assertAlive();\n this.assertNoConflict(type, options);\n\n const elementId = genId('el');\n const elementOpts: CheckoutElementOptions = {\n elementId,\n type,\n hostOrigin: this.hostOrigin,\n checkoutId: this.checkoutId,\n transport: this.transport,\n initialOptions: options,\n colorScheme: this.appearance?.colorScheme,\n appearance: this.appearance,\n locale: this.locale,\n onDestroy: (id: string) => this.releaseElement(id),\n };\n const element = CheckoutElement.create(elementOpts);\n this.elements.set(elementId, element);\n return element;\n }\n\n /**\n * Initiate a payment confirmation. Generates an operationId, sends the `confirm` command, and\n * returns a Promise fulfilled by `paymentResult` events with the same operationId.\n *\n * Behavior changes in 0.0.7: previously the Promise resolved on the first `paymentResult`,\n * including a non-final `pending` outcome. Now it resolves ONLY on a terminal outcome\n * (`succeeded` | `failed` | `canceled`); a `pending` outcome keeps it waiting.\n *\n * Watchdog: if no terminal outcome arrives within `resultTimeoutMs` (default\n * {@link CONFIRM_RESULT_DEADLINE_MS} = 120000ms) the Promise resolves\n * `{ status: 'pending', operationId, txnId? }`. This is NOT a failure: the payment may still\n * complete, so never treat it as failed and never retry blindly. Reconcile with\n * `getPaymentStatus()` or the `paymentResult` event.\n *\n * Slot semantics (duplicate-submit protection): the confirm slot stays occupied until a\n * terminal outcome arrives or `destroy()` is called. While it is occupied another `confirm()`\n * rejects with `CHECKOUT_BUSY`; this also holds after the watchdog resolved `pending`, and later\n * terminal outcomes are still delivered through `on('paymentResult', ...)`.\n *\n * If the `confirm` command is rejected by the runtime the payment was not started: the Promise\n * rejects with that error and the slot is freed. If the command itself times out\n * (`REQUEST_TIMEOUT`) the runtime may have started the payment: the Promise rejects with the\n * error augmented with `paymentStateKnown: false`, the slot stays occupied and a later terminal\n * `paymentResult` for this operation frees it. Do not retry; reconcile with `getPaymentStatus()`.\n *\n * `error` events with `paymentStateKnown === false` are informational and do not settle the\n * Promise.\n *\n * @param opts - Optional billing/shipping address, name, email, returnUrl, plus `onOperation`\n * and `resultTimeoutMs`.\n * @returns The terminal PaymentOutcome, or `{ status: 'pending' }` when the watchdog fires.\n * @throws rejects INSTANCE_DESTROYED when destroyed; rejects CHECKOUT_BUSY when in progress.\n */\n confirm(opts?: ConfirmOptions): Promise<PaymentOutcome> {\n if (this.destroyed) {\n return Promise.reject(\n makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed', 'runtime')\n );\n }\n if (this.pendingConfirm) {\n return Promise.reject(\n makeError(ErrorCode.CHECKOUT_BUSY, 'A payment confirmation is already in progress', 'runtime')\n );\n }\n\n // SDK-only options never go on the wire.\n const { onOperation, resultTimeoutMs, ...rest } = opts ?? {};\n const operationId = genId('op');\n const payload: ConfirmReq = { ...rest, operationId };\n const deadline =\n typeof resultTimeoutMs === 'number' && Number.isFinite(resultTimeoutMs) && resultTimeoutMs > 0\n ? resultTimeoutMs\n : CONFIRM_RESULT_DEADLINE_MS;\n\n return new Promise<PaymentOutcome>((resolve, reject) => {\n // Reserve the slot first, to prevent a concurrent confirm before accepted.\n const entry: PendingConfirm = {\n operationId,\n settled: false,\n resolve,\n reject,\n watchdog: null,\n lastPendingTxnId: undefined,\n };\n this.pendingConfirm = entry;\n\n entry.watchdog = setTimeout(() => {\n entry.watchdog = null;\n if (entry.settled) {\n return;\n }\n entry.settled = true;\n // Not a failure and not a rejection: the state is unknown. The slot stays held.\n const outcome: PaymentOutcome =\n entry.lastPendingTxnId !== undefined\n ? { status: 'pending', operationId, txnId: entry.lastPendingTxnId }\n : { status: 'pending', operationId };\n resolve(outcome);\n }, deadline);\n\n // Expose the operation id before the command leaves; a throwing callback must not break\n // the payment flow, so surface its error asynchronously.\n if (typeof onOperation === 'function') {\n try {\n onOperation(operationId);\n } catch (err) {\n setTimeout(() => {\n throw err;\n }, 0);\n }\n }\n\n this.transport.request('confirm', payload).catch((err: unknown) => {\n if (this.pendingConfirm !== entry) {\n return;\n }\n const error = err as CheckoutError;\n if (error && error.code === ErrorCode.REQUEST_TIMEOUT) {\n // The runtime may have started the payment: keep the slot, mark state unknown.\n if (!entry.settled) {\n entry.settled = true;\n this.clearWatchdog(entry);\n reject({ ...error, paymentStateKnown: false });\n }\n return;\n }\n // The runtime did not accept the command: free the slot and reject.\n this.pendingConfirm = null;\n this.clearWatchdog(entry);\n if (!entry.settled) {\n entry.settled = true;\n reject(error);\n }\n });\n });\n }\n\n /**\n * Get the latest session view (passes through the getSession command and writes back the local snapshot).\n *\n * @returns The latest PublicSessionView.\n * @throws rejects INSTANCE_DESTROYED when destroyed.\n */\n async getSession(): Promise<PublicSessionView> {\n this.assertAlive();\n const resp = (await this.transport.request('getSession', {})) as PublicSessionView;\n this.session = resp;\n return resp;\n }\n\n /**\n * The session's payment methods split into quick wallets (`express`) and everything else\n * (`regular`), from the local session snapshot (already filtered by `paymentMethods`).\n *\n * Each express entry carries `available` from the `expressCheckout` Element's availability\n * snapshot; it is `undefined` while no such Element exists or it has not reported yet.\n *\n * @returns The split view.\n * @throws INSTANCE_DESTROYED when destroyed.\n */\n getPaymentMethods(): PaymentMethodsView {\n this.assertAlive();\n let wallets: AvailableWallets | undefined;\n for (const element of this.elements.values()) {\n if (element.type === 'expressCheckout') {\n wallets = element.getAvailableWallets();\n }\n }\n const view: PaymentMethodsView = { express: [], regular: [] };\n for (const method of this.session.paymentMethods) {\n if (method.method === 'APPLE_PAY' || method.method === 'GOOGLE_PAY') {\n const available =\n wallets === undefined\n ? undefined\n : method.method === 'APPLE_PAY'\n ? wallets.applePay\n : wallets.googlePay;\n view.express.push({ ...method, available });\n } else {\n view.regular.push({ ...method });\n }\n }\n return view;\n }\n\n /**\n * Refresh the session (passes through the refresh command and writes back the local snapshot).\n *\n * @returns The refreshed PublicSessionView.\n * @throws rejects INSTANCE_DESTROYED when destroyed.\n */\n async refresh(): Promise<PublicSessionView> {\n this.assertAlive();\n const resp = (await this.transport.request('refresh', {})) as PublicSessionView;\n this.session = resp;\n return resp;\n }\n\n /**\n * Query the payment status (returns TxnStatus as-is, no transformation).\n *\n * @returns txnStatus (may be absent when the session is expired), sessionStatus and txnId.\n * @throws rejects INSTANCE_DESTROYED when destroyed.\n */\n async getPaymentStatus(): Promise<GetPaymentStatusResp> {\n this.assertAlive();\n return (await this.transport.request('getPaymentStatus', {})) as GetPaymentStatusResp;\n }\n\n /**\n * Update the checkout appearance/locale (does not change the session or the amount).\n *\n * @param patch - locale / appearance delta.\n * @throws rejects INSTANCE_DESTROYED when destroyed.\n */\n async updateCheckout(patch: {\n locale?: string;\n appearance?: Appearance;\n billingAddress?: AddressInfo;\n shippingAddress?: AddressInfo;\n }): Promise<void> {\n this.assertAlive();\n const payload: UpdateCheckoutReq = patch;\n await this.transport.request('updateCheckout', payload);\n }\n\n /**\n * Register a Checkout-level event handler (passes through the transport).\n *\n * @param event - Event name.\n * @param handler - Callback.\n * @throws INSTANCE_DESTROYED when destroyed.\n */\n on<E extends EventName>(event: E, handler: (payload: EventPayloadMap[E]) => void): void {\n this.assertAlive();\n // The only typed→loose cast: the transport is loosely typed and the protocol guarantees the\n // payload shape per event name. The same function identity is passed, so `off` works as is.\n this.transport.on(event, handler as (payload: unknown) => void);\n // Replay warnings raised during initialize to the first `warning` listener (once), async so\n // the caller finishes its setup before the handler runs.\n if (event === 'warning' && this.pendingWarnings.length > 0) {\n const pending = this.pendingWarnings;\n this.pendingWarnings = [];\n queueMicrotask(() => {\n if (this.destroyed) {\n return;\n }\n for (const w of pending) {\n (handler as (payload: WarningEvent) => void)(w);\n }\n });\n }\n }\n\n /**\n * Unregister an event handler (safe to call after destruction).\n *\n * @param event - Event name.\n * @param handler - The previously registered callback.\n */\n off<E extends EventName>(event: E, handler: (payload: EventPayloadMap[E]) => void): void {\n this.transport.off(event, handler as (payload: unknown) => void);\n }\n\n /**\n * Destroy the instance: idempotent. Releases all Elements, unbinds the paymentResult listener,\n * rejects the pending confirm with INSTANCE_DESTROYED, sends the destroy command and destroys\n * the transport. Any late paymentResult afterwards is ignored and does not overwrite an already\n * settled Promise.\n */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n\n // Release all Element handles.\n for (const element of this.elements.values()) {\n element.destroy();\n }\n this.elements.clear();\n\n // Unbind the paymentResult listener (no handler can be reached by a late result afterwards).\n this.transport.off('paymentResult', this.paymentResultHandler);\n\n // Reject the pending confirm with INSTANCE_DESTROYED.\n if (this.pendingConfirm) {\n const entry = this.pendingConfirm;\n this.pendingConfirm = null;\n this.clearWatchdog(entry);\n if (!entry.settled) {\n entry.settled = true;\n entry.reject(\n makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed', 'runtime')\n );\n }\n }\n\n // Notify the hosted side and destroy the transport (request after destroy is rejected by the transport itself).\n void Promise.resolve(this.transport.request('destroy', {})).catch(() => undefined);\n this.transport.destroy();\n }\n\n /** Throw INSTANCE_DESTROYED if already destroyed. */\n private assertAlive(): void {\n if (this.destroyed) {\n throw makeError(ErrorCode.INSTANCE_DESTROYED, 'Checkout instance has been destroyed', 'runtime');\n }\n }\n\n /** Mutual-exclusion check: throws ELEMENT_CONFLICT on conflict (derived live from the elements Map, does not mutate the registry). */\n private assertNoConflict(type: ElementType, options?: ElementOptions): void {\n const existing = [...this.elements.values()];\n const has = (t: ElementType): boolean => existing.some((e) => e.type === t);\n const hasCardField = (): boolean => existing.some((e) => CARD_FIELD_TYPES.includes(e.type));\n\n if (type === 'card') {\n if (has('card')) {\n throw makeError(ErrorCode.ELEMENT_CONFLICT, 'A combined card Element already exists');\n }\n if (hasCardField()) {\n throw makeError(\n ErrorCode.ELEMENT_CONFLICT,\n 'Combined card and split card fields are mutually exclusive; split card fields already exist'\n );\n }\n return;\n }\n if (CARD_FIELD_TYPES.includes(type)) {\n if (has('card')) {\n throw makeError(\n ErrorCode.ELEMENT_CONFLICT,\n 'Split card fields and combined card are mutually exclusive; a combined card already exists'\n );\n }\n // The same split field type cannot be duplicated.\n if (has(type)) {\n throw makeError(\n ErrorCode.ELEMENT_CONFLICT,\n `A split card field of type ${type} already exists`\n );\n }\n return;\n }\n if (type === 'address') {\n const mode = (options as { mode?: string } | undefined)?.mode;\n if (mode && existing.some((e) => e.type === 'address' && e.mode === mode)) {\n throw makeError(\n ErrorCode.ELEMENT_CONFLICT,\n `An address Element with mode=${mode} already exists`\n );\n }\n return;\n }\n if (type === 'expressCheckout') {\n if (has('expressCheckout')) {\n throw makeError(ErrorCode.ELEMENT_CONFLICT, 'An expressCheckout Element already exists');\n }\n return;\n }\n }\n\n /**\n * Element `destroy()` callback: remove this elementId from the mutual-exclusion registry (the\n * elements Map) to free the slot. Idempotent; when the whole instance is destroyed (destroyed\n * already set) it goes through the unified `elements.clear()` path, so this is a no-op here,\n * avoiding concurrent modification while iterating elements to call element.destroy().\n */\n private releaseElement(elementId: string): void {\n if (this.destroyed) {\n return;\n }\n this.elements.delete(elementId);\n }\n\n /** Handle the paymentResult event: fulfill the pending confirm by operationId; late/mismatched ones are ignored. */\n private handlePaymentResult(payload: unknown): void {\n if (this.destroyed) {\n return;\n }\n if (typeof payload !== 'object' || payload === null) {\n return;\n }\n const evt = payload as Partial<PaymentResultEvent>;\n const pending = this.pendingConfirm;\n if (!pending) {\n return;\n }\n if (evt.operationId !== pending.operationId) {\n return;\n }\n const outcome = evt.outcome;\n if (!outcome) {\n return;\n }\n if (outcome.status === 'pending') {\n // Non-terminal: keep waiting (and keep the slot) for the final outcome.\n pending.lastPendingTxnId = outcome.txnId ?? pending.lastPendingTxnId;\n return;\n }\n if (\n outcome.status !== 'succeeded' &&\n outcome.status !== 'failed' &&\n outcome.status !== 'canceled'\n ) {\n return;\n }\n // Terminal: free the slot; settle the Promise unless the watchdog/timeout already did.\n this.pendingConfirm = null;\n this.clearWatchdog(pending);\n if (!pending.settled) {\n pending.settled = true;\n pending.resolve(outcome);\n }\n }\n\n /** Clear a pending confirm's watchdog timer (idempotent). */\n private clearWatchdog(entry: PendingConfirm): void {\n if (entry.watchdog !== null) {\n clearTimeout(entry.watchdog);\n entry.watchdog = null;\n }\n }\n}\n","/**\n * createCheckout — the merchant SDK's single async entry (spec 4).\n *\n * Flow:\n * 1. Generate `checkoutId`, derive the hosted origin via `resolveHostOrigin(env, hostOrigin)`.\n * 2. Build the transport, `createHiddenIframe()` to load the hosted main iframe.\n * 3. Register onHello; wait for RuntimeHello (timeout 15s → reject RUNTIME_LOAD_FAILED).\n * 4. Pick a common major version (no intersection → reject PROTOCOL_UNSUPPORTED).\n * 5. Send `initialize` (sessionId/locale/appearance/paymentMethods) to obtain\n * capabilities + PublicSessionView; any step failing rejects and destroys the transport.\n * 6. Inject the handshake runtimeId into the transport, construct and resolve {@link CheckoutInstance}.\n *\n * Security constraint (AGENTS/spec): this layer only orchestrates handshake/initialization and\n * **never touches card values**.\n */\n\nimport { MainFrameTransport } from './transport/MainFrameTransport';\nimport { CheckoutInstance, type InstanceTransport } from './CheckoutInstance';\nimport { isValidRuntimeHello } from './transport/hello';\nimport { resolveHostOrigin, type Env } from './config/env';\nimport {\n ErrorCode,\n PROTOCOL_MAJOR,\n type Appearance,\n type AddressInfo,\n type CheckoutError,\n type InitializeReq,\n type InitializeResp,\n type PaymentMethodFilter,\n type RuntimeHello,\n} from '@sunbay/checkout-sdk-protocol';\n\n/** Handshake timeout (ms): matches the transport handshake timeout (15s). */\nconst HANDSHAKE_TIMEOUT_MS = 15_000;\n\n/**\n * Internal transport factory injectable when creating a CheckoutInstance (test/advanced use only).\n *\n * Real scenarios use the built-in MainFrameTransport; tests may inject a mock to drive hello/events.\n */\nexport type TransportFactory = (args: {\n checkoutId: string;\n hostOrigin: string;\n}) => InstanceTransport;\n\n/** createCheckout parameters. */\nexport interface CreateCheckoutOptions {\n /** Checkout session id created by the backend (required). */\n sessionId: string;\n /**\n * Client secret of the session (required). Returned by the merchant backend's `create-session`\n * call when `sessionType` is `embedded`. Hand it to the browser over an authenticated HTTPS\n * response; never put it in a URL or write it to logs.\n */\n checkoutClientSecret: string;\n /** Runtime environment (dev/test/prod), defaults to prod. */\n env?: Env;\n /** Override the hosted origin (takes precedence over env). */\n hostOrigin?: string;\n /**\n * Initial locale, e.g. `'en-US'` or `'zh-CN'`. Sent to the runtime and appended to every\n * Element iframe src, so the first frame renders in that language. Unknown values fall back to\n * the browser language. Change it later with `updateCheckout({ locale })`.\n */\n locale?: string;\n /** Appearance customization. */\n appearance?: Appearance;\n /** Payment method filter (subtractive/reordering only). */\n paymentMethods?: PaymentMethodFilter;\n /**\n * Host-collected billing address. When complete, Apple Pay / Google Pay do not ask the user for\n * it again, and it is used as the default for card `confirm()`.\n */\n billingAddress?: AddressInfo;\n /** Host-collected shipping address (complete = address + name + phone). Same rules as above. */\n shippingAddress?: AddressInfo;\n /** Internal injection point: custom transport factory (test use; not part of the public API contract). */\n __transportFactory?: TransportFactory;\n}\n\n/** Generate a unique id. */\nfunction genId(prefix: string): string {\n const rand = Math.random().toString(36).slice(2);\n return `${prefix}_${Date.now().toString(36)}_${rand}`;\n}\n\n/** Construct a structured CheckoutError (runtime category). */\nfunction makeError(code: string, message: string): CheckoutError {\n return {\n code,\n message,\n category: 'runtime',\n errorId: genId('err'),\n };\n}\n\n/** Default transport factory: the built-in MainFrameTransport. */\nconst defaultTransportFactory: TransportFactory = ({ checkoutId, hostOrigin }) =>\n new MainFrameTransport({ checkoutId, hostOrigin });\n\n/**\n * Create a checkout instance: resolves after a successful handshake + initialization.\n *\n * @param opts - Checkout parameters.\n * @returns A ready CheckoutInstance.\n * @throws reject INVALID_OPTIONS (missing/blank/non-string checkoutClientSecret, before any iframe\n * is created) / RUNTIME_LOAD_FAILED (handshake timeout) / PROTOCOL_UNSUPPORTED (no common major\n * version) / or the initialize business error.\n * @example\n * const checkout = await createCheckout({\n * sessionId: 'sess_x',\n * checkoutClientSecret: 'ccs_x', // from your backend's create-session (sessionType: embedded)\n * env: 'prod',\n * });\n */\nexport async function createCheckout(opts: CreateCheckoutOptions): Promise<CheckoutInstance> {\n // Validate first so a rejected call creates no iframe. Never echo the supplied value.\n if (typeof opts.checkoutClientSecret !== 'string' || opts.checkoutClientSecret.trim() === '') {\n throw makeError(ErrorCode.INVALID_OPTIONS, 'checkoutClientSecret is required');\n }\n const checkoutId = genId('co');\n const hostOrigin = resolveHostOrigin(opts.env, opts.hostOrigin);\n const factory = opts.__transportFactory ?? defaultTransportFactory;\n const transport = factory({ checkoutId, hostOrigin });\n\n // Start the hosted main iframe (hidden, 0 size).\n transport.createHiddenIframe();\n\n let hello: RuntimeHello;\n try {\n hello = await waitForHello(transport);\n } catch (err) {\n transport.destroy();\n throw err;\n }\n\n // Pick a common major version.\n if (!hello.supportedMajorVersions.includes(PROTOCOL_MAJOR)) {\n transport.destroy();\n throw makeError(\n ErrorCode.PROTOCOL_UNSUPPORTED,\n `No common major protocol version: SDK=${PROTOCOL_MAJOR}, runtime=${JSON.stringify(hello.supportedMajorVersions)}`\n );\n }\n\n // Inject the negotiated runtimeId: must happen before sending initialize, otherwise the\n // outbound envelope's runtimeId is an empty string, gets silently dropped by the main\n // endpoint, and causes initialize to time out.\n transport.setRuntimeId(hello.runtimeId);\n\n // Send initialize.\n const initReq: InitializeReq = {\n sessionId: opts.sessionId,\n checkoutClientSecret: opts.checkoutClientSecret,\n locale: opts.locale,\n appearance: opts.appearance,\n paymentMethods: opts.paymentMethods,\n billingAddress: opts.billingAddress,\n shippingAddress: opts.shippingAddress,\n };\n let initResp: InitializeResp;\n try {\n initResp = (await transport.request('initialize', initReq)) as InitializeResp;\n } catch (err) {\n transport.destroy();\n throw err as CheckoutError;\n }\n\n return new CheckoutInstance({\n checkoutId,\n runtimeId: hello.runtimeId,\n hostOrigin,\n transport,\n capabilities: initResp.capabilities,\n session: initResp.session,\n initialWarnings: initResp.warnings,\n appearance: opts.appearance,\n locale: opts.locale,\n });\n}\n\n/** Wait for RuntimeHello; reject RUNTIME_LOAD_FAILED on timeout. */\nfunction waitForHello(transport: InstanceTransport): Promise<RuntimeHello> {\n return new Promise<RuntimeHello>((resolve, reject) => {\n let settled = false;\n const timer = setTimeout(() => {\n if (settled) {\n return;\n }\n settled = true;\n reject(makeError(ErrorCode.RUNTIME_LOAD_FAILED, 'Timed out waiting for hosted runtime handshake'));\n }, HANDSHAKE_TIMEOUT_MS);\n\n transport.onHello((raw: unknown) => {\n if (settled || !isValidRuntimeHello(raw)) {\n // Malformed hello: ignore and keep waiting (the handshake timeout still applies).\n return;\n }\n settled = true;\n clearTimeout(timer);\n resolve(raw);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,MAAM,gBAAgB;AAEtB,MAAM,iBAAiB;AAgC9B,MAAM,iBAAiB,CAAC,WAAW,YAAY,OAAO;AAG/C,MAAM,sBAAN,cAAkC,MAAM;IAC3C,YAAY,SAAiB;AACzB,YAAM,OAAO;AACb,WAAK,OAAO;IAChB;EACJ;AAEA,WAAS,SAAS,OAAkD;AAChE,WAAO,OAAO,UAAU,YAAY,UAAU;EAClD;AAEA,WAAS,aAAa,KAA8B,KAAmB;AACnE,QAAI,OAAO,IAAI,GAAG,MAAM,UAAU;AAC9B,YAAM,IAAI,oBAAoB,mBAAmB,GAAG,8BAA8B;IACtF;EACJ;AAUO,WAAS,eAAe,UAA4B;AACvD,WAAO,KAAK,UAAU,QAAQ;EAClC;AAeO,WAAS,eAAe,MAAwB;AACnD,QAAI;AACJ,QAAI;AACA,eAAS,KAAK,MAAM,IAAI;IAC5B,QAAQ;AACJ,YAAM,IAAI,oBAAoB,4BAA4B;IAC9D;AAEA,QAAI,CAAC,SAAS,MAAM,GAAG;AACnB,YAAM,IAAI,oBAAoB,4BAA4B;IAC9D;AAEA,QAAI,OAAO,aAAa,eAAe;AACnC,YAAM,IAAI;QACN,qBAAqB,aAAa,eAAe,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