@vio-live/web-sdk 0.9.1 → 0.11.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/configuration.ts","../src/core/api/vio.ts","../src/core/types.ts","../src/core/api/commerce.ts","../src/core/api/cart-queries.ts","../src/core/checkout/payments/vipps.ts","../src/core/cart/cart-manager.ts","../src/core/checkout/payments/apple-pay.ts","../src/core/checkout/payments/klarna.ts","../src/core/checkout/payments/klarna-payments.ts","../src/core/checkout/payments/kustom.ts","../src/core/checkout/payments/qliro.ts","../src/core/checkout/payments/qliro-sync.ts","../src/core/checkout/payments/walley.ts","../src/core/checkout/checkout-manager.ts","../src/core/version.ts","../src/core/analytics/analytics-manager.ts","../src/core/client.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AA2DA,IAAM,YAAA,GAGF;AAAA,EACF,WAAA,EAAa;AAAA,IACX,OAAA,EAAS,0BAAA;AAAA,IACT,WAAA,EAAa,+BAAA;AAAA,IACb,UAAA,EAAY;AAAA,GACd;AAAA;AAAA,EAEA,OAAA,EAAS;AAAA,IACP,OAAA,EAAS,8BAAA;AAAA,IACT,WAAA,EAAa,+BAAA;AAAA,IACb,UAAA,EAAY;AAAA,GACd;AAAA,EACA,UAAA,EAAY;AAAA,IACV,OAAA,EAAS,sBAAA;AAAA,IACT,WAAA,EAAa,2BAAA;AAAA,IACb,UAAA,EAAY;AAAA;AAEhB,CAAA;AAEA,IAAM,yBAAN,MAA6B;AAAA,EAA7B,WAAA,GAAA;AACE,IAAA,IAAA,CAAQ,QAAA,GAAkC,IAAA;AAC1C,IAAA,IAAA,CAAQ,eAAkC,EAAC;AAAA,EAAA;AAAA,EAE3C,KAAK,KAAA,EAAwB;AAC3B,IAAA,IAAI,CAAC,KAAA,CAAM,MAAA,IAAU,OAAO,KAAA,CAAM,WAAW,QAAA,EAAU;AACrD,MAAA,MAAM,IAAI,MAAM,kDAAkD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Q,QAAA,CAAS,MAAA,EAAQ,CAAA;AAClG,IAAA,IAAA,CAAK,eAAA,CAAgB,GAAA,CAAI,SAAA,EAAW,MAAM,CAAA;AAC1C,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA,EAGA,gBAAgB,cAAA,EAAwC;AACtD,IAAA,MAAM,GAAA,GAAM,cAAc,GAAA,EAAI;AAC9B,IAAA,OAAO,qBAAqB,EAAE,QAAA,EAAU,IAAI,WAAA,EAAa,MAAA,EAAQ,gBAAgB,CAAA;AAAA,EACnF;AAAA,EAEQ,YAAY,SAAA,EAAwC;AAC1D,IAAA,MAAM,OAAO,IAAA,CAAK,eAAA;AAClB,IAAA,IAAI,CAAC,MAAM,OAAO,MAAA;AAClB,IAAA,MAAM,EAAA,GAAK,OAAO,SAAS,CAAA;AAC3B,IAAA,IAAI,OAAO,IAAA,CAAK,cAAA,EAAgB,EAAE,CAAA,KAAM,EAAA,SAAW,IAAA,CAAK,cAAA;AACxD,IAAA,OAAO,IAAA,CAAK,mBAAmB,IAAA,CAAK,CAAC,MAAM,MAAA,CAAO,CAAA,CAAE,EAAE,CAAA,KAAM,EAAE,CAAA;AAAA,EAChE;AACF,CAAA;AAQA,IAAM,UAAA,GAAa,UAAA;AACZ,IAAM,MACX,UAAA,CAAW,cAAA,KAAmB,UAAA,CAAW,cAAA,GAAiB,IAAI,SAAA,EAAU","file":"chunk-U2QG4IVJ.js","sourcesContent":["/**\n * Vio Configuration — singleton holding apiKey, environment, base URLs,\n * and optional payment-vendor publishable keys.\n *\n * Mirrors `VioConfiguration.shared` in the iOS SDK. Initialised once via\n * `Vio.init({ apiKey, ... })`; consumed via `Configuration.get()`.\n *\n * Secrets (apiKey) never come from inside the SDK — the consumer reads\n * them from env vars / their config and passes them to `Vio.init`.\n */\n\nexport type Environment = 'development' | 'testing' | 'production'\n\nexport interface VioConfig {\n /** Vio API key for this client app (from the Vio dashboard). */\n apiKey: string\n /** Target environment. Defaults to 'development'. */\n environment?: Environment\n /** Override REST API base. Defaults are env-aware. */\n apiBase?: string\n /** Override GraphQL base. Defaults are env-aware. */\n graphQLBase?: string\n /**\n * Override the analytics collector base (vio-analytics service).\n * Defaults are env-aware (`events-dev`/`events-staging`/`events.vio.live`).\n */\n eventsBase?: string\n /**\n * Stripe **publishable** key (`pk_test_xxx` or `pk_live_xxx`). Used for\n * Apple Pay (via Payment Request) and Card flows. Public-safe — fine\n * to expose in client bundles.\n */\n stripePublishableKey?: string\n /**\n * Klarna **Client Identifier** for Express Checkout (KEC). Public-safe.\n * From Merchant Portal → Payment settings → Client Identifiers. When set,\n * the checkout shows the Klarna Express button; when absent it degrades\n * to the plain method selector. Must match `klarnaEnvironment`.\n */\n klarnaClientId?: string\n /**\n * Klarna environment for the Express button. `playground` = sandbox\n * (test orders, no real money), `production` = live. Defaults to\n * `playground` so dev/test never hits live Klarna by accident.\n */\n klarnaEnvironment?: 'playground' | 'production'\n}\n\nexport interface ResolvedConfig {\n apiKey: string\n environment: Environment\n apiBase: string\n graphQLBase: string\n eventsBase: string\n stripePublishableKey?: string\n klarnaClientId?: string\n klarnaEnvironment: 'playground' | 'production'\n}\n\nconst DEFAULT_URLS: Record<\n Environment,\n { apiBase: string; graphQLBase: string; eventsBase: string }\n> = {\n development: {\n apiBase: 'https://api-dev.vio.live',\n graphQLBase: 'https://graph-ql-dev.vio.live',\n eventsBase: 'https://events-dev.vio.live',\n },\n // No separate staging GraphQL deployment yet — shares dev's.\n testing: {\n apiBase: 'https://api-staging.vio.live',\n graphQLBase: 'https://graph-ql-dev.vio.live',\n eventsBase: 'https://events-staging.vio.live',\n },\n production: {\n apiBase: 'https://api.vio.live',\n graphQLBase: 'https://graph-ql.vio.live',\n eventsBase: 'https://events.vio.live',\n },\n}\n\nclass ConfigurationSingleton {\n private resolved: ResolvedConfig | null = null\n private readyWaiters: Array<() => void> = []\n\n init(input: VioConfig): void {\n if (!input.apiKey || typeof input.apiKey !== 'string') {\n throw new Error('[Vio] apiKey is required in Vio.init({ apiKey })')\n }\n const env: Environment = input.environment ?? 'development'\n const defaults = DEFAULT_URLS[env]\n this.resolved = {\n apiKey: input.apiKey,\n environment: env,\n apiBase: input.apiBase ?? defaults.apiBase,\n graphQLBase: input.graphQLBase ?? defaults.graphQLBase,\n eventsBase: input.eventsBase ?? defaults.eventsBase,\n stripePublishableKey: input.stripePublishableKey,\n klarnaClientId: input.klarnaClientId,\n // Sandbox by default — live Klarna must be opted into explicitly.\n klarnaEnvironment: input.klarnaEnvironment ?? 'playground',\n }\n if (typeof console !== 'undefined') {\n const masked =\n input.apiKey.length > 4\n ? '*'.repeat(Math.max(0, input.apiKey.length - 4)) + input.apiKey.slice(-4)\n : '****'\n console.info('[Vio] Initialized', {\n environment: env,\n apiBase: this.resolved.apiBase,\n apiKey: masked,\n stripeConfigured: !!input.stripePublishableKey,\n klarnaConfigured: !!input.klarnaClientId,\n klarnaEnvironment: this.resolved.klarnaEnvironment,\n })\n }\n const waiters = this.readyWaiters\n this.readyWaiters = []\n for (const waiter of waiters) waiter()\n }\n\n get(): ResolvedConfig {\n if (!this.resolved) {\n throw new Error(\n '[Vio] Not initialized. Call Vio.init({ apiKey }) before using the SDK.',\n )\n }\n return this.resolved\n }\n\n get isInitialized(): boolean {\n return this.resolved !== null\n }\n\n /**\n * Resolves once `Vio.init()` has run, or after `timeoutMs` — whichever\n * comes first. Hosts that mount several independent components (e.g. Vev\n * blocks, which mount in no guaranteed order) may have one fire a GraphQL\n * call before another has called `Vio.init()`. Awaiting this briefly lets\n * that race resolve instead of silently sending an unauthenticated\n * request. Resolves `true` if init happened in time, `false` on timeout —\n * callers should still degrade gracefully either way.\n */\n whenReady(timeoutMs = 2000): Promise<boolean> {\n if (this.resolved) return Promise.resolve(true)\n return new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), timeoutMs)\n this.readyWaiters.push(() => {\n clearTimeout(timer)\n resolve(true)\n })\n })\n }\n\n /** For tests only. */\n reset(): void {\n this.resolved = null\n this.readyWaiters = []\n }\n}\n\nexport const Configuration = /* @__PURE__ */ new ConfigurationSingleton()\n","/**\n * Vio REST API client — talks to `api-dev.vio.live` (or override).\n *\n * Endpoints (mirrors the iOS SDK's surface):\n * GET /v2/mobile/config bootstrap (sponsors + market)\n * GET /v2/mobile/campaigns/:id/components placement components (TBD)\n * POST /v2/mobile/campaigns/:id/cart-intent cross-device cart-intent (TBD)\n *\n * Auth: `X-API-Key: <apiKey>` header (the top-level Vio apiKey).\n *\n * Note: until the backend exposes a dedicated `/v2/web/*` surface we\n * reuse the `/v2/mobile/*` paths — the apiKey identifies the client_app\n * and the response shape is platform-agnostic enough.\n */\n\nimport type { BootstrapResponse, PlacementComponent } from '../types.js'\n\nexport interface VioApiOptions {\n /** REST API base URL, e.g. `https://api-dev.vio.live`. */\n apiBase: string\n /** Top-level Vio apiKey for this client app. */\n apiKey: string\n}\n\nexport class VioApi {\n private readonly apiBase: string\n private readonly apiKey: string\n\n constructor(options: VioApiOptions) {\n if (!options.apiBase) throw new Error('[VioApi] apiBase is required')\n if (!options.apiKey) throw new Error('[VioApi] apiKey is required')\n this.apiBase = options.apiBase.replace(/\\/+$/, '')\n this.apiKey = options.apiKey\n }\n\n /**\n * Bootstrap — fetches client app config (sponsors with commerce keys,\n * default market, campaign id). Called once at SDK init.\n */\n async bootstrap(): Promise<BootstrapResponse> {\n return this.get<BootstrapResponse>('/v2/mobile/config')\n }\n\n /**\n * Get placement components for a campaign. Used by the carousel auto-fetch\n * mode (`<vio-product-carousel campaign-id=\"36\" location=\"news-favorites\">`).\n */\n async getComponents(campaignId: number | string): Promise<PlacementComponent[]> {\n const path = `/v2/mobile/campaigns/${encodeURIComponent(String(campaignId))}/components`\n const res = await this.get<{ components: PlacementComponent[] } | PlacementComponent[]>(path)\n return Array.isArray(res) ? res : (res?.components ?? [])\n }\n\n // MARK: - HTTP plumbing\n\n private async get<T>(path: string): Promise<T> {\n const url = `${this.apiBase}${path}`\n const res = await fetch(url, {\n method: 'GET',\n headers: {\n 'X-API-Key': this.apiKey,\n Accept: 'application/json',\n },\n })\n if (!res.ok) {\n throw new VioApiError(res.status, await safeText(res), `GET ${path}`)\n }\n return (await res.json()) as T\n }\n}\n\nexport class VioApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly body: string,\n public readonly endpoint: string,\n ) {\n super(`[VioApi] ${endpoint} → HTTP ${status}: ${body.slice(0, 200)}`)\n this.name = 'VioApiError'\n }\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return await res.text()\n } catch {\n return ''\n }\n}\n\nexport function createVioApi(options: VioApiOptions): VioApi {\n return new VioApi(options)\n}\n","/**\n * Vio types — Product / Sponsor / Bootstrap shapes.\n *\n * Product types mirror the Vio Commerce GraphQL schema.\n * Sponsor / Bootstrap shapes mirror the iOS SDK's bootstrap response so\n * we stay aligned cross-platform.\n */\n\nexport type ImageSize = 'thumbnail' | 'small' | 'medium' | 'large' | 'full'\n\nexport interface ProductPrice {\n amount: number\n currency_code: string\n compare_at?: number | null\n amount_incl_taxes?: number | null\n compare_at_incl_taxes?: number | null\n tax_amount?: number | null\n tax_rate?: number | null\n}\n\nexport interface ProductImage {\n id: string\n url: string\n width?: number | null\n height?: number | null\n order?: number | null\n}\n\nexport interface ProductOption {\n id: number\n name: string\n order: number\n values: string[]\n}\n\nexport interface ProductCategory {\n id: number\n name: string\n}\n\nexport interface ProductVariant {\n id: number\n barcode?: string | null\n quantity?: number | null\n sku?: string | null\n title?: string | null\n price: ProductPrice\n images: ProductImage[]\n}\n\nexport interface Product {\n id: number\n brand?: string | null\n title: string\n description?: string | null\n tags?: string | null\n sku: string\n quantity?: number | null\n price: ProductPrice\n variants: ProductVariant[]\n barcode?: string | null\n options: ProductOption[]\n categories?: ProductCategory[] | null\n images: ProductImage[]\n}\n\n/** Per-sponsor commerce config sourced from Vio bootstrap. */\nexport interface SponsorCommerceBlock {\n apiKey: string\n channelId?: string | null\n paymentMethods?: string[]\n}\n\nexport interface Sponsor {\n id: number\n name: string\n description?: string | null\n avatarUrl?: string | null\n logoUrl?: string | null\n primaryColor?: string | null\n secondaryColor?: string | null\n commerce: SponsorCommerceBlock\n}\n\n/**\n * Response shape of `GET /v2/mobile/config` (and likely future `/v2/web/config`).\n * Matches the iOS SDK's `SdkBootstrapResponse` model.\n */\nexport interface BootstrapResponse {\n campaignId?: number\n primarySponsor?: Sponsor\n secondarySponsors?: Sponsor[]\n market?: {\n countryCode: string\n currencyCode: string\n }\n}\n\n/**\n * A placement component returned by `/v2/mobile/campaigns/:id/components`.\n * Used by `<vio-product-carousel campaign-id=\"...\">` to know which products\n * to render at a given slot.\n */\nexport interface PlacementComponent {\n id: number\n componentType: string\n locationId: string\n sponsorId?: number\n config: {\n productIds?: number[]\n [key: string]: unknown\n }\n}\n\n/** Helper: extract a useful display price from a Product. */\nexport function displayPrice(product: Product): string {\n const p = product.price\n const amount = p.amount_incl_taxes ?? p.amount\n return formatPrice(amount, p.currency_code)\n}\n\n/**\n * Active shipping/market country for the page. The host (e.g. the Vev Config\n * block) sets `globalThis.__VIO_COUNTRY__` / localStorage `vio.country`; falls\n * back to NO.\n */\nexport function getGlobalCountryCode(): string {\n const g = globalThis as { __VIO_COUNTRY__?: string }\n if (g.__VIO_COUNTRY__) return g.__VIO_COUNTRY__\n if (typeof localStorage !== 'undefined') {\n try {\n const v = localStorage.getItem('vio.country')\n if (v) return v\n } catch {\n /* privacy mode */\n }\n }\n return 'NO'\n}\n\n/**\n * Active display locale for the page (number formatting + payment sheets).\n * Host sets `globalThis.__VIO_LOCALE__` / localStorage `vio.locale`; falls\n * back to nb-NO.\n */\nexport function getGlobalLocale(): string {\n const g = globalThis as { __VIO_LOCALE__?: string }\n if (g.__VIO_LOCALE__) return g.__VIO_LOCALE__\n if (typeof localStorage !== 'undefined') {\n try {\n const v = localStorage.getItem('vio.locale')\n if (v) return v\n } catch {\n /* privacy mode */\n }\n }\n return 'nb-NO'\n}\n\n/**\n * Currency symbol for display. With no explicit currency, a host-set override\n * (`__VIO_SYMBOL__` / vio.symbol) wins; otherwise a small per-currency map.\n */\nexport function getGlobalSymbol(currency?: string): string {\n const activeCurrency = currency || getGlobalCurrency()\n const g = globalThis as { __VIO_SYMBOL__?: string }\n if (!currency && g.__VIO_SYMBOL__) return g.__VIO_SYMBOL__\n if (!currency && typeof localStorage !== 'undefined') {\n try {\n const v = localStorage.getItem('vio.symbol')\n if (v) return v\n } catch {\n /* privacy mode */\n }\n }\n const curr = String(activeCurrency).toUpperCase()\n if (curr === 'NOK' || curr === 'DKK') return 'Kr'\n if (curr === 'SEK') return 'SEK'\n if (curr === 'EUR') return '€'\n if (curr === 'USD' || curr === 'CAD') return '$'\n if (curr === 'GBP') return '£'\n if (curr === 'CHF') return 'CHF'\n return activeCurrency\n}\n\n/**\n * Active display currency for the page. The host (e.g. the Vev Config block)\n * sets `globalThis.__VIO_CURRENCY__` / localStorage `vio.currency`; falls back\n * to NOK.\n */\nexport function getGlobalCurrency(): string {\n const g = globalThis as { __VIO_CURRENCY__?: string }\n if (g.__VIO_CURRENCY__) return g.__VIO_CURRENCY__\n if (typeof localStorage !== 'undefined') {\n try {\n const v = localStorage.getItem('vio.currency')\n if (v) return v\n } catch {\n /* privacy mode */\n }\n }\n return 'NOK'\n}\n\n/** Cache of validated locales — hosts can feed anything into vio.locale. */\nconst validatedLocales = new Map<string, string>()\n\n/** Return the locale if Intl accepts it, else nb-NO (a host-set `nb_NO` with\n * an underscore makes toLocaleString throw and blanks the whole render). */\nfunction safeLocale(locale: string): string {\n const cached = validatedLocales.get(locale)\n if (cached) return cached\n let resolved = 'nb-NO'\n try {\n if (Intl.NumberFormat.supportedLocalesOf([locale]).length > 0) resolved = locale\n } catch {\n /* structurally invalid tag — keep the fallback */\n }\n validatedLocales.set(locale, resolved)\n return resolved\n}\n\n/** Format a numeric amount + currency using the page locale and symbol map. */\nexport function formatPrice(amount: number, currency?: string): string {\n const activeCurrency = currency || getGlobalCurrency()\n const activeLocale = safeLocale(getGlobalLocale())\n const activeSymbol = getGlobalSymbol(activeCurrency)\n const formatted = amount\n .toLocaleString(activeLocale, { minimumFractionDigits: 0, maximumFractionDigits: 2 })\n // Normalize non-breaking space to regular space for predictable rendering.\n .replace(/ /g, ' ')\n return `${formatted} ${activeSymbol}`\n}\n\n/**\n * Helper: pick the first image URL (variant first, then product). Defensive:\n * accepts loose shapes (backend cart rows, catalog rows) where images may be\n * plain strings or live under image / imageUrl / image_url / primaryImage.\n */\nexport function primaryImageUrl(product: Product): string | undefined {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n const p = product as any\n if (!p || typeof p !== 'object') return undefined\n if (Array.isArray(p.variants) && p.variants.length > 0) {\n const vImages = p.variants[0]?.images\n if (Array.isArray(vImages) && vImages.length > 0) {\n const vUrl = typeof vImages[0] === 'string' ? vImages[0] : vImages[0]?.url\n if (vUrl) return vUrl\n }\n }\n if (Array.isArray(p.images) && p.images.length > 0) {\n const img0 = p.images[0]\n const url = typeof img0 === 'string' ? img0 : img0?.url\n if (url) return url\n }\n if (typeof p.image === 'string' && p.image) return p.image\n if (p.image && typeof p.image === 'object' && p.image.url) return p.image.url\n if (typeof p.imageUrl === 'string' && p.imageUrl) return p.imageUrl\n if (typeof p.image_url === 'string' && p.image_url) return p.image_url\n if (typeof p.primaryImage === 'string' && p.primaryImage) return p.primaryImage\n if (p.primaryImage && typeof p.primaryImage === 'object' && p.primaryImage.url) {\n return p.primaryImage.url\n }\n return undefined\n /* eslint-enable @typescript-eslint/no-explicit-any */\n}\n","/**\n * Commerce GraphQL client — talks to Vio Commerce.\n *\n * Mirrors the iOS SDK's `SdkClient.channel.product` surface, but uses\n * `graphql-request` (lightweight) instead of Apollo. Auth header: `Authorization: <apiKey>`\n * (per-sponsor commerce apiKey, NOT the top-level Vio apiKey).\n *\n * Usage:\n * const commerce = createCommerceClient({\n * endpoint: 'https://graph-ql-dev.vio.live',\n * apiKey: '<sponsor-commerce-apiKey>', // sponsor's commerce apiKey\n * })\n * const products = await commerce.channel.product.getByIds({\n * product_ids: [408895, 408896],\n * currency: 'NOK',\n * image_size: 'large',\n * })\n */\n\nimport { GraphQLClient } from 'graphql-request'\nimport { getGlobalCountryCode, getGlobalCurrency, type ImageSize, type Product } from '../types.js'\n\nexport interface CommerceClientOptions {\n /** Vio Commerce GraphQL endpoint, e.g. `https://graph-ql-dev.vio.live`. */\n endpoint: string\n /** Per-sponsor commerce apiKey (from bootstrap.primarySponsor.commerce.apiKey). */\n apiKey: string\n}\n\nconst GET_PRODUCTS_BY_IDS = /* GraphQL */ `\n query GetProductsByIds(\n $currency: String\n $imageSize: ImageSize\n $productIds: [Int!]\n $useCache: Boolean!\n $shippingCountryCode: String\n ) {\n Channel {\n GetProductsByIds(\n currency: $currency\n image_size: $imageSize\n product_ids: $productIds\n useCache: $useCache\n shipping_country_code: $shippingCountryCode\n ) {\n id\n brand\n title\n description\n tags\n sku\n quantity\n price {\n amount\n currency_code\n compare_at\n amount_incl_taxes\n compare_at_incl_taxes\n tax_amount\n tax_rate\n }\n variants {\n id\n barcode\n quantity\n sku\n title\n price {\n amount\n currency_code\n compare_at\n amount_incl_taxes\n compare_at_incl_taxes\n tax_amount\n tax_rate\n }\n images {\n id\n url\n width\n height\n order\n }\n }\n barcode\n options {\n id\n name\n order\n values\n }\n categories {\n id\n name\n }\n images {\n id\n url\n width\n height\n order\n }\n }\n }\n }\n`\n\nexport interface GetProductsByIdsOptions {\n product_ids: number[]\n currency?: string | null\n image_size?: ImageSize | null\n useCache?: boolean\n shipping_country_code?: string | null\n}\n\nclass ChannelProduct {\n constructor(private readonly client: GraphQLClient) {}\n\n /**\n * Fetch a batch of products by their numeric ids.\n * Returns an empty array if no ids are provided.\n */\n async getByIds(options: GetProductsByIdsOptions): Promise<Product[]> {\n if (!options.product_ids || options.product_ids.length === 0) return []\n\n const variables = {\n productIds: options.product_ids,\n // Page-level currency/country defaults (multi-market support).\n currency: options.currency ?? getGlobalCurrency(),\n imageSize: options.image_size ?? 'large',\n useCache: options.useCache ?? true,\n shippingCountryCode: options.shipping_country_code ?? getGlobalCountryCode(),\n }\n\n const data = await this.client.request<{\n Channel: { GetProductsByIds: Product[] }\n }>(GET_PRODUCTS_BY_IDS, variables)\n\n return data.Channel?.GetProductsByIds ?? []\n }\n}\n\nclass Channel {\n readonly product: ChannelProduct\n\n constructor(client: GraphQLClient) {\n this.product = new ChannelProduct(client)\n }\n}\n\n/** CommerceClient — namespaced facade, mirrors the iOS SdkClient. */\nexport class CommerceClient {\n readonly channel: Channel\n /** Underlying graphql-request client (escape hatch for custom queries). */\n readonly raw: GraphQLClient\n\n constructor(options: CommerceClientOptions) {\n if (!options.endpoint) throw new Error('[VioCommerce] endpoint is required')\n if (!options.apiKey) throw new Error('[VioCommerce] apiKey is required')\n\n this.raw = new GraphQLClient(options.endpoint, {\n headers: { Authorization: options.apiKey },\n })\n this.channel = new Channel(this.raw)\n }\n}\n\nexport function createCommerceClient(options: CommerceClientOptions): CommerceClient {\n return new CommerceClient(options)\n}\n","// GraphQL Queries and Mutations for VIO Cart & Checkout Services\n\nexport const CREATE_CART_MUTATION = `\nmutation CreateCart($customerSessionId: String!, $currency: String!, $shippingCountry: String) {\n Cart {\n CreateCart(customer_session_id: $customerSessionId, currency: $currency, shipping_country: $shippingCountry) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const ADD_ITEM_MUTATION = `\nmutation AddItem($cartId: String!, $lineItems: [LineItemInput!]!) {\n Cart {\n AddItem(cart_id: $cartId, line_items: $lineItems) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const DELETE_ITEM_MUTATION = `\nmutation DeleteItem($cartId: String!, $cartItemId: String!) {\n Cart {\n DeleteItem(cart_id: $cartId, cart_item_id: $cartItemId) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const UPDATE_ITEM_MUTATION = `\nmutation UpdateItem($cartId: String!, $cartItemId: String!, $shippingId: String, $qty: Int) {\n Cart {\n UpdateItem(cart_id: $cartId, cart_item_id: $cartItemId, shipping_id: $shippingId, qty: $qty) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const GET_CART_QUERY = `\nquery GetCart($cartId: String!) {\n Cart {\n GetCart(cart_id: $cartId) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const GET_LINE_ITEMS_BY_SUPPLIER_QUERY = `\nquery GetLineItemsBySupplier($cartId: String!) {\n Cart {\n GetLineItemsBySupplier(cart_id: $cartId) {\n supplier {\n id\n name\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n }\n }\n}\n`;\n\nexport const UPDATE_SHIPPINGS_BY_SUPPLIER_MUTATION = `\nmutation UpdateShippingsBySupplier($cartId: String!, $data: [DataUpdateShippingsBySupplier!]!) {\n Cart {\n UpdateShippingsBySupplier(cart_id: $cartId, data: $data) {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n }\n}\n`;\n\nexport const CREATE_CHECKOUT_MUTATION = `\nmutation CreateCheckout($cartId: String!) {\n Checkout {\n CreateCheckout(cart_id: $cartId) {\n buyer_accepts_purchase_conditions\n buyer_accepts_terms_conditions\n created_at\n updated_at\n id\n deleted_at\n success_url\n cancel_url\n payment_method\n email\n status\n checkout_url\n origin_payment_id\n billing_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n shipping_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n available_payment_methods {\n name\n }\n discount_code\n cart {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n totals {\n currency_code\n subtotal\n shipping\n total\n taxes\n tax_rate\n discounts\n }\n }\n }\n}\n`;\n\nexport const UPDATE_CHECKOUT_MUTATION = `\nmutation UpdateCheckout($checkoutId: String!, $status: String, $successUrl: String, $email: String, $cancelUrl: String, $paymentMethod: String, $shippingAddress: AddressArgs, $billingAddress: AddressArgs, $buyerAcceptsPurchaseConditions: Boolean, $buyerAcceptsTermsConditions: Boolean) {\n Checkout {\n UpdateCheckout(checkout_id: $checkoutId, status: $status, success_url: $successUrl, email: $email, cancel_url: $cancelUrl, payment_method: $paymentMethod, shipping_address: $shippingAddress, billing_address: $billingAddress, buyer_accepts_purchase_conditions: $buyerAcceptsPurchaseConditions, buyer_accepts_terms_conditions: $buyerAcceptsTermsConditions) {\n buyer_accepts_purchase_conditions\n buyer_accepts_terms_conditions\n created_at\n updated_at\n id\n deleted_at\n success_url\n cancel_url\n payment_method\n email\n status\n checkout_url\n origin_payment_id\n billing_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n shipping_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n available_payment_methods {\n name\n }\n discount_code\n cart {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n totals {\n currency_code\n subtotal\n shipping\n total\n taxes\n tax_rate\n discounts\n }\n }\n }\n}\n`;\n\nexport const GET_CHECKOUT_QUERY = `\nquery GetCheckout($checkoutId: String!) {\n Checkout {\n GetCheckout(checkout_id: $checkoutId) {\n buyer_accepts_purchase_conditions\n buyer_accepts_terms_conditions\n created_at\n updated_at\n id\n deleted_at\n success_url\n cancel_url\n payment_method\n email\n status\n checkout_url\n origin_payment_id\n billing_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n shipping_address {\n id\n first_name\n last_name\n phone_code\n phone\n company\n address1\n address2\n city\n province\n province_code\n country\n country_code\n zip\n }\n available_payment_methods {\n name\n }\n discount_code\n cart {\n cart_id\n customer_session_id\n shipping_country\n line_items {\n id\n supplier\n image {\n id\n url\n width\n height\n }\n sku\n barcode\n brand\n product_id\n title\n variant_id\n variant_title\n variant {\n option\n value\n }\n quantity\n price {\n amount\n currency_code\n discount\n compare_at\n compare_at_incl_taxes\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n shipping {\n id\n name\n description\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n available_shippings {\n id\n name\n description\n country_code\n price {\n amount\n currency_code\n amount_incl_taxes\n tax_amount\n tax_rate\n }\n }\n }\n subtotal\n shipping\n currency\n available_shipping_countries\n }\n totals {\n currency_code\n subtotal\n shipping\n total\n taxes\n tax_rate\n discounts\n }\n }\n }\n}\n`;\n\nexport const GET_AVAILABLE_PAYMENT_METHODS_QUERY = `\nquery Config {\n Payment {\n GetAvailablePaymentMethods {\n config {\n name\n type\n value\n }\n name\n }\n }\n}\n`;\n\n\n/**\n * Server-side cart / checkout GraphQL client (Vio Commerce).\n *\n * Ported from the hand-edited Vev bundle (Alan, 2026-07-28/29) into the SDK\n * source so the vendored bundle stays a pure esbuild artifact.\n */\n\nimport { Configuration } from '../configuration.js'\nimport { getGlobalCountryCode, getGlobalCurrency } from '../types.js'\n\n/** Transport options for a cart/checkout GraphQL call. */\nexport interface CartQueryOptions {\n endpoint?: string\n apiKey?: string\n /** Sponsor commerce key — goes in the Authorization header. */\n commerceKey?: string\n /** True when the commerce key came from a resolved sponsor (bootstrap).\n * False = we fell back to the host apiKey — writes like CreateCart should\n * NOT proceed with the wrong key (the cart would be orphaned). */\n sponsorResolved?: boolean\n}\n\n/**\n * Resolve endpoint + keys for cart GraphQL calls. Awaits Vio.bootstrap() once\n * if it hasn't run yet (the sponsor commerce keys come from bootstrap), then\n * uses the sponsor's commerce apiKey (via the Vio facade on globalThis,\n * avoiding an import cycle); falls back to the host apiKey.\n */\nexport async function getCartGraphQLOptions(sponsorId?: number): Promise<CartQueryOptions> {\n const facade = (\n globalThis as {\n __VIO_FACADE__?: {\n findSponsor?: (id: number) => unknown\n bootstrap?: () => Promise<unknown>\n bootstrapCache?: unknown\n }\n }\n ).__VIO_FACADE__\n if (facade && typeof facade.bootstrap === 'function' && !facade.bootstrapCache) {\n try {\n await facade.bootstrap()\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[Vio] getCartGraphQLOptions bootstrap await failed:', err)\n }\n }\n }\n\n // Hosts that mount several independent components (Vev blocks mount in no\n // guaranteed order) may have one query the commerce API before another has\n // called Vio.init(). Give that race a brief window to resolve rather than\n // silently sending an unauthenticated request.\n if (!Configuration.isInitialized) {\n await Configuration.whenReady()\n }\n\n const cfg = Configuration.isInitialized\n ? Configuration.get()\n : { apiKey: undefined, graphQLBase: 'https://graph-ql-dev.vio.live' }\n const anyCfg = cfg as { apiKey?: string; graphQLBase?: string }\n let commerceKey = anyCfg.apiKey\n let sponsorResolved = false\n if (sponsorId && typeof facade?.findSponsor === 'function') {\n const sponsor = facade.findSponsor(sponsorId) as\n | { commerce?: { apiKey?: string } }\n | undefined\n if (sponsor?.commerce?.apiKey) {\n commerceKey = sponsor.commerce.apiKey\n sponsorResolved = true\n }\n }\n return {\n endpoint: anyCfg.graphQLBase || 'https://graph-ql-dev.vio.live',\n apiKey: anyCfg.apiKey,\n commerceKey,\n sponsorResolved,\n }\n}\n\nconst CUSTOMER_SESSION_KEY = 'vio.customer_session_id.v1'\n\n/** Stable per-browser customer session id (backend CreateCart requires one). */\nexport function getCustomerSessionId(): string {\n if (typeof localStorage === 'undefined') return 'cs_session_default'\n let id = localStorage.getItem(CUSTOMER_SESSION_KEY)\n if (!id) {\n id = 'cs_' + Math.random().toString(36).slice(2, 11) + Date.now().toString(36)\n localStorage.setItem(CUSTOMER_SESSION_KEY, id)\n }\n return id\n}\n\ninterface GraphQLEnvelope {\n data?: Record<string, Record<string, unknown>>\n errors?: Array<{ message?: string }>\n}\n\n/** Execute a GraphQL query/mutation against the configured commerce endpoint.\n * Callers that skip `getCartGraphQLOptions()` (or pass a bare sponsorId) get\n * it resolved here instead of silently sending an unauthenticated request. */\nexport async function executeCartGraphQL(\n query: string,\n variables: Record<string, unknown>,\n options: CartQueryOptions | number | undefined = {},\n): Promise<GraphQLEnvelope> {\n const resolvedOptions: CartQueryOptions =\n typeof options === 'number'\n ? await getCartGraphQLOptions(options)\n : !options.apiKey && !options.commerceKey\n ? { ...(await getCartGraphQLOptions()), ...options }\n : options\n const { endpoint = 'https://graph-ql-dev.vio.live', apiKey, commerceKey } = resolvedOptions\n\n const headers: Record<string, string> = { 'Content-Type': 'application/json' }\n if (apiKey) headers['X-API-Key'] = apiKey\n if (commerceKey || apiKey) headers['Authorization'] = (commerceKey || apiKey) as string\n\n const res = await fetch(endpoint, {\n method: 'POST',\n headers,\n body: JSON.stringify({ query, variables }),\n })\n\n const json = (await res.json().catch(() => ({}))) as GraphQLEnvelope\n if (!res.ok || json.errors) {\n const errMsg = json.errors?.[0]?.message || `GraphQL request failed (HTTP ${res.status})`\n throw new Error(errMsg)\n }\n return json\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport async function createCart(\n customerSessionId: string,\n currency: string,\n shippingCountry?: string | null,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(\n CREATE_CART_MUTATION,\n {\n customerSessionId,\n currency: currency || getGlobalCurrency(),\n shippingCountry: shippingCountry || getGlobalCountryCode(),\n },\n options,\n )\n return json?.data?.Cart?.CreateCart\n}\n\nexport async function addItem(\n cartId: string,\n lineItems: unknown[],\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(ADD_ITEM_MUTATION, { cartId, lineItems }, options)\n return json?.data?.Cart?.AddItem\n}\n\nexport async function deleteItem(\n cartId: string,\n cartItemId: string,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(DELETE_ITEM_MUTATION, { cartId, cartItemId }, options)\n return json?.data?.Cart?.DeleteItem\n}\n\nexport async function updateItem(\n cartId: string,\n cartItemId: string,\n shippingId?: string | null,\n qty?: number | null,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(\n UPDATE_ITEM_MUTATION,\n { cartId, cartItemId, shippingId: shippingId || null, qty: qty != null ? qty : null },\n options,\n )\n return json?.data?.Cart?.UpdateItem\n}\n\nexport async function getCart(cartId: string, options?: CartQueryOptions): Promise<any> {\n const json = await executeCartGraphQL(GET_CART_QUERY, { cartId }, options)\n return json?.data?.Cart?.GetCart\n}\n\nexport async function getLineItemsBySupplier(\n cartId: string,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(GET_LINE_ITEMS_BY_SUPPLIER_QUERY, { cartId }, options)\n return json?.data?.Cart?.GetLineItemsBySupplier\n}\n\nexport async function updateShippingsBySupplier(\n cartId: string,\n data: unknown[],\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(\n UPDATE_SHIPPINGS_BY_SUPPLIER_MUTATION,\n { cartId, data },\n options,\n )\n return json?.data?.Cart?.UpdateShippingsBySupplier\n}\n\nexport async function createCheckout(cartId: string, options?: CartQueryOptions): Promise<any> {\n const json = await executeCartGraphQL(CREATE_CHECKOUT_MUTATION, { cartId }, options)\n return json?.data?.Checkout?.CreateCheckout\n}\n\nexport async function updateCheckout(\n variables: Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(UPDATE_CHECKOUT_MUTATION, variables, options)\n return json?.data?.Checkout?.UpdateCheckout\n}\n\nexport async function getCheckout(checkoutId: string, options?: CartQueryOptions): Promise<any> {\n const json = await executeCartGraphQL(GET_CHECKOUT_QUERY, { checkoutId }, options)\n return json?.data?.Checkout?.GetCheckout\n}\n\nexport async function getAvailablePaymentMethods(options?: CartQueryOptions): Promise<any> {\n const json = await executeCartGraphQL(GET_AVAILABLE_PAYMENT_METHODS_QUERY, {}, options)\n return json?.data?.Payment?.GetAvailablePaymentMethods\n}\n\nexport const CREATE_PAYMENT_STRIPE_MUTATION = `\nmutation CreatePaymentStripe($checkoutId: String!, $successUrl: String!, $paymentMethod: String!, $email: String!) {\n Payment {\n CreatePaymentStripe(checkout_id: $checkoutId, success_url: $successUrl, payment_method: $paymentMethod, email: $email) {\n order_id\n checkout_url\n }\n }\n}\n`\n\nexport async function createPaymentStripe(\n variables: Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_STRIPE_MUTATION, variables, options)\n return json?.data?.Payment?.CreatePaymentStripe\n}\n\nexport const CREATE_PAYMENT_APPLE_PAY_MUTATION = `\nmutation CreatePaymentApplePay($checkoutId: String!) {\n Payment {\n CreatePaymentApplePay(checkout_id: $checkoutId) {\n gateway\n gateway_merchant_id\n }\n }\n}\n`\n\n/** Register the Apple Pay payment on the backend checkout. Returns the gateway\n * info (gateway + gateway_merchant_id) the sheet/session should use. */\nexport async function createPaymentApplePay(\n variables: Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_APPLE_PAY_MUTATION, variables, options)\n return json?.data?.Payment?.CreatePaymentApplePay\n}\n\nexport const CONFIRM_PAYMENT_APPLE_PAY_MUTATION = `\nmutation ConfirmPaymentApplePay($checkoutId: String!, $applePayToken: String!, $email: String, $shippingAddress: ApplePayAddressInput) {\n Payment {\n ConfirmPaymentApplePay(checkout_id: $checkoutId, apple_pay_token: $applePayToken, email: $email, shipping_address: $shippingAddress) {\n order_id\n status\n }\n }\n}\n`\n\n/** Confirm (charge) the Apple Pay payment server-side. Called from the sheet's\n * authorize callback BEFORE completing it — the backend does the actual charge. */\nexport async function confirmPaymentApplePay(\n variables: Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<any> {\n const json = await executeCartGraphQL(CONFIRM_PAYMENT_APPLE_PAY_MUTATION, variables, options)\n return json?.data?.Payment?.ConfirmPaymentApplePay\n}\n\nexport {\n CREATE_PAYMENT_VIPPS_MUTATION,\n GET_VIPPS_STATUS_QUERY,\n createPaymentVipps,\n getVippsStatus,\n} from '../checkout/payments/vipps.js'\n\n","/**\n * Vipps MobilePay Payment Adapter — GraphQL Integration & Types.\n *\n * Vipps payment integration uses 2 GraphQL operations:\n *\n * 1. `CreatePaymentVipps` mutation:\n * Initiates a Vipps payment session for a checkout and returns `payment_url`.\n *\n * 2. `GetVippsStatus` query:\n * Queries Vipps payment state directly for a checkout (`state`).\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\n\n/**\n * GraphQL mutation to create a Vipps payment session.\n */\nexport const CREATE_PAYMENT_VIPPS_MUTATION = `\nmutation CreatePaymentVipps($checkoutId: String!, $email: String!, $returnUrl: String!) {\n Payment {\n CreatePaymentVipps(checkout_id: $checkoutId, email: $email, return_url: $returnUrl) {\n payment_url\n }\n }\n}\n`\n\n/**\n * GraphQL query to fetch current Vipps payment status.\n */\nexport const GET_VIPPS_STATUS_QUERY = `\nquery GetVippsStatus($checkoutId: String!) {\n Payment {\n GetVippsStatus(checkout_id: $checkoutId) {\n state\n }\n }\n}\n`\n\nexport interface CreatePaymentVippsVariables extends Record<string, unknown> {\n checkoutId: string\n email: string\n returnUrl: string\n}\n\nexport interface CreatePaymentVippsResponse {\n payment_url: string\n}\n\nexport interface GetVippsStatusVariables extends Record<string, unknown> {\n checkoutId: string\n}\n\nexport interface VippsStatusResult {\n state: string\n}\n\nexport type VippsPaymentState =\n | 'CREATED'\n | 'INITIATED'\n | 'AUTHORIZED'\n | 'TERMINATED'\n | 'EXPIRED'\n | string\n\n/**\n * Executes the `CreatePaymentVipps` GraphQL mutation.\n */\nexport async function createPaymentVipps(\n variables: CreatePaymentVippsVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<CreatePaymentVippsResponse | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_VIPPS_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentVipps as CreatePaymentVippsResponse) ?? null\n}\n\n/**\n * Executes the `GetVippsStatus` GraphQL query.\n */\nexport async function getVippsStatus(\n variables: GetVippsStatusVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<VippsStatusResult | null> {\n const json = await executeCartGraphQL(GET_VIPPS_STATUS_QUERY, variables, options)\n return (json?.data?.Payment?.GetVippsStatus as VippsStatusResult) ?? null\n}\n","/**\n * CartManager — multi-sponsor cart state.\n *\n * Mirrors iOS's `CartManager` + `cartsBySponsor`. Holds local state in\n * memory and persists to localStorage. Reactive: dispatches a `change`\n * CustomEvent that UI components subscribe to (Web Components react via\n * `requestUpdate()`).\n *\n * Server-side cart sync (Vio Commerce GraphQL CreateCart / AddToCart\n * mutations) is deferred to checkout time via the CheckoutManager —\n * this manager is purely client-side state for now.\n */\n\nimport {\n formatPrice,\n getGlobalCountryCode,\n getGlobalCurrency,\n primaryImageUrl,\n type Product,\n} from '../types.js'\nimport type { CartLineItem, SponsorCartState } from './types.js'\nimport {\n addItem as gqlAddItem,\n createCart as gqlCreateCart,\n deleteItem as gqlDeleteItem,\n getCart as gqlGetCart,\n getCartGraphQLOptions,\n getCustomerSessionId,\n getLineItemsBySupplier as gqlGetLineItemsBySupplier,\n updateItem as gqlUpdateItem,\n updateShippingsBySupplier as gqlUpdateShippingsBySupplier,\n} from '../api/cart-queries.js'\n\nconst STORAGE_KEY = 'vio.cart.v1'\n\nexport interface CartChangeDetail {\n cartsBySponsor: Map<number, SponsorCartState>\n itemCount: number\n}\n\nexport interface AddProductOptions {\n product: Product\n sponsorId: number\n sponsorName?: string\n quantity?: number\n variantId?: number\n}\n\n/** Minimal product shape — for callers who only have e.g. mock data, not a full Product. */\nexport interface AddManualOptions {\n productId: number\n sponsorId: number\n sponsorName?: string\n brand: string\n name: string\n unitPrice: number\n currency: string\n imageUrl: string\n quantity?: number\n variantId?: number\n}\n\nfunction lineId(): string {\n return 'li_' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36)\n}\n\n/** Normalise an id-ish value for matching: null/0/'null' → '' (no id). */\nfunction normId(val: unknown): string {\n if (val === null || val === undefined || val === 0 || val === '0' || val === 'null' || val === 'undefined') {\n return ''\n }\n return String(val).trim()\n}\n\nexport class CartManager extends EventTarget {\n private cartsBySponsor: Map<number, SponsorCartState>\n /** In-flight CreateCart per sponsor — two quick adds must share ONE backend\n * cart (two CreateCarts split the items and one silently disappears). */\n private cartIdPromises = new Map<number, Promise<string | undefined>>()\n /** Monotonic mutation counter per sponsor + last applied response, so a\n * slow response can't overwrite the state of a newer one. */\n private mutationSeq = new Map<number, number>()\n private appliedSeq = new Map<number, number>()\n /** In-flight AddItem/UpdateItem/DeleteItem per sponsor. Callers that need\n * the backend cart to reflect a just-made change (e.g. fetching shippings\n * right after an add) should `await waitForCartMutations(sponsorId)` first\n * — otherwise they can race the mutation and see the cart from before it\n * landed (Alan, 2026-08-18: shippings queried before AddItem settled,\n * came back empty). */\n private inFlightMutations = new Map<number, Promise<unknown>>()\n\n constructor() {\n super()\n this.cartsBySponsor = this.loadFromStorage()\n }\n\n private nextSeq(sponsorId: number): number {\n const n = (this.mutationSeq.get(sponsorId) ?? 0) + 1\n this.mutationSeq.set(sponsorId, n)\n return n\n }\n\n /** Resolves once any in-flight AddItem/UpdateItem/DeleteItem for this\n * sponsor has settled (success or failure). No-op if nothing is pending. */\n async waitForCartMutations(sponsorId: number): Promise<void> {\n const p = this.inFlightMutations.get(sponsorId)\n if (!p) return\n try {\n await p\n } catch {\n /* the mutation's own catch already handled/reported the failure */\n }\n }\n\n /** Apply a backend response only if no newer response was applied already. */\n private applyBackendCart(sponsorId: number, backendCart: unknown, seq: number): void {\n if (seq < (this.appliedSeq.get(sponsorId) ?? 0)) return\n this.appliedSeq.set(sponsorId, seq)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.updateFromBackendCart(sponsorId, backendCart as any)\n }\n\n /** Surface a cart sync problem to hosts/UI (and the console). */\n private emitError(message: string, err?: unknown): void {\n if (typeof console !== 'undefined') console.warn('[CartManager]', message, err ?? '')\n this.dispatchEvent(new CustomEvent('error', { detail: { message } }))\n if (typeof document !== 'undefined') {\n document.dispatchEvent(\n new CustomEvent('vio:cart-error', { bubbles: true, detail: { message } }),\n )\n }\n }\n\n // MARK: - Backend cart sync (Vio Commerce GraphQL)\n\n /** Ensure the sponsor cart exists server-side; returns its backend cart id. */\n async ensureCartId(\n sponsorId: number,\n currency?: string,\n shippingCountry?: string,\n ): Promise<string | undefined> {\n const activeCurrency = currency || getGlobalCurrency()\n const activeCountry = shippingCountry || getGlobalCountryCode()\n let cart = this.cartsBySponsor.get(sponsorId)\n if (!cart) {\n cart = { sponsorId, items: [], currency: activeCurrency, shippingCountry: activeCountry }\n this.cartsBySponsor.set(sponsorId, cart)\n } else {\n cart.shippingCountry = activeCountry\n }\n if (cart.cartId) return cart.cartId\n\n // Dedupe: concurrent callers share ONE CreateCart per sponsor.\n const inFlight = this.cartIdPromises.get(sponsorId)\n if (inFlight) return inFlight\n\n const creation = (async (): Promise<string | undefined> => {\n const opts = await getCartGraphQLOptions(sponsorId)\n // Never create a backend cart with the wrong key — a cart signed with\n // the host apiKey is orphaned once the sponsor key resolves later.\n if (!opts.sponsorResolved) {\n this.emitError(`no commerce key resolved for sponsor ${sponsorId} — cart not synced`)\n return undefined\n }\n const customerSessionId = getCustomerSessionId()\n try {\n const backendCart = await gqlCreateCart(\n customerSessionId,\n activeCurrency,\n activeCountry,\n opts,\n )\n if (backendCart?.cart_id) {\n cart.cartId = backendCart.cart_id\n if (Array.isArray(backendCart.line_items) && backendCart.line_items.length > 0) {\n this.updateFromBackendCart(sponsorId, backendCart)\n } else {\n // Fresh backend cart (no lines yet) — adopt the meta only. Calling\n // updateFromBackendCart here would wipe the optimistic local items.\n if (backendCart.currency) cart.currency = backendCart.currency\n if (backendCart.shipping_country) cart.shippingCountry = backendCart.shipping_country\n if (backendCart.subtotal != null) cart.subtotal = backendCart.subtotal\n if (backendCart.shipping != null) cart.shipping = backendCart.shipping\n if (backendCart.available_shipping_countries) {\n cart.availableShippingCountries = backendCart.available_shipping_countries\n }\n this.persist()\n this.emit()\n }\n }\n } catch (err) {\n this.emitError('createCart failed', err)\n }\n return cart.cartId\n })().finally(() => {\n this.cartIdPromises.delete(sponsorId)\n })\n\n this.cartIdPromises.set(sponsorId, creation)\n return creation\n }\n\n /** Overwrite local cart state with the backend cart response (source of truth). */\n updateFromBackendCart(\n sponsorId: number,\n backendCart: {\n cart_id?: string\n currency?: string\n shipping_country?: string\n subtotal?: number\n shipping?: number\n available_shipping_countries?: string[]\n line_items?: Array<{\n id: string\n product_id: number\n variant_id?: number | string | null\n variant_title?: string | null\n brand?: string | null\n title?: string | null\n quantity: number\n image?: string | { url?: string } | null\n imageUrl?: string | null\n image_url?: string | null\n price?: {\n amount?: number\n amount_incl_taxes?: number | null\n currency_code?: string\n } | null\n shipping?: unknown\n available_shippings?: unknown[]\n }>\n },\n ): void {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart) return\n if (backendCart.cart_id) cart.cartId = backendCart.cart_id\n if (backendCart.currency) cart.currency = backendCart.currency\n if (backendCart.shipping_country) cart.shippingCountry = backendCart.shipping_country\n if (backendCart.subtotal != null) cart.subtotal = backendCart.subtotal\n if (backendCart.shipping != null) cart.shipping = backendCart.shipping\n if (backendCart.available_shipping_countries) {\n cart.availableShippingCountries = backendCart.available_shipping_countries\n }\n\n if (Array.isArray(backendCart.line_items)) {\n const existingItems = cart.items || []\n if (backendCart.line_items.length === 0 && existingItems.length > 0) {\n // Backend says empty while we have optimistic local lines (add still\n // in flight) — keep the local view; a later sync will reconcile.\n this.persist()\n this.emit()\n return\n }\n cart.items = backendCart.line_items.map((li): CartLineItem => {\n const urlFromBackend =\n (typeof li.image === 'string' ? li.image : li.image?.url) ||\n li.imageUrl ||\n li.image_url ||\n ''\n // Match the backend line to a local one to preserve display fields the\n // backend may omit (image, brand, name, price).\n const matchedLocal = existingItems.find((existing) => {\n const p1 = normId(existing.productId)\n const p2 = normId(li.product_id)\n const v1 = normId(existing.variantId)\n const v2 = normId(li.variant_id)\n if (p1 && p2 && p1 === p2 && v1 === v2) return true\n if (v1 && v2 && v1 === v2) return true\n if (p1 && p2 && p1 === p2 && !v1 && !v2) return true\n const n1 = (existing.name || '').trim().toLowerCase()\n const n2 = (li.title || '').trim().toLowerCase()\n if (n1 && n2 && n1 === n2 && v1 === v2) return true\n return false\n })\n const imageUrl = urlFromBackend || matchedLocal?.imageUrl || ''\n\n return {\n id: li.id,\n cartItemId: li.id,\n productId: li.product_id,\n sponsorId,\n variantId: li.variant_id != null ? Number(li.variant_id) : undefined,\n brand: li.brand || matchedLocal?.brand || '',\n name: li.title\n ? li.variant_title\n ? `${li.title} — ${li.variant_title}`\n : li.title\n : matchedLocal?.name || '',\n unitPrice: li.price?.amount_incl_taxes ?? li.price?.amount ?? matchedLocal?.unitPrice ?? 0,\n currency: li.price?.currency_code || backendCart.currency || matchedLocal?.currency || 'NOK',\n imageUrl,\n quantity: li.quantity,\n shipping: li.shipping,\n availableShippings: li.available_shippings,\n }\n })\n }\n this.persist()\n this.emit()\n\n // Replay quantity intents recorded while the line had no backend id yet.\n if (this.pendingQtyIntents.size > 0) {\n const currentCart = this.cartsBySponsor.get(sponsorId)\n for (const [key, qty] of [...this.pendingQtyIntents]) {\n const line = currentCart?.items.find(\n (i) => this.intentKey(i.productId, i.variantId) === key && i.cartItemId,\n )\n if (line) {\n this.pendingQtyIntents.delete(key)\n if (line.quantity !== qty) {\n this.updateQuantity(line.cartItemId!, sponsorId, qty)\n }\n }\n }\n }\n }\n\n // MARK: - Mutations\n\n /** Add a Product DTO to a sponsor's cart. Bumps quantity if already present.\n * When a variantId is given, the line uses the VARIANT's price / image / title\n * (not the product base), so different combinations are priced correctly. */\n addProduct(opts: AddProductOptions): CartLineItem {\n const variant =\n opts.variantId != null\n ? opts.product.variants?.find((v) => v.id === opts.variantId)\n : undefined\n const price = variant?.price ?? opts.product.price\n // Tax-inclusive is the consumer-facing price; `amount` is the fallback.\n const unitPrice = price.amount_incl_taxes ?? price.amount ?? 0\n const imageUrl = variant?.images?.[0]?.url || primaryImageUrl(opts.product) || ''\n const name = variant?.title\n ? `${opts.product.title} — ${variant.title}`\n : opts.product.title\n return this.addManual({\n productId: opts.product.id,\n sponsorId: opts.sponsorId,\n sponsorName: opts.sponsorName,\n brand: opts.product.brand ?? '',\n name,\n unitPrice,\n currency: price.currency_code,\n imageUrl,\n quantity: opts.quantity,\n variantId: opts.variantId,\n })\n }\n\n /** Add a manually-specified line item (no Product DTO). */\n addManual(opts: AddManualOptions): CartLineItem {\n const qty = Math.max(1, opts.quantity ?? 1)\n let cart = this.cartsBySponsor.get(opts.sponsorId)\n if (!cart) {\n cart = {\n sponsorId: opts.sponsorId,\n sponsorName: opts.sponsorName,\n items: [],\n currency: opts.currency,\n }\n this.cartsBySponsor.set(opts.sponsorId, cart)\n } else if (opts.sponsorName && !cart.sponsorName) {\n cart.sponsorName = opts.sponsorName\n }\n\n // Robust dedupe: backend-synced lines may carry ids as strings / omit\n // fields, so match on normalised product+variant ids with a name fallback.\n const existing = cart.items.find((i) => {\n const p1 = normId(i.productId)\n const p2 = normId(opts.productId)\n const v1 = normId(i.variantId)\n const v2 = normId(opts.variantId)\n if (p1 && p2 && p1 === p2 && v1 === v2) return true\n if (v1 && v2 && v1 === v2) return true\n if (p1 && p2 && p1 === p2 && !v1 && !v2) return true\n const n1 = (i.name || '').trim().toLowerCase()\n const n2 = (opts.name || '').trim().toLowerCase()\n if (n1 && n2 && n1 === n2 && v1 === v2) return true\n return false\n })\n if (existing) {\n existing.quantity += qty\n } else {\n const item: CartLineItem = {\n id: lineId(),\n productId: opts.productId,\n sponsorId: opts.sponsorId,\n variantId: opts.variantId,\n brand: opts.brand,\n name: opts.name,\n unitPrice: opts.unitPrice,\n currency: opts.currency,\n imageUrl: opts.imageUrl,\n quantity: qty,\n }\n cart.items.push(item)\n }\n this.persist()\n this.emit()\n\n const addedItem = existing ?? cart.items[cart.items.length - 1]!\n const addedLineId = addedItem.id\n\n // Async sync with the backend cart. Optimistic — but a REJECTED AddItem\n // reverts the local line (a ghost line means the UI total and the charged\n // total diverge silently).\n const seq = this.nextSeq(opts.sponsorId)\n const mutation = (async () => {\n try {\n const cartId = await this.ensureCartId(opts.sponsorId, opts.currency || undefined)\n if (cartId) {\n const gqlOpts = await getCartGraphQLOptions(opts.sponsorId)\n const lineItemsInput = [\n {\n product_id: Number(opts.productId || 0),\n quantity: qty,\n variant_id: opts.variantId != null ? Number(opts.variantId) : null,\n },\n ]\n const resCart = await gqlAddItem(cartId, lineItemsInput, gqlOpts)\n if (resCart && Array.isArray(resCart.line_items)) {\n this.applyBackendCart(opts.sponsorId, resCart, seq)\n }\n }\n // No cartId (no commerce key): the cart stays local-only; checkout is\n // blocked upstream, so no ghost-charge risk.\n } catch (err) {\n // Revert the optimistic add — subtract what THIS add contributed.\n const c = this.cartsBySponsor.get(opts.sponsorId)\n const line = c?.items.find((i) => i.id === addedLineId)\n if (c && line) {\n line.quantity -= qty\n if (line.quantity <= 0) c.items = c.items.filter((i) => i !== line)\n if (c.items.length === 0) this.cartsBySponsor.delete(opts.sponsorId)\n this.persist()\n this.emit()\n }\n this.emitError('AddItem rejected by the backend — item removed from the cart', err)\n }\n })()\n this.inFlightMutations.set(opts.sponsorId, mutation)\n void mutation.finally(() => {\n if (this.inFlightMutations.get(opts.sponsorId) === mutation) {\n this.inFlightMutations.delete(opts.sponsorId)\n }\n })\n\n return addedItem\n }\n\n /** Quantity intents for lines whose backend id hasn't arrived yet — replayed\n * when the AddItem response reconciles (keyed by product::variant). */\n private pendingQtyIntents = new Map<string, number>()\n\n private intentKey(productId: unknown, variantId: unknown): string {\n return `${normId(productId)}::${normId(variantId)}`\n }\n\n updateQuantity(lineItemId: string, sponsorId: number, quantity: number): void {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart) return\n const item = cart.items.find((i) => i.id === lineItemId || i.cartItemId === lineItemId)\n if (!item) return\n const targetItemId = item.cartItemId\n if (quantity <= 0) {\n cart.items = cart.items.filter((i) => i !== item)\n // Choke point de la baja: sale acá y no en la UI para que también\n // cuente cuando el host llama removeItem() por API.\n if (typeof document !== 'undefined') {\n document.dispatchEvent(\n new CustomEvent('vio:removed-from-cart', {\n bubbles: true,\n detail: {\n productId: item.productId,\n variantId: item.variantId,\n name: item.name,\n brand: item.brand,\n price: item.unitPrice,\n quantity: item.quantity,\n currency: item.currency,\n sponsorId,\n },\n }),\n )\n }\n } else {\n item.quantity = quantity\n }\n if (cart.items.length === 0) this.cartsBySponsor.delete(sponsorId)\n this.persist()\n this.emit()\n\n if (!cart.cartId) return\n\n // The line hasn't been assigned its backend id yet (AddItem in flight):\n // sending the local id would 404. Record the intent — it's replayed as\n // soon as the reconcile lands.\n if (!targetItemId) {\n this.pendingQtyIntents.set(this.intentKey(item.productId, item.variantId), quantity)\n return\n }\n\n const backendCartId = cart.cartId\n const seq = this.nextSeq(sponsorId)\n const mutation = (async () => {\n try {\n const gqlOpts = await getCartGraphQLOptions(sponsorId)\n const resCart =\n quantity <= 0\n ? await gqlDeleteItem(backendCartId, targetItemId, gqlOpts)\n : await gqlUpdateItem(backendCartId, targetItemId, null, quantity, gqlOpts)\n if (resCart && Array.isArray(resCart.line_items)) {\n this.applyBackendCart(sponsorId, resCart, seq)\n }\n } catch (err) {\n this.emitError('Update/DeleteItem failed — cart re-synced from backend', err)\n void this.fetchCartFromBackend(sponsorId)\n }\n })()\n this.inFlightMutations.set(sponsorId, mutation)\n void mutation.finally(() => {\n if (this.inFlightMutations.get(sponsorId) === mutation) {\n this.inFlightMutations.delete(sponsorId)\n }\n })\n }\n\n removeItem(lineItemId: string, sponsorId: number): void {\n this.updateQuantity(lineItemId, sponsorId, 0)\n }\n\n clearSponsorCart(sponsorId: number): void {\n if (this.cartsBySponsor.delete(sponsorId)) {\n this.persist()\n this.emit()\n }\n }\n\n clearAllCarts(): void {\n if (this.cartsBySponsor.size === 0) return\n this.cartsBySponsor.clear()\n this.persist()\n this.emit()\n }\n\n /** Refresh the local cart from the backend (source of truth). */\n async fetchCartFromBackend(sponsorId: number): Promise<unknown> {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart?.cartId) return null\n const gqlOpts = await getCartGraphQLOptions(sponsorId)\n const resCart = await gqlGetCart(cart.cartId, gqlOpts)\n if (resCart) this.updateFromBackendCart(sponsorId, resCart)\n return resCart\n }\n\n /** Line items grouped by supplier (shipping is per-supplier server-side). */\n async fetchLineItemsBySupplier(sponsorId: number): Promise<unknown> {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart?.cartId) return null\n const gqlOpts = await getCartGraphQLOptions(sponsorId)\n return gqlGetLineItemsBySupplier(cart.cartId, gqlOpts)\n }\n\n /** Set the chosen shipping option per supplier on the backend cart. */\n async updateShippingsBySupplier(\n sponsorId: number,\n data: Array<{ shipping_id: string; supplier_id: number }>,\n ): Promise<unknown> {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart?.cartId) return null\n const gqlOpts = await getCartGraphQLOptions(sponsorId)\n const resCart = await gqlUpdateShippingsBySupplier(cart.cartId, data, gqlOpts)\n if (resCart && Array.isArray(resCart.line_items)) {\n this.updateFromBackendCart(sponsorId, resCart)\n }\n return resCart\n }\n\n // MARK: - Read accessors\n\n getAllCarts(): Map<number, SponsorCartState> {\n return new Map(this.cartsBySponsor)\n }\n\n getCart(sponsorId: number): SponsorCartState | undefined {\n return this.cartsBySponsor.get(sponsorId)\n }\n\n get itemCount(): number {\n let count = 0\n for (const cart of this.cartsBySponsor.values()) {\n for (const item of cart.items) count += item.quantity\n }\n return count\n }\n\n subtotalForSponsor(sponsorId: number): number {\n const cart = this.cartsBySponsor.get(sponsorId)\n if (!cart) return 0\n return cart.items.reduce((sum, i) => sum + i.unitPrice * i.quantity, 0)\n }\n\n get totalAcrossSponsors(): number {\n let sum = 0\n for (const cart of this.cartsBySponsor.values()) {\n for (const item of cart.items) sum += item.unitPrice * item.quantity\n }\n return sum\n }\n\n get primaryCurrency(): string {\n for (const cart of this.cartsBySponsor.values()) return cart.currency\n return 'NOK'\n }\n\n formatTotal(): string {\n return formatPrice(this.totalAcrossSponsors, this.primaryCurrency)\n }\n\n // MARK: - Persistence\n\n private persist(): void {\n if (typeof localStorage === 'undefined') return\n try {\n const obj: Record<string, SponsorCartState> = {}\n for (const [k, v] of this.cartsBySponsor) obj[String(k)] = v\n localStorage.setItem(STORAGE_KEY, JSON.stringify(obj))\n } catch {\n // Ignore quota / privacy errors.\n }\n }\n\n private loadFromStorage(): Map<number, SponsorCartState> {\n if (typeof localStorage === 'undefined') return new Map()\n try {\n const raw = localStorage.getItem(STORAGE_KEY)\n if (!raw) return new Map()\n const obj = JSON.parse(raw) as Record<string, SponsorCartState>\n const map = new Map<number, SponsorCartState>()\n for (const [k, v] of Object.entries(obj)) {\n const id = parseInt(k, 10)\n if (!Number.isNaN(id) && v && Array.isArray(v.items)) map.set(id, v)\n }\n return map\n } catch {\n return new Map()\n }\n }\n\n private emit(): void {\n const detail: CartChangeDetail = {\n cartsBySponsor: this.getAllCarts(),\n itemCount: this.itemCount,\n }\n this.dispatchEvent(new CustomEvent<CartChangeDetail>('change', { detail }))\n }\n}\n","/**\n * Apple Pay on the Web — via Stripe Payment Request API.\n *\n * Architecture decision (matches iOS Vio SDK pattern):\n * - One Stripe **publishable key** for the Vio platform (global, set\n * via `Vio.init({ stripePublishableKey })`).\n * - One **Stripe Connect account id** per sponsor — sourced from\n * `Vio.bootstrap()` response. Without it, the payment lands on the\n * platform account instead of the merchant.\n *\n * Apple Pay on the Web prerequisites (Stripe-managed for us):\n * - Stripe Connect account is enabled for Apple Pay\n * - Domain registration for Apple Pay (Stripe handles via Dashboard)\n * - Safari + macOS/iOS device with Apple Pay configured\n *\n * In Chrome / non-Apple browsers `canMakePayment()` returns null, so the\n * UI hides the Apple Pay button automatically.\n */\n\nconst STRIPE_JS_URL = 'https://js.stripe.com/v3'\n\nexport interface ApplePayConfig {\n /** Stripe platform publishable key (pk_live_xxx or pk_test_xxx). */\n publishableKey: string\n /** Sponsor's Stripe Connect account (acct_xxx). Optional but recommended. */\n connectedAccount?: string\n /** Amount in the smallest unit of the currency (e.g. øre for NOK, cents for USD). */\n amount: number\n /** ISO currency code, lowercased internally for Stripe. */\n currency: string\n /** Two-letter country code, e.g. \"NO\". */\n country: string\n /** Label shown in the Apple Pay sheet (merchant or order name). */\n label: string\n /** Whether to ask the user for payer name. */\n requestPayerName?: boolean\n /** Whether to ask the user for payer email. */\n requestPayerEmail?: boolean\n /** Whether to ask for shipping address. */\n requestShipping?: boolean\n /**\n * Shipping options shown natively in the Apple Pay sheet. `amount` is in the\n * smallest unit (øre). When set, `requestShipping` is forced on and the sheet\n * total = `amount` (items) + the selected option; switching options updates\n * the total live (Apple Pay native shipping).\n */\n shippingOptions?: Array<{ id: string; label: string; detail?: string; amount: number }>\n /**\n * Charge hook, run INSIDE the sheet's authorize event with the tokenized\n * payment. Must perform the real (backend) charge and throw on failure —\n * only then does the sheet close with success; a throw closes it with\n * failure. Its resolved value is surfaced as `ApplePayResult.confirmation`.\n */\n onAuthorize?: (result: ApplePayResult) => Promise<unknown>\n}\n\nexport interface ApplePayResult {\n /** Stripe PaymentMethod id (pm_xxx) — pass to backend to confirm the PaymentIntent. */\n paymentMethodId: string\n payerName?: string\n payerEmail?: string\n payerPhone?: string\n shippingAddress?: {\n line1?: string\n line2?: string\n city?: string\n postal_code?: string\n state?: string\n country?: string\n }\n /** Whatever `onAuthorize` resolved with (e.g. backend order_id/status). */\n confirmation?: unknown\n}\n\nlet stripeJsPromise: Promise<unknown> | null = null\n\n/** Warm the Stripe.js load ahead of time (safe to call anywhere, never throws). */\nexport function preloadStripeJs(): void {\n if (typeof window === 'undefined') return\n void loadStripeJs().catch(() => {})\n}\n\n/** Dynamically load Stripe.js exactly once. */\nfunction loadStripeJs(): Promise<unknown> {\n if (stripeJsPromise) return stripeJsPromise\n if (typeof document === 'undefined') {\n return Promise.reject(new Error('[VioApplePay] Stripe.js requires a browser environment'))\n }\n stripeJsPromise = new Promise<unknown>((resolve, reject) => {\n const w = window as unknown as { Stripe?: unknown }\n if (w.Stripe) {\n resolve(w.Stripe)\n return\n }\n const existing = document.querySelector(\n `script[src^=\"${STRIPE_JS_URL}\"]`,\n ) as HTMLScriptElement | null\n if (existing) {\n existing.addEventListener('load', () => resolve(w.Stripe))\n existing.addEventListener('error', () =>\n reject(new Error('[VioApplePay] Failed to load Stripe.js')),\n )\n return\n }\n const script = document.createElement('script')\n script.src = STRIPE_JS_URL\n script.async = true\n script.addEventListener('load', () => resolve(w.Stripe))\n script.addEventListener('error', () =>\n reject(new Error('[VioApplePay] Failed to load Stripe.js')),\n )\n document.head.appendChild(script)\n })\n return stripeJsPromise\n}\n\ninterface StripeCanMakePaymentResult {\n applePay?: boolean\n googlePay?: boolean\n link?: boolean\n}\n\ninterface StripePaymentRequest {\n canMakePayment(): Promise<StripeCanMakePaymentResult | null>\n show(): void\n on(event: string, handler: (ev: unknown) => void): void\n}\n\ninterface StripeInstance {\n paymentRequest(options: Record<string, unknown>): StripePaymentRequest\n}\n\ntype StripeFactory = (\n publishableKey: string,\n options?: { stripeAccount?: string },\n) => StripeInstance\n\nasync function getStripe(config: ApplePayConfig): Promise<StripeInstance> {\n const Stripe = (await loadStripeJs()) as StripeFactory\n return Stripe(\n config.publishableKey,\n config.connectedAccount ? { stripeAccount: config.connectedAccount } : undefined,\n )\n}\n\nfunction buildRequestOptions(config: ApplePayConfig): Record<string, unknown> {\n const ship = config.shippingOptions\n // With shipping options, the sheet's total = items + the (first/selected) option.\n const preselectedShipping = ship && ship.length > 0 ? ship[0]!.amount : 0\n return {\n country: config.country,\n currency: config.currency.toLowerCase(),\n total: { label: config.label, amount: config.amount + preselectedShipping },\n requestPayerName: config.requestPayerName ?? true,\n requestPayerEmail: config.requestPayerEmail ?? true,\n requestShipping: ship && ship.length > 0 ? true : (config.requestShipping ?? false),\n ...(ship && ship.length > 0 ? { shippingOptions: ship } : {}),\n disableWallets: ['link', 'googlePay'],\n }\n}\n\n/**\n * Check whether Apple Pay is available right now (Safari + supported device\n * + Stripe configured + domain registered).\n *\n * Returns false on any failure path — never throws.\n */\nexport async function checkApplePayAvailability(config: ApplePayConfig): Promise<boolean> {\n if (typeof window === 'undefined') return false\n // Quick precheck — Apple Pay is only on Safari + supported macOS/iOS devices.\n if (typeof (window as unknown as { ApplePaySession?: unknown }).ApplePaySession === 'undefined') {\n return false\n }\n if (!config.publishableKey) return false\n try {\n const stripe = await getStripe(config)\n const pr = stripe.paymentRequest(buildRequestOptions(config))\n const result = await pr.canMakePayment()\n return !!result?.applePay\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioApplePay] availability check failed:', err)\n }\n return false\n }\n}\n\n/**\n * Show the Apple Pay sheet. Resolves with the payment method id (`pm_xxx`)\n * after the user authorises, or rejects on cancel / error.\n *\n * The backend must then confirm a Stripe PaymentIntent with this\n * payment method id (server-side step, not handled here).\n */\nexport async function showApplePaySheet(config: ApplePayConfig): Promise<ApplePayResult | null> {\n if (!config.publishableKey) {\n throw new Error('[VioApplePay] publishableKey is required')\n }\n const stripe = await getStripe(config)\n const pr = stripe.paymentRequest(buildRequestOptions(config))\n const canMake = await pr.canMakePayment()\n if (!canMake?.applePay) {\n throw new Error('[VioApplePay] Apple Pay is not available on this device')\n }\n return new Promise<ApplePayResult | null>((resolve, reject) => {\n let settled = false\n // Apple requires the address-change event to be answered or the sheet stalls.\n pr.on('shippingaddresschange', (raw: unknown) => {\n const ev = raw as { updateWith: (u: Record<string, unknown>) => void }\n ev.updateWith({ status: 'success' })\n })\n pr.on('paymentmethod', (raw: unknown) => {\n const ev = raw as {\n paymentMethod: { id: string }\n payerName?: string\n payerEmail?: string\n payerPhone?: string\n shippingAddress?: ApplePayResult['shippingAddress']\n complete: (status: 'success' | 'fail') => void\n }\n settled = true\n const result: ApplePayResult = {\n paymentMethodId: ev.paymentMethod.id,\n payerName: ev.payerName,\n payerEmail: ev.payerEmail,\n payerPhone: ev.payerPhone,\n shippingAddress: ev.shippingAddress,\n }\n // Fail-closed: the backend charge (onAuthorize) runs BEFORE the sheet\n // closes. Success only if the charge succeeded.\n void (async () => {\n try {\n const confirmation = config.onAuthorize ? await config.onAuthorize(result) : undefined\n ev.complete('success')\n resolve({ ...result, confirmation })\n } catch (err) {\n ev.complete('fail')\n reject(err)\n }\n })()\n })\n pr.on('cancel', () => {\n // User closed the sheet — not an error.\n if (!settled) resolve(null)\n })\n pr.show()\n })\n}\n\nexport interface PreparedApplePay {\n /** True if Apple Pay can be shown (canMakePayment resolved with applePay). */\n available: boolean\n /**\n * Open the Apple Pay sheet. MUST be invoked synchronously from the click\n * handler — the async work (Stripe.js load + canMakePayment) already ran in\n * `prepareApplePay`, so this fires `pr.show()` inside the user gesture. Apple\n * blocks the sheet if `show()` is reached after an `await`.\n */\n show(): Promise<ApplePayResult>\n}\n\n/**\n * Pre-create the Apple Pay PaymentRequest and resolve `canMakePayment()` ahead\n * of the click. Express buttons should call this on load/render, then call the\n * returned `show()` synchronously on tap — preserving the user gesture that\n * Apple requires to open the sheet.\n */\nexport async function prepareApplePay(config: ApplePayConfig): Promise<PreparedApplePay> {\n const unavailable = (msg: string): PreparedApplePay => ({\n available: false,\n show: () => Promise.reject(new Error(msg)),\n })\n if (typeof window === 'undefined' || !config.publishableKey) {\n return unavailable('[VioApplePay] unavailable')\n }\n if (typeof (window as unknown as { ApplePaySession?: unknown }).ApplePaySession === 'undefined') {\n return unavailable('[VioApplePay] ApplePaySession not available')\n }\n try {\n const stripe = await getStripe(config)\n const pr = stripe.paymentRequest(buildRequestOptions(config))\n // Recompute the total live when the user switches shipping option in the\n // Apple Pay sheet: total = items (config.amount) + chosen option amount.\n if (config.shippingOptions && config.shippingOptions.length > 0) {\n pr.on('shippingoptionchange', (raw: unknown) => {\n const ev = raw as {\n shippingOption?: { id?: string }\n updateWith: (u: Record<string, unknown>) => void\n }\n const opt = config.shippingOptions?.find((o) => o.id === ev.shippingOption?.id)\n ev.updateWith({\n status: 'success',\n total: { label: config.label, amount: config.amount + (opt?.amount ?? 0) },\n })\n })\n }\n pr.on('shippingaddresschange', (raw: unknown) => {\n const ev = raw as { updateWith: (u: Record<string, unknown>) => void }\n ev.updateWith({ status: 'success' })\n })\n const result = await pr.canMakePayment()\n if (!result?.applePay) return unavailable('[VioApplePay] Apple Pay not available')\n return {\n available: true,\n show(): Promise<ApplePayResult> {\n return new Promise<ApplePayResult>((resolve, reject) => {\n let settled = false\n pr.on('paymentmethod', (raw: unknown) => {\n const ev = raw as {\n paymentMethod: { id: string }\n payerName?: string\n payerEmail?: string\n payerPhone?: string\n shippingAddress?: ApplePayResult['shippingAddress']\n complete: (status: 'success' | 'fail') => void\n }\n settled = true\n const res: ApplePayResult = {\n paymentMethodId: ev.paymentMethod.id,\n payerName: ev.payerName,\n payerEmail: ev.payerEmail,\n payerPhone: ev.payerPhone,\n shippingAddress: ev.shippingAddress,\n }\n void (async () => {\n try {\n const confirmation = config.onAuthorize ? await config.onAuthorize(res) : undefined\n ev.complete('success')\n resolve({ ...res, confirmation })\n } catch (err) {\n ev.complete('fail')\n reject(err)\n }\n })()\n })\n pr.on('cancel', () => {\n if (!settled) reject(new Error('[VioApplePay] User cancelled Apple Pay'))\n })\n pr.show() // synchronous — must run inside the click gesture\n })\n },\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioApplePay] prepare failed:', err)\n }\n return unavailable('[VioApplePay] prepare failed')\n }\n}\n","/**\n * Klarna Express Checkout (KEC) — via the Klarna Web SDK v2.\n *\n * Frontend half of the flow (the only half that runs client-side):\n * 1. Load the Klarna Web SDK ESM module from Klarna's CDN.\n * 2. `KlarnaSDK({ clientId, products: ['PAYMENT'] })` → SDK instance.\n * 3. `Klarna.Payment.button({ paymentRequest, initiationMode })` → button.\n * 4. `button.mount(container)` renders the express button.\n * 5. User taps it → Klarna popup → on success the SDK yields an\n * **authorization token**.\n *\n * The authorization token is NOT an order. The merchant **backend** must\n * exchange it for an order against the Klarna Payments API\n * (`POST /payments/v1/authorizations/{token}/order`, Basic auth with the\n * server-side Klarna API key). That step needs secret credentials and is\n * intentionally out of this client module — we surface the token via\n * `onAuthorize` and let the host (or, later, vio-backend) create the order.\n *\n * Verified against Klarna Web SDK v2 docs (module URL, KlarnaSDK init,\n * Payment.button().mount(), authorization-token result). The exact\n * authorize *event name* varies by SDK minor version, so the subscription\n * below is defensive — it normalises across the documented shapes.\n *\n * Prerequisites (merchant-configured, like Stripe domain reg for Apple Pay):\n * - Klarna merchant account + a **Client Identifier** (Merchant Portal →\n * Payment settings → Client Identifiers).\n * - The integration domain registered under \"Allowed Origins\".\n * - A server-side Klarna API key for the order-creation step (backend).\n */\n\nimport { getGlobalLocale } from '../../types.js'\n\n/** Klarna Web SDK v2 ESM module (loaded from Klarna's CDN at runtime). */\nexport const KLARNA_SDK_URL = 'https://js.klarna.com/web-sdk/v2/klarna.mjs'\n\n/** One line in the express button's purchase data. Amounts in MINOR units. */\nexport interface KlarnaLineItem {\n name: string\n quantity: number\n /** Line total (unitPrice × quantity), minor units (e.g. øre for NOK). */\n totalAmount: number\n /** Per-unit price, minor units. Optional. */\n unitPrice?: number\n /** Merchant SKU / product reference. Optional. */\n reference?: string\n /** Absolute image URL. Optional. */\n imageUrl?: string\n}\n\n/** Payment request handed to the KEC button. Amounts in MINOR units. */\nexport interface KlarnaPaymentRequestData {\n /** ISO currency code (e.g. \"NOK\"). */\n currency: string\n /** Order total in minor units. */\n amount: number\n /** Line items — shown in the Klarna sheet. */\n supplementaryPurchaseData?: { lineItems: KlarnaLineItem[] }\n}\n\nexport interface KlarnaConfig {\n /** Klarna Client Identifier (public-safe — fine in client bundles). */\n clientId: string\n /** Optional BCP-47 locale, e.g. \"nb-NO\". */\n locale?: string\n /**\n * Klarna environment. `playground` = sandbox (test orders, \"TEST DRIVE\"\n * badge, no real money). `production` = live. Defaults to the SDK's own\n * default when omitted. The clientId must be generated for the matching\n * environment in the Klarna Merchant Portal.\n */\n environment?: 'playground' | 'production'\n}\n\nexport interface KlarnaAuthorizeResult {\n /** Authorization token — backend exchanges it for an order. */\n authorizationToken: string\n /** Klarna may require a finalize step (multistep flows). */\n finalizeRequired?: boolean\n /** Raw payload from the SDK, for debugging / forward-compat. */\n raw?: unknown\n}\n\nexport interface KlarnaButtonHandle {\n unmount(): void\n}\n\n// ── Minimal structural typings for the runtime-loaded SDK ────────────────\n// We don't ship Klarna's .d.ts; the SDK is fetched at runtime, so these are\n// just enough to call it type-safely.\n\ninterface KlarnaButtonInstance {\n mount(container: string | HTMLElement): KlarnaButtonInstance\n unmount(): KlarnaButtonInstance\n on(event: string, cb: (...args: unknown[]) => unknown): KlarnaButtonInstance\n}\n\ninterface KlarnaPaymentNamespace {\n button(config: Record<string, unknown>): KlarnaButtonInstance\n /**\n * Opens the Klarna flow. Takes a callback that returns the payment-request\n * data (or a Promise of it). Must be invoked synchronously from the\n * button's `click` handler so the popup keeps the user gesture. Resolves\n * with the authorization result once the user completes the popup.\n */\n initiate(resolvePaymentRequest: () => unknown): Promise<unknown>\n on?(event: string, cb: (...args: unknown[]) => unknown): unknown\n}\n\ninterface KlarnaSdkInstance {\n Payment: KlarnaPaymentNamespace\n}\n\ntype KlarnaSdkFactory = (config: Record<string, unknown>) => Promise<KlarnaSdkInstance>\n\n// Memoise the SDK instance per clientId so re-opening checkout reuses it.\nconst sdkCache = new Map<string, Promise<KlarnaSdkInstance>>()\n\nfunction loadKlarnaSdk(config: KlarnaConfig): Promise<KlarnaSdkInstance> {\n if (typeof window === 'undefined') {\n return Promise.reject(new Error('[VioKlarna] requires a browser environment'))\n }\n if (!config.clientId) {\n return Promise.reject(new Error('[VioKlarna] clientId is required'))\n }\n // Key the cache by clientId + environment so switching env re-inits.\n const cacheKey = `${config.clientId}:${config.environment ?? 'default'}`\n const cached = sdkCache.get(cacheKey)\n if (cached) return cached\n\n // Dynamic import of an absolute CDN URL. `@vite-ignore` stops the bundler\n // from trying to resolve/inline it — it stays a runtime fetch.\n const url = KLARNA_SDK_URL\n const promise = import(/* @vite-ignore */ url)\n .then((mod: { KlarnaSDK?: KlarnaSdkFactory; default?: KlarnaSdkFactory }) => {\n const factory = mod.KlarnaSDK ?? mod.default\n if (typeof factory !== 'function') {\n throw new Error('[VioKlarna] KlarnaSDK factory not found in module')\n }\n return factory({\n clientId: config.clientId,\n products: ['PAYMENT'],\n ...(config.locale ? { locale: config.locale } : {}),\n ...(config.environment ? { environment: config.environment } : {}),\n })\n })\n .catch((err) => {\n // Don't poison the cache on failure — allow a later retry.\n sdkCache.delete(cacheKey)\n throw err\n })\n sdkCache.set(cacheKey, promise)\n return promise\n}\n\n/**\n * True if Klarna Express can be offered right now (clientId set + SDK loads).\n * Never throws — returns false on any failure path (mirrors Apple Pay).\n */\nexport async function isKlarnaAvailable(config: KlarnaConfig): Promise<boolean> {\n if (typeof window === 'undefined' || !config.clientId) return false\n try {\n await loadKlarnaSdk(config)\n return true\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioKlarna] availability check failed:', err)\n }\n return false\n }\n}\n\n/** Recursively search a result object for an authorization token. */\nfunction findAuthToken(value: unknown, depth = 0): string | undefined {\n if (!value || depth > 4 || typeof value !== 'object') return undefined\n const o = value as Record<string, unknown>\n for (const key of ['authorizationToken', 'authorization_token', 'authToken']) {\n if (typeof o[key] === 'string' && (o[key] as string).length > 0) return o[key] as string\n }\n for (const k of Object.keys(o)) {\n const found = findAuthToken(o[k], depth + 1)\n if (found) return found\n }\n return undefined\n}\n\n/**\n * Build + mount the Klarna Express button into `container`.\n *\n * Flow (Klarna Web SDK v2): the button's `click` handler **synchronously**\n * calls `Klarna.Payment.initiate(cb)` — `cb` returns the payment-request\n * data. That call opens the Klarna popup (the synchronous call preserves the\n * user gesture). The returned Promise resolves with the authorization result\n * once the user completes the popup; we pull the authorization token out and\n * hand it to `onAuthorize`. The token is NOT an order — the backend creates\n * the order from it.\n */\nexport async function mountKlarnaExpressButton(opts: {\n config: KlarnaConfig\n container: HTMLElement\n paymentRequest: KlarnaPaymentRequestData\n /** URL Klarna returns to after a redirect-based completion. Required by KEC. */\n returnUrl?: string\n /**\n * sessionStorage key + payload to persist BEFORE launching. On a redirect\n * completion the page reloads (the initiate() promise is lost), so the\n * resume handler reads this back to recreate the order. Survives the\n * cross-origin redirect because sessionStorage is per-tab.\n */\n pendingKey?: string\n pendingContext?: unknown\n onAuthorize: (result: KlarnaAuthorizeResult) => void\n onError?: (err: unknown) => void\n}): Promise<KlarnaButtonHandle> {\n const sdk = await loadKlarnaSdk(opts.config)\n\n const button = sdk.Payment.button({\n id: 'vio-klarna-express',\n // `PAY` = one-time purchase (vs BUY/SUBSCRIBE). Must be an array.\n intents: ['PAY'],\n // initiationMode belongs on the BUTTON config (per Klarna Web SDK docs),\n // NOT inside the initiate() data — when set only in initiate() the SDK\n // falls back to its default (DEVICE_BEST → desktop popup), which opened\n // and closed without completing. Forcing REDIRECT here makes the click do\n // a full-page navigation to Klarna's hosted journey, returning via\n // `returnUrl` (recovered by resumeKlarnaReturn()).\n initiationMode: 'REDIRECT',\n })\n\n // Clean origin+path (no existing query/hash) so Klarna's appended result\n // params land on a predictable URL the resume handler can parse.\n const returnUrl =\n opts.returnUrl ??\n (typeof window !== 'undefined'\n ? window.location.origin + window.location.pathname\n : '')\n\n let settled = false\n button.on('click', () => {\n // Persist the pending order so a REDIRECT completion (page reloads, this\n // promise never resolves) can be recovered on the return page.\n if (opts.pendingKey && opts.pendingContext && typeof sessionStorage !== 'undefined') {\n try {\n sessionStorage.setItem(opts.pendingKey, JSON.stringify(opts.pendingContext))\n } catch {\n /* storage unavailable — popup mode still works via the promise */\n }\n }\n // initiate() MUST be called synchronously here — going async first would\n // drop the user-gesture and the browser would block the popup.\n const promise = sdk.Payment.initiate(() => ({\n currency: opts.paymentRequest.currency,\n paymentAmount: opts.paymentRequest.amount,\n intents: ['PAY'],\n locale: getGlobalLocale(),\n // REDIRECT = full-page navigation to Klarna's hosted journey, then back\n // to `returnUrl` with the result. We force this (vs DEVICE_BEST's desktop\n // popup) because the popup proved unreliable here — it opened and closed\n // without completing. The redirect flow has no popup-blocker / window-\n // messaging failure modes; the return is recovered via resumeKlarnaReturn().\n initiationMode: 'REDIRECT',\n returnUrl,\n ...(opts.paymentRequest.supplementaryPurchaseData\n ? { supplementaryPurchaseData: opts.paymentRequest.supplementaryPurchaseData }\n : {}),\n }))\n\n Promise.resolve(promise)\n .then((result) => {\n if (settled) return\n const token = findAuthToken(result)\n if (token) {\n settled = true\n opts.onAuthorize({ authorizationToken: token, raw: result })\n } else if (typeof console !== 'undefined') {\n // Resolved without a recognisable token — log so we can map the\n // shape. Don't confirm the order on an ambiguous resolve.\n console.warn('[VioKlarna] authorize resolved without a token:', result)\n }\n })\n .catch((err) => {\n // Reject = user cancelled or a validation/auth error. Not a success.\n opts.onError?.(err)\n })\n\n // Hand the same promise back to the SDK (its contract for the handler).\n return promise\n })\n\n button.mount(opts.container)\n\n return {\n unmount: () => {\n try {\n button.unmount()\n } catch {\n /* already gone */\n }\n },\n }\n}\n\n/**\n * Read a Klarna authorization token from the current URL's query string.\n * Klarna's redirect completion appends it; param name varies, so check the\n * known variants. Returns the token + the param name found (to clean later).\n */\nexport function readKlarnaTokenFromUrl(): { token: string; param: string } | null {\n if (typeof window === 'undefined') return null\n const params = new URLSearchParams(window.location.search)\n for (const name of [\n 'authorization_token',\n 'authorizationToken',\n 'klarna_authorization_token',\n 'vio_klarna_token',\n ]) {\n const v = params.get(name)\n if (v && v.length > 0 && v !== '{klarna.authorization_token}') {\n return { token: v, param: name }\n }\n }\n return null\n}\n\n/** Strip the given query params from the URL without reloading. */\nexport function cleanUrlParams(params: string[]): void {\n if (typeof window === 'undefined' || !window.history?.replaceState) return\n const url = new URL(window.location.href)\n let changed = false\n for (const p of params) {\n if (url.searchParams.has(p)) {\n url.searchParams.delete(p)\n changed = true\n }\n }\n if (changed) window.history.replaceState({}, '', url.toString())\n}\n\n/**\n * Subscribe to the SDK's namespace-level `complete`/`error` events. On a\n * REDIRECT return the SDK resumes its persisted session and fires `complete`\n * with the authorization token — this is how we recover the token when the\n * page reloaded and the initiate() promise was lost.\n *\n * Never throws; logs and resolves even if the SDK can't load.\n */\nexport async function listenForKlarnaCompletion(opts: {\n config: KlarnaConfig\n onComplete: (result: KlarnaAuthorizeResult) => void\n onError?: (err: unknown) => void\n}): Promise<void> {\n let sdk: KlarnaSdkInstance\n try {\n sdk = await loadKlarnaSdk(opts.config)\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioKlarna] resume: SDK load failed:', err)\n }\n return\n }\n let settled = false\n const onComplete = (...args: unknown[]) => {\n if (settled) return\n for (const a of args) {\n const token = findAuthToken(a)\n if (token) {\n settled = true\n opts.onComplete({ authorizationToken: token, raw: a })\n return\n }\n }\n }\n try {\n sdk.Payment.on?.('complete', onComplete)\n } catch {\n /* unsupported */\n }\n try {\n sdk.Payment.on?.('error', (...a: unknown[]) => opts.onError?.(a[0]))\n } catch {\n /* unsupported */\n }\n}\n","/**\n * Klarna Payments — classic widget flow (`kp/lib/v1/api.js`).\n *\n * This is the alternative to KEC (Web SDK v2 button + `initiate` redirect).\n * Instead of a public `clientId` + origin handshake (which 403'd on the\n * `klarnaevt` bridge from localhost), it uses a **server-minted client_token**:\n *\n * 1. Backend creates a Payments session → `client_token` + categories\n * (POST /v2/commerce/klarna/sessions, server-side Basic-auth API key).\n * 2. We load Klarna's widget **inline** (an iframe) into a container via\n * `Klarna.Payments.init({ client_token })` + `Klarna.Payments.load(...)`.\n * 3. The customer picks/fills a method; `Klarna.Payments.authorize(...)`\n * yields an `authorization_token`.\n * 4. Backend exchanges the token for a real order (existing /orders route).\n *\n * No redirect, no popup, no public clientId — so the origin/handshake failure\n * mode simply doesn't apply here.\n */\n\n/** Klarna Payments JS library (classic). Loaded via <script>, sets window.Klarna. */\nexport const KLARNA_KP_LIB_URL = 'https://x.klarnacdn.net/kp/lib/v1/api.js'\n\nexport interface KlarnaPaymentsCategory {\n identifier: string\n name: string\n asset_urls?: { descriptive?: string; standard?: string }\n}\n\n// ── Minimal runtime typings for the <script>-loaded global ────────────────\ninterface KpLoadResult {\n show_form?: boolean\n error?: unknown\n}\ninterface KpAuthorizeResult {\n approved?: boolean\n show_form?: boolean\n authorization_token?: string\n finalize_required?: boolean\n error?: unknown\n}\ninterface KlarnaPaymentsApi {\n init(opts: { client_token: string }): void\n load(\n opts: { container: string | HTMLElement; payment_method_category?: string },\n data: Record<string, unknown>,\n cb?: (res: KpLoadResult) => void,\n ): void\n authorize(\n opts: { payment_method_category?: string; auto_finalize?: boolean },\n data: Record<string, unknown>,\n cb?: (res: KpAuthorizeResult) => void,\n ): void\n /** Debug/lifecycle events — e.g. 'fullscreenOverlayShown'/'fullscreenOverlayHidden'. */\n on?(event: string, cb: () => void): void\n}\ninterface KlarnaGlobal {\n Payments: KlarnaPaymentsApi\n}\n\ndeclare global {\n interface Window {\n Klarna?: KlarnaGlobal\n klarnaAsyncCallback?: () => void\n }\n}\n\nlet kpLoad: Promise<KlarnaGlobal> | null = null\n\n/** Load kp/lib/v1/api.js once; resolves when window.Klarna.Payments is ready. */\nfunction loadKpLib(): Promise<KlarnaGlobal> {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return Promise.reject(new Error('[VioKlarnaKP] requires a browser environment'))\n }\n if (window.Klarna?.Payments) return Promise.resolve(window.Klarna)\n if (kpLoad) return kpLoad\n\n kpLoad = new Promise<KlarnaGlobal>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error('[VioKlarnaKP] kp/lib/v1/api.js load timed out')),\n 12000,\n )\n const ready = () => {\n clearTimeout(timer)\n if (window.Klarna?.Payments) resolve(window.Klarna)\n else reject(new Error('[VioKlarnaKP] Klarna global missing after ready'))\n }\n // Klarna invokes window.klarnaAsyncCallback once the lib is initialised.\n const prev = window.klarnaAsyncCallback\n window.klarnaAsyncCallback = () => {\n if (typeof prev === 'function') {\n try {\n prev()\n } catch {\n /* host callback threw — ignore */\n }\n }\n ready()\n }\n\n const existing = document.querySelector<HTMLScriptElement>(\n `script[src=\"${KLARNA_KP_LIB_URL}\"]`,\n )\n if (existing) {\n // Script already in the DOM (e.g. re-open). If Klarna is up, resolve now;\n // otherwise our klarnaAsyncCallback above will fire.\n if (window.Klarna?.Payments) ready()\n } else {\n const s = document.createElement('script')\n s.src = KLARNA_KP_LIB_URL\n s.async = true\n s.onerror = () => {\n clearTimeout(timer)\n kpLoad = null\n reject(new Error('[VioKlarnaKP] failed to load kp/lib/v1/api.js'))\n }\n document.head.appendChild(s)\n }\n }).catch((err) => {\n kpLoad = null // allow retry\n throw err\n })\n\n return kpLoad\n}\n\nexport interface KlarnaPaymentsWidgetInput {\n clientToken: string\n /** Klarna session id (native GraphQL flow) — informational, for callers/logs. */\n sessionId?: string\n categories: KlarnaPaymentsCategory[]\n container: HTMLElement\n /** Category to load first. Defaults to the first available. */\n category?: string\n}\n\nexport interface KlarnaPaymentsWidget {\n /** Categories offered by the session (pay_now / pay_later / pay_over_time). */\n categories: KlarnaPaymentsCategory[]\n /** Currently selected payment_method_category. */\n selected: string\n /** (Re)load the widget for a category into the container. */\n load(category?: string): Promise<{ showForm: boolean }>\n /**\n * Authorize a category. Resolves with the authorization token, rejects on\n * decline/cancel/error. `category` overrides `selected` for this call (and\n * reloads the widget first if it differs) — pass it explicitly rather than\n * relying on `selected` alone, since a caller UI's own state and the\n * widget's internal `selected` can drift. `data` is an optional order-data\n * update (the session already carries the lines; pass billing/extra if\n * available).\n */\n authorize(category?: string, data?: Record<string, unknown>): Promise<string>\n}\n\n/** True if the Klarna Payments lib can load in this environment. */\nexport async function isKlarnaPaymentsAvailable(): Promise<boolean> {\n if (typeof window === 'undefined') return false\n try {\n await loadKpLib()\n return true\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioKlarnaKP] availability check failed:', err)\n }\n return false\n }\n}\n\n/**\n * Init Klarna Payments with a server-minted client_token and mount the widget.\n * Returns a handle to (re)load categories and to authorize.\n */\n/** Pick the direct-payment category (\"Betal nå\") when the session offers one —\n * the demo sells physical goods paid up front, not financing. Ported from\n * Alan's round-5 improvement. */\nexport function findPayNowCategory(categories: KlarnaPaymentsCategory[]): string | null {\n if (!Array.isArray(categories) || categories.length === 0) return null\n const byId = (re: RegExp) => categories.find((c) => c?.identifier && re.test(c.identifier))\n const byName = (re: RegExp) => categories.find((c) => c?.name && re.test(c.name))\n const cat =\n categories.find((c) => c?.identifier === 'pay_now') ??\n byName(/betal\\s*n[åa]|pay\\s*now/i) ??\n byId(/pay_now|direct_debit|direct_bank_transfer|pay_in_full|klarna_pay_now/i) ??\n byName(/direkte|bank|kort|straks|sofort/i) ??\n categories.find((c) => c?.identifier && !/pay_later|pay_over_time|slice_it/.test(c.identifier))\n console.log('findPayNowCategory - Selected: ', cat)\n return cat?.identifier ?? null\n}\n\nexport async function createKlarnaPaymentsWidget(\n input: KlarnaPaymentsWidgetInput,\n): Promise<KlarnaPaymentsWidget> {\n const Klarna = await loadKpLib()\n console.log('[DEBUG Klarna] Initializing Klarna Payments')\n Klarna.Payments.init({ client_token: input.clientToken })\n console.log('[DEBUG Klarna] Klarna Payments initialized')\n Klarna.Payments.on?.('fullscreenOverlayShown', () => {\n console.log('[DEBUG Klarna] FULLSCREEN OVERLAY SHOWN')\n })\n Klarna.Payments.on?.('fullscreenOverlayHidden', () => {\n console.log('[DEBUG Klarna] FULLSCREEN OVERLAY HIDDEN')\n })\n\n let selected =\n input.category ??\n findPayNowCategory(input.categories) ??\n input.categories[0]?.identifier ??\n 'pay_now'\n if (typeof console !== 'undefined') {\n console.log('[VioKlarna] Received payment_method_categories from backend:', input.categories)\n console.log('[VioKlarna] Selected initial payment_method_category:', selected)\n }\n\n const load = (category?: string): Promise<{ showForm: boolean }> => {\n if (category) selected = category\n if (typeof console !== 'undefined') {\n console.log(\n '[VioKlarna] Klarna.Payments.load calling with payment_method_category:',\n selected,\n 'container:',\n input.container,\n )\n }\n // Clear any previously-rendered iframe before reloading a different\n // category — Klarna's widget doesn't always replace its own markup\n // cleanly on a second load() into the same container.\n if (input.container && 'innerHTML' in input.container) {\n input.container.innerHTML = ''\n }\n return new Promise((resolve, reject) => {\n try {\n // 3-arg form per Klarna docs: (options, data, callback). The empty\n // data object is required — a 2-arg call risks the SDK treating the\n // callback as `data` and never invoking it.\n Klarna.Payments.load(\n { container: input.container, payment_method_category: selected },\n {},\n (res) => {\n if (typeof console !== 'undefined') {\n console.log(\n '[VioKlarna] Klarna.Payments.load response for payment_method_category:',\n selected,\n res,\n )\n }\n if (res?.error) reject(res.error)\n else resolve({ showForm: res?.show_form !== false })\n },\n )\n } catch (err) {\n reject(err)\n }\n })\n }\n\n return {\n categories: input.categories,\n get selected() {\n return selected\n },\n load,\n async authorize(category?: string, data?: Record<string, unknown>): Promise<string> {\n const cat = category || selected\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] BEFORE AUTHORIZE', {\n argumentCategory: category,\n argumentData: data,\n selected,\n resolvedCategory: cat,\n })\n }\n // If the caller asked for a category different from what's currently\n // loaded, reload the widget first — authorizing against a stale\n // `selected` would charge/confirm the wrong payment method category.\n if (cat && cat !== selected) {\n await load(cat)\n }\n const finalData = { payment_method_category: cat, ...(data ?? {}) }\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] FINAL AUTHORIZE', { cat, selected, finalData })\n }\n return new Promise<string>((resolve, reject) => {\n try {\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] ABOUT TO CALL AUTHORIZE')\n }\n Klarna.Payments.authorize(\n { payment_method_category: cat, auto_finalize: true },\n finalData,\n (res) => {\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] RAW AUTHORIZE RESPONSE:', JSON.stringify(res, null, 2))\n }\n if (res?.approved && res.authorization_token) {\n resolve(res.authorization_token)\n } else if (res?.error) {\n reject(res.error)\n } else if (res?.finalize_required) {\n reject(new Error('Klarna requires a finalize step (multistep)'))\n } else {\n // approved:false without an error == user cancelled / declined.\n reject(new Error('Klarna authorization was not approved'))\n }\n },\n )\n if (typeof console !== 'undefined') {\n console.log('[DEBUG Klarna] AUTHORIZE CALL RETURNED')\n }\n } catch (err) {\n reject(err)\n }\n })\n },\n }\n}\n","/**\n * Kustom (former Klarna Checkout) — embedded KCO v3 checkout.\n *\n * Kustom kept the Klarna Checkout dialect on its own hosts, so the flow is\n * the classic KCO embed:\n *\n * 1. Vio Commerce creates the order (`Payment { CreatePaymentKustom }`,\n * authed with the sponsor's commerce API key; the seller's own\n * kco_*_api_* key lives server-side, per seller, never here).\n * 2. The response's `html_snippet` is injected into a container — it\n * renders Kustom's iframe, which collects address, shipping AND payment\n * by itself (the widget does everything; no Vio address form).\n * 3. On completion Kustom redirects to the confirmation URL\n * (`?order_id=…&payment_processor=KUSTOM`), where the SDK re-reads the\n * order (`Payment { GetKustomOrder }`) and renders its confirmation\n * snippet — KCO's own receipt.\n *\n * The Commerce order itself is created server-side by Kustom's push webhook\n * (shopcart /checkout/payment/kustom/ok) — the browser never confirms money.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\n\n/** KCO order fields the SDK consumes (the full order is much larger). */\nexport interface KustomOrder {\n order_id: string\n status: string\n html_snippet: string\n purchase_country?: string\n purchase_currency?: string\n}\n\nexport const CREATE_PAYMENT_KUSTOM_MUTATION = `\nmutation CreatePaymentKustom($checkoutId: String!, $countryCode: String!, $href: String!, $email: String) {\n Payment {\n CreatePaymentKustom(checkout_id: $checkoutId, country_code: $countryCode, href: $href, email: $email) {\n order_id\n status\n html_snippet\n purchase_country\n purchase_currency\n }\n }\n}\n`\n\nexport const GET_KUSTOM_ORDER_QUERY = `\nquery GetKustomOrder($orderId: String!) {\n Payment {\n GetKustomOrder(order_id: $orderId) {\n order_id\n status\n html_snippet\n purchase_country\n purchase_currency\n }\n }\n}\n`\n\nexport interface CreatePaymentKustomVariables extends Record<string, unknown> {\n checkoutId: string\n countryCode: string\n href: string\n email?: string\n}\n\nexport async function createPaymentKustom(\n variables: CreatePaymentKustomVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<KustomOrder | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_KUSTOM_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentKustom as KustomOrder) ?? null\n}\n\nexport async function getKustomOrder(\n orderId: string,\n options?: CartQueryOptions,\n): Promise<KustomOrder | null> {\n const json = await executeCartGraphQL(GET_KUSTOM_ORDER_QUERY, { orderId }, options)\n return (json?.data?.Payment?.GetKustomOrder as KustomOrder) ?? null\n}\n\n/**\n * The page URL Kustom appends its redirect params to. shopcart builds the\n * confirmation URL as `${href}?order_id={checkout.order.id}&…`, so the href\n * MUST NOT already carry a query string — origin + pathname only.\n */\nexport function kustomCleanHref(): string {\n if (typeof window === 'undefined' || !window.location) return ''\n return `${window.location.origin}${window.location.pathname}`\n}\n\n/**\n * Inject a KCO html_snippet and EXECUTE its inline scripts — innerHTML alone\n * leaves <script> tags inert, so each one is recreated node-by-node. This is\n * the standard Klarna Checkout embed technique, unchanged under Kustom.\n */\nexport function renderKustomSnippet(container: HTMLElement, htmlSnippet: string): void {\n container.innerHTML = htmlSnippet\n const scripts = Array.from(container.querySelectorAll('script'))\n for (const oldScript of scripts) {\n const newScript = document.createElement('script')\n for (const attr of Array.from(oldScript.attributes)) {\n newScript.setAttribute(attr.name, attr.value)\n }\n newScript.text = oldScript.text\n oldScript.parentNode?.replaceChild(newScript, oldScript)\n }\n}\n","/**\n * Qliro Checkout — embedded checkout via Vio Commerce.\n *\n * Same embed philosophy as Kustom (the widget collects address, shipping\n * AND payment), different provider API underneath — shopcart normalizes\n * Qliro's Merchant API (OrderId / CustomerCheckoutStatus / OrderHtmlSnippet)\n * to the { order_id, status, html_snippet } shape both flows share:\n *\n * 1. `Payment { CreatePaymentQliro }` creates the order and returns the\n * snippet (sponsor-key authed; the seller's MerchantApiKey/Secret live\n * server-side, per seller, never here).\n * 2. The snippet is injected (script-executing embed, shared with Kustom).\n * 3. On completion Qliro redirects to the confirmation URL\n * (`?checkout_id=…&payment_processor=QLIRO`); the SDK re-reads the\n * order via `Payment { GetQliroOrder(checkout_id) }` — Qliro\n * correlates by the OWNING CHECKOUT, not the order id — and renders\n * the snippet again, which shows Qliro's own receipt.\n *\n * The Commerce order is created server-side by Qliro's push webhook\n * (shopcart /checkout/payment/qliro/ok) — the browser never confirms money.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\nimport { kustomCleanHref, renderKustomSnippet } from './kustom.js'\n\n/** Normalized Qliro order (shopcart maps the PascalCase Merchant API). */\nexport interface QliroOrder {\n order_id: string\n /** Qliro CustomerCheckoutStatus: InProcess | Completed | OnHold | Refused. */\n status: string\n html_snippet: string\n purchase_country?: string\n purchase_currency?: string\n total_price?: number\n}\n\n/**\n * The Vio theme tokens Qliro can be dressed with.\n *\n * Qliro fixes its appearance at CREATE ORDER — there is no way to restyle the\n * widget once it has rendered — so the tokens have to travel with the order.\n * They are sent as Vio tokens, not Qliro field names: the mapping and the\n * validation live in shopcart, where they can be tested without a browser.\n */\nexport interface QliroTheme {\n accent?: string\n surface?: string\n radiusMd?: string\n radiusLg?: string\n}\n\n/**\n * The theme as the host page has actually resolved it.\n *\n * Reads the COMPUTED values, not the SDK's defaults: `--vio-*` are custom\n * properties any host — a Vev block, a publisher's stylesheet — is free to\n * override, and the whole point is that Qliro matches what the shopper is\n * looking at. Returns undefined outside a browser, or when nothing resolved.\n */\nexport function readVioTheme(): QliroTheme | undefined {\n if (typeof globalThis === 'undefined') return undefined\n const doc = (globalThis as any).document\n const getComputed = (globalThis as any).getComputedStyle\n if (!doc?.documentElement || typeof getComputed !== 'function') return undefined\n let style: any\n try {\n style = getComputed(doc.documentElement)\n } catch {\n return undefined\n }\n const read = (name: string): string | undefined => {\n const value = style?.getPropertyValue?.(name)?.trim()\n return value || undefined\n }\n const theme: QliroTheme = {\n accent: read('--vio-color-accent'),\n surface: read('--vio-color-surface'),\n radiusMd: read('--vio-radius-md'),\n radiusLg: read('--vio-radius-lg'),\n }\n return Object.values(theme).some(Boolean) ? theme : undefined\n}\n\nexport const CREATE_PAYMENT_QLIRO_MUTATION = `\nmutation CreatePaymentQliro($checkoutId: String!, $countryCode: String!, $href: String!, $email: String, $theme: QliroThemeInput) {\n Payment {\n CreatePaymentQliro(checkout_id: $checkoutId, country_code: $countryCode, href: $href, email: $email, theme: $theme) {\n order_id\n status\n html_snippet\n purchase_country\n purchase_currency\n total_price\n }\n }\n}\n`\n\nexport const GET_QLIRO_ORDER_QUERY = `\nquery GetQliroOrder($checkoutId: String!) {\n Payment {\n GetQliroOrder(checkout_id: $checkoutId) {\n order_id\n status\n html_snippet\n purchase_country\n purchase_currency\n total_price\n }\n }\n}\n`\n\nexport interface CreatePaymentQliroVariables extends Record<string, unknown> {\n checkoutId: string\n countryCode: string\n href: string\n email?: string\n theme?: QliroTheme\n}\n\nexport async function createPaymentQliro(\n variables: CreatePaymentQliroVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<QliroOrder | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_QLIRO_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentQliro as QliroOrder) ?? null\n}\n\nexport async function getQliroOrder(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<QliroOrder | null> {\n const json = await executeCartGraphQL(GET_QLIRO_ORDER_QUERY, { checkoutId }, options)\n return (json?.data?.Payment?.GetQliroOrder as QliroOrder) ?? null\n}\n\n/** Query-less page URL — shopcart appends ?checkout_id=…&payment_processor=QLIRO. */\nexport const qliroCleanHref = kustomCleanHref\n\n/** Script-executing snippet injection — identical technique to Kustom/KCO. */\nexport const renderQliroSnippet = renderKustomSnippet\n","/**\n * Qliro's browser-side protocol (`q1`).\n *\n * The embedded widget publishes a `q1` object on the window and calls a\n * globally-defined `q1Ready` once it has rendered. Everything the customer\n * does inside the iframe — picking a shipping method, changing their address,\n * having a payment declined — is only observable through these listeners.\n * Without them the widget is a black box: the customer can change the\n * shipping and our own summary keeps showing the old total.\n *\n * Two rules from Qliro's documentation shape this module:\n *\n * 1. **Lock before touching the backend.** Otherwise the customer can\n * complete the purchase while the order is still being synchronized.\n * 2. **Compare before unlocking.** Otherwise a second change interrupts the\n * synchronization of the first.\n *\n * We compare on `MerchantUpdateVersion`, the token Qliro echoes back through\n * `onOrderUpdated`, rather than on totals. Totals cannot be the test here: in\n * the modes where Qliro owns the shipping amount our total and Qliro's\n * legitimately differ, and the customer would sit locked out of a checkout\n * that is in fact up to date.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\n\nexport const SYNC_PAYMENT_QLIRO_MUTATION = `\nmutation SyncPaymentQliro($checkoutId: String!) {\n Payment {\n SyncPaymentQliro(checkout_id: $checkoutId) {\n order_id\n update_version\n total_price\n }\n }\n}\n`\n\nexport interface QliroSyncResult {\n order_id: string\n /** Token to wait for in `onOrderUpdated` before unlocking. */\n update_version: string\n total_price: number\n}\n\nexport async function syncPaymentQliro(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<QliroSyncResult | null> {\n const json = await executeCartGraphQL(SYNC_PAYMENT_QLIRO_MUTATION, { checkoutId }, options)\n return (json?.data?.Payment?.SyncPaymentQliro as QliroSyncResult) ?? null\n}\n\n/** The slice of Qliro's `q1` this module uses. */\nexport interface Q1 {\n lock(): void\n unlock(): void\n onCheckoutLoaded(cb: () => void): void\n onOrderUpdated(cb: (order: any) => void): void\n onShippingMethodChanged(cb: (shipping: any) => void): void\n onShippingPriceChanged(cb: (price: number, totalPrice: number) => void): void\n onCustomerInfoChanged(cb: (customer: any) => void): void\n onPaymentMethodChanged(cb: (paymentMethod: any) => void): void\n onPaymentDeclined(cb: (reason: string, message?: string) => void): void\n onSessionExpired(cb: () => void): void\n}\n\nexport type QliroEvent =\n | { type: 'loaded' }\n | { type: 'shipping-changed'; shipping: any }\n | { type: 'shipping-price-changed'; price: number; totalPrice: number }\n | { type: 'customer-changed'; customer: any }\n | { type: 'payment-method-changed'; paymentMethod: any }\n | { type: 'payment-declined'; reason: string; message?: string }\n | { type: 'session-expired' }\n | { type: 'sync-failed'; error: unknown }\n\nexport interface QliroListenerOptions {\n checkoutId: string\n /** Forwarded to the gateway call (sponsor key, endpoint…). */\n queryOptions?: CartQueryOptions\n /** Everything the customer does inside the iframe, for the host UI. */\n onEvent?: (event: QliroEvent) => void\n /**\n * Safety valve. If Qliro never answers a lock with `onOrderUpdated` the\n * customer would be locked out of paying entirely, so the lock is released\n * anyway after this long. Being briefly out of sync is recoverable; a\n * checkout that cannot be completed is not.\n */\n unlockTimeoutMs?: number\n}\n\nconst DEFAULT_UNLOCK_TIMEOUT_MS = 15_000\n\nexport interface QliroController {\n /**\n * Push the current cart onto the Qliro order, holding the widget locked\n * throughout. Resolves once Qliro confirms it is showing this version, or\n * once the safety timeout releases the lock.\n */\n sync(): Promise<QliroSyncResult | null>\n /** Remove the listeners and release any lock still held. */\n destroy(): void\n}\n\n/**\n * Register the listeners and return a handle to synchronize the order.\n *\n * Must be called BEFORE the Qliro snippet is injected: the widget invokes\n * `window.q1Ready` once, as it finishes rendering, and never again.\n */\nexport function installQliroListeners(options: QliroListenerOptions): QliroController {\n const { checkoutId, queryOptions, onEvent } = options\n const unlockTimeoutMs = options.unlockTimeoutMs ?? DEFAULT_UNLOCK_TIMEOUT_MS\n const win = globalThis as any\n\n let q1: Q1 | null = null\n let destroyed = false\n /**\n * The synchronization in flight.\n *\n * Armed BEFORE the server call, not after. Qliro can push `onOrderUpdated`\n * the instant the PUT lands — before our own `await` continuation runs — and\n * an echo that arrives with no waiter registered is an echo lost, leaving\n * the customer locked out until the safety timeout. So echoes seen since\n * the lock are recorded, and matched against the version once we know it.\n */\n let pending: {\n version: string | null\n echoes: Array<string | null>\n resolve: () => void\n timer: any\n } | null = null\n\n const emit = (event: QliroEvent): void => {\n try {\n onEvent?.(event)\n } catch {\n /* a host listener must never break the checkout */\n }\n }\n\n const settle = (): void => {\n if (!pending) return\n clearTimeout(pending.timer)\n const { resolve } = pending\n pending = null\n try {\n q1?.unlock()\n } catch {\n /* the widget may already be gone */\n }\n resolve()\n }\n\n /**\n * Does an echo acknowledge the version we are waiting for?\n *\n * An echo with no version at all counts: orders created before\n * `MerchantUpdateVersion` existed still report updates, and an update is an\n * update. An echo naming a DIFFERENT version does not — that is someone\n * else's synchronization, or an older one of ours.\n */\n const acknowledges = (echo: string | null, version: string | null): boolean => {\n // Our version is not known until the server answers. An echo that arrives\n // before that is kept, not accepted: accepting it would unlock on a stale\n // update that happens to land in the same window.\n if (version === null) return false\n return !echo || echo === version\n }\n\n /** Settle if anything seen since the lock already acknowledged the version. */\n const settleIfAcknowledged = (): void => {\n if (!pending) return\n if (pending.echoes.some((echo) => acknowledges(echo, pending!.version))) {\n settle()\n }\n }\n\n const previousQ1Ready = win.q1Ready\n win.q1Ready = (instance: Q1) => {\n // Another q1Ready may already be installed on the page (a second widget,\n // or the host's own). Chain rather than clobber.\n try {\n previousQ1Ready?.(instance)\n } catch {\n /* not ours to fix */\n }\n if (destroyed) return\n q1 = instance\n\n instance.onCheckoutLoaded(() => emit({ type: 'loaded' }))\n\n instance.onOrderUpdated((order: any) => {\n // Qliro echoes the version once the checkout is actually showing it.\n if (!pending) return\n const echoed: string | null =\n order?.merchantUpdateVersion ?? order?.MerchantUpdateVersion ?? null\n // Recorded even when the version is not known yet — see `pending`.\n pending.echoes.push(echoed)\n settleIfAcknowledged()\n })\n\n // Qliro owns the shipping choice: it is made inside the widget, and Qliro\n // writes the resulting line onto the order itself. These are reported so\n // the host summary can show the same total the customer is looking at —\n // not to overrule the choice.\n instance.onShippingMethodChanged((shipping: any) =>\n emit({ type: 'shipping-changed', shipping }),\n )\n instance.onShippingPriceChanged((price: number, totalPrice: number) =>\n emit({ type: 'shipping-price-changed', price, totalPrice }),\n )\n instance.onCustomerInfoChanged((customer: any) =>\n emit({ type: 'customer-changed', customer }),\n )\n instance.onPaymentMethodChanged((paymentMethod: any) =>\n emit({ type: 'payment-method-changed', paymentMethod }),\n )\n instance.onPaymentDeclined((reason: string, message?: string) =>\n emit({ type: 'payment-declined', reason, message }),\n )\n\n // A checkout session lasts 90 minutes; the order itself lasts 48 hours.\n // Updating the order mints a new session, which is exactly what `sync`\n // does — so the recovery from an expired session is a sync.\n instance.onSessionExpired(() => {\n emit({ type: 'session-expired' })\n void controller.sync()\n })\n }\n\n const controller: QliroController = {\n async sync(): Promise<QliroSyncResult | null> {\n if (destroyed) return null\n // A synchronization already in flight owns the lock; releasing it here\n // would let the customer pay against a half-updated order.\n if (pending) settle()\n\n // Qliro's first rule: lock before touching our server, so the customer\n // cannot complete the purchase mid-synchronization.\n try {\n q1?.lock()\n } catch {\n /* no widget yet — the sync still has to reach the server */\n }\n // Armed before the call so an echo that races the response is caught.\n const settled = new Promise<void>((resolve) => {\n pending = {\n version: null,\n echoes: [],\n resolve,\n timer: setTimeout(settle, unlockTimeoutMs),\n }\n })\n\n let result: QliroSyncResult | null = null\n try {\n result = await syncPaymentQliro(checkoutId, queryOptions)\n } catch (error) {\n emit({ type: 'sync-failed', error })\n settle()\n await settled\n return null\n }\n if (destroyed || !result?.update_version || !q1) {\n settle()\n await settled\n return result\n }\n // Qliro's second rule: unlock only once the orders match.\n if (pending) {\n pending.version = result.update_version\n settleIfAcknowledged()\n }\n await settled\n return result\n },\n\n destroy(): void {\n destroyed = true\n settle()\n if (win.q1Ready) win.q1Ready = previousQ1Ready\n q1 = null\n },\n }\n\n return controller\n}\n","/**\n * Walley (former Collector) — embedded checkout via Vio Commerce.\n *\n * Third embedded provider, same category as Kustom/Qliro: the widget\n * collects address, shipping AND payment by itself.\n *\n * 1. `Payment { CreatePaymentWalley }` initializes the session (sponsor-key\n * authed; the seller's own Walley credentials live server-side, per\n * seller, never here) and returns a SYNTHESIZED html_snippet — Walley's\n * real embed is a `<script data-token>` loader, so shopcart wraps it\n * in the same shape Kustom/Qliro use, and this module reuses their\n * exact script-executing injection.\n * 2. Walley's own script renders the iframe. On completion it dispatches\n * the DOM event `walleyCheckoutPurchaseCompleted` — the PRIMARY success\n * signal, no page reload needed. `redirectPageUri` is registered too\n * (`?checkout_id=…&payment_processor=WALLEY`, same contract as\n * Kustom/Qliro) as a safety net in case the event is missed (tab\n * backgrounded, page reload).\n * 3. Either path re-reads the session (`Payment { GetWalleyOrder }`) BY\n * OWNING CHECKOUT — same as Qliro — and re-renders Walley's own\n * receipt.\n *\n * The Commerce order itself is created server-side by Walley's notification\n * webhook (shopcart /checkout/payment/walley/ok) — the browser never\n * confirms money.\n */\n\nimport { executeCartGraphQL, type CartQueryOptions } from '../../api/cart-queries.js'\nimport { kustomCleanHref, renderKustomSnippet } from './kustom.js'\n\n/** Normalized Walley session (shopcart maps privateId/publicToken/status). */\nexport interface WalleyOrder {\n order_id: string\n /** Walley status: Initialized | CustomerIdentified | CommittedToPurchase | PurchaseCompleted | Aborted. */\n status: string\n html_snippet: string\n public_token?: string\n purchase_country?: string\n purchase_currency?: string\n total_price?: number\n}\n\nexport const CREATE_PAYMENT_WALLEY_MUTATION = `\nmutation CreatePaymentWalley($checkoutId: String!, $countryCode: String!, $href: String!, $email: String) {\n Payment {\n CreatePaymentWalley(checkout_id: $checkoutId, country_code: $countryCode, href: $href, email: $email) {\n order_id\n status\n html_snippet\n public_token\n purchase_country\n purchase_currency\n total_price\n }\n }\n}\n`\n\nexport const GET_WALLEY_ORDER_QUERY = `\nquery GetWalleyOrder($checkoutId: String!) {\n Payment {\n GetWalleyOrder(checkout_id: $checkoutId) {\n order_id\n status\n html_snippet\n public_token\n purchase_country\n purchase_currency\n total_price\n }\n }\n}\n`\n\nexport interface CreatePaymentWalleyVariables extends Record<string, unknown> {\n checkoutId: string\n countryCode: string\n href: string\n email?: string\n}\n\nexport async function createPaymentWalley(\n variables: CreatePaymentWalleyVariables | Record<string, unknown>,\n options?: CartQueryOptions,\n): Promise<WalleyOrder | null> {\n const json = await executeCartGraphQL(CREATE_PAYMENT_WALLEY_MUTATION, variables, options)\n return (json?.data?.Payment?.CreatePaymentWalley as WalleyOrder) ?? null\n}\n\nexport async function getWalleyOrder(\n checkoutId: string,\n options?: CartQueryOptions,\n): Promise<WalleyOrder | null> {\n const json = await executeCartGraphQL(GET_WALLEY_ORDER_QUERY, { checkoutId }, options)\n return (json?.data?.Payment?.GetWalleyOrder as WalleyOrder) ?? null\n}\n\n/** Query-less page URL — shopcart appends ?checkout_id=…&payment_processor=WALLEY. */\nexport const walleyCleanHref = kustomCleanHref\n\n/** Script-executing snippet injection — identical technique to Kustom/Qliro. */\nexport const renderWalleySnippet = renderKustomSnippet\n\n/** Name of the DOM event Walley's own embed script dispatches on success. */\nexport const WALLEY_PURCHASE_COMPLETED_EVENT = 'walleyCheckoutPurchaseCompleted'\n","/**\n * CheckoutManager — orchestrates the checkout flow.\n *\n * Stable contract: open / setAddress / selectPaymentMethod / close.\n * Per-vendor payment integrations plug into the corresponding method:\n * - Apple Pay → `startApplePay()` (Stripe Payment Request, this iteration)\n * - Klarna / Vipps / Card → land in subsequent iterations\n *\n * Dispatches `change` (state changes) and `payment-select` (user picked\n * a method) and `payment-complete` (vendor sheet completed successfully).\n */\n\nimport type { CartLineItem } from '../cart/types.js'\nimport type { CartManager } from '../cart/cart-manager.js'\nimport { Configuration } from '../configuration.js'\nimport {\n checkApplePayAvailability,\n prepareApplePay,\n preloadStripeJs,\n showApplePaySheet,\n type ApplePayResult,\n} from './payments/apple-pay.js'\nimport {\n cleanUrlParams,\n isKlarnaAvailable,\n listenForKlarnaCompletion,\n mountKlarnaExpressButton,\n readKlarnaTokenFromUrl,\n type KlarnaAuthorizeResult,\n type KlarnaButtonHandle,\n type KlarnaLineItem,\n type KlarnaPaymentRequestData,\n} from './payments/klarna.js'\nimport {\n createKlarnaPaymentsWidget,\n isKlarnaPaymentsAvailable,\n type KlarnaPaymentsCategory,\n} from './payments/klarna-payments.js'\nimport {\n createPaymentVipps as gqlCreatePaymentVipps,\n getVippsStatus as gqlGetVippsStatus,\n} from './payments/vipps.js'\nimport {\n createPaymentKustom as gqlCreatePaymentKustom,\n getKustomOrder as gqlGetKustomOrder,\n kustomCleanHref,\n renderKustomSnippet,\n type KustomOrder,\n} from './payments/kustom.js'\nimport {\n createPaymentQliro as gqlCreatePaymentQliro,\n readVioTheme,\n getQliroOrder as gqlGetQliroOrder,\n type QliroOrder,\n} from './payments/qliro.js'\nimport {\n installQliroListeners,\n type QliroController,\n type QliroEvent,\n type QliroSyncResult,\n} from './payments/qliro-sync.js'\nimport {\n createPaymentWalley as gqlCreatePaymentWalley,\n getWalleyOrder as gqlGetWalleyOrder,\n WALLEY_PURCHASE_COMPLETED_EVENT,\n type WalleyOrder,\n} from './payments/walley.js'\nimport {\n confirmPaymentApplePay as gqlConfirmPaymentApplePay,\n createCheckout as gqlCreateCheckout,\n createPaymentApplePay as gqlCreatePaymentApplePay,\n createPaymentStripe as gqlCreatePaymentStripe,\n executeCartGraphQL,\n getAvailablePaymentMethods as gqlGetAvailablePaymentMethods,\n getCartGraphQLOptions,\n getCheckout as gqlGetCheckout,\n getLineItemsBySupplier as gqlGetLineItemsBySupplier,\n updateCheckout as gqlUpdateCheckout,\n updateShippingsBySupplier as gqlUpdateShippingsBySupplier,\n type CartQueryOptions,\n} from '../api/cart-queries.js'\nimport { getGlobalCountryCode, getGlobalCurrency, getGlobalLocale } from '../types.js'\n\n/**\n * Best-effort human-readable string for an unknown thrown/rejected value.\n * Klarna's SDK rejects with plain objects, so `String(err)` would collapse to\n * \"[object Object]\"; we pull a known message field or JSON-serialise so the\n * real reason stays visible.\n */\nfunction describeError(err: unknown): string {\n if (err instanceof Error) return err.message\n if (typeof err === 'string') return err\n if (err && typeof err === 'object') {\n const o = err as Record<string, unknown>\n for (const k of ['message', 'error', 'reason', 'description']) {\n if (typeof o[k] === 'string' && o[k]) return o[k] as string\n }\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n }\n return String(err)\n}\n\n/** sessionStorage key for a pending Klarna purchase (survives redirect). */\nconst KLARNA_PENDING_KEY = 'vio.klarna.pending.v1'\n\ninterface KlarnaPendingContext {\n sponsorId: number\n currency: string\n orderAmount: number\n orderLines: Array<{\n name: string\n quantity: number\n unit_price: number\n total_amount: number\n reference?: string\n /** Klarna line type, e.g. \"shipping_fee\". */\n type?: string\n }>\n /** Backend checkout id (native GraphQL flow). */\n checkoutId?: string\n /** Klarna Payments session id (native GraphQL flow). */\n sessionId?: string\n /** Klarna Payments client token (native GraphQL flow). */\n clientToken?: string\n}\n\n/** A shipping option offered in the checkout. `price` in minor units (øre). */\nexport interface KlarnaShippingOption {\n id: string\n method: string\n description: string\n price: number\n tax_amount: number\n tax_rate: number\n preselected: boolean\n /** Backend supplier the option belongs to (server-side shippings). */\n supplierId?: string\n /** Display name from the backend (mirror of `method`). */\n name?: string\n country_code?: string\n /** Price in MAJOR units, as delivered by the backend. */\n priceMajor?: number\n currency?: string\n}\n\n/**\n * Shipping options offered for express purchases. Amounts in minor units (øre).\n * The chosen one is added to the order total + as a `shipping_fee` line so the\n * Klarna order reconciles. (Klarna Payments doesn't render a shipping picker —\n * KCO/KSA would, but the account isn't provisioned — so the picker is ours.)\n */\nexport const KLARNA_SHIPPING_OPTIONS: KlarnaShippingOption[] = [\n {\n id: 'standard',\n method: 'Standard',\n description: '3–5 virkedager',\n price: 4900,\n tax_amount: 0,\n tax_rate: 0,\n preselected: true,\n },\n {\n id: 'express',\n method: 'Express',\n description: '1–2 virkedager',\n price: 9900,\n tax_amount: 0,\n tax_rate: 0,\n preselected: false,\n },\n]\nimport type { CheckoutAddress, CheckoutState, PaymentMethod } from './types.js'\n\n// MARK: - Klarna native (Vio Commerce GraphQL Payment mutations)\n\nconst CREATE_PAYMENT_KLARNA_NATIVE_MUTATION = `\nmutation CreatePaymentKlarnaNative($checkoutId: String!, $countryCode: String, $currency: String, $locale: String, $returnUrl: String, $intent: String, $customer: KlarnaNativeCustomerInput, $billingAddress: KlarnaNativeAddressInput, $shippingAddress: KlarnaNativeAddressInput, $autoCapture: Boolean) {\n Payment {\n CreatePaymentKlarnaNative(checkout_id: $checkoutId, country_code: $countryCode, currency: $currency, locale: $locale, return_url: $returnUrl, intent: $intent, customer: $customer, billing_address: $billingAddress, shipping_address: $shippingAddress, auto_capture: $autoCapture) {\n client_token\n session_id\n purchase_country\n purchase_currency\n cart_id\n checkout_id\n payment_method_categories {\n identifier\n name\n asset_urls {\n descriptive\n standard\n }\n }\n }\n }\n}\n`\n\nconst CONFIRM_PAYMENT_KLARNA_NATIVE_MUTATION = `\nmutation ConfirmPaymentKlarnaNative($checkoutId: String!, $authorizationToken: String!, $autoCapture: Boolean, $billingAddress: KlarnaNativeAddressInput, $shippingAddress: KlarnaNativeAddressInput, $customer: KlarnaNativeCustomerInput) {\n Payment {\n ConfirmPaymentKlarnaNative(checkout_id: $checkoutId, authorization_token: $authorizationToken, auto_capture: $autoCapture, billing_address: $billingAddress, shipping_address: $shippingAddress, customer: $customer) {\n order_id\n checkout_id\n fraud_status\n order {\n order_id\n status\n purchase_country\n purchase_currency\n locale\n billing_address {\n given_name\n family_name\n email\n street_address\n postal_code\n city\n country\n }\n shipping_address {\n given_name\n family_name\n email\n street_address\n postal_code\n city\n country\n }\n order_amount\n order_tax_amount\n total_line_items_price\n order_lines {\n type\n name\n quantity\n unit_price\n tax_rate\n total_amount\n total_discount_amount\n total_tax_amount\n merchant_data\n }\n merchant_urls {\n terms\n checkout\n confirmation\n push\n }\n html_snippet\n started_at\n last_modified_at\n options {\n allow_separate_shipping_address\n date_of_birth_mandatory\n require_validate_callback_success\n phone_mandatory\n auto_capture\n }\n shipping_options {\n id\n name\n price\n tax_amount\n tax_rate\n preselected\n }\n merchant_data\n selected_shipping_option {\n id\n name\n price\n tax_amount\n tax_rate\n preselected\n }\n }\n }\n }\n}\n`\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nfunction buildKlarnaCustomer(address: any): Record<string, unknown> | null {\n if (!address) return null\n return {\n dob: address.dob || address.date_of_birth || null,\n email: address.email || null,\n organization_registration_id:\n address.organization_registration_id || address.org_id || null,\n phone: address.phone || address.telephone || null,\n type: address.type || 'person',\n }\n}\n\nfunction buildKlarnaAddress(address: any): Record<string, unknown> | null {\n if (!address) return null\n return {\n city: address.city || null,\n country: address.country || address.countryCode || getGlobalCountryCode(),\n email: address.email || null,\n family_name:\n address.familyName || address.family_name || address.last_name || address.lastName || null,\n given_name:\n address.givenName || address.given_name || address.first_name || address.firstName || null,\n phone: address.phone || null,\n postal_code: address.postalCode || address.postal_code || address.zip || null,\n region: address.region || address.state || null,\n street_address:\n address.streetAddress ||\n address.street_address ||\n address.address1 ||\n address.street ||\n address.address || // CheckoutAddress uses plain `address` for the street\n null,\n // street_address2 intentionally omitted — the KlarnaNativeAddressInput\n // backend type rejects it.\n }\n}\n\n/** Map any address-ish object to the backend checkout address input shape. */\nfunction buildCheckoutAddress(address: any): Record<string, unknown> | null {\n if (!address) return null\n const firstName =\n address.firstName || address.first_name || address.givenName || address.given_name || null\n const lastName =\n address.lastName || address.last_name || address.familyName || address.family_name || null\n const address1 =\n address.address || address.address1 || address.street || address.street_address || null\n const city = address.city || null\n const zip = address.postalCode || address.postal_code || address.zip || null\n const country_code = address.countryCode || address.country_code || address.country || getGlobalCountryCode()\n\n if (!firstName && !lastName && !address1 && !city && !zip) return null\n\n return {\n first_name: firstName,\n last_name: lastName,\n address1: address1,\n city: city,\n zip: zip,\n country_code: country_code,\n }\n}\n\n/**\n * Klarna/Stripe/Vipps require an https return_url — normalise whatever the\n * page has, optionally appending query params (used to detect the redirect\n * return and show the confirmation).\n */\nfunction resolveHttpsReturnUrl(\n overrideUrl?: string | null,\n params: Record<string, unknown> | null = null,\n): string {\n let url = overrideUrl ?? undefined\n if (!url && typeof window !== 'undefined' && window.location) {\n url = window.location.href\n }\n if (!url || typeof url !== 'string' || url.startsWith('about:') || url.startsWith('file:')) {\n url = 'https://vev.design/checkout/confirmation'\n }\n if (url.startsWith('http://')) {\n url = 'https://' + url.slice(7)\n } else if (!url.startsWith('https://')) {\n url = 'https://' + url.replace(/^[a-zA-Z]+:\\/\\//, '')\n }\n\n if (params && typeof params === 'object') {\n try {\n const parsed = new URL(url)\n Object.keys(params).forEach((k) => {\n if (params[k] !== undefined && params[k] !== null) {\n parsed.searchParams.set(k, String(params[k]))\n }\n })\n return parsed.toString()\n } catch {\n const queryStr = Object.keys(params)\n .filter((k) => params[k] !== undefined && params[k] !== null)\n .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(params[k]))}`)\n .join('&')\n if (queryStr) {\n url += (url.includes('?') ? '&' : '?') + queryStr\n }\n }\n }\n\n return url\n}\n\n/** Execute a Payment.* mutation with the sponsor's commerce key. */\nasync function executeKlarnaGraphQL(\n query: string,\n variables: Record<string, unknown>,\n sponsorId?: number,\n): Promise<any> {\n return executeCartGraphQL(query, variables, await getCartGraphQLOptions(sponsorId))\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nexport interface CheckoutChangeDetail {\n state: CheckoutState | null\n}\n\nexport interface PaymentSelectDetail {\n method: PaymentMethod\n state: CheckoutState\n}\n\nexport interface PaymentCompleteDetail {\n method: PaymentMethod\n state: CheckoutState\n result: ApplePayResult | KlarnaAuthorizeResult | unknown\n}\n\nexport interface PaymentErrorDetail {\n method: PaymentMethod\n error: string\n}\n\n/** Handle for the Klarna Payments (classic widget) flow. */\nexport interface KlarnaPaymentsHandle {\n /** Categories offered by the session (pay_now / pay_later / pay_over_time). */\n categories: KlarnaPaymentsCategory[]\n /** Shipping options in effect (backend per-supplier, or the static fallback). */\n shippings: KlarnaShippingOption[]\n /** Currently selected category. */\n readonly selected: string\n /** (Re)load the widget for a category. */\n load(category?: string): Promise<{ showForm: boolean }>\n /** Authorize a category (defaults to whatever's currently selected) and,\n * on approval, create the order. */\n authorize(category?: string): Promise<void>\n /** Tear down the mounted widget. */\n unmount(): void\n}\n\nexport class CheckoutManager extends EventTarget {\n private state: CheckoutState | null = null\n private applePayAvailableCache: boolean | null = null\n\n /** Gateway hints learned from CreatePaymentApplePay (per session). The\n * backend's gateway_merchant_id may be a publishable key (pk_…) or a Stripe\n * Connect account (acct_…) — stored defensively by prefix. */\n private applePayPublishableKey: string | null = null\n private applePayConnectedAccount: string | null = null\n private klarnaAvailableCache: boolean | null = null\n /** Live q1 listeners while a Qliro widget is mounted. */\n private qliroController: QliroController | null = null\n private klarnaOrderInFlight = false\n /** Last backend shippings fetched (per-supplier), for UI reuse. */\n private lastFetchedShippings: KlarnaShippingOption[] = []\n /** Per-sponsor payment methods cache + in-flight dedupe. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private paymentMethodsCache = new Map<number, any>()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private paymentMethodsPromises = new Map<number, Promise<any>>()\n\n constructor(private readonly cartManager: CartManager) {\n super()\n // Warm Stripe.js early: Apple Pay's sheet must open synchronously inside\n // the tap gesture, so the library can't be lazy-loaded at click time.\n preloadStripeJs()\n }\n\n open(sponsorId: number): CheckoutState {\n const cart = this.cartManager.getCart(sponsorId)\n if (!cart || cart.items.length === 0) {\n throw new Error(`[VioCheckout] sponsor ${sponsorId} has no cart items`)\n }\n this.state = {\n sponsorId,\n subtotal: this.cartManager.subtotalForSponsor(sponsorId),\n // Page-level currency wins over whatever the persisted cart carries —\n // the host may have switched currency since the cart was created.\n currency: getGlobalCurrency(),\n }\n this.emit()\n return this.state\n }\n\n close(): void {\n this.state = null\n this.applePayAvailableCache = null\n this.klarnaAvailableCache = null\n this.emit()\n }\n\n // MARK: - Backend checkout (Vio Commerce GraphQL)\n\n /* eslint-disable @typescript-eslint/no-explicit-any */\n\n /** Create the backend checkout for the sponsor's cart (auto-accepts terms). */\n async createCheckout(sponsorId: number): Promise<any> {\n const cart = this.cartManager.getCart(sponsorId)\n let cartId = cart?.cartId\n if (!cartId) {\n cartId = await this.cartManager.ensureCartId(sponsorId, cart?.currency)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${sponsorId}`)\n }\n }\n const opts = await getCartGraphQLOptions(sponsorId)\n const checkout = await gqlCreateCheckout(cartId, opts)\n if (checkout?.id) {\n this.state = {\n ...(this.state ?? { sponsorId, subtotal: 0, currency: getGlobalCurrency() }),\n sponsorId,\n checkoutId: checkout.id,\n checkout,\n }\n this.emit()\n try {\n const updated = await gqlUpdateCheckout(\n {\n checkoutId: checkout.id,\n buyerAcceptsPurchaseConditions: true,\n buyerAcceptsTermsConditions: true,\n },\n opts,\n )\n if (updated?.id) {\n this.state = { ...this.state, checkout: updated }\n this.emit()\n return updated\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] Failed to auto-accept terms & purchase conditions:', err)\n }\n }\n }\n return checkout\n }\n\n /** Update the backend checkout (terms are re-asserted unless overridden). */\n async updateCheckout(variables: Record<string, unknown>, sponsorId?: number): Promise<any> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n const fullVars = {\n buyerAcceptsPurchaseConditions: true,\n buyerAcceptsTermsConditions: true,\n ...variables,\n }\n const updated = await gqlUpdateCheckout(fullVars, opts)\n if (updated?.id && this.state) {\n this.state = { ...this.state, checkoutId: updated.id, checkout: updated }\n this.emit()\n }\n return updated\n }\n\n async getCheckout(checkoutId: string, sponsorId?: number): Promise<any> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetCheckout(checkoutId, opts)\n }\n\n /**\n * Payment methods enabled for the sponsor (backend-configured). Memoised per\n * sponsor with in-flight dedupe — several UI components ask on every open.\n */\n async getAvailablePaymentMethods(sponsorId?: number): Promise<any> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) return null\n\n if (this.paymentMethodsCache.has(spId)) {\n return this.paymentMethodsCache.get(spId)\n }\n const inFlight = this.paymentMethodsPromises.get(spId)\n if (inFlight) return inFlight\n\n const promise = (async () => {\n try {\n const opts = await getCartGraphQLOptions(spId)\n const res = await gqlGetAvailablePaymentMethods(opts)\n // Never cache empty/failed responses — a transient blip would freeze\n // the payment grid for the whole page session.\n if (res) this.paymentMethodsCache.set(spId, res)\n return res\n } finally {\n this.paymentMethodsPromises.delete(spId)\n }\n })()\n\n this.paymentMethodsPromises.set(spId, promise)\n return promise\n }\n\n clearPaymentMethodsCache(): void {\n this.paymentMethodsCache.clear()\n this.paymentMethodsPromises.clear()\n }\n\n /**\n * Real shipping options from the backend cart (per supplier), mapped to the\n * KlarnaShippingOption shape (minor units). Empty array on failure/no\n * options — Klarna callers use that as-is (no static fallback anymore, see\n * 2026-08-18: it only ever papered over a race, now fixed via\n * `waitForCartMutations`). `KLARNA_SHIPPING_OPTIONS` is still used\n * separately by Apple Pay's synchronous sheet setup, which can't await\n * this at all.\n */\n async fetchAvailableShippings(sponsorId?: number): Promise<KlarnaShippingOption[]> {\n try {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) return []\n // A quick add-then-checkout can race an in-flight AddItem — wait for it\n // to settle so this reads the cart it actually produced, not a stale\n // pre-add snapshot (Alan, 2026-08-18: shippings came back empty this way).\n await this.cartManager.waitForCartMutations(spId)\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) {\n cartId = await this.cartManager.ensureCartId(spId)\n }\n if (!cartId) return []\n const opts = await getCartGraphQLOptions(spId)\n const supplierGroups = await gqlGetLineItemsBySupplier(cartId, opts)\n const firstGroup = Array.isArray(supplierGroups) ? supplierGroups[0] : null\n const shippings = firstGroup?.available_shippings ?? []\n if (Array.isArray(shippings) && shippings.length > 0) {\n const supplierId = firstGroup?.supplier?.id\n const mapped: KlarnaShippingOption[] = shippings.map((s: any, idx: number) => {\n const priceObj = s.price ?? {}\n const amount =\n typeof priceObj.amount_incl_taxes === 'number'\n ? priceObj.amount_incl_taxes\n : typeof priceObj.amount === 'number'\n ? priceObj.amount\n : 0\n return {\n id: String(s.id),\n supplierId: supplierId != null ? String(supplierId) : undefined,\n method: s.name || 'Default Shipping',\n name: s.name || 'Default Shipping',\n description: s.description || '',\n country_code: s.country_code || 'NO',\n price: Math.round(amount * 100),\n priceMajor: amount,\n currency: priceObj.currency_code || getGlobalCurrency(),\n tax_amount: Math.round((priceObj.tax_amount ?? 0) * 100),\n tax_rate: Math.round((priceObj.tax_rate ?? 0) * 100),\n preselected: idx === 0,\n }\n })\n this.lastFetchedShippings = mapped\n return mapped\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] fetchAvailableShippings failed:', err)\n }\n }\n return []\n }\n\n /** Set the chosen shipping per supplier on the backend cart. */\n async updateShippingsBySupplier(\n data: Array<{ shipping_id: string; supplier_id: number }>,\n sponsorId?: number,\n ): Promise<any> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) return null\n const cart = this.cartManager.getCart(spId)\n if (!cart?.cartId) return null\n const opts = await getCartGraphQLOptions(spId)\n const updated = await gqlUpdateShippingsBySupplier(cart.cartId, data, opts)\n if (updated) {\n this.cartManager.updateFromBackendCart(spId, updated)\n }\n return updated\n }\n\n /**\n * Shared setup for the redirect payment links (Stripe / Vipps): ensure the\n * backend cart + checkout exist, push email/address onto the checkout, and\n * return everything the payment mutation needs.\n */\n private async prepareRedirectPayment(\n sponsorId: number | undefined,\n formData: unknown,\n extraUpdateVars: Record<string, unknown> = {},\n ): Promise<{ spId: number; checkoutId: string; emailVal: string; opts: CartQueryOptions }> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for payment')\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) {\n cartId = await this.cartManager.ensureCartId(spId)\n }\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n\n const opts = await getCartGraphQLOptions(spId)\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n const checkoutRes = await gqlCreateCheckout(cartId, opts)\n checkoutId = checkoutRes?.id\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout — cannot start the payment')\n }\n\n // Vipps collects the address in its own flow — never push one onto the\n // checkout for it (the backend rejects partial Vipps addresses).\n const isVipps = extraUpdateVars?.paymentMethod === 'Vipps'\n const addr =\n typeof formData === 'object' && formData !== null ? formData : this.state?.address\n const addressObj = !isVipps ? buildCheckoutAddress(addr) : null\n const emailVal =\n (typeof formData === 'string'\n ? formData\n : (formData as { email?: string } | undefined)?.email) ||\n this.state?.address?.email ||\n ''\n if (!emailVal || !emailVal.includes('@')) {\n // Never mint a payment link with a fabricated email — the order's\n // receipt/contact would be wrong forever.\n throw new Error('[CheckoutManager] email is required to start the payment')\n }\n\n const updateVars: Record<string, unknown> = {\n checkoutId,\n email: emailVal,\n buyerAcceptsPurchaseConditions: true,\n buyerAcceptsTermsConditions: true,\n ...extraUpdateVars,\n }\n if (addressObj) {\n updateVars.shippingAddress = addressObj\n updateVars.billingAddress = addressObj\n }\n\n try {\n const updated = await gqlUpdateCheckout(updateVars, opts)\n if (updated?.id) {\n this.state = {\n ...(this.state ?? { sponsorId: spId, subtotal: 0, currency: getGlobalCurrency() }),\n sponsorId: spId,\n checkoutId: updated.id,\n checkout: updated,\n }\n this.emit()\n checkoutId = updated.id\n }\n } catch (err) {\n // Redirecting after a failed UpdateCheckout would charge with a stale\n // (or missing) address/email — abort instead.\n throw new Error(\n `[CheckoutManager] could not persist checkout details: ${describeError(err)}`,\n )\n }\n\n // (Narrowing: the assignment inside the try widens the type again.)\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout — cannot start the payment')\n }\n return { spId, checkoutId, emailVal, opts }\n }\n\n /** Redirect the top window to a payment provider URL. */\n private static redirectTo(url: string): void {\n if (typeof window === 'undefined') return\n try {\n if (window.top && window.top !== window) {\n window.top.location.href = url\n } else {\n window.location.href = url\n }\n } catch {\n window.open(url, '_top') || window.open(url, '_blank')\n }\n }\n\n /**\n * Stripe payment link: create/refresh the backend checkout, mint the Stripe\n * Checkout URL (CreatePaymentStripe) and redirect. The return URL carries\n * vio_payment/vio_method/checkout_id so the page can show the confirmation.\n */\n async startStripePayment(sponsorId?: number, formData?: unknown): Promise<any> {\n const { spId, checkoutId, emailVal, opts } = await this.prepareRedirectPayment(\n sponsorId,\n formData,\n { paymentMethod: 'Stripe' },\n )\n const successUrl = resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'stripe',\n vio_sponsor: spId,\n checkout_id: checkoutId,\n })\n const stripeRes = await gqlCreatePaymentStripe(\n { checkoutId, successUrl, paymentMethod: 'Stripe', email: emailVal },\n opts,\n )\n if (stripeRes?.checkout_url) {\n CheckoutManager.redirectTo(stripeRes.checkout_url)\n return stripeRes\n }\n throw new Error('Stripe payment link generation failed: missing checkout_url')\n }\n\n /**\n * Vipps payment link: same flow as Stripe — CreatePaymentVipps → redirect to\n * payment_url.\n */\n async startVippsPayment(sponsorId?: number, formData?: unknown): Promise<any> {\n const { spId, checkoutId, emailVal, opts } = await this.prepareRedirectPayment(\n sponsorId,\n formData,\n { paymentMethod: 'Vipps' },\n )\n const returnUrl = resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'vipps',\n vio_sponsor: spId,\n checkout_id: checkoutId,\n })\n const vippsRes = await gqlCreatePaymentVipps(\n { checkoutId, email: emailVal, returnUrl },\n opts,\n )\n if (vippsRes?.payment_url) {\n CheckoutManager.redirectTo(vippsRes.payment_url)\n return vippsRes\n }\n throw new Error('Vipps payment link generation failed: missing payment_url')\n }\n\n /** Vipps' own payment state for the checkout — see getVippsStatus in\n * cart-queries.ts for why this exists instead of trusting GetCheckout. */\n async getVippsStatus(checkoutId: string, sponsorId?: number): Promise<{ state?: string } | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetVippsStatus({ checkoutId }, opts)\n }\n\n /**\n * Kustom (former Klarna Checkout) — create the KCO order via Vio Commerce\n * and render its html_snippet into `container`. The widget collects\n * address, shipping and payment by itself; the SDK renders nothing else.\n */\n async mountKustomCheckout(\n container: HTMLElement,\n sponsorId?: number,\n ): Promise<KustomOrder> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for Kustom')\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) cartId = await this.cartManager.ensureCartId(spId)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n const opts = await getCartGraphQLOptions(spId)\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n // createCheckout(), NOT the raw mutation: shopcart refuses to start a\n // payment on a checkout whose buyer has not accepted the purchase\n // conditions (\"Is required that customer accepted purchase conditions\"),\n // and that acceptance is part of createCheckout(). Creating it raw here\n // made every embedded method fail whenever IT was the one to create the\n // checkout — which is the normal path when the shopper picks the method\n // straight from the cart.\n const checkoutRes = await this.createCheckout(spId)\n checkoutId = checkoutRes?.id\n if (checkoutId && this.state) {\n this.state = { ...this.state, checkoutId }\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Kustom order')\n }\n // href MUST be query-less: shopcart appends ?order_id=…&payment_processor=KUSTOM\n const href = kustomCleanHref()\n const order = await gqlCreatePaymentKustom(\n {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n href,\n email: this.state?.address?.email || undefined,\n },\n opts,\n )\n if (!order?.html_snippet) {\n throw new Error('Kustom order creation failed: missing html_snippet')\n }\n renderKustomSnippet(container, order.html_snippet)\n return order\n }\n\n /** Re-read a Kustom order — used on the confirmation return trip. */\n async getKustomOrder(orderId: string, sponsorId?: number): Promise<KustomOrder | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetKustomOrder(orderId, opts)\n }\n\n /** Render a Kustom html_snippet (e.g. the confirmation receipt) into a container. */\n renderKustomSnippet(container: HTMLElement, htmlSnippet: string): void {\n renderKustomSnippet(container, htmlSnippet)\n }\n\n /**\n * Qliro Checkout — create the order via Vio Commerce and render its\n * html_snippet into `container` (widget-does-everything, like Kustom).\n */\n async mountQliroCheckout(\n container: HTMLElement,\n sponsorId?: number,\n ): Promise<QliroOrder> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for Qliro')\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) cartId = await this.cartManager.ensureCartId(spId)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n const opts = await getCartGraphQLOptions(spId)\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n // createCheckout(), NOT the raw mutation: shopcart refuses to start a\n // payment on a checkout whose buyer has not accepted the purchase\n // conditions (\"Is required that customer accepted purchase conditions\"),\n // and that acceptance is part of createCheckout(). Creating it raw here\n // made every embedded method fail whenever IT was the one to create the\n // checkout — which is the normal path when the shopper picks the method\n // straight from the cart.\n const checkoutRes = await this.createCheckout(spId)\n checkoutId = checkoutRes?.id\n if (checkoutId && this.state) {\n this.state = { ...this.state, checkoutId }\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Qliro order')\n }\n // href MUST be query-less: shopcart appends ?checkout_id=…&payment_processor=QLIRO\n const href = kustomCleanHref()\n const order = await gqlCreatePaymentQliro(\n {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n href,\n email: this.state?.address?.email || undefined,\n // Qliro cannot be restyled once rendered, so the host page's theme has\n // to travel with the order.\n theme: readVioTheme(),\n },\n opts,\n )\n if (!order?.html_snippet) {\n throw new Error('Qliro order creation failed: missing html_snippet')\n }\n // BEFORE the snippet: Qliro calls `window.q1Ready` once, as the widget\n // finishes rendering, and never again. Installed after the injection, the\n // listeners would simply never fire.\n this.qliroController?.destroy()\n this.qliroController = installQliroListeners({\n checkoutId,\n queryOptions: opts,\n onEvent: (event) => this.onQliroEvent(event),\n })\n renderKustomSnippet(container, order.html_snippet)\n return order\n }\n\n /**\n * Everything the customer does inside the Qliro iframe, re-published as a\n * DOM event so a host page can follow a checkout it cannot see into.\n */\n private onQliroEvent(event: QliroEvent): void {\n this.dispatchEvent(\n new CustomEvent<QliroEvent>('qliro-event', {\n detail: event,\n bubbles: true,\n composed: true,\n }),\n )\n // Qliro owns the shipping choice — this only keeps our own summary\n // showing the same total the customer is looking at.\n if (event.type === 'shipping-changed' || event.type === 'shipping-price-changed') {\n this.emit()\n }\n }\n\n /**\n * Push the current cart onto the open Qliro order.\n *\n * Call it after changing the cart while the widget is open: it holds\n * `q1.lock()` across the round trip and unlocks once Qliro confirms it is\n * showing the new version. A no-op when no Qliro widget is mounted.\n */\n async syncQliroOrder(): Promise<QliroSyncResult | null> {\n return (await this.qliroController?.sync()) ?? null\n }\n\n /** Drop the Qliro listeners and release any lock still held. */\n destroyQliroListeners(): void {\n this.qliroController?.destroy()\n this.qliroController = null\n }\n\n /** Re-read the Qliro order owned by a checkout — the confirmation trip. */\n async getQliroOrder(checkoutId: string, sponsorId?: number): Promise<QliroOrder | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetQliroOrder(checkoutId, opts)\n }\n\n /**\n * Mount the Walley embedded checkout. `onPurchaseCompleted` fires as soon\n * as Walley's own script dispatches its success event INSIDE the widget —\n * no redirect needed. `getWalleyOrder`/the confirmation-URL fallback\n * remain for the case the event is missed (tab backgrounded, reload).\n */\n async mountWalleyCheckout(\n container: HTMLElement,\n sponsorId?: number,\n onPurchaseCompleted?: (order: WalleyOrder) => void,\n ): Promise<WalleyOrder> {\n const spId = sponsorId ?? this.state?.sponsorId\n if (!spId) throw new Error('[CheckoutManager] no sponsor for Walley')\n const cart = this.cartManager.getCart(spId)\n let cartId = cart?.cartId\n if (!cartId) cartId = await this.cartManager.ensureCartId(spId)\n if (!cartId) {\n throw new Error(`[CheckoutManager] Failed to obtain cart_id for sponsor ${spId}`)\n }\n const opts = await getCartGraphQLOptions(spId)\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n // createCheckout(), NOT the raw mutation: shopcart refuses to start a\n // payment on a checkout whose buyer has not accepted the purchase\n // conditions (\"Is required that customer accepted purchase conditions\"),\n // and that acceptance is part of createCheckout(). Creating it raw here\n // made every embedded method fail whenever IT was the one to create the\n // checkout — which is the normal path when the shopper picks the method\n // straight from the cart.\n const checkoutRes = await this.createCheckout(spId)\n checkoutId = checkoutRes?.id\n if (checkoutId && this.state) {\n this.state = { ...this.state, checkoutId }\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Walley order')\n }\n // href MUST be query-less: shopcart appends ?checkout_id=…&payment_processor=WALLEY\n const href = kustomCleanHref()\n const order = await gqlCreatePaymentWalley(\n {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n href,\n email: this.state?.address?.email || undefined,\n },\n opts,\n )\n if (!order?.html_snippet) {\n throw new Error('Walley order creation failed: missing html_snippet')\n }\n renderKustomSnippet(container, order.html_snippet)\n if (onPurchaseCompleted) {\n const handler = () => {\n document.removeEventListener(WALLEY_PURCHASE_COMPLETED_EVENT, handler)\n onPurchaseCompleted(order)\n }\n document.addEventListener(WALLEY_PURCHASE_COMPLETED_EVENT, handler, { once: true })\n }\n return order\n }\n\n /** Re-read the Walley session owned by a checkout — the confirmation trip. */\n async getWalleyOrder(checkoutId: string, sponsorId?: number): Promise<WalleyOrder | null> {\n const opts = await getCartGraphQLOptions(sponsorId ?? this.state?.sponsorId)\n return gqlGetWalleyOrder(checkoutId, opts)\n }\n\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n setAddress(address: CheckoutAddress): void {\n if (!this.state) return\n // Immutable update — a fresh object reference so reactive UIs (Lit\n // `@state`, which compares by identity) actually re-render.\n this.state = { ...this.state, address }\n this.emit()\n }\n\n selectPaymentMethod(method: PaymentMethod): void {\n if (!this.state) return\n // New reference (see setAddress) so the selection re-renders.\n this.state = { ...this.state, paymentMethod: method }\n this.emit()\n this.dispatchEvent(\n new CustomEvent<PaymentSelectDetail>('payment-select', {\n detail: { method, state: this.state },\n }),\n )\n }\n\n // MARK: - Apple Pay (Stripe Payment Request)\n\n /**\n * The Stripe publishable key for a sponsor, taken from its own commerce\n * channel (`GetAvailablePaymentMethods` → Stripe → config.publishableKey).\n *\n * The channel is the right source: the key belongs to the brand's Stripe\n * account, so two brands on one page each get theirs, and a host never has\n * to configure it. `Vio.init({ stripePublishableKey })` still wins when set,\n * which keeps existing integrations working and allows an override.\n */\n private async resolveStripePublishableKey(sponsorId?: number): Promise<string> {\n const cfg = Configuration.isInitialized ? Configuration.get() : null\n if (cfg?.stripePublishableKey) return cfg.stripePublishableKey\n if (this.applePayPublishableKey) return this.applePayPublishableKey\n try {\n // Memoised per sponsor upstream, so this is cheap on repeat calls.\n const methods = await this.getAvailablePaymentMethods(sponsorId)\n const stripe = (methods as Array<{ name?: string; config?: Array<{ name?: string; value?: string }> }> | null)\n ?.find((m) => String(m?.name ?? '').toLowerCase() === 'stripe')\n const key = stripe?.config?.find((c) => c?.name === 'publishableKey')?.value\n if (typeof key === 'string' && key.startsWith('pk_')) {\n this.applePayPublishableKey = key\n return key\n }\n } catch {\n /* channel unreachable — treat as \"no Apple Pay\", never throw */\n }\n return ''\n }\n\n /**\n * Returns true if Apple Pay can be shown on this device + Stripe config.\n * Result is memoised — call `clearApplePayCache()` if config changes.\n */\n async isApplePayAvailable(country = 'NO'): Promise<boolean> {\n if (this.applePayAvailableCache !== null) return this.applePayAvailableCache\n const publishableKey = await this.resolveStripePublishableKey(this.state?.sponsorId)\n if (!publishableKey || !this.state) {\n this.applePayAvailableCache = false\n return false\n }\n const amount = toSmallestUnit(this.state.subtotal, this.state.currency)\n const available = await checkApplePayAvailability({\n publishableKey,\n connectedAccount: this.findStripeConnectAccount() ?? undefined,\n amount,\n currency: this.state.currency,\n country,\n label: 'Vio',\n })\n this.applePayAvailableCache = available\n return available\n }\n\n clearApplePayCache(): void {\n this.applePayAvailableCache = null\n }\n\n /**\n * Prepare Apple Pay for the product-page express button (no active checkout\n * needed). Pre-creates the Stripe PaymentRequest + resolves canMakePayment so\n * the returned `show()` can fire synchronously inside the tap (Apple blocks\n * the sheet if `show()` is reached after an await). `show()` resolves the\n * sheet, then dispatches `payment-complete` (→ confirmation) or\n * `payment-error`. `available` is true only when Apple Pay will actually work.\n */\n async prepareApplePayFor(\n amount: number,\n currency: string,\n country = 'NO',\n ): Promise<{ available: boolean; show: () => Promise<void> }> {\n const publishableKey = await this.resolveStripePublishableKey(this.state?.sponsorId)\n if (!publishableKey) return { available: false, show: async () => {} }\n const prepared = await prepareApplePay({\n publishableKey,\n connectedAccount:\n this.applePayConnectedAccount ?? this.findStripeConnectAccount() ?? undefined,\n amount: toSmallestUnit(amount, currency),\n currency,\n country,\n label: 'Vio',\n // Native Apple Pay shipping — same Standard/Express options as Klarna.\n shippingOptions: KLARNA_SHIPPING_OPTIONS.map((o) => ({\n id: o.id,\n label: o.method,\n detail: o.description,\n amount: o.price,\n })),\n // The real backend charge — sponsor resolved at authorize-time (the\n // product-detail button calls checkout.open() before show()).\n onAuthorize: (raw) => {\n const spId =\n this.state?.sponsorId ?? [...this.cartManager.getAllCarts().keys()][0]\n if (spId == null) {\n return Promise.reject(new Error('[VioCheckout] no sponsor for Apple Pay'))\n }\n return this.buildApplePayAuthorize(spId)(raw)\n },\n })\n return {\n available: prepared.available,\n show: async (): Promise<void> => {\n try {\n const result = await prepared.show()\n this.selectPaymentMethod('apple-pay')\n const state: CheckoutState =\n this.state ?? { sponsorId: 0, subtotal: amount, currency }\n this.dispatchEvent(\n new CustomEvent<PaymentCompleteDetail>('payment-complete', {\n detail: { method: 'apple-pay', state, result },\n }),\n )\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Apple Pay express failed:', err)\n }\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'apple-pay', error: describeError(err) },\n }),\n )\n }\n },\n }\n }\n\n /**\n * Prepare an Apple Pay express charge for an arbitrary amount (e.g. the whole\n * cart) with NO active checkout. Unlike `prepareApplePayFor`, the returned\n * `show()` RESOLVES with the result (or `null` on cancel/failure) and does\n * NOT dispatch the global `payment-complete` — so no checkout overlay appears.\n * The caller (the cart drawer) renders its own confirmation. `show()` must be\n * called synchronously inside the tap (Apple's user-gesture rule).\n */\n async prepareApplePayExpress(\n amount: number,\n currency: string,\n country = 'NO',\n sponsorId?: number,\n ): Promise<{ available: boolean; show: () => Promise<ApplePayResult | null> }> {\n const publishableKey = await this.resolveStripePublishableKey(sponsorId ?? this.state?.sponsorId)\n if (!publishableKey) return { available: false, show: async () => null }\n const spId =\n sponsorId ?? this.state?.sponsorId ?? [...this.cartManager.getAllCarts().keys()][0]\n const prepared = await prepareApplePay({\n publishableKey,\n connectedAccount:\n this.applePayConnectedAccount ?? this.findStripeConnectAccount() ?? undefined,\n amount: toSmallestUnit(amount, currency),\n currency,\n country,\n label: 'Vio',\n // Native Apple Pay shipping (same Standard/Express options as Klarna) —\n // selected inside the sheet, so it's not a separate checkout step.\n shippingOptions: KLARNA_SHIPPING_OPTIONS.map((o) => ({\n id: o.id,\n label: o.method,\n detail: o.description,\n amount: o.price,\n })),\n // The real backend charge, run inside the sheet's authorize event.\n ...(spId != null ? { onAuthorize: this.buildApplePayAuthorize(spId) } : {}),\n })\n return {\n available: prepared.available,\n show: async (): Promise<ApplePayResult | null> => {\n try {\n return await prepared.show()\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] cart Apple Pay express failed:', err)\n }\n return null\n }\n },\n }\n }\n\n /** The charge closure run inside the Apple Pay sheet's authorize event —\n * shared by the checkout button and the cart's express button. Fail-closed:\n * any failure throws and the sheet closes with failure, nothing confirmed. */\n private buildApplePayAuthorize(spId: number): (raw: ApplePayResult) => Promise<unknown> {\n return async (raw: ApplePayResult): Promise<unknown> => {\n let checkoutId = this.state?.checkoutId\n if (!checkoutId) {\n const created = await this.createCheckout(spId)\n checkoutId = created?.id ?? this.state?.checkoutId\n }\n if (!checkoutId) {\n throw new Error('[VioCheckout] could not obtain a checkout for Apple Pay')\n }\n const email = raw.payerEmail || this.state?.address?.email || ''\n // Record the method (+ email) on the checkout. Non-fatal: Confirm carries\n // the email too, and the charge is what decides the outcome.\n try {\n await this.updateCheckout(\n { checkoutId, paymentMethod: 'Apple Pay', ...(email ? { email } : {}) },\n spId,\n )\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] updateCheckout before Apple Pay confirm failed:', err)\n }\n }\n const gqlOpts = await getCartGraphQLOptions(spId)\n const createRes = await gqlCreatePaymentApplePay({ checkoutId }, gqlOpts)\n const gatewayId = String(createRes?.gateway_merchant_id ?? '')\n if (gatewayId.startsWith('pk_')) this.applePayPublishableKey = gatewayId\n else if (gatewayId.startsWith('acct_')) this.applePayConnectedAccount = gatewayId\n\n const addr = (raw.shippingAddress ?? {}) as Record<string, unknown>\n const str = (v: unknown): string => (typeof v === 'string' ? v : '')\n const lines = Array.isArray(addr.addressLine) ? (addr.addressLine as string[]) : []\n const fullName = str(addr.name) || raw.payerName || ''\n const shippingAddress = {\n address1: lines[0] || str(addr.line1) || '',\n address2: lines[1] || str(addr.line2) || '',\n city: str(addr.locality) || str(addr.city) || '',\n company: '',\n country: str(addr.country) || '',\n country_code: str(addr.countryCode) || getGlobalCountryCode(),\n first_name: str(addr.givenName) || fullName.split(' ')[0] || '',\n last_name: str(addr.familyName) || fullName.split(' ').slice(1).join(' ') || '',\n phone: str(addr.phone) || str(addr.phoneNumber) || raw.payerPhone || '',\n phone_code: '',\n province: str(addr.administrativeArea) || str(addr.state) || '',\n province_code: '',\n zip: str(addr.postalCode) || str(addr.postal_code) || '',\n }\n\n const confirmRes = await gqlConfirmPaymentApplePay(\n { checkoutId, applePayToken: raw.paymentMethodId, email, shippingAddress },\n gqlOpts,\n )\n const status = String(confirmRes?.status ?? '').toLowerCase()\n if (!confirmRes || CheckoutManager.APPLE_PAY_FAILED_STATUSES.has(status)) {\n throw new Error(\n `[VioCheckout] Apple Pay confirmation failed (status: ${confirmRes?.status ?? 'none'})`,\n )\n }\n return { orderId: confirmRes?.order_id, status: confirmRes?.status }\n }\n }\n\n /** Backend statuses from ConfirmPaymentApplePay that mean the charge did\n * NOT go through — anything here fails the sheet (fail-closed). */\n private static readonly APPLE_PAY_FAILED_STATUSES = new Set([\n 'failed', 'declined', 'rejected', 'cancelled', 'canceled', 'error', 'expired',\n ])\n\n /**\n * Launches the Apple Pay sheet and charges server-side INSIDE the sheet's\n * authorize event (round-5 wiring, contract from the commerce backend):\n * 1. ensure a backend checkout exists (create if missing)\n * 2. UpdateCheckout(paymentMethod: \"Apple Pay\" + payer email)\n * 3. CreatePaymentApplePay → gateway hints (pk_/acct_ stored by prefix)\n * 4. ConfirmPaymentApplePay(token, email, shipping) → the REAL charge;\n * a failed/absent confirmation throws → the sheet closes with failure\n * Resolves null if the user closes the sheet. On success, dispatches\n * `payment-complete` with the backend order id in `result.confirmation`.\n */\n async startApplePay(options: {\n country?: string\n label?: string\n sponsorId?: number\n } = {}): Promise<ApplePayResult | null> {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const spId = options.sponsorId ?? this.state.sponsorId\n const publishableKey = await this.resolveStripePublishableKey(spId)\n if (!publishableKey) {\n throw new Error(\n '[VioCheckout] No Stripe publishable key configured. Pass `stripePublishableKey` to Vio.init({ ... }).',\n )\n }\n const amount = toSmallestUnit(this.state.subtotal, this.state.currency)\n const onAuthorize = this.buildApplePayAuthorize(spId)\n\n const result = await showApplePaySheet({\n publishableKey,\n connectedAccount:\n this.applePayConnectedAccount ?? this.findStripeConnectAccount() ?? undefined,\n amount,\n currency: this.state.currency,\n country: options.country ?? 'NO',\n label: options.label ?? 'Vio',\n onAuthorize,\n })\n if (!result) return null // user closed the sheet — no event, nothing charged\n\n this.selectPaymentMethod('apple-pay')\n this.dispatchEvent(\n new CustomEvent<PaymentCompleteDetail>('payment-complete', {\n detail: { method: 'apple-pay', state: this.state, result },\n }),\n )\n return result\n }\n\n // MARK: - Klarna Express Checkout (Klarna Web SDK v2)\n\n /**\n * True if the Klarna Express button can be offered (clientId configured +\n * SDK loads). Memoised per active checkout. Never throws.\n */\n async isKlarnaExpressAvailable(): Promise<boolean> {\n if (this.klarnaAvailableCache !== null) return this.klarnaAvailableCache\n const cfg = Configuration.isInitialized ? Configuration.get() : null\n const clientId = cfg?.klarnaClientId ?? ''\n if (!clientId || !this.state) {\n this.klarnaAvailableCache = false\n return false\n }\n const available = await isKlarnaAvailable({\n clientId,\n locale: getGlobalLocale(),\n environment: cfg?.klarnaEnvironment,\n })\n this.klarnaAvailableCache = available\n return available\n }\n\n clearKlarnaCache(): void {\n this.klarnaAvailableCache = null\n }\n\n /**\n * Build the Klarna payment request from the active cart — amounts in the\n * currency's minor unit (øre/cents), one line item per cart line.\n */\n buildKlarnaPaymentRequest(): KlarnaPaymentRequestData {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const currency = this.state.currency\n const lineItems: KlarnaLineItem[] = this.items.map((item) => {\n const unitPrice = toSmallestUnit(item.unitPrice, currency)\n return {\n name: item.name || item.brand || 'Produkt',\n quantity: item.quantity,\n unitPrice,\n totalAmount: unitPrice * item.quantity,\n reference: String(item.productId),\n ...(item.imageUrl ? { imageUrl: item.imageUrl } : {}),\n }\n })\n return {\n currency,\n amount: toSmallestUnit(this.state.subtotal, currency),\n supplementaryPurchaseData: { lineItems },\n }\n }\n\n /**\n * Mount the Klarna Express button into `container`. On a successful\n * authorization, fires `payment-complete` with the authorization token —\n * the host (or vio-backend) then creates the Klarna order server-side.\n *\n * Returns the button handle so the UI can unmount on teardown.\n */\n async mountKlarnaExpress(container: HTMLElement): Promise<KlarnaButtonHandle> {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const cfg = Configuration.get()\n if (!cfg.klarnaClientId) {\n throw new Error(\n '[VioCheckout] No Klarna client id configured. Pass `klarnaClientId` to Vio.init({ ... }).',\n )\n }\n const pendingContext = this.buildKlarnaPendingContext()\n return mountKlarnaExpressButton({\n config: {\n clientId: cfg.klarnaClientId,\n locale: getGlobalLocale(),\n environment: cfg.klarnaEnvironment,\n },\n container,\n paymentRequest: this.buildKlarnaPaymentRequest(),\n pendingKey: KLARNA_PENDING_KEY,\n pendingContext,\n // POPUP path: the initiate() promise resolves in-page with the token.\n onAuthorize: (result) => {\n void this.completeKlarnaOrder(result.authorizationToken, pendingContext, result)\n },\n onError: (err) => {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Klarna Express cancelled/error:', err)\n }\n // Surface the error in the UI (not just the console). Klarna's reject\n // payload is often a plain object, so serialise it instead of letting\n // String(err) collapse to \"[object Object]\" — we need the real reason\n // (e.g. validation field, unsupported initiationMode, blocked origin)\n // visible on screen while we stabilise the flow.\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: describeError(err) },\n }),\n )\n },\n })\n }\n\n /**\n * Klarna Payments — classic widget flow (server client_token). Creates a\n * session on vio-backend, then mounts Klarna's inline widget into\n * `container`. Returns a handle to switch category and to authorize → which\n * on approval creates the order via the same backend /orders route as KEC.\n *\n * Unlike `mountKlarnaExpress`, this needs no public `klarnaClientId` and no\n * origin handshake — auth is the server-side API key.\n */\n async mountKlarnaPayments(\n container: HTMLElement,\n opts?: { withShipping?: boolean; shippingId?: string; category?: string },\n ): Promise<KlarnaPaymentsHandle> {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const sponsorId = this.state.sponsorId\n\n // 1. Real per-supplier shippings from the backend cart. No static\n // fallback for Klarna anymore — fetchAvailableShippings now waits for\n // any in-flight cart mutation, so an empty result means the backend\n // genuinely has nothing, not a race; falling back to stale hardcoded\n // prices would be worse than surfacing that honestly.\n const shippings = await this.fetchAvailableShippings(sponsorId)\n\n // With shipping: add the CHOSEN shipping option as a shipping_fee line +\n // bump the total. (Klarna Payments doesn't render a picker; ours lives in\n // the checkout UI and re-mounts this widget with the new total on change.)\n const { ctx } = opts?.withShipping\n ? this.buildKlarnaInstantContext(opts.shippingId, shippings)\n : { ctx: this.buildKlarnaPendingContext() }\n\n // 2. Persist the chosen shipping on the backend cart.\n const selectedOpt = shippings.find((s) => s.id === opts?.shippingId) ?? shippings[0]\n if (selectedOpt?.id && selectedOpt?.supplierId) {\n try {\n await this.updateShippingsBySupplier(\n [{ shipping_id: selectedOpt.id, supplier_id: Number(selectedOpt.supplierId) }],\n sponsorId,\n )\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] updateShippingsBySupplier failed during mount:', err)\n }\n }\n }\n\n // 3. Backend checkout (CreatePaymentKlarnaNative requires a checkout_id).\n let checkoutId = ctx.checkoutId ?? this.state.checkoutId\n try {\n const checkoutRes = await this.createCheckout(sponsorId)\n if (checkoutRes?.id) {\n checkoutId = checkoutRes.id\n ctx.checkoutId = checkoutRes.id\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] CreateCheckout before Klarna init failed:', err)\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Klarna session')\n }\n\n // 4. Klarna Payments session via the commerce GraphQL (native flow).\n const address = this.state.address\n const activeCurrency = getGlobalCurrency()\n if (this.state) this.state = { ...this.state, currency: activeCurrency }\n ctx.currency = activeCurrency\n const variables = {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n currency: activeCurrency,\n locale: getGlobalLocale(),\n returnUrl: resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'klarna',\n vio_sponsor: sponsorId,\n checkout_id: checkoutId,\n }),\n intent: 'buy',\n customer: buildKlarnaCustomer(address),\n billingAddress: buildKlarnaAddress(address),\n shippingAddress: buildKlarnaAddress(address),\n autoCapture: true,\n }\n\n const json = await executeKlarnaGraphQL(\n CREATE_PAYMENT_KLARNA_NATIVE_MUTATION,\n variables,\n sponsorId,\n )\n const nativeRes = json?.data?.Payment?.CreatePaymentKlarnaNative\n if (!nativeRes || !nativeRes.client_token) {\n throw new Error('Klarna session creation failed: missing client_token')\n }\n if (typeof console !== 'undefined') {\n console.log(\n '[VioCheckout] CreatePaymentKlarnaNative payment_method_categories:',\n nativeRes.payment_method_categories,\n )\n }\n if (nativeRes.checkout_id) {\n ctx.checkoutId = nativeRes.checkout_id\n this.state = { ...this.state, checkoutId: nativeRes.checkout_id }\n }\n if (nativeRes.session_id) {\n ctx.sessionId = nativeRes.session_id\n this.state = { ...this.state, sessionId: nativeRes.session_id }\n }\n ctx.clientToken = nativeRes.client_token\n this.state = { ...this.state, clientToken: nativeRes.client_token }\n\n // 5. Mount the inline widget and load the first category.\n const widget = await createKlarnaPaymentsWidget({\n clientToken: nativeRes.client_token,\n sessionId: nativeRes.session_id,\n categories: nativeRes.payment_method_categories ?? [],\n category: opts?.category,\n container,\n })\n await widget.load()\n\n return {\n categories: widget.categories,\n shippings,\n get selected() {\n return widget.selected\n },\n load: (category?: string) => widget.load(category),\n authorize: async (category?: string): Promise<void> => {\n try {\n // The session already carries the order (country/currency/lines);\n // Klarna collects customer details in its widget. Address/customer\n // are passed as a best-effort supplement when we already have them\n // from the checkout form — Klarna's own widget can still fill gaps.\n const addr = buildKlarnaAddress(this.state?.address)\n const customer = buildKlarnaCustomer(this.state?.address)\n const authData = {\n ...(addr ? { billing_address: addr, shipping_address: addr } : {}),\n ...(customer ? { customer } : {}),\n }\n const token = await widget.authorize(category, authData)\n await this.completeKlarnaOrder(token, ctx, { authorizationToken: token })\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Klarna Payments authorize failed:', err)\n }\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: describeError(err) },\n }),\n )\n }\n },\n unmount: () => {\n try {\n container.innerHTML = ''\n } catch {\n /* already gone */\n }\n },\n }\n }\n\n /** True if the Klarna Payments widget lib can load (UI gate). */\n async klarnaPaymentsAvailable(): Promise<boolean> {\n return isKlarnaPaymentsAvailable()\n }\n\n /** Cart snapshot + chosen shipping line/amount, for express purchases. */\n private buildKlarnaInstantContext(\n shippingId?: string,\n availableShippings: KlarnaShippingOption[] = [],\n ): {\n ctx: KlarnaPendingContext\n shippingOptions: KlarnaShippingOption[]\n } {\n const base = this.buildKlarnaPendingContext()\n const options = availableShippings\n const shipping =\n (shippingId ? options.find((o) => o.id === shippingId) : undefined) ??\n options.find((o) => o.preselected) ??\n options[0]\n const orderLines = [...base.orderLines]\n if (shipping) {\n orderLines.push({\n name: `Frakt – ${shipping.method || shipping.name}`,\n quantity: 1,\n unit_price: shipping.price,\n total_amount: shipping.price,\n reference: `shipping:${shipping.id}`,\n type: 'shipping_fee',\n })\n }\n return {\n ctx: {\n ...base,\n orderLines,\n orderAmount: base.orderAmount + (shipping?.price ?? 0),\n },\n shippingOptions: options,\n }\n }\n\n /**\n * Express instant purchase — go straight to Klarna's own modal, no checkout\n * overlay. Creates a session (with shipping options), loads the widget into a\n * hidden container, then authorizes (which opens Klarna's confirm modal). On\n * approval creates the order → `payment-complete` (host shows confirmation);\n * on failure → `payment-error`. Call `open(sponsorId)` first.\n */\n async startKlarnaInstant(): Promise<void> {\n if (!this.state) throw new Error('[VioCheckout] no active checkout — call open() first')\n const sponsorId = this.state.sponsorId\n const shippings = await this.fetchAvailableShippings(sponsorId)\n const { ctx } = this.buildKlarnaInstantContext(undefined, shippings)\n\n // 1. Backend checkout + Klarna Payments session via commerce GraphQL.\n let clientToken: string\n let categories: KlarnaPaymentsCategory[]\n try {\n let checkoutId = ctx.checkoutId ?? this.state.checkoutId\n try {\n const checkoutRes = await this.createCheckout(sponsorId)\n if (checkoutRes?.id) {\n checkoutId = checkoutRes.id\n ctx.checkoutId = checkoutRes.id\n }\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[CheckoutManager] CreateCheckout before Klarna instant failed:', err)\n }\n }\n if (!checkoutId) {\n throw new Error('[CheckoutManager] no backend checkout for the Klarna session')\n }\n\n const address = this.state.address\n const activeCurrency = getGlobalCurrency()\n this.state = { ...this.state, currency: activeCurrency }\n ctx.currency = activeCurrency\n const variables = {\n checkoutId,\n countryCode: getGlobalCountryCode(),\n currency: activeCurrency,\n locale: getGlobalLocale(),\n returnUrl: resolveHttpsReturnUrl(null, {\n vio_payment: 'success',\n vio_method: 'klarna',\n vio_sponsor: sponsorId,\n checkout_id: checkoutId,\n }),\n intent: 'buy',\n customer: buildKlarnaCustomer(address),\n billingAddress: buildKlarnaAddress(address),\n shippingAddress: buildKlarnaAddress(address),\n autoCapture: true,\n }\n\n const json = await executeKlarnaGraphQL(\n CREATE_PAYMENT_KLARNA_NATIVE_MUTATION,\n variables,\n sponsorId,\n )\n const nativeRes = json?.data?.Payment?.CreatePaymentKlarnaNative\n if (!nativeRes || !nativeRes.client_token) {\n throw new Error('Klarna instant session failed: missing client_token')\n }\n if (nativeRes.checkout_id) {\n ctx.checkoutId = nativeRes.checkout_id\n this.state = { ...this.state, checkoutId: nativeRes.checkout_id }\n }\n if (nativeRes.session_id) {\n ctx.sessionId = nativeRes.session_id\n this.state = { ...this.state, sessionId: nativeRes.session_id }\n }\n ctx.clientToken = nativeRes.client_token\n this.state = { ...this.state, clientToken: nativeRes.client_token }\n clientToken = nativeRes.client_token\n categories = nativeRes.payment_method_categories ?? []\n } catch (err) {\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: describeError(err) },\n }),\n )\n return\n }\n\n // 2. Hidden container → load → authorize (opens Klarna's own modal).\n const container = document.createElement('div')\n container.setAttribute('aria-hidden', 'true')\n container.style.cssText =\n 'position:fixed;left:-9999px;top:0;width:1px;height:1px;overflow:hidden;'\n document.body.appendChild(container)\n try {\n const widget = await createKlarnaPaymentsWidget({\n clientToken,\n sessionId: ctx.sessionId,\n categories,\n container,\n })\n await widget.load()\n const token = await widget.authorize()\n await this.completeKlarnaOrder(token, ctx, { authorizationToken: token })\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Klarna instant failed:', err)\n }\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: describeError(err) },\n }),\n )\n } finally {\n try {\n container.remove()\n } catch {\n /* already gone */\n }\n }\n }\n\n /**\n * REDIRECT path: call once on app load. If a Klarna purchase was launched\n * (pending context persisted) and we're back with a token — from the URL or\n * the SDK's resumed `complete` event — finish creating the order + confirm.\n */\n async resumeKlarnaReturn(): Promise<void> {\n if (typeof sessionStorage === 'undefined') return\n const raw = sessionStorage.getItem(KLARNA_PENDING_KEY)\n if (!raw) return\n let pending: KlarnaPendingContext\n try {\n pending = JSON.parse(raw) as KlarnaPendingContext\n } catch {\n sessionStorage.removeItem(KLARNA_PENDING_KEY)\n return\n }\n\n // 1) Token already in the URL (most redirect flows append it).\n const fromUrl = readKlarnaTokenFromUrl()\n if (fromUrl) {\n cleanUrlParams([fromUrl.param])\n await this.completeKlarnaOrder(fromUrl.token, pending, { authorizationToken: fromUrl.token })\n return\n }\n\n // No recognised token param — log what Klarna actually returned so the\n // param name can be mapped if the SDK `complete` event doesn't fire.\n if (typeof window !== 'undefined' && typeof console !== 'undefined' && window.location.search) {\n console.warn(\n '[VioCheckout] Klarna return: no known token param. URL was:',\n window.location.search,\n )\n }\n\n // 2) Otherwise let the SDK resume its session and fire `complete`.\n const cfg = Configuration.isInitialized ? Configuration.get() : null\n if (!cfg?.klarnaClientId) return\n await listenForKlarnaCompletion({\n config: { clientId: cfg.klarnaClientId, locale: getGlobalLocale(), environment: cfg.klarnaEnvironment },\n onComplete: (result) => {\n void this.completeKlarnaOrder(result.authorizationToken, pending, result)\n },\n onError: (err) => {\n if (typeof console !== 'undefined') {\n console.warn('[VioCheckout] Klarna resume error:', err)\n }\n },\n })\n }\n\n /** Snapshot of the active cart for redirect recovery (minor units). */\n private buildKlarnaPendingContext(): KlarnaPendingContext {\n if (!this.state) throw new Error('[VioCheckout] no active checkout')\n const currency = this.state.currency\n return {\n sponsorId: this.state.sponsorId,\n currency,\n orderAmount: toSmallestUnit(this.state.subtotal, currency),\n orderLines: this.items.map((item) => {\n const unitPrice = toSmallestUnit(item.unitPrice, currency)\n return {\n name: item.name || item.brand || 'Produkt',\n quantity: item.quantity,\n unit_price: unitPrice,\n total_amount: unitPrice * item.quantity,\n reference: String(item.productId),\n }\n }),\n }\n }\n\n /**\n * POST the token + order lines to vio-backend (it holds the secret API key\n * and creates the real Klarna order). On success → `payment-complete`; on\n * failure → `payment-error`. Idempotent: clears the pending key so the\n * popup and redirect paths can't double-fire.\n */\n private async completeKlarnaOrder(\n authorizationToken: string,\n ctx: KlarnaPendingContext,\n result: KlarnaAuthorizeResult,\n ): Promise<void> {\n // Idempotency guard — first caller wins (also without sessionStorage).\n if (this.klarnaOrderInFlight) return\n this.klarnaOrderInFlight = true\n // A token can only be confirmed once — a retry with an already-confirmed\n // token (network blip after a successful confirm) would create a second\n // order with autoCapture: double charge.\n if (\n typeof sessionStorage !== 'undefined' &&\n sessionStorage.getItem('vio.klarna.confirmed.v1') === authorizationToken\n ) {\n this.klarnaOrderInFlight = false\n return\n }\n try {\n const checkoutId =\n ctx?.checkoutId ?? this.state?.checkoutId ?? String(ctx?.sponsorId ?? this.state?.sponsorId ?? '')\n const address = this.state?.address\n const variables = {\n checkoutId,\n authorizationToken,\n autoCapture: true,\n billingAddress: buildKlarnaAddress(address),\n shippingAddress: buildKlarnaAddress(address),\n customer: buildKlarnaCustomer(address),\n }\n\n const json = await executeKlarnaGraphQL(\n CONFIRM_PAYMENT_KLARNA_NATIVE_MUTATION,\n variables,\n ctx?.sponsorId ?? this.state?.sponsorId,\n )\n const confirmRes = json?.data?.Payment?.ConfirmPaymentKlarnaNative\n if (!confirmRes) {\n throw new Error('Klarna order confirmation failed: missing response data')\n }\n const orderData = confirmRes.order || confirmRes\n\n // Success: only NOW is the pending context consumed (keeping it until\n // here lets the redirect path retry a confirm that never ran).\n if (typeof sessionStorage !== 'undefined') {\n sessionStorage.setItem('vio.klarna.confirmed.v1', authorizationToken)\n sessionStorage.removeItem(KLARNA_PENDING_KEY)\n }\n\n // Synthesize a checkout state for the confirmation if the live one was\n // lost to a redirect reload.\n const state: CheckoutState =\n this.state ?? { sponsorId: ctx.sponsorId, subtotal: ctx.orderAmount, currency: ctx.currency }\n this.dispatchEvent(\n new CustomEvent<PaymentCompleteDetail>('payment-complete', {\n detail: {\n method: 'klarna',\n state,\n // chargedTotal in MAJOR units (incl. shipping for express) for the\n // confirmation screen. ctx.orderAmount is minor (øre) → /100.\n // Prefer the amount Klarna actually charged (includes shipping in\n // every flow); the local ctx misses shipping outside express.\n result: {\n ...result,\n order: orderData,\n chargedTotal:\n typeof orderData?.order_amount === 'number'\n ? orderData.order_amount / 100\n : ctx.orderAmount / 100,\n },\n },\n }),\n )\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.error('[VioCheckout] Klarna order creation failed:', err)\n }\n this.dispatchEvent(\n new CustomEvent<PaymentErrorDetail>('payment-error', {\n detail: { method: 'klarna', error: err instanceof Error ? err.message : String(err) },\n }),\n )\n } finally {\n this.klarnaOrderInFlight = false\n }\n }\n\n // MARK: - Accessors\n\n get currentState(): CheckoutState | null {\n return this.state\n }\n\n get items(): CartLineItem[] {\n if (!this.state) return []\n return this.cartManager.getCart(this.state.sponsorId)?.items ?? []\n }\n\n // MARK: - Internals\n\n /**\n * Resolve the Stripe Connect account for the active sponsor — for now\n * pulled from bootstrap cache if present. Returns undefined if not set\n * (Stripe will route to the platform account in that case).\n */\n private findStripeConnectAccount(): string | undefined {\n // Placeholder hook — when bootstrap exposes per-sponsor stripeAccount\n // we'll wire it here. For now returns undefined.\n return undefined\n }\n\n private emit(): void {\n this.dispatchEvent(\n new CustomEvent<CheckoutChangeDetail>('change', { detail: { state: this.state } }),\n )\n }\n}\n\n/**\n * Stripe expects amounts in the smallest currency unit. NOK/SEK/DKK/EUR/USD\n * are all hundredths (øre, öre, øre, cents, cents). JPY is the exception\n * (no fractional unit).\n */\nfunction toSmallestUnit(amount: number, currency: string): number {\n const zeroDecimal = new Set(['JPY', 'KRW', 'VND'])\n if (zeroDecimal.has(currency.toUpperCase())) return Math.round(amount)\n return Math.round(amount * 100)\n}\n","/**\n * SDK version reported in analytics events (`sdk_version`) and available\n * to consumers. Kept as a constant (not a package.json import) so the\n * core stays bundler-agnostic.\n *\n * RELEASE CHECKLIST: bump together with package.json (see CONTRIBUTING).\n */\nexport const SDK_VERSION = '0.11.0'\n","/**\n * Vio.analytics — the web SDK's half of the Vio Analytics pipeline.\n *\n * Events flow to the Vio collector (`POST <eventsBase>/v1/events`, repo\n * vio-live/vio-analytics) which owns raw storage (ClickHouse) and vendor\n * fan-out (Mixpanel today). THE SDK NEVER TALKS TO VENDORS — swapping or\n * dropping a vendor is a server-side change, zero client releases.\n * Wire contract: vio-analytics `docs/EVENTS_CONTRACT.md` (v1, snake_case).\n *\n * Design rules:\n * - SIDE-EFFECT-FREE MODULE. Nothing runs at import time (tsup/tree-shaking\n * contract, see lessons/web-sdk-tsup-singleton-and-build). Listeners are\n * installed by an explicit `Vio.analytics.start()`.\n * - `track()` works BEFORE `Vio.init()` — events queue and flush once the\n * SDK is configured (transport resolves at flush time, not at track time).\n * - SSR-safe: without `window` every call is a silent no-op.\n * - Retries are safe: `event_id` is stable per event, the collector\n * dedupes. Queue is bounded (drop-oldest) so a dead collector can never\n * grow memory unbounded.\n * - Anti-double-count: the SDK only reports what the server can't see.\n * Votes/participations are server truth; `ad_activation`/`cart_intent`\n * are mirrored server-side, never from here.\n *\n * Three sinks, matching the Vev precedent (vio-vev analytics.ts, which\n * becomes an adapter over this in F3):\n * 1. collector (default ON once started)\n * 2. window.dataLayer — GA4/GTM (opt-in `start({ dataLayer: true })`,\n * the publisher-facing feature; NOT part of the Vio pipeline)\n * 3. `vio:analytics` DOM event — always when started (inspector/bridges)\n */\n\nimport { Configuration } from '../configuration.js'\nimport { SDK_VERSION } from '../version.js'\nimport type { CartManager, CartChangeDetail } from '../cart/cart-manager.js'\nimport type { CartLineItem } from '../cart/types.js'\n\n// ── Taxonomy (client-side subset of contract v1) ────────────────────────────\n\nexport const ANALYTICS_EVENT_NAMES = [\n // commerce (GA4-compatible)\n 'view_item_list',\n 'select_item',\n 'view_item',\n 'add_to_cart',\n 'remove_from_cart',\n 'view_cart',\n 'begin_checkout',\n 'purchase',\n // engagement\n 'component_impression',\n 'component_click',\n 'ad_impression',\n 'ad_click',\n 'poll_impression',\n 'contest_impression',\n // session\n 'session_start',\n 'session_end',\n // diagnóstico — lo que salió MAL (ver EVENTS_CONTRACT.md)\n 'checkout_error',\n 'sdk_error',\n] as const\n\nexport type AnalyticsEventName = (typeof ANALYTICS_EVENT_NAMES)[number]\n\n/** Camel-case for DX; mapped to the snake_case wire format at build time. */\nexport interface AnalyticsContext {\n campaignId?: number\n broadcastId?: string\n campaignComponentId?: number\n appPlacementId?: number\n locationId?: string\n componentTemplateId?: string\n sponsorId?: number\n activationId?: number\n contentUrl?: string\n /**\n * The host's own id for the piece of content the component sits in — an\n * article id in a CMS, a page id in a site builder. Carried verbatim so the\n * host can join Vio's funnel back onto its own per-article reporting\n * (revenue stops being an estimate). Left alone by the SDK.\n */\n contentId?: string | number\n /** Human-readable content snapshot; auto-filled from document.title. */\n contentTitle?: string\n /** Código corto del fallo (`sdk_error` / `checkout_error`). */\n errorCode?: string\n variant?: string\n}\n\nexport interface AnalyticsItemInput {\n productId: number | string\n name?: string\n brand?: string\n variantId?: number | string\n price?: number\n quantity?: number\n}\n\nexport interface AnalyticsCommerce {\n items?: AnalyticsItemInput[]\n value?: number\n currency?: string\n orderId?: string\n paymentMethod?: string\n}\n\nexport interface TrackOptions {\n context?: AnalyticsContext\n commerce?: AnalyticsCommerce\n props?: Record<string, unknown>\n}\n\nexport interface AnalyticsStartOptions {\n /** Where the SDK is embedded: 'vev' | 'replit' | 'custom' | … Default 'custom'. */\n host?: string\n /**\n * Arrancar en modo cookieless hasta que el host llame `setConsent(true)`.\n * Default false: el SDK asume que el CMP del publisher ya decidió si nos\n * carga. Los publishers EU que necesitan medir antes del consentimiento\n * (o no pueden persistir sin él) ponen true.\n */\n requireConsent?: boolean\n /**\n * Install the automatic funnel listeners (vio:added-to-cart,\n * vio:checkout-open, vio:open-cart, vio:payment-success). Default true.\n * Hosts with their OWN instrumentation choke point (e.g. the Vev module,\n * which forwards every event through trackEvent()) set false so the same\n * user action is never tracked twice — they keep the session/batching/\n * transport engine and call track() themselves.\n */\n autoTrack?: boolean\n /**\n * Adopt the host's session id instead of minting one. A host that already\n * tracks its readers (its own impressions, dwell, clicks) needs Vio's\n * purchases to land in the SAME session, or the two datasets cannot be\n * joined. Pass the id the host already stores; omit it and the SDK keeps\n * its own rotating session.\n */\n sessionId?: string\n /** Send to the Vio collector. Default true. */\n collector?: boolean\n /** Also push GA4 e-commerce events to window.dataLayer (publisher feature). */\n dataLayer?: boolean\n /** console.debug every event. */\n debug?: boolean\n}\n\n// ── Tunables (contract-aligned) ─────────────────────────────────────────────\n\nconst SESSION_TTL_MS = 30 * 60 * 1000 // rolling 30-min session\nconst FLUSH_INTERVAL_MS = 5_000\nconst FLUSH_AT_COUNT = 20\nconst MAX_QUEUE = 500 // drop-oldest beyond this\nconst RETRY_BACKOFF_MS = [2_000, 4_000, 8_000]\nconst ANON_KEY = 'vio.anon.v1'\nconst SESSION_KEY = 'vio.session.v1'\n\n/** Impression rule: ≥50% visible for ≥1s, once per (session, component). */\nconst IMPRESSION_THRESHOLD = 0.5\nconst IMPRESSION_DWELL_MS = 1_000\n\n// ── Wire shape (snake_case, contract v1) ────────────────────────────────────\n\ninterface WireEvent {\n event_id: string\n name: AnalyticsEventName\n ts: string\n surface: 'web'\n host?: string\n sdk_version: string\n session_id: string\n anon_id: string\n external_user_id?: string\n context?: Record<string, unknown>\n commerce?: Record<string, unknown>\n props?: Record<string, unknown>\n}\n\n// ── Manager ─────────────────────────────────────────────────────────────────\n\nexport class AnalyticsManager extends EventTarget {\n private started = false\n private options: Required<\n Pick<AnalyticsStartOptions, 'collector' | 'dataLayer' | 'debug' | 'autoTrack'>\n > & {\n host: string\n } = { host: 'custom', collector: true, dataLayer: false, debug: false, autoTrack: true }\n\n private queue: WireEvent[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n private retryAttempt = 0\n private retryNotBefore = 0\n private externalUserId: string | undefined\n\n private sessionId: string | null = null\n private requireConsent = false\n private consentGranted = false\n private anonIdCache: string | null = null\n\n /** Set via start({ sessionId }) — the host owns the session, we follow. */\n private externalSessionId: string | null = null\n private sessionStartedAt = 0\n /** Impression once-per-(session, component) guard; reset on session rotation. */\n private impressedComponents = new Set<string>()\n\n /** Last NON-EMPTY cart snapshot — `purchase` uses it because several flows\n * (Apple Pay) clear the cart BEFORE `vio:payment-success` fires. */\n private lastCartSnapshot: { items: CartLineItem[]; currency?: string } | null = null\n\n private teardown: Array<() => void> = []\n\n // MARK: - Public API\n\n /**\n * Install listeners + begin flushing. Explicit on purpose (no module\n * side-effects). Safe to call twice (second call only updates options).\n */\n /**\n * Consentimiento (ePrivacy/GDPR). Por defecto el SDK asume que el host ya\n * lo gestionó — su CMP decide si nos carga. Con `requireConsent: true`\n * arranca en modo **cookieless**: mide la visita con ids efímeros en\n * memoria y NO escribe nada en localStorage hasta que el host llame\n * `setConsent(true)`. Retirarlo borra lo persistido.\n */\n setConsent(granted: boolean): void {\n this.consentGranted = granted\n if (granted) {\n // Promueve los ids efímeros a persistentes: la visita en curso no se\n // parte en dos por haber aceptado a mitad de camino.\n if (this.anonIdCache) safeStorageSet(ANON_KEY, this.anonIdCache)\n if (this.sessionId) this.persistSession()\n return\n }\n safeStorageRemove(ANON_KEY)\n safeStorageRemove(SESSION_KEY)\n }\n\n /** ¿Podemos escribir en el dispositivo? */\n private get canPersist(): boolean {\n return !this.requireConsent || this.consentGranted\n }\n\n start(options: AnalyticsStartOptions = {}): void {\n this.requireConsent = options.requireConsent === true\n this.options = {\n host: options.host ?? this.options.host,\n collector: options.collector ?? this.options.collector,\n dataLayer: options.dataLayer ?? this.options.dataLayer,\n debug: options.debug ?? this.options.debug,\n autoTrack: options.autoTrack ?? this.options.autoTrack,\n }\n // A host-supplied session id wins over our own: it is the only way the\n // host can join Vio's funnel onto the events it already collects.\n if (options.sessionId) this.externalSessionId = options.sessionId\n\n if (this.started || !hasDom()) return\n this.started = true\n\n this.ensureSession() // emits session_start\n\n this.flushTimer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS)\n\n const onPageHide = () => {\n this.trackSessionEnd()\n this.flushWithBeacon()\n }\n window.addEventListener('pagehide', onPageHide)\n this.teardown.push(() => window.removeEventListener('pagehide', onPageHide))\n\n if (this.options.autoTrack) this.installAutoListeners()\n }\n\n /** Stop timers + listeners (tests / SPA unmount). Queue survives. */\n stop(): void {\n if (this.flushTimer) clearInterval(this.flushTimer)\n this.flushTimer = null\n for (const fn of this.teardown.splice(0)) fn()\n this.started = false\n }\n\n /** Attach the partner's user id (opaque) to all subsequent events. */\n identify(externalUserId: string | null): void {\n this.externalUserId = externalUserId ?? undefined\n }\n\n /** Queue one event. Works pre-init and pre-start (SSR: no-op). */\n track(name: AnalyticsEventName, opts: TrackOptions = {}): void {\n if (!hasDom()) return\n const event = this.buildEvent(name, opts)\n if (!event) return\n\n if (this.options.debug) {\n console.debug('[Vio.analytics]', event.name, event)\n }\n // DOM sink — inspector/bridges (always once started; harmless before).\n try {\n window.dispatchEvent(new CustomEvent('vio:analytics', { detail: event }))\n } catch {\n /* CustomEvent unavailable — ignore */\n }\n if (this.options.dataLayer) pushGa4(event)\n\n this.queue.push(event)\n if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE)\n if (this.queue.length >= FLUSH_AT_COUNT) void this.flush()\n }\n\n /**\n * Impression helper: observes an element and tracks ONE\n * `component_impression` per (session, campaignComponentId) when the\n * contract's rule is met (≥50% visible, ≥1s dwell). Returns an\n * unobserve function.\n */\n observeImpression(\n element: Element,\n context: AnalyticsContext = {},\n opts: {\n name?: Extract<AnalyticsEventName, 'component_impression' | 'ad_impression'>\n /** Dedupe key override. Defaults to the strongest id available:\n * campaignComponentId → locationId → componentTemplateId. */\n key?: string\n /** Called the one time the impression is tracked (e.g. to fire a\n * companion view_item_list). */\n onImpression?: () => void\n } = {},\n ): () => void {\n if (!hasDom() || typeof IntersectionObserver === 'undefined') return () => {}\n const name = opts.name ?? 'component_impression'\n const dedupe =\n opts.key ??\n String(\n context.campaignComponentId ??\n context.locationId ??\n context.componentTemplateId ??\n 'component',\n )\n let dwellTimer: ReturnType<typeof setTimeout> | null = null\n\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting && entry.intersectionRatio >= IMPRESSION_THRESHOLD) {\n if (dwellTimer) continue\n dwellTimer = setTimeout(() => {\n const key = `${name}:${dedupe}`\n this.ensureSession()\n if (this.impressedComponents.has(key)) return\n this.impressedComponents.add(key)\n this.track(name, { context })\n opts.onImpression?.()\n observer.disconnect()\n }, IMPRESSION_DWELL_MS)\n } else if (dwellTimer) {\n clearTimeout(dwellTimer) // left the viewport before the dwell — not an impression\n dwellTimer = null\n }\n }\n },\n { threshold: [IMPRESSION_THRESHOLD] },\n )\n observer.observe(element)\n return () => {\n if (dwellTimer) clearTimeout(dwellTimer)\n observer.disconnect()\n }\n }\n\n /** Force a flush (mostly for tests). */\n async flush(): Promise<void> {\n if (!this.options.collector) {\n this.queue = []\n return\n }\n if (this.queue.length === 0) return\n if (!Configuration.isInitialized) return // transport unknown — hold the queue\n if (Date.now() < this.retryNotBefore) return\n\n const batch = this.queue.splice(0, MAX_QUEUE)\n const body = JSON.stringify({\n apiKey: Configuration.get().apiKey,\n sent_at: new Date().toISOString(),\n events: batch,\n })\n try {\n const res = await fetch(`${eventsBase()}/v1/events`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body,\n keepalive: batch.length <= 20, // keepalive caps payload at ~64KB\n })\n if (res.status === 401 || res.status === 400) {\n // Config problem, not transient — drop, don't loop forever.\n console.warn(`[Vio.analytics] collector rejected batch (HTTP ${res.status}) — dropped`)\n this.retryAttempt = 0\n return\n }\n if (!res.ok) throw new Error(`HTTP ${res.status}`)\n this.retryAttempt = 0\n } catch {\n // Requeue at the FRONT (same event_ids — server dedupes) + backoff.\n this.queue.unshift(...batch)\n const backoff =\n RETRY_BACKOFF_MS[Math.min(this.retryAttempt, RETRY_BACKOFF_MS.length - 1)] ?? 8_000\n this.retryAttempt++\n this.retryNotBefore = Date.now() + backoff\n }\n }\n\n // MARK: - Internals\n\n private buildEvent(name: AnalyticsEventName, opts: TrackOptions): WireEvent | null {\n this.ensureSession()\n if (!this.sessionId) return null\n const anonId = this.anonId()\n if (!anonId) return null\n\n const boot = vioBootstrapCache()\n const ctx = opts.context ?? {}\n const context: Record<string, unknown> = compact({\n campaign_id: ctx.campaignId ?? boot?.campaignId,\n broadcast_id: ctx.broadcastId,\n campaign_component_id: ctx.campaignComponentId,\n app_placement_id: ctx.appPlacementId,\n location_id: ctx.locationId,\n component_template_id: ctx.componentTemplateId,\n sponsor_id: ctx.sponsorId,\n activation_id: ctx.activationId,\n content_url: ctx.contentUrl ?? (typeof location !== 'undefined' ? location.href : undefined),\n // The host's own content id — its join key back onto its reporting.\n content_id: ctx.contentId,\n // Deletion-proof reporting: sources have no trash bin — the title\n // snapshotted at event time keeps reports legible if content dies.\n error_code: ctx.errorCode,\n content_title:\n ctx.contentTitle ??\n (typeof document !== 'undefined' && document.title\n ? document.title.slice(0, 255)\n : undefined),\n variant: ctx.variant,\n })\n\n const com = opts.commerce\n const commerce = com\n ? compact({\n items: com.items?.map((i) =>\n compact({\n product_id: String(i.productId),\n name: i.name,\n brand: i.brand,\n variant_id: i.variantId !== undefined ? String(i.variantId) : undefined,\n price: i.price,\n quantity: i.quantity,\n }),\n ),\n value: com.value,\n currency: com.currency,\n order_id: com.orderId,\n payment_method: com.paymentMethod,\n })\n : undefined\n\n return {\n event_id: uuid(),\n name,\n ts: new Date().toISOString(),\n surface: 'web',\n host: this.options.host,\n sdk_version: SDK_VERSION,\n session_id: this.sessionId,\n anon_id: anonId,\n ...(this.externalUserId ? { external_user_id: this.externalUserId } : {}),\n ...(Object.keys(context).length ? { context } : {}),\n ...(commerce ? { commerce } : {}),\n ...(opts.props ? { props: opts.props } : {}),\n }\n }\n\n /** Guarda la sesión solo si podemos escribir en el dispositivo. */\n private persistSession(now: number = Date.now()): void {\n if (!this.canPersist || !this.sessionId) return\n safeStorageSet(\n SESSION_KEY,\n JSON.stringify({\n id: this.sessionId,\n ts: now,\n startedAt: this.sessionStartedAt ?? now,\n }),\n )\n }\n\n private anonId(): string | null {\n if (this.anonIdCache) return this.anonIdCache\n const stored = this.canPersist ? safeStorageGet(ANON_KEY) : null\n if (stored) {\n this.anonIdCache = stored\n return stored\n }\n const id = `a-${uuid()}`\n // Sin consentimiento el id vive solo en memoria: se mide la visita, no\n // queda rastro en el dispositivo.\n if (this.canPersist) safeStorageSet(ANON_KEY, id)\n this.anonIdCache = (this.canPersist ? safeStorageGet(ANON_KEY) : null) ?? id\n return this.anonIdCache\n }\n\n /** Rolling session: renewed by activity, rotated after 30 min idle. */\n private ensureSession(): void {\n const now = Date.now()\n if (!this.sessionId) {\n const stored = this.canPersist ? safeStorageGet(SESSION_KEY) : null\n if (stored) {\n try {\n const parsed = JSON.parse(stored) as { id: string; ts: number; startedAt: number }\n if (now - parsed.ts < SESSION_TTL_MS) {\n this.sessionId = parsed.id\n this.sessionStartedAt = parsed.startedAt ?? now\n }\n } catch {\n /* corrupted — rotate */\n }\n }\n } else {\n const stored = this.canPersist ? safeStorageGet(SESSION_KEY) : null\n if (stored) {\n try {\n if (now - (JSON.parse(stored) as { ts: number }).ts >= SESSION_TTL_MS) {\n this.sessionId = null // idle too long — rotate\n }\n } catch {\n this.sessionId = null\n }\n }\n }\n\n if (this.externalSessionId) {\n // The host rotates its own session; we never expire or replace it.\n if (this.sessionId !== this.externalSessionId) {\n this.sessionId = this.externalSessionId\n this.sessionStartedAt = now\n this.impressedComponents.clear()\n }\n }\n\n if (!this.sessionId) {\n this.sessionId = `s-${uuid()}`\n this.sessionStartedAt = now\n this.impressedComponents.clear()\n this.persistSession(now)\n this.track('session_start')\n } else {\n this.persistSession(now)\n }\n }\n\n private trackSessionEnd(): void {\n if (!this.sessionId) return\n this.track('session_end', {\n props: { duration_ms: Date.now() - this.sessionStartedAt },\n })\n }\n\n private flushWithBeacon(): void {\n if (!this.options.collector || this.queue.length === 0) return\n if (!Configuration.isInitialized) return\n const batch = this.queue.splice(0, MAX_QUEUE)\n const body = JSON.stringify({\n apiKey: Configuration.get().apiKey,\n sent_at: new Date().toISOString(),\n events: batch,\n })\n // text/plain skips the CORS preflight a beacon can't perform; the\n // collector parses it as JSON (contract §transport).\n const ok =\n typeof navigator !== 'undefined' &&\n typeof navigator.sendBeacon === 'function' &&\n navigator.sendBeacon(`${eventsBase()}/v1/events`, new Blob([body], { type: 'text/plain' }))\n if (!ok) this.queue.unshift(...batch) // beacon refused — keep for a live flush\n }\n\n /**\n * Auto-instrumentation over the SDK's own DOM events — the host app\n * writes ZERO tracking code for the commerce funnel.\n */\n private installAutoListeners(): void {\n const on = (type: string, handler: (ev: Event) => void) => {\n window.addEventListener(type, handler)\n this.teardown.push(() => window.removeEventListener(type, handler))\n }\n\n // Cart snapshot — kept fresh so `purchase` survives the pre-success\n // cart clear (Apple Pay flow).\n const cart = vioCart()\n if (cart) {\n const onChange = (ev: Event) => {\n const detail = (ev as CustomEvent<CartChangeDetail>).detail\n if (!detail) return\n const items: CartLineItem[] = []\n detail.cartsBySponsor?.forEach((state) => items.push(...state.items))\n if (items.length > 0) {\n this.lastCartSnapshot = { items: items.map((i) => ({ ...i })), currency: items[0]?.currency }\n }\n }\n cart.addEventListener('change', onChange)\n this.teardown.push(() => cart.removeEventListener('change', onChange))\n }\n\n on('vio:added-to-cart', (ev) => {\n const d = (ev as CustomEvent<{ productId?: number | string; sponsorId?: number; quantity?: number; variantId?: number | string }>).detail ?? {}\n const line = this.findLine(d.productId, d.variantId)\n this.track('add_to_cart', {\n context: { sponsorId: d.sponsorId !== undefined ? Number(d.sponsorId) : undefined },\n commerce: {\n items: [\n {\n productId: d.productId ?? line?.productId ?? '',\n name: line?.name,\n brand: line?.brand,\n variantId: d.variantId ?? line?.variantId,\n price: line?.unitPrice,\n quantity: d.quantity ?? 1,\n },\n ],\n value: line ? line.unitPrice * (d.quantity ?? 1) : undefined,\n currency: line?.currency,\n },\n })\n })\n\n on('vio:removed-from-cart', (ev) => {\n const d = (ev as CustomEvent<{\n productId?: number | string\n variantId?: number | string\n name?: string\n brand?: string\n price?: number\n quantity?: number\n currency?: string\n sponsorId?: number\n }>).detail ?? {}\n if (d.productId === undefined) return\n this.track('remove_from_cart', {\n context: { sponsorId: d.sponsorId },\n commerce: {\n items: [\n {\n productId: d.productId,\n variantId: d.variantId,\n name: d.name,\n brand: d.brand,\n price: d.price,\n quantity: d.quantity,\n },\n ],\n value: (d.price ?? 0) * (d.quantity ?? 1),\n currency: d.currency,\n },\n })\n })\n\n // Diagnóstico: sin esto, \"el carrito falló\" es indistinguible de\n // \"el usuario se fue\".\n on('vio:cart-error', (ev) => {\n const d = (ev as CustomEvent<{ message?: string }>).detail ?? {}\n this.track('sdk_error', {\n context: { errorCode: 'cart_error' },\n props: d.message ? { message: String(d.message).slice(0, 500) } : undefined,\n })\n })\n\n on('vio:product-click', (ev) => {\n const d = (ev as CustomEvent<{\n productId?: number | string\n sponsorId?: number\n name?: string\n brand?: string\n price?: number | string\n }>).detail ?? {}\n if (d.productId === undefined) return\n const price = Number(d.price)\n this.track('select_item', {\n context: { sponsorId: d.sponsorId !== undefined ? Number(d.sponsorId) : undefined },\n commerce: {\n items: [\n {\n productId: d.productId,\n name: d.name,\n brand: d.brand,\n price: Number.isFinite(price) ? price : undefined,\n },\n ],\n },\n })\n })\n\n on('vio:open-cart', () => {\n const snap = this.cartCommerce()\n this.track('view_cart', snap ? { commerce: snap } : {})\n })\n\n on('vio:checkout-open', (ev) => {\n const d = (ev as CustomEvent<{ sponsorId?: number }>).detail ?? {}\n const snap = this.cartCommerce(d.sponsorId)\n this.track('begin_checkout', {\n context: { sponsorId: d.sponsorId },\n ...(snap ? { commerce: snap } : {}),\n })\n })\n\n on('vio:payment-success', (ev) => {\n const d = (ev as CustomEvent<{ method?: string; sponsorId?: number | string; orderId?: string }>).detail ?? {}\n const sponsorId = d.sponsorId !== undefined ? Number(d.sponsorId) : undefined\n const snap = this.cartCommerce(sponsorId) // falls back to pre-clear snapshot\n this.track('purchase', {\n context: { sponsorId },\n commerce: {\n ...(snap ?? {}),\n orderId: d.orderId,\n paymentMethod: d.method,\n },\n })\n })\n }\n\n /** Current cart → commerce payload; falls back to the pre-clear snapshot. */\n private cartCommerce(sponsorId?: number): AnalyticsCommerce | null {\n let items: CartLineItem[] = []\n const cart = vioCart()\n if (cart) {\n cart.getAllCarts().forEach((state, id) => {\n if (sponsorId === undefined || id === sponsorId) items.push(...state.items)\n })\n }\n if (items.length === 0 && this.lastCartSnapshot) {\n items = this.lastCartSnapshot.items.filter(\n (i) => sponsorId === undefined || i.sponsorId === sponsorId,\n )\n }\n if (items.length === 0) return null\n return {\n items: items.map((i) => ({\n productId: i.productId,\n name: i.name,\n brand: i.brand,\n variantId: i.variantId,\n price: i.unitPrice,\n quantity: i.quantity,\n })),\n value: items.reduce((sum, i) => sum + i.unitPrice * (i.quantity ?? 1), 0),\n currency: items[0]?.currency ?? this.lastCartSnapshot?.currency,\n }\n }\n\n private findLine(\n productId?: number | string,\n variantId?: number | string,\n ): CartLineItem | undefined {\n const pool: CartLineItem[] = []\n vioCart()\n ?.getAllCarts()\n .forEach((state) => pool.push(...state.items))\n if (pool.length === 0 && this.lastCartSnapshot) pool.push(...this.lastCartSnapshot.items)\n return pool.find(\n (i) =>\n String(i.productId) === String(productId) &&\n (variantId === undefined || String(i.variantId) === String(variantId)),\n )\n }\n}\n\n// ── Module-level helpers (pure; no side effects) ────────────────────────────\n\nfunction hasDom(): boolean {\n return typeof window !== 'undefined'\n}\n\nfunction uuid(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n // Ancient-browser fallback (non-cryptographic is fine for event ids).\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)\n })\n}\n\nfunction safeStorageGet(key: string): string | null {\n try {\n return window.localStorage.getItem(key)\n } catch {\n return null\n }\n}\n\nfunction safeStorageRemove(key: string): void {\n try {\n window.localStorage.removeItem(key)\n } catch {\n /* private mode / blocked */\n }\n}\n\nfunction safeStorageSet(key: string, value: string): void {\n try {\n window.localStorage.setItem(key, value)\n } catch {\n /* private mode / blocked — ephemeral ids are acceptable */\n }\n}\n\nfunction compact<T extends Record<string, unknown>>(obj: T): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(obj)) {\n if (v !== undefined && v !== null && v !== '') out[k] = v\n }\n return out\n}\n\n/** Collector base URL for the active environment (override: `eventsBase`). */\nfunction eventsBase(): string {\n return Configuration.get().eventsBase\n}\n\n// Late imports via the global facade to avoid a circular module edge\n// (client.ts imports this file for the getter type).\ninterface FacadeLike {\n bootstrapCache: { campaignId?: number } | null\n cart: CartManager\n}\nfunction vioFacade(): FacadeLike | null {\n const g = globalThis as unknown as { __VIO_FACADE__?: FacadeLike }\n return g.__VIO_FACADE__ ?? null\n}\nfunction vioBootstrapCache(): { campaignId?: number } | null {\n return vioFacade()?.bootstrapCache ?? null\n}\nfunction vioCart(): CartManager | null {\n try {\n return vioFacade()?.cart ?? null\n } catch {\n return null\n }\n}\n\n// ── GA4 dataLayer sink (publisher feature; NOT the Vio pipeline) ────────────\n\nfunction pushGa4(event: WireEvent): void {\n const commerceNames = new Set([\n 'view_item_list',\n 'select_item',\n 'view_item',\n 'add_to_cart',\n 'view_cart',\n 'begin_checkout',\n 'purchase',\n ])\n if (!commerceNames.has(event.name)) return\n const w = window as unknown as { dataLayer?: unknown[] }\n w.dataLayer = w.dataLayer || []\n const commerce = (event.commerce ?? {}) as {\n items?: Array<Record<string, unknown>>\n value?: number\n currency?: string\n order_id?: string\n }\n // GA4 best practice: clear the previous ecommerce object before each push.\n w.dataLayer.push({ ecommerce: null })\n w.dataLayer.push({\n event: event.name,\n ecommerce: compact({\n currency: commerce.currency,\n value: commerce.value,\n transaction_id: commerce.order_id,\n items: commerce.items?.map((i) =>\n compact({\n item_id: i.product_id,\n item_name: i.name,\n item_brand: i.brand,\n item_variant: i.variant_id,\n price: i.price,\n quantity: i.quantity,\n }),\n ),\n }),\n })\n}\n","/**\n * Vio — public SDK entry point + facade.\n *\n * Usage:\n * import { Vio } from 'vio'\n * Vio.init({ apiKey: 'xxx' }) // backend-bound calls require this\n * await Vio.bootstrap() // GET /v2/mobile/config\n *\n * // Client-side primitives — no init needed:\n * Vio.cart.addProduct({ product, sponsorId: 3 })\n * Vio.checkout.open(3)\n *\n * // Backend-bound:\n * const products = await Vio.commerceFor(3).channel.product.getByIds({\n * product_ids: [408895],\n * })\n */\n\nimport { Configuration, type VioConfig } from './configuration.js'\nimport { createVioApi, type VioApi } from './api/vio.js'\nimport { createCommerceClient, type CommerceClient } from './api/commerce.js'\nimport { CartManager } from './cart/cart-manager.js'\nimport { CheckoutManager } from './checkout/checkout-manager.js'\nimport { AnalyticsManager } from './analytics/analytics-manager.js'\nimport type { BootstrapResponse, Sponsor } from './types.js'\n\nclass VioFacade {\n private apiInstance: VioApi | null = null\n private commerceClients = new Map<number, CommerceClient>()\n private bootstrapPromise: Promise<BootstrapResponse> | null = null\n private cachedBootstrap: BootstrapResponse | null = null\n /** Last bootstrap failure — short backoff so cart mutations don't hammer a\n * dead endpoint on every call. */\n private bootstrapFailedAt = 0\n\n // Client-side managers — created lazily on first access. They don't\n // need Vio.init() to work (state is purely local).\n private cartManager: CartManager | null = null\n private checkoutManager: CheckoutManager | null = null\n private analyticsManager: AnalyticsManager | null = null\n\n init(config: VioConfig): void {\n Configuration.init(config)\n // Reset cached backend instances so a re-init picks up the new config.\n this.apiInstance = null\n this.commerceClients.clear()\n this.bootstrapPromise = null\n this.cachedBootstrap = null\n this.bootstrapFailedAt = 0\n // A new key/environment invalidates the per-sponsor payment methods too.\n this.checkoutManager?.clearPaymentMethodsCache()\n // NOTE: cart / checkout managers are NOT reset — user cart state is\n // independent of SDK re-config.\n }\n\n get isInitialized(): boolean { return Configuration.isInitialized }\n get config() { return Configuration.get() }\n\n // MARK: - Client-side managers (no init required)\n\n /** Multi-sponsor cart manager. Reactive — listen via addEventListener('change', ...). */\n get cart(): CartManager {\n if (!this.cartManager) this.cartManager = new CartManager()\n return this.cartManager\n }\n\n /** Checkout flow manager. Subscribes to cart state via the CartManager. */\n get checkout(): CheckoutManager {\n if (!this.checkoutManager) this.checkoutManager = new CheckoutManager(this.cart)\n return this.checkoutManager\n }\n\n /**\n * Analytics — track() queues even pre-init; nothing is sent (and no\n * listeners are installed) until an explicit `Vio.analytics.start()`.\n */\n get analytics(): AnalyticsManager {\n if (!this.analyticsManager) this.analyticsManager = new AnalyticsManager()\n return this.analyticsManager\n }\n\n // MARK: - Backend-bound\n\n /** Lazy VioApi for REST endpoints on `api-dev.vio.live`. */\n get api(): VioApi {\n if (!this.apiInstance) {\n const cfg = Configuration.get()\n this.apiInstance = createVioApi({ apiBase: cfg.apiBase, apiKey: cfg.apiKey })\n }\n return this.apiInstance\n }\n\n /**\n * Bootstrap — fetches client config and caches it. Dedupes in-flight\n * concurrent requests.\n */\n async bootstrap(): Promise<BootstrapResponse> {\n if (this.cachedBootstrap) return this.cachedBootstrap\n if (this.bootstrapPromise) return this.bootstrapPromise\n // Failure backoff: don't re-fire a request for 5s after a failure —\n // every cart mutation awaits bootstrap, so a dead endpoint would\n // otherwise add a failed round-trip per click.\n if (this.bootstrapFailedAt && Date.now() - this.bootstrapFailedAt < 5_000) {\n throw new Error('[Vio] bootstrap recently failed — backing off')\n }\n this.bootstrapPromise = this.api\n .bootstrap()\n .then((res) => {\n this.cachedBootstrap = res\n this.bootstrapFailedAt = 0\n return res\n })\n .catch((err) => {\n this.bootstrapFailedAt = Date.now()\n throw err\n })\n .finally(() => {\n this.bootstrapPromise = null\n })\n return this.bootstrapPromise\n }\n\n get bootstrapCache(): BootstrapResponse | null {\n return this.cachedBootstrap\n }\n\n /**\n * Get a CommerceClient scoped to a specific sponsor (via bootstrap).\n * Throws if bootstrap hasn't been called or the sponsor is unknown.\n */\n commerceFor(sponsorId: number): CommerceClient {\n // Coacción a número: los web-components pasan sponsorId como string\n // (atributo), y findSponsor compara con `===` contra el id numérico.\n sponsorId = Number(sponsorId) as number\n const existing = this.commerceClients.get(sponsorId)\n if (existing) return existing\n const sponsor = this.findSponsor(sponsorId)\n if (!sponsor) {\n throw new Error(\n `[Vio] Sponsor ${sponsorId} not found in bootstrap. Call Vio.bootstrap() first or pass commerce-key directly.`,\n )\n }\n const cfg = Configuration.get()\n const client = createCommerceClient({ endpoint: cfg.graphQLBase, apiKey: sponsor.commerce.apiKey })\n this.commerceClients.set(sponsorId, client)\n return client\n }\n\n /** Get a CommerceClient using an explicit commerce apiKey (skip bootstrap). */\n commerceWithKey(commerceApiKey: string): CommerceClient {\n const cfg = Configuration.get()\n return createCommerceClient({ endpoint: cfg.graphQLBase, apiKey: commerceApiKey })\n }\n\n private findSponsor(sponsorId: number): Sponsor | undefined {\n const boot = this.cachedBootstrap\n if (!boot) return undefined\n const id = Number(sponsorId)\n if (Number(boot.primarySponsor?.id) === id) return boot.primarySponsor\n return boot.secondarySponsors?.find((s) => Number(s.id) === id)\n }\n}\n\n// Cross-bundle singleton. Some hosts (e.g. Vev) bundle each component into its\n// own chunk, so a plain module-level instance would give EACH chunk its own\n// `Vio` — separate cart + bootstrap cache. That breaks shared state (one chunk\n// bootstraps, another reads an empty cache → \"Sponsor not found\"). Anchoring the\n// facade on `globalThis` means every copy resolves to the SAME instance within a\n// page. SSR-safe: `globalThis` exists in Node too.\nconst _vioGlobal = globalThis as unknown as { __VIO_FACADE__?: VioFacade }\nexport const Vio: VioFacade =\n _vioGlobal.__VIO_FACADE__ ?? (_vioGlobal.__VIO_FACADE__ = new VioFacade())\n"]}