tf-checkout-react 2.0.0-beta.1 → 2.0.0-beta.2
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.
- package/dist/index.esm.js +473 -263
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +473 -263
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/EmbeddedCheckout.tsx +6 -1
- package/src/auth/AuthModal.tsx +3 -3
- package/src/auth/ForgotPasswordForm.tsx +4 -6
- package/src/auth/LoginForm.tsx +2 -2
- package/src/auth/RegisterForm.tsx +2 -2
- package/src/auth/ResetPasswordForm.tsx +7 -7
- package/src/configure.ts +1 -5
- package/src/confirmer.ts +1 -5
- package/src/sections/AddOns.tsx +14 -7
- package/src/sections/BillingInfo.tsx +40 -33
- package/src/sections/Confirmation.tsx +8 -6
- package/src/sections/OrderSummary.tsx +7 -5
- package/src/sections/Payment.tsx +17 -13
- package/src/sections/Tickets.tsx +32 -15
- package/src/sections/billing/BillingAddressFields.tsx +19 -13
- package/src/sections/billing/TicketHoldersCard.tsx +103 -94
- package/src/ui/CheckoutProvider.tsx +5 -1
- package/src/ui/InstallmentPicker.tsx +4 -2
- package/src/ui/PaymentMethods.tsx +82 -76
- package/src/ui/TimerBanner.tsx +7 -3
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../../tf-checkout-shared/src/client/storage.ts","../../tf-checkout-shared/src/client/config.ts","../../tf-checkout-shared/src/client/errors.ts","../../tf-checkout-shared/src/client/cookies.ts","../../tf-checkout-shared/src/client/session.ts","../../tf-checkout-shared/src/client/http.ts","../../tf-checkout-shared/src/constants/endpoints.ts","../../tf-checkout-shared/src/constants/gateways.ts","../../tf-checkout-shared/src/constants/redirectMethods.ts","../../tf-checkout-shared/src/logic/gateway.ts","../../tf-checkout-shared/src/logic/pricing.ts","../../tf-checkout-shared/src/logic/checkout.ts","../../tf-checkout-shared/src/logic/payment.ts","../../tf-checkout-shared/src/logic/paymentPlan.ts","../../tf-checkout-shared/src/logic/account.ts","../../tf-checkout-shared/src/logic/auth.ts","../../tf-checkout-shared/src/logic/verification.ts","../../tf-checkout-shared/src/engine/store.ts","../../tf-checkout-shared/src/engine/confirmer.ts","../../tf-checkout-shared/src/engine/sheets.ts","../../tf-checkout-shared/src/engine/errors.ts","../../tf-checkout-shared/src/api/index.ts","../../tf-checkout-shared/src/api/profile.ts","../../tf-checkout-shared/src/api/auth.ts","../../tf-checkout-shared/src/api/geo.ts","../../tf-checkout-shared/src/api/engagement.ts","../../tf-checkout-shared/src/api/orders.ts","../../tf-checkout-shared/src/api/resale.ts","../../tf-checkout-shared/src/api/confirmation.ts","../../tf-checkout-shared/src/api/preRegistration.ts","../../tf-checkout-shared/src/api/delegation.ts","../../tf-checkout-shared/src/api/seatmap.ts","../../tf-checkout-shared/src/api/events.ts","../../tf-checkout-shared/src/api/cart.ts","../../tf-checkout-shared/src/api/order.ts","../../tf-checkout-shared/src/api/payment.ts","../../tf-checkout-shared/src/engine/engine.ts","../../tf-checkout-shared/src/services.ts","../../tf-checkout-shared/src/hooks/index.ts","../../tf-checkout-shared/src/hooks/auth.ts","../../tf-checkout-shared/src/hooks/authFlow.ts","../../tf-checkout-shared/src/hooks/keys.ts","../../tf-checkout-shared/src/hooks/session.ts","../../tf-checkout-shared/src/hooks/profile.ts","../../tf-checkout-shared/src/hooks/geo.ts","../../tf-checkout-shared/src/hooks/events.ts","../../tf-checkout-shared/src/hooks/orders.ts","../../tf-checkout-shared/src/hooks/engagement.ts","../../tf-checkout-shared/src/hooks/checkout.ts","../../tf-checkout-shared/src/i18n/locales/en.ts","../../tf-checkout-shared/src/i18n/resolve.ts","../../tf-checkout-shared/src/i18n/locales/es-MX.ts","../../tf-checkout-shared/src/i18n/locales/index.ts","../src/confirmer.ts","../src/xendit.ts","../src/instance.ts","../src/useCheckout.ts","../src/configure.ts","../src/CardInput.tsx","../src/ui/CheckoutProvider.tsx","../src/ui/cx.ts","../src/ui/I18nProvider.tsx","../src/ui/InstallmentPicker.tsx","../src/ui/Button.tsx","../src/ui/Loader.tsx","../src/ui/theme.ts","../src/ui/Card.tsx","../src/ui/Field.tsx","../src/ui/CustomFields.tsx","../src/ui/PaymentMethods.tsx","../src/ui/Stepper.tsx","../src/ui/QuantitySelect.tsx","../src/ui/PriceLine.tsx","../src/ui/Timer.tsx","../src/ui/TimerBanner.tsx","../src/auth/AuthModal.tsx","../src/auth/ForgotPasswordForm.tsx","../src/auth/LoginForm.tsx","../src/auth/PasswordInput.tsx","../src/auth/RegisterForm.tsx","../src/auth/ResetPasswordForm.tsx","../src/sections/Tickets.tsx","../src/sections/SeatMap.tsx","../src/sections/seatMap.utils.ts","../src/sections/AddOns.tsx","../src/sections/BillingInfo.tsx","../src/sections/billing/BillingAddressFields.tsx","../src/sections/billing/BuyerField.tsx","../src/sections/billing/fieldRules.ts","../src/sections/billing/TicketHoldersCard.tsx","../src/sections/Payment.tsx","../src/sections/OrderSummary.tsx","../src/sections/IDVerification.tsx","../src/sections/Confirmation.tsx","../src/sections/OrderConfirmation.tsx","../src/sections/OrderIDVerification.tsx","../src/EmbeddedCheckout.tsx","../src/ResumedCheckout.tsx"],"sourcesContent":["/**\n * tf-checkout-react — the web checkout, built on `tf-checkout-shared`.\n *\n * One import gives you the whole SDK (ttf, ENDPOINTS, dtos, logic, the engine)\n * PLUS the web platform layer: a `useCheckout` with Stripe + popup + inline\n * Xendit pre-wired, `<CardInput/>` / `<XenditCardInput/>`, and `configureCheckout`.\n *\n * import { configureCheckout, useCheckout, CardInput, ttf } from 'tf-checkout-react'\n */\n\n// Load the SDK styles once. Consumers do not need a separate CSS import.\nimport 'react-international-phone/style.css'\nimport './checkout.css'\n\n// The entire shared SDK (the web `useCheckout` below overrides the SDK's).\nexport * from 'tf-checkout-shared'\n\n// Web platform layer\nexport { useCheckout, type UseCheckoutOptions } from './useCheckout'\nexport { configureCheckout, localStorageAdapter } from './configure'\nexport { CardInput, StripePaymentElement, XenditCardInput } from './CardInput'\n\n// Component library: the themeable provider + primitives + section components.\nexport * from './ui'\nexport * from './auth'\nexport * from './sections'\nexport {\n EmbeddedCheckout,\n type EmbeddedCheckoutProps,\n type EmbeddedCheckoutAuthOptions,\n} from './EmbeddedCheckout'\nexport { ResumedCheckout, type ResumedCheckoutProps } from './ResumedCheckout'\n\nexport { webConfirmer, webPorts, webXenditTokenizer } from './instance'\nexport {\n createWebStripeConfirmer,\n createWebPorts,\n type WebStripeConfirmer,\n} from './confirmer'\nexport {\n createWebXenditTokenizer,\n type WebXenditTokenizer,\n type XenditCardFields,\n} from './xendit'\n","/**\n * The one platform seam the SDK's transport needs: somewhere to keep tokens.\n *\n * Web passes a `localStorage`-backed adapter, React Native an MMKV-backed one.\n * If a consumer configures nothing, we fall back to an in-memory map so the SDK\n * still works in tests and SSR (tokens just don't survive a reload).\n *\n * Deliberately synchronous — web `localStorage` and RN MMKV are both sync, and\n * a sync contract keeps the axios interceptors trivial. If you only have an\n * async store (AsyncStorage), wrap it with a small sync mirror.\n */\nexport interface StorageAdapter {\n getItem(key: string): string | null | undefined\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\n/** Process-lifetime fallback store. Not persisted — good enough for tests/SSR. */\nexport const createMemoryStorage = (): StorageAdapter => {\n const map = new Map<string, string>()\n return {\n getItem: (key) => (map.has(key) ? (map.get(key) as string) : null),\n setItem: (key, value) => void map.set(key, value),\n removeItem: (key) => void map.delete(key),\n }\n}\n","/**\n * One-time setup for the SDK. Call `configure()` at app start, before any\n * `ttf.*` call or hook runs. Everything downstream (transport, session, api)\n * reads this single record — there is no other global state.\n */\nimport { createMemoryStorage, StorageAdapter } from './storage'\n\nexport type TtfEnv = 'PROD' | 'STAG' | 'DEV'\n\n/** Host origins (NO /api suffix) — the one base-URL notion every layer derives\n * from. '' is valid: same-origin (e.g. behind a dev proxy). */\nexport const ENV_HOSTS: Record<TtfEnv, string> = {\n PROD: 'https://www.ticketfairy.com',\n STAG: 'https://test.ticketfairy.com',\n DEV: 'https://sandbox.ticketfairy.com',\n}\n\n/** Explicit `baseUrl` wins (even ''); otherwise the env host (default PROD).\n * A value in the old full-base form (…/api) is accepted — the /api suffix is\n * stripped here and re-appended for the transport. */\nexport const resolveHost = (env?: TtfEnv, baseUrl?: string): string => {\n if (baseUrl === undefined) return ENV_HOSTS[env ?? 'PROD']\n const trimmed = baseUrl.replace(/\\/+$/, '')\n return /\\/api$/.test(trimmed) ? trimmed.replace(/\\/api$/, '') : trimmed\n}\n\n/**\n * Extra auth material the consumer hands us — called on EVERY request; whatever\n * headers it returns are merged in last (they win over the SDK's own). Pass a\n * bearer token, a session cookie, an API key — anything. This is the flexible\n * \"bring your own auth\" seam. Return `undefined` to add nothing this request.\n */\nexport type AuthProvider = () => Record<string, string> | undefined\n\nexport interface TtfConfig {\n /** Host origin, e.g. `https://www.ticketfairy.com` — the `/api` path is\n * appended internally. `''` = same-origin. Omit to use `env`. */\n baseUrl?: string\n /** Picks the TicketFairy host when `baseUrl` is omitted. Defaults to PROD. */\n env?: TtfEnv\n /** OAuth client id issued to your brand. */\n clientId: string\n /** OAuth client secret issued to your brand. */\n clientSecret: string\n /** Value for the `X-Source-Origin` header (your domain). Optional. */\n sourceOrigin?: string\n /** Where tokens live. Defaults to an in-memory store (not persisted). */\n storage?: StorageAdapter\n /** Bring-your-own auth: return headers to attach to every request (token,\n * cookie, custom). Merged last, so it overrides the SDK's own headers. */\n auth?: AuthProvider\n /** Cookie-based session auth: forward the `X-TF-ECOMMERCE` login ticket (+\n * browser cookies where they exist) as headers, and capture the rotating\n * ones back from responses. Sign-in rides the legacy `/auth` session flow —\n * no bearer is minted, so the backend session that holds a reserved cart\n * survives a mid-checkout login. Enable when the app shares a session cookie\n * with TicketFairy (same-domain / SSO), runs anonymous cookie carts, or is a\n * native app (React Native persists the ticket via the storage adapter —\n * the RN `configureCheckout` turns this on by default). */\n cookieAuth?: boolean\n}\n\n/** Fully-resolved config — `storage`, `host`, and `apiBaseUrl` always present. */\nexport interface ResolvedTtfConfig extends TtfConfig {\n storage: StorageAdapter\n /** Host origin, no `/api` (e.g. `https://www.ticketfairy.com`). '' = same-origin. */\n host: string\n /** The transport base: `<host>/api`. */\n apiBaseUrl: string\n}\n\nlet current: ResolvedTtfConfig | null = null\n\n/** Wire the SDK. Idempotent — the last call wins. */\nexport const configure = (config: TtfConfig): void => {\n const host = resolveHost(config.env, config.baseUrl)\n current = {\n ...config,\n storage: config.storage ?? createMemoryStorage(),\n host,\n apiBaseUrl: `${host}/api`,\n }\n}\n\n/** Read the active config, or throw a pointed error if `configure()` was skipped. */\nexport const getConfig = (): ResolvedTtfConfig => {\n if (!current) {\n throw new Error(\n 'TicketFairy SDK is not configured — call configure({ baseUrl, clientId, clientSecret }) once at app start.'\n )\n }\n return current\n}\n\n/** The host origin (no `/api`) — for the few endpoints served off the root\n * (e.g. `/ajax/contact-email`) and for absolutizing icon paths. */\nexport const getOriginUrl = (): string => getConfig().host\n\n/** True once `configure()` has run. Lets callers branch without catching. */\nexport const isConfigured = (): boolean => current !== null\n","/**\n * One error shape for the whole SDK. Every api function rejects with a\n * `TtfError`, so callers (and hooks) branch on `.status` / `.code` instead of\n * digging through axios internals. `message` is always safe to show a user.\n */\nimport { AxiosError } from 'axios'\n\nexport class TtfError extends Error {\n /** HTTP status, or 0 for network/transport failures. */\n readonly status: number\n /** Backend error code when present (e.g. `INVALID_CREDENTIALS`). */\n readonly code?: string\n /** The raw payload, for callers that need more than the message. */\n readonly data?: unknown\n\n constructor(message: string, status: number, code?: string, data?: unknown) {\n super(message)\n this.name = 'TtfError'\n this.status = status\n this.code = code\n this.data = data\n }\n}\n\nconst flattenMessages = (value: unknown): string[] => {\n if (typeof value === 'string') return value.trim() ? [value.trim()] : []\n if (Array.isArray(value)) return value.flatMap(flattenMessages)\n if (value && typeof value === 'object')\n return Object.values(value).flatMap(flattenMessages)\n return []\n}\n\n/** Pull the friendliest message the backend gave us, including the legacy\n * `{ message: { email: [\"already registered\"] } }` validation shape. */\nconst messageFrom = (payload: unknown, fallback: string): string => {\n if (typeof payload === 'string' && payload.trim()) return payload\n if (payload && typeof payload === 'object') {\n const record = payload as Record<string, unknown>\n const candidate =\n record.message ??\n record.error ??\n record.error_description ??\n (Array.isArray(record.errors) ? (record.errors[0] as any)?.message : undefined)\n if (typeof candidate === 'string' && candidate.trim()) return candidate\n const messages = flattenMessages(candidate)\n if (messages.length > 0) return messages.join('\\n')\n }\n return fallback\n}\n\nconst codeFrom = (payload: unknown): string | undefined => {\n if (payload && typeof payload === 'object') {\n const code = (payload as Record<string, unknown>).code\n if (typeof code === 'string') return code\n }\n return undefined\n}\n\n/** Normalize any thrown value into a `TtfError`. Never throws itself. */\nexport const toTtfError = (\n error: unknown,\n fallback = 'Something went wrong'\n): TtfError => {\n if (error instanceof TtfError) return error\n if (error instanceof AxiosError) {\n const status = error.response?.status ?? 0\n const payload = error.response?.data\n return new TtfError(\n messageFrom(payload, error.message || fallback),\n status,\n codeFrom(payload),\n payload\n )\n }\n if (error instanceof Error) return new TtfError(error.message || fallback, 0)\n return new TtfError(fallback, 0)\n}\n","/**\n * Cookie access for the opt-in `cookieAuth` transport path (forwarding the\n * session cookies as headers). In the browser this is `document.cookie`.\n * Outside the browser (React Native) the same names are persisted through the\n * configured storage adapter instead — the backend accepts the session ticket\n * as a header, so a \"cookie\" only needs to survive relaunches, not be a real\n * browser cookie. This is what lets native ride the legacy cookie-session\n * login (same session as the reserved cart) with the ticket in MMKV.\n */\nimport { getConfig, isConfigured } from './config'\n\nconst hasDocument = (): boolean =>\n typeof document !== 'undefined' && typeof document.cookie === 'string'\n\nconst escapeName = (name: string): string =>\n name.replace(/([.$?*|{}()[\\]\\\\/+^])/g, '\\\\$1')\n\n/** Storage key for the non-browser fallback. */\nconst storageKey = (name: string): string => `tf_cookie_${name}`\n\nconst storageRead = (name: string): string | null => {\n if (!isConfigured()) return null\n return getConfig().storage.getItem(storageKey(name)) ?? null\n}\n\nconst storageWrite = (name: string, value: string): void => {\n if (!isConfigured()) return\n getConfig().storage.setItem(storageKey(name), value)\n}\n\nconst storageDelete = (name: string): void => {\n if (!isConfigured()) return\n getConfig().storage.removeItem(storageKey(name))\n}\n\n/** Read one cookie by name, or null when absent. */\nexport const readCookie = (name: string): string | null => {\n if (!hasDocument()) return storageRead(name)\n const match = document.cookie.match(new RegExp(`(?:^|; )${escapeName(name)}=([^;]*)`))\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Write a session-scoped cookie (path=/), or persist via storage off-browser. */\nexport const writeCookie = (name: string, value: string): void => {\n if (!hasDocument()) {\n storageWrite(name, value)\n return\n }\n document.cookie = `${name}=${value}; path=/`\n}\n\n/**\n * Expire a browser cookie for both host-only and domain-scoped variants.\n * White-labels can receive X-TF-ECOMMERCE from either their own host or a\n * parent domain, so deleting only one form can make logout appear to fail.\n * Off-browser there is exactly one stored variant to remove.\n */\nexport const deleteCookie = (name: string): void => {\n if (!hasDocument()) {\n storageDelete(name)\n return\n }\n\n const expired = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0; path=/`\n // Host-only cookie.\n document.cookie = expired\n\n if (typeof window === 'undefined') return\n const hostname = window.location?.hostname ?? ''\n if (!hostname || hostname === 'localhost' || /^\\d+(?:\\.\\d+){3}$/.test(hostname)) {\n return\n }\n\n const parts = hostname.split('.')\n for (let index = 0; index < parts.length - 1; index += 1) {\n const domain = parts.slice(index).join('.')\n document.cookie = `${expired}; domain=${domain}`\n document.cookie = `${expired}; domain=.${domain}`\n }\n}\n\n/** The raw `document.cookie` string ('' outside the browser — the storage\n * fallback carries named cookies as individual headers, never a cookie jar). */\nexport const allCookies = (): string => (hasDocument() ? document.cookie : '')\n","/**\n * Token bookkeeping, one level above the raw storage adapter. The transport\n * reads these on every request; `auth.ts` writes them on login and clears them\n * on logout / 401. Keys match what the backend hands back so a future migration\n * off the legacy client stays drop-in.\n */\nimport { getConfig, isConfigured } from './config'\nimport { deleteCookie, readCookie } from './cookies'\n\nconst ACCESS_TOKEN = 'tf_access_token'\nconst REFRESH_TOKEN = 'tf_refresh_token'\nconst GUEST_TOKEN = 'tf_auth_guest_token'\nconst LEGACY_GUEST_TOKEN = 'auth_guest_token'\nconst CART_GUEST_TOKEN = 'tf_checkout_cart_guest_token'\n\ntype SessionListener = () => void\nconst listeners = new Set<SessionListener>()\n\nconst emitSessionChange = (): void => {\n for (const listener of listeners) listener()\n}\n\n/** Notify subscribers after a cookie-session login that writes no bearer token\n * (so `setTokens`' own notification never fires). Web sign-in rides the legacy\n * `/auth` cookie flow: the X-TF-ECOMMERCE ticket lands via the response\n * interceptor, and this lets `useAuthSession` observe the signed-in state. */\nexport const notifyCookieSession = (): void => emitSessionChange()\n\n/** React/platform bindings subscribe here instead of maintaining a second auth\n * flag. Tokens remain the single source of truth. */\nexport const subscribeSession = (listener: SessionListener): (() => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nexport const getAccessToken = (): string | null =>\n getConfig().storage.getItem(ACCESS_TOKEN) ?? null\n\nexport const getGuestToken = (): string | null =>\n getConfig().storage.getItem(GUEST_TOKEN) ??\n getConfig().storage.getItem(LEGACY_GUEST_TOKEN) ??\n null\n\nexport const setTokens = (tokens: { access?: string; refresh?: string }): void => {\n const { storage } = getConfig()\n if (tokens.access) storage.setItem(ACCESS_TOKEN, tokens.access)\n if (tokens.refresh) storage.setItem(REFRESH_TOKEN, tokens.refresh)\n if (tokens.access || tokens.refresh) emitSessionChange()\n}\n\n/** The transport captures the rotating guest token from response headers.\n * Keep the legacy key synchronized while old and new checkout clients coexist. */\nexport const setGuestToken = (token: string): void => {\n const { storage } = getConfig()\n storage.setItem(GUEST_TOKEN, token)\n storage.setItem(LEGACY_GUEST_TOKEN, token)\n}\n\n/** Pin the identity that owns the active reservation. OAuth can rotate the\n * general guest token during a mid-checkout login, but the cart must keep using\n * the token captured immediately after add-to-cart. */\nexport const pinCartGuestToken = (): void => {\n if (!isConfigured()) return\n const token = getGuestToken()\n if (token) getConfig().storage.setItem(CART_GUEST_TOKEN, token)\n}\n\nexport const getCartGuestToken = (): string | null =>\n isConfigured() ? (getConfig().storage.getItem(CART_GUEST_TOKEN) ?? null) : null\n\nexport const clearCartGuestToken = (): void => {\n if (isConfigured()) getConfig().storage.removeItem(CART_GUEST_TOKEN)\n}\n\nexport const clearSession = (): void => {\n const { storage } = getConfig()\n storage.removeItem(ACCESS_TOKEN)\n storage.removeItem(REFRESH_TOKEN)\n storage.removeItem(GUEST_TOKEN)\n storage.removeItem(LEGACY_GUEST_TOKEN)\n storage.removeItem(CART_GUEST_TOKEN)\n deleteCookie('X-TF-ECOMMERCE')\n emitSessionChange()\n}\n\n/**\n * True when a signed-in access token is present. Cookie-enabled web consumers\n * also recognize an existing legacy storefront session during migration.\n */\nexport const isAuthenticated = (): boolean =>\n Boolean(getAccessToken() || (getConfig().cookieAuth && readCookie('X-TF-ECOMMERCE')))\n","/**\n * The SDK's single HTTP transport. One axios instance, built lazily from\n * `configure()` and rebuilt only if the config reference changes.\n *\n * Matches the engine's checkout client exactly: base is `<host>/api`, the\n * JSON:API content headers, `withCredentials` for the web session cookie, and a\n * request interceptor that sends both identities during the guest → authenticated\n * transition: the bearer identifies the buyer while `Authorization-Guest`\n * preserves the cart that was reserved before login.\n *\n * Self-contained by design: imports nothing from checkout-flow / checkout-core.\n */\nimport axios, {\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n InternalAxiosRequestConfig,\n} from 'axios'\n\nimport { allCookies, readCookie, writeCookie } from './cookies'\nimport { getConfig, ResolvedTtfConfig } from './config'\nimport { toTtfError } from './errors'\nimport {\n clearSession,\n getAccessToken,\n getCartGuestToken,\n getGuestToken,\n setGuestToken,\n} from './session'\n\n/** Persist the guest session token the backend echoes on every response. Always\n * on: it is the cookieless session carrier, and bearer-auth consumers (React\n * Native) need it to keep the reserved cart across a mid-checkout login. */\nconst captureGuestToken = (res: AxiosResponse): void => {\n const guest = res.headers?.['authorization-guest']\n if (guest) setGuestToken(String(guest))\n}\n\n/** Persist the login cookie the backend hands back. Browser-only (`cookieAuth`). */\nconst captureCookieSession = (res: AxiosResponse): void => {\n const xtf = res.headers?.['x-tf-ecommerce']\n if (xtf) writeCookie('X-TF-ECOMMERCE', String(xtf))\n}\n\n/** A logged-in buyer can still own a cart created moments earlier as a guest:\n * the bearer identifies the buyer while `Authorization-Guest` preserves the\n * cart's session. Without it the backend swaps a bearer request onto a\n * synthetic empty session (init.php) and on-checkout 422s \"cart expired\". */\nexport const resolveAuthorizationHeaders = (\n accessToken: string | null,\n guestToken: string | null\n): Record<string, string> => ({\n ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),\n ...(guestToken ? { 'Authorization-Guest': guestToken } : {}),\n})\n\nlet instance: AxiosInstance | null = null\nlet builtFrom: ResolvedTtfConfig | null = null\n\nconst build = (config: ResolvedTtfConfig): AxiosInstance => {\n const http = axios.create({\n baseURL: config.apiBaseUrl,\n timeout: 30_000,\n withCredentials: true,\n headers: {\n Accept: 'application/vnd.api+json',\n 'Content-Type': 'application/vnd.api+json',\n },\n })\n\n http.interceptors.request.use((req: InternalAxiosRequestConfig) => {\n const access = getAccessToken()\n const authorization = resolveAuthorizationHeaders(\n access,\n getCartGuestToken() ?? getGuestToken()\n )\n for (const [key, value] of Object.entries(authorization)) {\n req.headers.set(key, value)\n }\n if (config.sourceOrigin) req.headers.set('X-Source-Origin', config.sourceOrigin)\n\n // Cookie-based session context, opt-in for browser white-labels.\n if (config.cookieAuth) {\n const xtf = readCookie('X-TF-ECOMMERCE')\n if (xtf) req.headers.set('X-TF-ECOMMERCE', xtf)\n const cookies = allCookies()\n if (cookies) req.headers.set('Additional-Cookies', cookies)\n }\n\n // Bring-your-own auth wins — merged last (token, cookie, or anything).\n const extra = config.auth?.()\n if (extra) {\n for (const [key, value] of Object.entries(extra)) req.headers.set(key, value)\n }\n return req\n })\n\n http.interceptors.response.use(\n (res) => {\n captureGuestToken(res)\n if (config.cookieAuth) captureCookieSession(res)\n return res\n },\n (error) => {\n if (error?.response) {\n captureGuestToken(error.response)\n if (config.cookieAuth) captureCookieSession(error.response)\n }\n if (error?.response?.status === 401) clearSession()\n return Promise.reject(error)\n }\n )\n\n return http\n}\n\n/** The active axios instance, rebuilt if `configure()` was called with a new object. */\nexport const getHttp = (): AxiosInstance => {\n const config = getConfig()\n if (!instance || builtFrom !== config) {\n instance = build(config)\n builtFrom = config\n }\n return instance\n}\n\n/** Drop the cached instance — used by tests and after `configure()` swaps. */\nexport const resetHttp = (): void => {\n instance = null\n builtFrom = null\n}\n\n// --- thin verbs: return response data, throw a normalized TtfError ----------\n\nexport const get = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {\n try {\n return (await getHttp().get<T>(url, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const post = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().post<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const put = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().put<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const patch = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().patch<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const del = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {\n try {\n return (await getHttp().delete<T>(url, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n","/**\n * THE endpoint registry — every path the SDK calls, in one place, grouped by\n * domain to mirror `api/`, `dtos/`, and the `ttf` facade. No api function spells\n * a URL inline; they all read from here.\n *\n * Conventions:\n * - Paths are relative to the transport base (`<host>/api`) — see `client/http`.\n * A few legacy endpoints live off `/api` (`event/:id/time-slot-by-date`,\n * `event/:id/reservation/refresh/`); those omit the `v1/` prefix on purpose.\n * - `auth.contactEmail` is origin-rooted (NOT under `/api`) — it's joined with\n * `getOriginUrl()` at the call site.\n * - Static resources are string constants; parameterized ones are builder\n * functions that take the id/hash. Dynamic query params (pagination, filters)\n * are appended by the api function — only canonical flags that ARE the\n * endpoint (`?payment_config=1`) are baked in here.\n */\n\nimport { Id } from '../dtos/common'\n\nexport const ENDPOINTS = {\n /** OAuth login, registration, password recovery, and identity verification. */\n auth: {\n /** OAuth step 1 — exchange email+password for an authorization code. */\n authorizeRn: (clientId: Id) => `v1/oauth/authorize-rn?client_id=${clientId}`,\n /** OAuth step 2 — exchange the code for an access token. */\n accessToken: 'v1/oauth/access_token',\n /** Create an account (multipart form data). */\n registerRn: 'v1/oauth/register-rn',\n /** Cookie session — `DELETE` to sign out. */\n session: '/auth',\n /** Request a \"forgot password\" email (web). */\n restorePassword: '/auth/restore-password',\n /** Request a \"forgot password\" email (React Native variant). */\n restorePasswordRn: 'v1/oauth/restore-password-rn',\n /** Complete a password reset with the token from the email. */\n resetPassword: '/auth/reset-password',\n /** Existing-account lookup — ORIGIN-rooted + form-encoded, NOT under /api.\n * Joined with `getOriginUrl()` at the call site. */\n contactEmail: 'ajax/contact-email/',\n /** Read the signed-in user's identity-verification status (Netverify). */\n verificationInfo: 'v1/authenticate/get-verification-info',\n /** `GET` mints the hosted verification URL; `PATCH` marks it PENDING. */\n verify: 'v1/authenticate/verify',\n },\n\n /** The signed-in user's profile. */\n profile: {\n get: '/customer/profile/',\n },\n\n /** Billing-select geography. */\n geo: {\n /** All selectable countries. */\n countries: '/countries/list',\n /** States/provinces for a country (id→name map). */\n states: (countryId: Id) => `/countries/${countryId}/states/`,\n },\n\n /** Event catalog + engagement — everything keyed by an event id. */\n events: {\n /** `GET v1/event/:id` — event details (seated detection, slug, name). */\n info: (eventId: Id) => `v1/event/${eventId}`,\n /** Purchasable ticket types (+ promo/waiting-list metadata). */\n tickets: (eventId: Id) => `v1/event/${eventId}/tickets/`,\n /** Ticket types for one date of a time-slot event (legacy, off /api). */\n timeSlotByDate: (eventId: Id) => `event/${eventId}/time-slot-by-date`,\n /** Event add-ons. */\n addOns: (eventId: Id) => `v1/event/${eventId}/add-ons`,\n /** Custom-field groups (order / ticket / add-on scopes). */\n customFields: (eventId: Id) => `v1/event/${eventId}/custom_fields/`,\n /** Terms/conditions the buyer may need to accept. */\n conditions: (eventId: Id) => `v1/event/${eventId}/conditions`,\n /** Apply a promo/access code to the session. */\n promo: (eventId: Id) => `v1/event/${eventId}/promo`,\n /** Session currency preference (multi-currency events). */\n currency: (eventId: Id) => `v1/event/${eventId}/currency`,\n /** Unlock a password-protected event. */\n authenticate: (eventId: Id) => `v1/event/${eventId}/authenticate`,\n /** Tracking pixel (page view / order attribution). */\n track: (eventId: Id) => `v1/event/${eventId}/track`,\n /** Write ORDER-level custom-field values after the order exists. */\n orderDataCapture: (eventId: Id) => `v1/event/${eventId}/order-data-capture`,\n /** Write TICKET-level (per-holder) custom-field values. */\n ticketDataCapture: (eventId: Id) => `v1/event/${eventId}/ticket-data-capture`,\n /** Attribute the session to a referrer/promoter. */\n referrer: (eventId: Id) => `v1/event/${eventId}/referrer`,\n /** Join the sold-out waiting list. */\n waitingList: (eventId: Id) => `v1/event/${eventId}/add_to_waiting_list`,\n /** Submit RSVP details. */\n rsvp: (eventId: Id) => `v1/event/${eventId}/send-rsvp-info`,\n },\n\n /** Cart + pricing session. */\n cart: {\n /** Read the cart back (pins the event's payment method into the session). */\n get: 'v1/cart/',\n /** Cart + pre-order payment config (identifies the gateway pre-order). */\n withPaymentConfig: 'v1/cart?payment_config=1',\n /** Cart + display-ready server price breakdown; optional add-on query. */\n withPriceBreakdown: (addOnsQuery?: string) =>\n `v1/cart?price_breakdown=1${addOnsQuery ? `&${addOnsQuery}` : ''}`,\n /** Replace the whole cart with the current ticket selection. */\n addToCart: (eventId: Id) => `v1/event/${eventId}/add-to-cart/`,\n /** Price the cart (+ add-ons). */\n checkout: 'v1/checkout',\n /** Checkout gates for the current session (names_required, field gates). */\n checkoutConfigs: 'v1/checkout-configs',\n /** Payment-plan charge by explicit payment method (saved-card shortcut). */\n paymentPlan: (orderHash: string) => `cart/payment-plan/${orderHash}`,\n },\n\n /** Order lifecycle — create, review, finalize. */\n order: {\n /** Create the order from buyer + holders + add-ons (the on-checkout body). */\n create: 'v1/on-checkout/',\n /** Post-order review — gateway identity + Stripe/plan secrets + totals. */\n review: (orderHash: string) => `v1/order/${orderHash}/review`,\n /** Finalize a paid/pending order (emails receipt/voucher, defers webhook). */\n success: (orderHash: string) => `v1/order/${orderHash}/success/`,\n /** Complete a free (zero-total) registration. */\n completeFreeRegistration: (orderHash: string) =>\n `v1/order/${orderHash}/complete_free_registration`,\n /** Guard: does the signed-in user own this order hash. */\n verifyCustomer: (orderHash: string) => `v1/order/${orderHash}/verify-customer-order`,\n /** ID-verification round trip (`?url=1` mints the provider session URL). */\n idVerification: (orderHash: string, mintUrl?: boolean) =>\n `v1/order/${orderHash}/id-verification${mintUrl ? '?url=1' : ''}`,\n /** Confirmation-page payload for a completed order. */\n confirmation: (orderHash: string) => `v1/order/${orderHash}/payment/complete`,\n },\n\n /** Payment rails — the per-gateway wire after the order exists. */\n payment: {\n /** Xendit charges (e-wallets AND cards) — form-encoded, not JSON:API. */\n submitPayment: (orderHash: string) => `payments/submit-payment/${orderHash}`,\n /** OXXO: move the order to the pending-voucher state before the confirm. */\n prepareOxxo: (orderHash: string) => `order/${orderHash}/prepare-for-oxxo`,\n /** Per-payment-method-type fee re-price (re-fetch the review after). */\n methodType: (orderHash: string) => `v1/order/${orderHash}/payment-method-type`,\n /** MSI installment offers (between PM creation and the confirm). */\n installmentOffers: (orderHash: string) => `stripe/${orderHash}/installment-offers`,\n /** MSI confirm (server-side; follow with handleNextAction only). */\n confirmInstallments: (orderHash: string) =>\n `stripe/${orderHash}/confirm-installments`,\n /** PayPal Standard step 1 — switch the placed order's method. */\n changeMethod: 'v1/change-payment-method',\n /** PayPal Standard step 2 — the {action_url, fields} to top-level POST. */\n paypalForm: (orderHash: string) => `v1/order/${orderHash}/paypal-form`,\n /** Server-side confirm for redirect-based Stripe methods. */\n confirmRedirect: (orderHash: string) =>\n `v1/order/${orderHash}/stripe/confirm-redirect`,\n /** Schedule a payment plan against a new card's PaymentMethod. */\n paymentPlanCreate: (orderHash: string) => `v1/order/${orderHash}/payment_plan/create`,\n },\n\n /** Account — the buyer's own orders and tickets. */\n account: {\n /** Order history (server-paginated; caller appends page/limit/filter query). */\n orders: 'v1/account/orders/',\n /** One order's full detail. */\n order: (orderId: Id) => `v1/account/order/${orderId}`,\n /** The buyer's tickets/wallet (caller appends the query). */\n tickets: 'v1/account/tickets/',\n /** Twilio-backed phone validation. */\n validatePhone: (phone: string) =>\n `/v1/account/validate_phone?phone=${encodeURIComponent(phone)}`,\n },\n\n /** Ticket resale. */\n resale: {\n sell: (ticketId: Id) => `v1/ticket/${ticketId}/sell`,\n process: (ticketId: Id) => `v1/ticket/${ticketId}/process`,\n decline: (ticketId: Id) => `v1/ticket/${ticketId}/decline`,\n },\n\n /** Pre-registration (\"register interest, then share\"). */\n preRegistration: {\n /** Confirm pre-registration for an event. */\n confirm: (eventId: Id) => `v1/event/${eventId}/pre-registration/confirm`,\n /** Influencers/promoters available to share to. */\n influencers: (eventId: Id) => `v1/event/${eventId}/pre-registration/influencers`,\n /** The post-confirm share page (options + current standing). */\n confirmationPage: (hash: string) => `/v1/pre-registration/${hash}/confirmation-page`,\n /** Record a share action (a referral phase step). */\n submitAction: (hash: string) => `/v1/pre-registration/${hash}/submit-action`,\n },\n\n /** Guest ticket delegation (claim a ticket via an access link). */\n delegation: {\n /** Whether the recipient already has an account. */\n customerExists: (accessHash: string) =>\n `/v1/delegation-access/${accessHash}/customer-exists`,\n /** The claim page (event + ticket context). */\n consumerPageInfo: (accessHash: string) =>\n `v1/delegation-access/${accessHash}/consumer-page-info`,\n /** Issue (claim) the delegated ticket. */\n issueTicket: (accessHash: string) =>\n `v1/delegation-access/${accessHash}/issue-ticket`,\n },\n\n /** Seated events — the seat picker's wire. */\n seatmap: {\n /** The venue seat map. */\n data: (eventId: Id) => `v1/event/${eventId}/seat-map-data`,\n /** Live seat statuses (poll during selection). */\n statuses: (eventId: Id) => `v1/event/${eventId}/seats/status`,\n /** Reserve a seat selection. */\n reserve: (eventId: Id) => `v1/event/${eventId}/seats/reserve`,\n /** Release a held reservation. */\n deleteReserved: (eventId: Id) => `v1/event/${eventId}/seats/delete-reserved`,\n /** Extend a reservation's TTL (legacy, off /api). */\n refreshReservation: (eventId: Id) => `event/${eventId}/reservation/refresh/`,\n },\n} as const\n\n/** The `ENDPOINTS` shape, for callers that want to type against it. */\nexport type Endpoints = typeof ENDPOINTS\n","/**\n * Gateway-level constant sets: which Stripe payment-method types re-price the\n * order, and the Xendit processor rules. Pure data — the logic that reads them\n * lives in `logic/`.\n */\n\n/** Non-single-charge Stripe payment modes: every type here re-prices the order\n * before the client confirm. Card and wallet payments stay single_charge and\n * skip the call. */\nexport const FEE_MODE_PAYMENT_METHOD_TYPES: ReadonlySet<string> = new Set([\n 'afterpay_clearpay',\n 'zip',\n 'affirm',\n 'klarna',\n 'bancontact',\n 'paypal',\n 'ideal',\n 'cashapp',\n 'oxxo',\n 'crypto',\n 'mb_way',\n])\n\n/** Xendit wallet keys that need one extra buyer-typed field before charging. */\nexport const XENDIT_EWALLET_EXTRA_FIELD: Readonly<Record<string, string>> = {\n jenius_pay: 'cashtag',\n ovo: 'phoneNumber',\n}\n\n/** Xendit selector rows that are NOT one-tap e-wallet charges (cards tokenize\n * client-side, bank transfers issue virtual accounts) — filter these out when\n * offering the wallet buttons. */\nexport const XENDIT_NON_EWALLET_PROCESSORS: ReadonlySet<string> = new Set([\n 'credit_card',\n 'bank_transfer',\n 'virtual_account',\n])\n","/**\n * Redirect-based Stripe payment methods (Klarna/Afterpay/Affirm/iDEAL-class)\n * the WebView/popup round trip supports, keyed by the server's\n * payment_method_types spelling.\n */\nexport const SUPPORTED_REDIRECT_METHODS: ReadonlySet<string> = new Set([\n 'klarna',\n 'afterpay_clearpay',\n 'affirm',\n 'ideal',\n 'bancontact',\n 'eps',\n 'giropay',\n 'p24',\n 'alipay',\n 'grabpay',\n 'cashapp',\n 'paypal',\n])\n\n/** Filters a server `paymentMethodTypes` list to the redirect methods the flow\n * supports (order preserved, unknown types dropped). */\nexport const listRedirectMethods = (paymentMethodTypes?: string[] | null): string[] =>\n (paymentMethodTypes || []).filter(\n (type) => typeof type === 'string' && SUPPORTED_REDIRECT_METHODS.has(type)\n )\n","/**\n * Gateway identity — which processor an event/order pays through, read the same\n * way the hosted embed keys on it. Post-order (`detectGateway`, off the review's\n * payment_method) and pre-order (`identifyPreOrderGateway` + the Xendit/PayPal\n * config, off the cart payment block).\n */\nimport type {\n Gateway,\n PayPalTabConfig,\n PreOrderGateway,\n PreOrderPaymentConfig,\n XenditPreOrderConfig,\n XenditProcessor,\n} from '../dtos'\n\n/** Post-order gateway from the review's payment_method block. */\nexport const detectGateway = (\n paymentMethod: Record<string, unknown> | null | undefined\n): Gateway => {\n const pm = paymentMethod || {}\n if (pm.stripe_publishable_key || pm.stripe_client_secret) return 'stripe'\n const name = String(pm.name || '').toLowerCase()\n if (pm.razorpay_key_id || pm.key_id || name.indexOf('razorpay') !== -1) {\n return 'razorpay'\n }\n if (pm.xendit_publishable_key || name.indexOf('xendit') !== -1) return 'xendit'\n return 'unsupported'\n}\n\nconst paymentBlock = (\n cartAttributes: Record<string, unknown> | null | undefined\n): Record<string, unknown> | null => {\n const payment = cartAttributes && (cartAttributes.payment as Record<string, unknown>)\n return payment && typeof payment === 'object' ? payment : null\n}\n\n/** Pre-order gateway from the cart payment-config block. Null when unrecognised. */\nexport const identifyPreOrderGateway = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PreOrderGateway | null => {\n const payment = paymentBlock(cartAttributes)\n const gateway = payment && payment.gateway\n if (\n gateway === 'stripe_payment_intents' ||\n gateway === 'xendit' ||\n gateway === 'razorpay'\n ) {\n return gateway\n }\n return null\n}\n\n/** Xendit pre-order config (publishable key, processors, UI). Null when the\n * event isn't Xendit or the key is missing. */\nexport const xenditPreOrderConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): XenditPreOrderConfig | null => {\n const payment = paymentBlock(cartAttributes)\n if (!payment || payment.gateway !== 'xendit') return null\n const method = payment.payment_method as Record<string, unknown> | undefined\n const publishableKey = method && method.xendit_publishable_key\n if (typeof publishableKey !== 'string' || !publishableKey) return null\n return {\n publishableKey,\n onBehalfOf:\n typeof method?.xendit_on_behalf_of === 'string' && method.xendit_on_behalf_of\n ? method.xendit_on_behalf_of\n : null,\n processors: Array.isArray(payment.payment_processors)\n ? (payment.payment_processors as XenditProcessor[])\n : [],\n failureReasons:\n payment.failure_reasons && typeof payment.failure_reasons === 'object'\n ? (payment.failure_reasons as Record<string, string>)\n : {},\n ui:\n payment.ui && typeof payment.ui === 'object'\n ? (payment.ui as Record<string, string>)\n : {},\n }\n}\n\n/** PayPal Standard tab config off the cart payment block. Null when absent. */\nexport const paypalTabConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PayPalTabConfig | null => {\n const payment = paymentBlock(cartAttributes)\n const paypal = payment && (payment.paypal as PayPalTabConfig | null)\n if (!paypal || typeof paypal !== 'object') return null\n if (!paypal.payment_method_id || !paypal.payment_method_hash) return null\n return paypal\n}\n\n/** Pre-order deferred Stripe Elements config (single-page card mount). Null in\n * every fallback case (no config, non-Stripe, free cart). */\nexport const resolvePaymentConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PreOrderPaymentConfig | null => {\n const payment = cartAttributes && (cartAttributes.payment as PreOrderPaymentConfig)\n if (!payment || typeof payment !== 'object') return null\n if (!payment.elements_config || !payment.basic_config || !payment.basic_config.apiKey) {\n return null\n }\n return payment\n}\n","/**\n * Pricing logic — resolve the display-ready server breakdown, build the\n * display-only add-on query, and map `stripe_wallets` to the Payment Element\n * wallets option (payment-plan mode forces both wallets off — they can't\n * authorize future installments).\n */\nimport type { PriceBreakdown, StripeWallets, WalletsOption } from '../dtos'\n\n/** Query-string form of the display-only add-on map: `add_ons[<id>]=<qty>`.\n * The server caps at 50 entries / qty 100 and drops anything not in the cart. */\nexport const priceBreakdownAddOnsQuery = (\n addOns: Record<string | number, number> | null | undefined\n): string =>\n Object.entries(addOns || {})\n .filter(([id, qty]) => Number(id) > 0 && Number(qty) > 0)\n .map(([id, qty]) => `add_ons[${Number(id)}]=${Number(qty)}`)\n .join('&')\n\n/** Pull the `price_breakdown` block off cart attributes. Null when the backend\n * doesn't serve it (older backends) — callers keep their own rendering. */\nexport const resolvePriceBreakdown = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PriceBreakdown | null => {\n const breakdown =\n cartAttributes && (cartAttributes.price_breakdown as PriceBreakdown | null)\n if (!breakdown || typeof breakdown !== 'object') return null\n if (typeof breakdown.total !== 'string' || !Array.isArray(breakdown.tickets)) {\n return null\n }\n return {\n ...breakdown,\n add_ons: Array.isArray(breakdown.add_ons) ? breakdown.add_ons : [],\n }\n}\n\nexport const walletsOption = (\n stripeWallets: StripeWallets | null | undefined,\n paymentPlanMode = false\n): WalletsOption => {\n if (paymentPlanMode) {\n return { applePay: 'never', googlePay: 'never' }\n }\n const w = stripeWallets || {}\n return {\n applePay: w.applePay === false || w.applePay === 'never' ? 'never' : 'auto',\n googlePay: w.googlePay === false || w.googlePay === 'never' ? 'never' : 'auto',\n }\n}\n","/**\n * Checkout logic — compose the on-checkout body (in-body per-ticket capture,\n * order data_capture, buyer fields), evaluate buyer-field gates, find missing\n * required add-ons, and detect seated events.\n *\n * `buildOnCheckoutBody` matters: on_checkout is the SAME engine the hosted\n * checkout runs, and REQUIRED custom fields are validated AT PLACEMENT — events\n * with required fields can only be placed when the capture rides this body.\n */\nimport type {\n BuyerFieldVisibility,\n CheckoutBilling,\n CheckoutBreakdown,\n CheckoutHolder,\n CustomFieldValues,\n EventAddon,\n EventCustomField,\n EventCustomFieldGroup,\n FieldGates,\n OnCheckoutAttributes,\n OnCheckoutInput,\n RequiredAddOnLike,\n TicketSelection,\n TicketType,\n} from '../dtos'\n\nconst hasKeys = (value?: Record<string, unknown>) =>\n !!value && Object.keys(value).length > 0\n\n/** True when a custom-field answer has been provided (array = at least one). */\nexport const hasValue = (value: string | string[] | undefined): boolean =>\n Array.isArray(value)\n ? value.length > 0\n : Boolean(value !== undefined && String(value).trim())\n\n/** The checkout's single email rule — UIs must not re-derive their own. */\nexport const isEmail = (value: string | undefined): boolean =>\n /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(value?.trim() ?? '')\n\n/** The checkout's single phone rule: 7–15 digits, punctuation ignored. */\nexport const isPhone = (value: string | undefined): boolean => {\n const digits = value?.replace(/\\D/g, '') ?? ''\n return digits.length >= 7 && digits.length <= 15\n}\n\nconst ageOn = (billing: CheckoutBilling, now: Date): number | null => {\n const { dobDay, dobMonth, dobYear } = billing\n if (!dobDay || !dobMonth || !dobYear) return null\n let age = now.getUTCFullYear() - dobYear\n const birthdayPassed =\n now.getUTCMonth() + 1 > dobMonth ||\n (now.getUTCMonth() + 1 === dobMonth && now.getUTCDate() >= dobDay)\n if (!birthdayPassed) age -= 1\n return age\n}\n\nconst ticketSlots = (\n breakdown: CheckoutBreakdown | undefined,\n selections: TicketSelection[]\n): { ticketTypeId?: string }[] => {\n const slots: { ticketTypeId?: string }[] = []\n if (breakdown?.tickets.length) {\n for (const line of breakdown.tickets)\n for (let i = 0; i < line.quantity; i++)\n slots.push({ ticketTypeId: line.ticketTypeId })\n return slots\n }\n for (const selection of selections)\n for (let i = 0; i < selection.quantity; i++) slots.push({})\n return slots\n}\n\n/**\n * Does a ticket-scoped custom field apply to this ticket type? A field with no\n * `ticketTypeIds` applies to every ticket. This is the single owner of the rule\n * — the UIs previously each carried their own copy.\n */\nexport const fieldAppliesToTicketType = (\n field: Pick<EventCustomField, 'ticketTypeIds'>,\n ticketTypeId?: string | number\n): boolean =>\n !ticketTypeId ||\n !field.ticketTypeIds ||\n field.ticketTypeIds.map(String).includes(String(ticketTypeId))\n\n/** The ticket-scoped fields that apply to a given ticket type. */\nexport const ticketFieldsFor = <T extends Pick<EventCustomField, 'ticketTypeIds'>>(\n fields: T[],\n ticketTypeId?: string | number\n): T[] => fields.filter((field) => fieldAppliesToTicketType(field, ticketTypeId))\n\n/**\n * Are every required field in `fields` answered? Mirrors the engine's own\n * preflight, including its rule that `image` fields are server-authoritative\n * and never block the client.\n */\nexport const customFieldsComplete = (\n fields: EventCustomField[],\n values: CustomFieldValues\n): boolean =>\n fields\n .filter((field) => field.required && field.type !== 'image')\n .every((field) => hasValue(values[field.name]))\n\nconst requiredFields = (\n groups: EventCustomFieldGroup[],\n scope: 'order' | 'ticket'\n): EventCustomField[] =>\n groups\n .filter((group) => group.scope === scope)\n .flatMap((group) => group.fields)\n // Image upload is not supported by this checkout yet. The server remains\n // authoritative for those fields, matching the engine preflight.\n .filter((field) => field.required && field.type !== 'image')\n\nexport interface CheckoutDetailsState {\n billing?: CheckoutBilling\n holders: CheckoutHolder[]\n selections: TicketSelection[]\n breakdown?: CheckoutBreakdown\n holderNamesRequired: boolean\n fieldGates: BuyerFieldVisibility\n customFields: EventCustomFieldGroup[]\n}\n\nexport interface CheckoutDetailsValidationOptions {\n /** Embedded guest checkout asks the buyer to type their email twice. */\n requireEmailConfirmation?: boolean\n /** Always collect one named holder per selected ticket. The hosted event\n * checkout normally follows the backend holder-name/custom-field gates;\n * tf-sports' embedded flow opts into this stricter policy. */\n collectTicketHolders?: boolean\n /** Storefront parity: collect email and phone for every ticket holder. */\n requireHolderContact?: boolean\n /** Injectable clock keeps minimum-age checks deterministic in tests. */\n now?: Date\n}\n\n/**\n * One source of truth for every buyer/holder field that must be completed\n * before payment. UI sections use the returned labels for gating and the\n * framework-agnostic engine calls the same function during preflight.\n */\nexport const missingCheckoutDetails = (\n state: CheckoutDetailsState,\n options: CheckoutDetailsValidationOptions = {}\n): string[] => {\n const missing: string[] = []\n const billing = state.billing\n if (!billing) return ['Billing details']\n\n if (!billing.firstName.trim()) missing.push('First name')\n if (!billing.lastName.trim()) missing.push('Last name')\n if (!isEmail(billing.email)) missing.push('Valid email address')\n if (\n options.requireEmailConfirmation &&\n billing.confirmEmail?.trim().toLowerCase() !== billing.email.trim().toLowerCase()\n ) {\n missing.push('Matching email confirmation')\n }\n\n const gates = state.fieldGates\n if (gates.nationalityRequired && !billing.nationality?.trim()) {\n missing.push('Nationality')\n }\n if (gates.genderRequired && !billing.gender?.trim()) missing.push('Gender')\n if (gates.requireInstagram && !billing.instagramHandle?.trim()) {\n missing.push('Instagram handle')\n }\n if (gates.phoneRequired && !isPhone(billing.phone)) missing.push('Valid phone number')\n if (gates.dobRequired) {\n const age = ageOn(billing, options.now ?? new Date())\n if (age === null) missing.push('Date of birth')\n else if (gates.minimumAge !== undefined && age < gates.minimumAge) {\n missing.push(`Age ${gates.minimumAge} or older`)\n }\n }\n if (gates.showAddress) {\n if (!billing.streetAddress?.trim()) missing.push('Street address')\n if (!billing.city?.trim()) missing.push('City')\n if (!billing.zip?.trim()) missing.push('ZIP / postcode')\n if (!billing.countryId) missing.push('Country')\n if (billing.stateRequired && !billing.stateId) missing.push('State / county')\n }\n\n for (const field of requiredFields(state.customFields, 'order')) {\n if (!hasValue(billing.dataCapture?.[field.name])) {\n missing.push(field.label || field.name)\n }\n }\n\n const slots = ticketSlots(state.breakdown, state.selections)\n const ticketFields = requiredFields(state.customFields, 'ticket')\n const holderNamesRequired =\n state.holderNamesRequired || options.collectTicketHolders === true\n const needsHolders = holderNamesRequired || ticketFields.length > 0\n const holderContactRequired = options.requireHolderContact && needsHolders\n if (needsHolders) {\n slots.forEach((slot, index) => {\n const holder = state.holders[index]\n const ticketNumber = index + 1\n if (holderNamesRequired) {\n if (!holder?.firstName.trim()) {\n missing.push(`Ticket ${ticketNumber} holder first name`)\n }\n if (!holder?.lastName.trim()) {\n missing.push(`Ticket ${ticketNumber} holder last name`)\n }\n }\n if (holderContactRequired) {\n if (!isEmail(holder?.email)) {\n missing.push(`Ticket ${ticketNumber} holder email`)\n }\n if (!isPhone(holder?.phone)) {\n missing.push(`Ticket ${ticketNumber} holder phone`)\n }\n }\n for (const field of ticketFields) {\n const ticketTypeId = holder?.ticketTypeId ?? slot.ticketTypeId\n if (\n field.ticketTypeIds &&\n ticketTypeId &&\n !field.ticketTypeIds.map(String).includes(String(ticketTypeId))\n ) {\n continue\n }\n if (!hasValue(holder?.ticketDataCapture?.[field.name])) {\n missing.push(`${field.label || field.name} (ticket ${ticketNumber})`)\n }\n }\n })\n }\n\n return missing\n}\n\n/** Merge the parity fields into an existing attributes `base` object. */\nexport const buildOnCheckoutBody = (\n input: OnCheckoutInput,\n base: Record<string, unknown> = {}\n): OnCheckoutAttributes & Record<string, unknown> => {\n const attributes: OnCheckoutAttributes & Record<string, unknown> = { ...base }\n\n const buyer = input.buyerFields || {}\n if (buyer.nationality !== undefined && buyer.nationality !== '') {\n attributes.nationality = buyer.nationality\n }\n if (buyer.gender) {\n attributes.gender = buyer.gender\n }\n if (buyer.instagramHandle) {\n attributes.instagram_handle = buyer.instagramHandle\n }\n\n if (hasKeys(input.dataCapture)) {\n attributes.data_capture = { ...input.dataCapture }\n }\n\n if (input.ticketHolders && input.ticketHolders.length) {\n const holders: Array<Record<string, unknown>> = []\n const ticketDataCapture: Array<Record<string, unknown>> = []\n let hasTicketCapture = false\n\n input.ticketHolders.forEach((holder) => {\n const row: Record<string, unknown> = {\n first_name: holder.firstName || '',\n last_name: holder.lastName || '',\n }\n if (holder.email !== undefined) row.email = holder.email\n if (holder.phone !== undefined) row.phone = holder.phone\n if (holder.ticketTypeId !== undefined) {\n row.ticket_type_id = holder.ticketTypeId\n }\n const capture = holder.ticketDataCapture || {}\n if (hasKeys(capture)) {\n row.ticket_data_capture = { ...capture }\n hasTicketCapture = true\n }\n holders.push(row)\n ticketDataCapture.push(hasKeys(capture) ? { ...capture } : {})\n })\n\n attributes.ticket_holders = holders\n\n if (hasTicketCapture) {\n attributes.ticket_data_capture = ticketDataCapture\n }\n }\n\n if (hasKeys(input.addOns)) {\n attributes.add_ons = { ...(input.addOns as Record<string, number>) }\n }\n\n if (hasKeys(input.addOnDataCapture)) {\n attributes.add_on_data_capture = { ...input.addOnDataCapture }\n }\n\n return attributes\n}\n\n/** Evaluate the buyer-field gates off `GET v1/checkout-configs` (next_page_info). */\nexport const evaluateFieldGates = (\n gates: FieldGates | null | undefined\n): BuyerFieldVisibility => {\n const g = gates || {}\n const showNationality = !!g.show_nationality_field\n const showGender = !!g.show_gender_field\n const minAge = g.minimum_age == null ? undefined : Number(g.minimum_age)\n return {\n showNationality,\n nationalityRequired: showNationality && !!g.nationality_field_required,\n showGender,\n genderRequired: showGender && !!g.gender_field_required,\n requireInstagram: !!g.require_instagram,\n showPhone: !g.hide_phone_field,\n phoneRequired: !!g.phone_required,\n showDob: !!g.age_required,\n dobRequired: !!g.age_required,\n minimumAge: Number.isFinite(minAge) ? minAge : undefined,\n showAddress: !g.free_ticket,\n }\n}\n\n/**\n * The required add-ons the selection is still missing. Empty means the\n * requirement is satisfied. A sold-out required add-on (stock exactly 0) is\n * exempt — it never blocks placement (the hosted rule).\n */\nexport const missingRequiredAddOns = <T extends RequiredAddOnLike>(\n addOns: T[] | null | undefined,\n selectedQuantities: Record<string | number, number> | null | undefined\n): T[] =>\n (addOns || []).filter((addOn) => {\n if (!addOn.required || addOn.active === false) return false\n if (addOn.stock === 0) return false\n return (Number(selectedQuantities?.[addOn.id]) || 0) < 1\n })\n\n/** The hosted cap when nothing else bounds an add-on (embed-checkout-app.js). */\nexport const ADD_ON_DEFAULT_MAX_QUANTITY = 10\n\n/**\n * The selectable quantity cap for ONE add-on — the minimum of every bound that\n * applies, mirroring the hosted `order_add_on` partial exactly:\n *\n * - `flagLimitToTicketQuantity` → the number of tickets in the cart\n * - `limitPerTicket` → `limitPerTicket × ticketQuantity`\n * - `maxQuantity` → itself (already min'd with available stock\n * server-side on public reads)\n * - nothing set → the hosted default of 10\n * - `isCheckbox` → a yes/no choice, so at most 1\n *\n * This is NOT cosmetic: the server hard-rejects quantities above these\n * (`add_on_max_quantity`), so an over-generous picker builds an order that\n * fails at placement. `stock` is deliberately not a candidate — on public\n * reads it is only a sold-out signal (0 or null), never a count.\n */\nexport const addOnMaxQuantity = (\n addOn: Pick<\n EventAddon,\n 'flagLimitToTicketQuantity' | 'limitPerTicket' | 'maxQuantity' | 'isCheckbox'\n >,\n ticketQuantity: number\n): number => {\n const candidates: number[] = []\n if (addOn.flagLimitToTicketQuantity) candidates.push(ticketQuantity)\n if (addOn.limitPerTicket && addOn.limitPerTicket > 0) {\n candidates.push(Math.floor(addOn.limitPerTicket) * ticketQuantity)\n }\n if (addOn.maxQuantity && addOn.maxQuantity > 0) {\n candidates.push(Math.floor(addOn.maxQuantity))\n }\n const max = candidates.length\n ? Math.max(0, Math.min(...candidates))\n : ADD_ON_DEFAULT_MAX_QUANTITY\n return addOn.isCheckbox ? Math.min(max, 1) : max\n}\n\n/**\n * The selectable quantity bounds for a ticket type's dropdown: `{ min, max,\n * step }`. Tables are the subtlety — their quantity is a GUEST count (bounded by\n * `minGuests`/`maxGuests`), not a count of tickets, so a \"full table of 8\" must\n * offer 8…maxGuests and never a smaller number; the generic `min/maxQuantity`\n * stay 1/10 on the wire and would wrongly let the buyer pick fewer. `step` is the\n * `multiplier` (the cart sells in blocks of N). Mirrors the old checkout's\n * `getTicketSelectOptions(maxCount, minCount, multiplier)` with\n * `maxCount = isTable ? maxGuests : maxQuantity`.\n */\nexport const ticketQuantityRange = (\n ticket: Pick<\n TicketType,\n 'isTable' | 'minQuantity' | 'maxQuantity' | 'minGuests' | 'maxGuests' | 'multiplier'\n >\n): { min: number; max: number; step: number } => ({\n min: ticket.isTable ? (ticket.minGuests ?? ticket.minQuantity) : ticket.minQuantity,\n max: ticket.isTable ? (ticket.maxGuests ?? ticket.maxQuantity) : ticket.maxQuantity,\n step: ticket.multiplier || 1,\n})\n\n/**\n * Reserved-seating detection. A seated event sells through a seat-map picker, so\n * a surface without one hands the buyer off to the event page. Accepts event\n * details, the cart/payment payload, or raw event attributes.\n */\nexport const isSeatedEvent = (event: object | null | undefined): boolean => {\n const e = (event || {}) as Record<string, unknown>\n return !!(e.seatMapAllowed || e.flagSeatMapAllowed || e.seat_map_allowed === 'yes')\n}\n","/**\n * Payment logic — the pure request-builders and response-interpreters each rail\n * needs: redirect confirm, OXXO voucher, PayPal Standard, saved-card plan, fee\n * re-price, MSI installments, and Xendit e-wallets. The `payment` api calls\n * these; they touch no transport.\n */\nimport { FEE_MODE_PAYMENT_METHOD_TYPES } from '../constants'\nimport type {\n ChangePaymentMethodInput,\n InstallmentOffer,\n InstallmentOffers,\n OxxoVoucher,\n PaymentMethodTypeInput,\n PaymentMethodTypeRequest,\n PayPalForm,\n RedirectConfirmResponse,\n RedirectOutcome,\n SavedPlanCard,\n XenditChargeOutcome,\n XenditEWalletChargeInput,\n} from '../dtos'\n\n// --- redirect methods ------------------------------------------------------\n\nexport const interpretRedirectConfirm = (\n response: RedirectConfirmResponse\n): RedirectOutcome => {\n if (response.requires_action && response.redirect_url) {\n return { kind: 'redirect', url: response.redirect_url }\n }\n if (response.requires_action && response.client_secret) {\n return {\n kind: 'inline_action',\n clientSecret: response.client_secret,\n nextActionType: response.next_action_type || '',\n }\n }\n if (response.requires_action) {\n return { kind: 'unresolved_action', status: response.status }\n }\n return { kind: 'settled', status: response.status }\n}\n\n// --- OXXO ------------------------------------------------------------------\n\n/** Read the voucher off a confirmed PaymentIntent's next action — tolerant of\n * both the web (oxxo_display_details) and RN (voucherURL) shapes. */\nexport const oxxoVoucherFromNextAction = (\n nextAction: Record<string, unknown> | null | undefined\n): OxxoVoucher | null => {\n if (!nextAction || typeof nextAction !== 'object') return null\n\n const details = nextAction.oxxo_display_details as Record<string, unknown> | undefined\n if (details && typeof details.hosted_voucher_url === 'string') {\n return {\n voucherUrl: details.hosted_voucher_url,\n voucherNumber: typeof details.number === 'string' ? details.number : null,\n expiresAt: typeof details.expires_after === 'number' ? details.expires_after : null,\n }\n }\n\n if (typeof nextAction.voucherURL === 'string' && nextAction.voucherURL) {\n return {\n voucherUrl: nextAction.voucherURL,\n voucherNumber:\n typeof nextAction.voucherNumber === 'string' ? nextAction.voucherNumber : null,\n expiresAt: typeof nextAction.expiration === 'number' ? nextAction.expiration : null,\n }\n }\n\n return null\n}\n\n// --- PayPal Standard + saved-card plan -------------------------------------\n\nexport const buildChangePaymentMethodAttributes = (\n input: ChangePaymentMethodInput\n): Record<string, unknown> => ({\n payment_method_id: input.paymentMethodId,\n payment_method_hash: input.paymentMethodHash,\n order_id: Number(input.orderId),\n order_hash: input.orderHash,\n redirect: false,\n})\n\nexport const resolvePayPalForm = (\n attributes: Record<string, unknown> | null | undefined\n): PayPalForm | null => {\n const actionUrl = attributes && attributes.action_url\n const fields = attributes && attributes.fields\n if (typeof actionUrl !== 'string' || !actionUrl) return null\n if (!fields || typeof fields !== 'object') return null\n return { action_url: actionUrl, fields: fields as Record<string, string> }\n}\n\n/** The saved-card shortcut off the review's payment_method — null unless the\n * plan configuration carries a reusable card. */\nexport const savedPlanCard = (\n paymentMethod: Record<string, unknown> | null | undefined\n): SavedPlanCard | null => {\n const plan = paymentMethod?.stripe_payment_plan_configuration as\n | Record<string, unknown>\n | undefined\n const savedCard = plan?.saved_card as Record<string, unknown> | undefined\n const paymentMethodId = savedCard?.stripe_payment_method_id\n if (typeof paymentMethodId !== 'string' || !paymentMethodId) return null\n return {\n last4: typeof savedCard?.last_4_digits === 'string' ? savedCard.last_4_digits : '',\n paymentMethodId,\n }\n}\n\n// --- fee re-price ----------------------------------------------------------\n\nexport const requiresFeeReprice = (type: string | null | undefined): boolean =>\n !!type && FEE_MODE_PAYMENT_METHOD_TYPES.has(type)\n\nexport const buildPaymentMethodTypeAttributes = (\n input: PaymentMethodTypeInput\n): PaymentMethodTypeRequest => ({\n payment_method_type: input.paymentMethodType,\n order_id: Number(input.orderId),\n order_hash: input.orderHash,\n stripe_intent_id: input.stripeIntentId,\n})\n\n/** A PaymentIntent client secret is `pi_<id>_secret_<nonce>` — the review\n * carries the secret, the re-price endpoint wants the id. Null for setup-intent\n * secrets (seti_…) and anything else. */\nexport const paymentIntentIdFromClientSecret = (\n clientSecret: string | null | undefined\n): string | null => {\n const match = /^(pi_[A-Za-z0-9]+)_secret_/.exec(clientSecret || '')\n return match ? match[1] : null\n}\n\n// --- MSI installments ------------------------------------------------------\n\nexport const buildInstallmentOffersFields = (input: {\n paymentIntentId: string\n paymentMethodId: string\n}): Record<string, string> => ({\n payment_intent: input.paymentIntentId,\n payment_method: input.paymentMethodId,\n})\n\nexport const resolveInstallmentOffers = (\n raw: Record<string, unknown> | null | undefined\n): InstallmentOffers => ({\n installments: Array.isArray(raw?.installments)\n ? (raw?.installments as InstallmentOffer[])\n : [],\n installmentsSupported: !!raw?.installments_supported,\n original:\n raw?.original && typeof raw.original === 'object'\n ? (raw.original as InstallmentOffers['original'])\n : {},\n})\n\nexport const buildConfirmInstallmentsFields = (input: {\n paymentIntentId: string\n offer: InstallmentOffer\n}): Record<string, string> => ({\n payment_intent: input.paymentIntentId,\n 'installments[count]': String(input.offer.count),\n 'installments[interval]': input.offer.interval,\n 'installments[type]': input.offer.type,\n})\n\nexport const confirmInstallmentsHasNextAction = (\n raw: Record<string, unknown> | null | undefined\n): boolean => !!raw?.has_next_action\n\n// --- Xendit e-wallets ------------------------------------------------------\n\n/** The flat form-field map (PHP bracket notation) the charge endpoint reads —\n * send it form-encoded, never as JSON. */\nexport const buildXenditEWalletChargeFields = (\n input: XenditEWalletChargeInput\n): Record<string, string> => {\n const fields: Record<string, string> = {\n order: String(input.orderId),\n orderHash: input.orderHash,\n 'paymentData[paymentType]': input.paymentType,\n }\n if (input.cashtag) fields['paymentData[data][cashtag]'] = input.cashtag\n if (input.phoneNumber) fields['paymentData[data][phoneNumber]'] = input.phoneNumber\n return fields\n}\n\nexport const interpretXenditChargeResponse = (\n raw: Record<string, unknown> | null | undefined\n): XenditChargeOutcome => {\n const redirectUrl = raw && raw.redirectUrl\n if (typeof redirectUrl === 'string' && redirectUrl) {\n return {\n kind: 'redirect',\n url: redirectUrl,\n notice: typeof raw?.popupMessage === 'string' ? raw.popupMessage : null,\n }\n }\n const reason =\n (typeof raw?.message === 'string' && raw.message) ||\n (typeof raw?.failure_reason === 'string' && raw.failure_reason) ||\n 'The payment could not be started. Please try again or pick a different payment method.'\n return { kind: 'failed', reason }\n}\n","/**\n * Payment-plan terms — the buyer-facing disclosure block.\n *\n * A faithful port of the hosted checkout's `renderPaymentPlanSelector`\n * (embed-checkout-app.js), which composes these paragraphs from the same\n * `payment_plan_configuration` the backend already sends us. Everything here is\n * pure string composition over the preview DTO, so web and native render the\n * identical wording and one set of tests covers both.\n *\n * This is not cosmetic copy. The admin-fee line states a real per-installment\n * charge, and the non-refundable line states what the buyer forfeits if they\n * default. A plan UI that omits them is understating the cost of the purchase.\n *\n * Wording is the hosted DEFAULT for each i18n key. Consumers that already\n * localize can map over the returned parts by `id`.\n */\nimport type { CheckoutPaymentPlanPreview } from '../dtos'\n\n/** The default word for a plan when the brand hasn't renamed it. */\nexport const DEFAULT_PLAN_TERMINOLOGY = 'Payment Plan'\n\n/** The brand's word for the plan — \"Payment Plan\", \"Layaway\", … */\nexport const planTerminology = (plan?: CheckoutPaymentPlanPreview | null): string =>\n plan?.terminology?.trim() || DEFAULT_PLAN_TERMINOLOGY\n\n/** `currency_symbol` + 2dp, matching the hosted `money()` helper exactly. */\nexport const formatPlanMoney = (\n plan: CheckoutPaymentPlanPreview | null | undefined,\n value: number | null | undefined\n): string => {\n const symbol = plan?.currencySymbol ?? ''\n const num = Number(value)\n return `${symbol}${Number.isFinite(num) ? num.toFixed(2) : String(value ?? '')}`\n}\n\n/** \"Click to pay in 3 payments with a Payment Plan\" — the opt-in label. */\nexport const planCheckboxLabel = (plan: CheckoutPaymentPlanPreview): string =>\n `Click to pay in ${plan.totalInstallments ?? 0} payments with a ${planTerminology(plan)}`\n\n/** The plan's submit CTA — \"Confirm Payment Plan\". */\nexport const planConfirmLabel = (plan?: CheckoutPaymentPlanPreview | null): string =>\n `Confirm ${planTerminology(plan)}`\n\n/** \"CN Brand TTF Payment Plan Terms\" — the terms heading. */\nexport const planTermsTitle = (plan: CheckoutPaymentPlanPreview): string =>\n `${plan.manufacturerName ?? ''} ${planTerminology(plan)} Terms`.trim()\n\n/** One paragraph of the terms block. `id` is stable for localization/testing. */\nexport interface PlanTermsParagraph {\n id: 'schedule' | 'adminFee' | 'nonRefundable' | 'custom' | 'note'\n text: string\n}\n\n/**\n * The schedule sentence — five variants, selected exactly as the hosted block\n * does: down-payment (event-anchored final / two-payment / many), the plain\n * two-payment case, then the general auto-equal / staged wording.\n */\nconst scheduleParagraph = (plan: CheckoutPaymentPlanPreview): string => {\n const terminology = planTerminology(plan)\n const installments = Math.trunc(Number(plan.totalInstallments ?? 0)) || 0\n const periodicity = plan.interval == null ? '' : String(plan.interval)\n const installmentPrice = formatPlanMoney(plan, plan.pricePerInstallment)\n const confirm = `By clicking on the \"Confirm ${terminology}\" button`\n\n if (plan.downPaymentEnabled && plan.downPaymentAmount != null) {\n const amount = formatPlanMoney(plan, plan.downPaymentAmount)\n const remaining = Math.max(installments - 1, 1)\n if (remaining === 1 && plan.isEventAnchored && plan.finalChargeDate) {\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by a final payment of ${installmentPrice} on ${plan.finalChargeDate}.`\n }\n if (remaining === 1) {\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by a final payment of ${installmentPrice} in ${periodicity} days.`\n }\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by ${remaining} further payments of ${installmentPrice}, drawn from your account every ${periodicity} days.`\n }\n\n if (installments === 2) {\n return `${confirm}, you are starting your ${terminology} of 2 payments of ${installmentPrice}, with the first payment taken today and the final payment in ${periodicity} days.`\n }\n\n return `${confirm}, you are starting your ${terminology} of ${installments} payments of ${installmentPrice}, which will be drawn from your account every ${periodicity} days, with the first payment taken today.`\n}\n\n/**\n * The full terms block, in render order. Empty when there is nothing to state\n * (no installment shape), so callers can render unconditionally.\n */\nexport const paymentPlanTerms = (\n plan: CheckoutPaymentPlanPreview | null | undefined\n): PlanTermsParagraph[] => {\n if (!plan || (plan.totalInstallments == null && plan.pricePerInstallment == null)) {\n return []\n }\n\n const parts: PlanTermsParagraph[] = [{ id: 'schedule', text: scheduleParagraph(plan) }]\n\n const hasAdminFee = Boolean(plan.hasAdminFee && plan.adminFee)\n if (hasAdminFee) {\n parts.push({\n id: 'adminFee',\n text: `This includes a non-refundable admin fee of ${formatPlanMoney(plan, plan.adminFee)} per payment.`,\n })\n }\n\n // The hosted flow folds the admin fee into the cancellation sentence unless\n // the event opts out — hence a clause rather than its own paragraph.\n const additionalClause =\n hasAdminFee && !plan.hideNonRefundableAdminFeeText\n ? ` and an admin fee of ${formatPlanMoney(plan, plan.adminFee)} for each installment paid,`\n : ''\n const forfeited = formatPlanMoney(plan, plan.totalNonRefundableAmount)\n const cancelled =\n 'If you do not complete your payments, your order will be cancelled. At that point,'\n const refunded = 'Any remaining amount you have paid will be refunded.'\n\n if (plan.nonRefundableType === 'fixed' && plan.totalNonRefundableAmount) {\n parts.push({\n id: 'nonRefundable',\n text: `${cancelled} a set amount of ${forfeited}${additionalClause} will not be refunded. ${refunded}`,\n })\n } else if (plan.nonRefundableType === 'percent' && plan.nonRefundableAmount) {\n parts.push({\n id: 'nonRefundable',\n text: `${cancelled} ${plan.nonRefundableAmount}% of your order total (${forfeited})${additionalClause} will not be refunded. ${refunded}`,\n })\n }\n\n if (plan.customMessage) {\n parts.push({ id: 'custom', text: String(plan.customMessage) })\n }\n\n parts.push({\n id: 'note',\n text: 'NOTE: If today’s payment fails, your plan will not activate. Your tickets will not be issued until you complete your final payment.',\n })\n\n return parts\n}\n","/**\n * Account/session logic — interpret the existing-account lookup and drive the\n * multi-currency preference sync.\n */\nimport type {\n ContactEmailResponse,\n CurrencyState,\n CurrencySync,\n CurrencySyncOptions,\n CurrencyTransport,\n ExistingAccount,\n} from '../dtos'\n\n/** Normalize the `/ajax/contact-email` response to a boolean existence flag. */\nexport const interpretContactEmail = (\n raw: Partial<ContactEmailResponse> | null | undefined\n): ExistingAccount => {\n const exists = !!raw && !raw.error && Number(raw.exists) === 1\n return {\n exists,\n verified: exists && typeof raw?.verified === 'boolean' ? raw.verified : null,\n }\n}\n\n/** True when the event offers more than one currency (render a switcher only\n * then — currency selection exists solely for multi-currency events). */\nexport const isMultiCurrency = (state: CurrencyState | null | undefined): boolean =>\n !!state && Array.isArray(state.available) && state.available.length > 1\n\n/**\n * Run a currency sync through the injected transport. A bare sync (no code)\n * geo-seeds and reports state; a code switches it (requiresCatalogRefresh — a\n * currency change is a full reprice, so refetch the catalog and reset selection).\n */\nexport const syncCurrency = async (\n transport: CurrencyTransport,\n eventId: string | number,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencySync> => {\n const state = await transport(eventId, code, options)\n return {\n state,\n requiresCatalogRefresh: !!code,\n }\n}\n","/**\n * Authentication rules shared by web and React Native. This module is pure:\n * no React, browser APIs, FormData, or transport. Platform UI owns only field\n * rendering while the API layer owns the final multipart encoding.\n */\nimport type {\n AuthFieldErrors,\n AuthLoginInput,\n AuthRegistrationInput,\n AuthValidationResult,\n} from '../dtos'\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst SPECIAL_CHARACTER = /[^A-Za-z0-9]/\n\nconst result = (errors: AuthFieldErrors): AuthValidationResult => ({\n valid: Object.keys(errors).length === 0,\n errors,\n})\n\nexport const normalizeAuthEmail = (email: string): string => email.trim().toLowerCase()\n\nexport const validateLoginInput = (input: AuthLoginInput): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const email = normalizeAuthEmail(input.email)\n if (!email) errors.email = 'Email is required.'\n else if (!EMAIL.test(email)) errors.email = 'Enter a valid email address.'\n if (!input.password) errors.password = 'Password is required.'\n return result(errors)\n}\n\nexport const validatePasswordResetEmail = (email: string): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const normalized = normalizeAuthEmail(email)\n if (!normalized) errors.email = 'Email is required.'\n else if (!EMAIL.test(normalized)) errors.email = 'Enter a valid email address.'\n return result(errors)\n}\n\nexport const validateRegistrationInput = (\n input: AuthRegistrationInput,\n options: { requireAddress?: boolean; requireState?: boolean } = {}\n): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const email = normalizeAuthEmail(input.email)\n\n if (!input.firstName.trim()) errors.firstName = 'First name is required.'\n if (!input.lastName.trim()) errors.lastName = 'Last name is required.'\n if (!email) errors.email = 'Email is required.'\n else if (!EMAIL.test(email)) errors.email = 'Enter a valid email address.'\n\n if (!input.password) errors.password = 'Password is required.'\n else if (input.password.length < 8)\n errors.password = 'Password must be at least 8 characters.'\n else if (!SPECIAL_CHARACTER.test(input.password))\n errors.password = 'Password must include a special character.'\n\n if (!input.passwordConfirmation) errors.passwordConfirmation = 'Confirm your password.'\n else if (input.passwordConfirmation !== input.password)\n errors.passwordConfirmation = 'Passwords do not match.'\n\n if (options.requireAddress) {\n if (!input.streetAddress?.trim()) errors.streetAddress = 'Street address is required.'\n if (!input.city?.trim()) errors.city = 'City is required.'\n if (!input.zip?.trim()) errors.zip = 'ZIP / postcode is required.'\n if (!input.countryId) errors.countryId = 'Country is required.'\n }\n if (options.requireState && !input.stateId)\n errors.stateId = 'State / region is required.'\n\n return result(errors)\n}\n\n/** Map the platform-neutral shape to the backend's registration contract. */\nexport const buildRegistrationFields = (\n input: AuthRegistrationInput\n): Record<string, string> => {\n const fields: Record<string, string> = {\n first_name: input.firstName.trim(),\n last_name: input.lastName.trim(),\n email: normalizeAuthEmail(input.email),\n password: input.password,\n password_confirmation: input.passwordConfirmation,\n }\n\n const optional: Array<[string, string | undefined]> = [\n ['phone', input.phone?.trim()],\n ['street_address', input.streetAddress?.trim()],\n ['city', input.city?.trim()],\n ['zip', input.zip?.trim()],\n ['country', input.countryId],\n ['state', input.stateId],\n ]\n for (const [key, value] of optional) {\n if (value) fields[key] = value\n }\n return { ...fields, ...input.registrationFields }\n}\n","/**\n * ID-verification poller — a NEED_ID_VERIFICATION order signals\n * `needIdVerification`; the buyer completes the provider check in a new\n * tab/window while this polls `GET v1/order/:hash/id-verification` until\n * verified. Pure state machine — fetch and clock are injected, so it runs\n * identically in React, React Native, and tests (5s ticks, capped).\n */\nimport type {\n IdVerificationCallbacks,\n IdVerificationPoller,\n IdVerificationStatus,\n} from '../dtos'\n\nexport const ID_VERIFICATION_POLL_MS = 5000\nexport const ID_VERIFICATION_MAX_TICKS = 60\nexport const ID_VERIFICATION_MAX_CONSECUTIVE_FAILURES = 3\n\nexport const createIdVerificationPoller = (\n callbacks: IdVerificationCallbacks\n): IdVerificationPoller => {\n const schedule =\n callbacks.schedule || ((fn: () => void, ms: number) => setTimeout(fn, ms))\n let ticks = 0\n let consecutiveFailures = 0\n let stopped = false\n // Injected schedulers can't be portably cancelled, so a generation token\n // invalidates ticks scheduled by a previous start()/stop() cycle.\n let generation = 0\n\n const scheduleNextOrTimeout = (\n runGeneration: number,\n status?: IdVerificationStatus\n ) => {\n ticks += 1\n if (ticks >= ID_VERIFICATION_MAX_TICKS) {\n callbacks.onPhase('timeout', status)\n return\n }\n schedule(() => tick(runGeneration), ID_VERIFICATION_POLL_MS)\n }\n\n const tick = (runGeneration: number) => {\n if (stopped || runGeneration !== generation) return\n callbacks\n .fetchStatus()\n .then((status) => {\n if (stopped || runGeneration !== generation) return\n consecutiveFailures = 0\n if (status.verified || !status.required) {\n callbacks.onPhase('verified', status)\n return\n }\n scheduleNextOrTimeout(runGeneration, status)\n })\n .catch(() => {\n if (stopped || runGeneration !== generation) return\n // Transient failures keep polling — the buyer may be mid-check — but a\n // persistently failing endpoint surfaces as an error instead of five\n // silent minutes.\n consecutiveFailures += 1\n if (consecutiveFailures >= ID_VERIFICATION_MAX_CONSECUTIVE_FAILURES) {\n callbacks.onPhase('error')\n return\n }\n scheduleNextOrTimeout(runGeneration)\n })\n }\n\n return {\n start: () => {\n stopped = false\n ticks = 0\n consecutiveFailures = 0\n generation += 1\n // Capture before onPhase — a synchronously re-entrant start() inside the\n // callback must make THIS run stale, not adopt its token.\n const runGeneration = generation\n callbacks.onPhase('polling')\n tick(runGeneration)\n },\n stop: () => {\n stopped = true\n generation += 1\n },\n }\n}\n","/**\n * The checkout store — a tiny framework-agnostic observable over the\n * `CheckoutSnapshot`. The engine writes to it; `useCheckout()` (or a plain\n * `subscribe()` in a non-React app) reads from it. No React, no globals: the\n * same store instance drives web, React Native, Node, and tests.\n *\n * State updates are immutable (a new snapshot object each change) so\n * `useSyncExternalStore` and shallow-equality consumers re-render correctly.\n *\n * `progress` is separate on purpose: it holds the retry-safety bookkeeping\n * (which order exists, whether it's been charged) that must NEVER be part of\n * the reactive snapshot — it's how retries avoid creating a second order or\n * charging twice.\n */\nimport type { CheckoutSnapshot } from '../dtos'\n\nexport type CheckoutListener = (snapshot: CheckoutSnapshot) => void\n\n/** Retry-safety bookkeeping — mutated directly by the engine, never rendered. */\nexport interface OrderProgress {\n /** The created order's hash — a retry reuses it instead of minting a second. */\n orderHash?: string\n /** True once the charge landed — a retry then only replays finalization. */\n paymentConfirmed?: boolean\n}\n\nexport interface CheckoutStore {\n /** The current snapshot (stable reference until the next change). */\n getState: () => CheckoutSnapshot\n /** Merge a partial snapshot (or a function of the current one) and notify. */\n setState: (\n patch:\n | Partial<CheckoutSnapshot>\n | ((prev: CheckoutSnapshot) => Partial<CheckoutSnapshot>)\n ) => void\n /** Subscribe to changes; returns an unsubscribe function. */\n subscribe: (listener: CheckoutListener) => () => void\n /** Reset to the initial idle snapshot (and clear progress) and notify. */\n reset: () => void\n /** Retry-safety state (order hash + charged flag). Not reactive. */\n progress: OrderProgress\n /** Drop any half-created order — the cart contents changed, so a previously\n * created order is stale and must not be reused. */\n invalidateOrderProgress: () => void\n /** Move to the terminal 'expired' state and clear progress. */\n expireCart: () => void\n}\n\n/** The empty checkout — what every store starts at and `reset()` returns to. */\nexport const initialSnapshot = (): CheckoutSnapshot => ({\n status: 'idle',\n selections: [],\n ticketTypeIds: [],\n customFields: [],\n holderNamesRequired: false,\n fieldGates: {\n showNationality: false,\n nationalityRequired: false,\n showGender: false,\n genderRequired: false,\n requireInstagram: false,\n showPhone: false,\n phoneRequired: false,\n showDob: false,\n dobRequired: false,\n showAddress: false,\n },\n addOns: {},\n holders: [],\n consent: { ttfOptIn: false, brandOptIn: false },\n})\n\nexport const createCheckoutStore = (\n initial: CheckoutSnapshot = initialSnapshot()\n): CheckoutStore => {\n let state = initial\n const listeners = new Set<CheckoutListener>()\n // .forEach (not for-of) so the SDK stays iterable under an es5 consumer target.\n const emit = () => {\n listeners.forEach((listener) => listener(state))\n }\n\n const store: CheckoutStore = {\n progress: {},\n getState: () => state,\n setState: (patch) => {\n const next = typeof patch === 'function' ? patch(state) : patch\n state = { ...state, ...next }\n emit()\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n reset: () => {\n state = initialSnapshot()\n store.progress = {}\n emit()\n },\n invalidateOrderProgress: () => {\n store.progress = {}\n },\n expireCart: () => {\n store.progress = {}\n state = { ...state, status: 'expired' }\n emit()\n },\n }\n return store\n}\n","/**\n * The payment-confirmation port — the hexagonal seam that keeps the engine\n * framework- AND payment-SDK-agnostic. The orchestration is pure TS EXCEPT for\n * the calls that talk to a Stripe SDK (init, read intent status, confirm card /\n * wallet). Those live behind this interface: React Native binds it with\n * @stripe/stripe-react-native, web with stripe-js, tests with a fake.\n *\n * Status vocabulary: confirmers return Stripe PaymentIntent statuses in the RN\n * SDK's PascalCase form ('Succeeded' | 'RequiresCapture' | 'Processing' | …).\n * Adapters over SDKs with other spellings (stripe-js is lowercase) normalize.\n */\nimport type { CheckoutBilling, InstallmentOffer, PayPalForm } from '../dtos'\n\nexport interface PaymentConfirmer {\n /** Initialize the underlying SDK for the given keys. */\n init(options: {\n publishableKey: string\n /** Stripe connected-account id (already cleaned — never ''). */\n accountId?: string\n /** Apple Pay merchant id, when the platform supports it. */\n merchantIdentifier?: string\n /** App deep-link scheme (React Native) — redirect methods return through it. */\n urlScheme?: string\n }): Promise<void>\n\n /** Status of the PaymentIntent behind `clientSecret`, or undefined when it\n * can't be retrieved. Used to skip re-charging on retries. */\n getIntentStatus(clientSecret: string): Promise<string | undefined>\n\n /** Confirm a card payment. Returns the resulting intent status or throws. */\n confirmCard(clientSecret: string, billing: CheckoutBilling): Promise<string | undefined>\n\n /** Present the platform-pay sheet (Apple Pay on iOS). Returns the resulting\n * intent status or throws — a user-cancelled sheet is an error. */\n confirmApplePay(\n clientSecret: string,\n total: string,\n currencyCode: string,\n merchant: { merchantCountryCode?: string; merchantName?: string }\n ): Promise<string | undefined>\n\n /** Present the Google Pay sheet (Android). Optional — only platforms with a\n * native Google Pay SDK bind it; unbound, the engine throws UNSUPPORTED_GATEWAY. */\n confirmGooglePay?(\n clientSecret: string,\n total: string,\n currencyCode: string,\n merchant: {\n merchantCountryCode?: string\n merchantName?: string\n /** Use Google Pay's TEST environment (no real charge). */\n testEnv?: boolean\n }\n ): Promise<string | undefined>\n}\n\n/**\n * A payment is confirmed enough to finalize in any of these states: Succeeded\n * (auto-capture), RequiresCapture (manual-capture authorizes now, captures\n * later — NOT a failure), or Processing (settling asynchronously).\n */\nexport const CONFIRMED_INTENT_STATUSES: string[] = [\n 'Succeeded',\n 'RequiresCapture',\n 'Processing',\n]\n\n/**\n * A Stripe connected-account id, or undefined when there is none. The backend\n * returns '' for platform-account events; passing '' sets an empty\n * `Stripe-Account` header, which Stripe rejects — coerce empties to undefined.\n */\nexport const cleanAccountId = (id?: string | null): string | undefined =>\n id && id.trim() ? id : undefined\n\n/**\n * Optional confirmer capabilities the alternative rails need. A platform that\n * doesn't implement one simply can't run that rail — the engine throws a typed\n * UNSUPPORTED_GATEWAY error instead of failing mid-payment.\n */\nexport interface PaymentConfirmerExtras {\n /** Create a card PaymentMethod (MSI offer lookup runs between creation and\n * the confirm). Returns the PaymentMethod id. */\n createCardPaymentMethod?(billing: CheckoutBilling): Promise<string>\n /** Create a redirect-method PaymentMethod (Klarna/Afterpay/iDEAL-class).\n * Returns the id, or null when the platform can't express the type. */\n createRedirectPaymentMethod?(\n methodType: string,\n billing: CheckoutBilling\n ): Promise<string | null>\n /** Run the pending next action of a SERVER-confirmed intent (MSI). Throws on\n * failure; never confirms a second time. */\n handleNextAction?(clientSecret: string): Promise<void>\n /** Confirm an OXXO voucher intent. Returns the raw nextAction payload (engine\n * extracts the voucher) plus any error — Stripe can report an error while\n * still issuing the voucher. */\n confirmOxxo?(\n clientSecret: string,\n billing: CheckoutBilling\n ): Promise<{ error?: string; nextAction?: unknown }>\n /** Payment plan (new card): confirm the review's SetupIntent to SAVE the card\n * — NOTHING is charged; the plan schedules server-side. Returns the saved\n * PaymentMethod id, or throws. */\n confirmPaymentPlanSetup?(\n clientSecret: string,\n billing: CheckoutBilling\n ): Promise<string>\n /** Payment plan (saved-card shortcut): confirm an on-session card payment\n * against an EXISTING PaymentMethod — the 3DS step runs only when the plan\n * charge comes back requires_action. Throws on failure. */\n confirmSavedCardPayment?(clientSecret: string, paymentMethodId: string): Promise<void>\n}\n\n/** What a provider page run should load: a URL, or an inline HTML document\n * (PayPal's auto-submitting top-level form). */\nexport interface ProviderPageRequest {\n uri?: string\n html?: string\n /** Base URL for an inline document (relative return-leg resolution). */\n baseUrl?: string\n /** Navigating to a URL with this prefix ends the run as 'success'. */\n returnUrlPrefix: string\n}\n\nexport interface ProviderPageOutcome {\n event: 'success' | 'dismiss' | 'failed'\n /** The intercepted return URL (carries e.g. `redirect_status`). */\n returnUrl?: string\n /** Payload posted by data-driven sheets (Razorpay's `razorpay_payment_id`,\n * Xendit card tokenization's `token`) — the platform's plumbing delivers it. */\n data?: Record<string, unknown>\n description?: string\n}\n\n/**\n * The full port set the pay rails run on. `confirmer` is required (card/Apple\n * Pay); the rest are optional platform capabilities:\n * - providerPage: run a provider's page and resolve on the return leg (a\n * WebView sheet on RN, a redirect/popup on web).\n * - openUrl: open an external URL (OXXO voucher, ID-verification).\n * - onInstallmentOffers: offer MSI plans; resolve the chosen one, or null to\n * decline and fall through to a normal single charge.\n * - tokenizeXenditCard: tokenize a Xendit card inline (web); when absent the\n * engine runs the Xendit card document through `providerPage`.\n */\nexport interface CheckoutPorts extends PaymentConfirmerExtras {\n confirmer: PaymentConfirmer\n providerPage?: (request: ProviderPageRequest) => Promise<ProviderPageOutcome>\n openUrl?: (url: string) => void | Promise<void>\n onInstallmentOffers?: (offers: InstallmentOffer[]) => Promise<InstallmentOffer | null>\n tokenizeXenditCard?: (params: {\n publishableKey: string\n amount: string | number\n billing: CheckoutBilling\n onBehalfOf?: string | null\n }) => Promise<Record<string, unknown>>\n}\n\n/** A typed \"this platform can't run this rail\" error — consumers branch on\n * `code` to hand off to the event page. */\nexport const unsupportedGatewayError = (message?: string): Error & { code: string } => {\n const err = new Error(\n message ??\n \"This payment method isn't available in the app. Please finish buying on the event page.\"\n ) as Error & { code: string }\n err.code = 'UNSUPPORTED_GATEWAY'\n return err\n}\n\nconst escapeHtmlAttribute = (value: string) =>\n value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n\n/**\n * PayPal Standard runs as a TOP-LEVEL form POST (PayPal refuses framing) — an\n * auto-submitting form document is all the provider page needs to load.\n */\nexport const buildAutoSubmitFormHtml = (form: PayPalForm): string => {\n const inputs = Object.entries(form.fields)\n .map(\n ([name, value]) =>\n `<input type=\"hidden\" name=\"${escapeHtmlAttribute(name)}\" value=\"${escapeHtmlAttribute(String(value ?? ''))}\" />`\n )\n .join('\\n ')\n\n return `<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n </head>\n <body>\n <form id=\"gateway-form\" method=\"POST\" action=\"${escapeHtmlAttribute(form.action_url)}\">\n ${inputs}\n </form>\n <script>\n document.getElementById('gateway-form').submit();\n </script>\n </body>\n</html>`\n}\n","/**\n * Gateway sheet documents (Razorpay web checkout, Xendit card tokenization) —\n * pure HTML string builders the `providerPage` port loads (a WebView on RN, a\n * popup on web). No runtime deps: these just build a document; the raw card\n * details never leave the page — only the resulting token/payment id is posted\n * back through the provider-page outcome.\n */\nexport interface RazorpayCheckoutHtmlOptions {\n keyId: string\n /** Charge amount in minor units (paise) — the server's pay_now × 100. */\n amountMinor: number\n description?: string\n buyerName?: string\n buyerEmail?: string\n orderHash: string\n}\n\n/**\n * Razorpay hosted checkout inside a WebView. Reports back via\n * `window.ReactNativeWebView.postMessage` with `{event:'success',\n * razorpay_payment_id}` / `{event:'dismiss'}` / `{event:'failed', description}`.\n * `notes.order_hash` ties the charge to the order server-side.\n */\nexport const buildRazorpayCheckoutHtml = (\n options: RazorpayCheckoutHtmlOptions\n): string => {\n const rzpOptions = JSON.stringify({\n key: options.keyId,\n amount: Math.round(options.amountMinor),\n name: 'Ticket Fairy',\n description: options.description || '',\n prefill: {\n name: options.buyerName || '',\n email: options.buyerEmail || '',\n },\n notes: {\n order_hash: options.orderHash,\n },\n })\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<script src=\"https://checkout.razorpay.com/v1/checkout.js\"></script>\n</head>\n<body style=\"margin:0;background:#ffffff\">\n<script>\n function report(payload) {\n if (window.ReactNativeWebView) {\n window.ReactNativeWebView.postMessage(JSON.stringify(payload));\n }\n }\n try {\n var options = ${rzpOptions};\n options.handler = function (response) {\n report({\n event: 'success',\n razorpay_payment_id: response && response.razorpay_payment_id,\n });\n };\n options.modal = {\n ondismiss: function () {\n report({ event: 'dismiss' });\n },\n };\n var rzp = new Razorpay(options);\n rzp.on('payment.failed', function (resp) {\n report({\n event: 'failed',\n description: resp && resp.error && resp.error.description,\n });\n });\n rzp.open();\n } catch (e) {\n report({ event: 'failed', description: e && e.message });\n }\n</script>\n</body>\n</html>`\n}\n\nexport interface XenditCheckoutHtmlOptions {\n publishableKey: string\n /** Tokenization amount — the server-returned pay-now figure verbatim. The\n * CHARGE amount stays server-side in submit-payment. */\n amount: number | string\n buyerFirstName?: string\n buyerLastName?: string\n buyerEmail?: string\n buyerPhone?: string\n onBehalfOf?: string | null\n}\n\n/**\n * Xendit card tokenization inside a WebView: card entry, `Xendit.card.createToken`\n * with 3DS (the challenge iframe re-invokes the handler when it resolves),\n * reporting `{event:'success', token}` / `{event:'failed', description}`.\n */\nexport const buildXenditCheckoutHtml = (options: XenditCheckoutHtmlOptions): string => {\n const opts = JSON.stringify({\n publishableKey: options.publishableKey,\n amount: options.amount,\n firstName: options.buyerFirstName || '',\n lastName: options.buyerLastName || '',\n email: options.buyerEmail || '',\n phone: options.buyerPhone || '',\n onBehalfOf: options.onBehalfOf || null,\n })\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<script src=\"https://js.xendit.co/v1/xendit.min.js\"></script>\n<style>\n body { margin: 0; background: #ffffff; font-family: -apple-system, Roboto, sans-serif; }\n .wrap { padding: 16px; }\n label { display: block; font-size: 14px; margin-bottom: 12px; color: #333; }\n input { display: block; width: 100%; box-sizing: border-box; margin-top: 4px;\n padding: 12px 10px; font-size: 16px; border: 1px solid #e0e0e0; border-radius: 8px; }\n .row { display: flex; gap: 12px; }\n .row label { flex: 1; }\n .note { font-size: 13px; color: #666; margin-bottom: 12px; display: none; }\n .err { font-size: 13px; color: #c0392b; margin-bottom: 12px; min-height: 16px; }\n button { width: 100%; padding: 14px; font-size: 16px; border: 0; border-radius: 8px;\n background: #111111; color: #ffffff; }\n button:disabled { opacity: 0.5; }\n #threeds { display: none; position: fixed; inset: 0; background: #ffffff; }\n #threeds iframe { width: 100%; height: 100%; border: 0; }\n</style>\n</head>\n<body>\n<div class=\"wrap\">\n <label>Card number\n <input id=\"num\" inputmode=\"numeric\" autocomplete=\"cc-number\">\n </label>\n <div class=\"row\">\n <label>Expiry (MM/YY)\n <input id=\"exp\" inputmode=\"numeric\" autocomplete=\"cc-exp\" placeholder=\"MM/YY\">\n </label>\n <label>Security code\n <input id=\"cvn\" type=\"password\" inputmode=\"numeric\" autocomplete=\"cc-csc\">\n </label>\n </div>\n <div class=\"note\" id=\"note\">Your bank may ask you to confirm it’s really you.</div>\n <div class=\"err\" id=\"err\"></div>\n <button id=\"pay\">Submit Payment</button>\n</div>\n<div id=\"threeds\"><iframe id=\"threedsFrame\"></iframe></div>\n<script>\n var OPTS = ${opts};\n var payBtn = document.getElementById('pay');\n var errBox = document.getElementById('err');\n var note = document.getElementById('note');\n var threeds = document.getElementById('threeds');\n var threedsFrame = document.getElementById('threedsFrame');\n var submitting = false;\n\n function report(payload) {\n if (window.ReactNativeWebView) {\n window.ReactNativeWebView.postMessage(JSON.stringify(payload));\n }\n }\n function reset(message) {\n submitting = false;\n payBtn.disabled = false;\n note.style.display = 'none';\n threeds.style.display = 'none';\n threedsFrame.src = 'about:blank';\n errBox.textContent = message || '';\n }\n\n function handler(err, token) {\n if (err) {\n reset(err.message || 'Your payment was not accepted. Please try again or use a different card.');\n return;\n }\n if (token.status === 'VERIFIED') {\n threeds.style.display = 'none';\n report({ event: 'success', token: token });\n } else if (token.status === 'IN_REVIEW' && token.payer_authentication_url) {\n note.style.display = 'block';\n threedsFrame.src = token.payer_authentication_url;\n threeds.style.display = 'block';\n } else {\n var reason = token && token.failure_reason ? ' (' + token.failure_reason + ')' : '';\n reset('Your payment was not accepted' + reason + '. Please try again or use a different card.');\n }\n }\n\n payBtn.addEventListener('click', function () {\n if (submitting) return;\n errBox.textContent = '';\n var number = (document.getElementById('num').value || '').replace(/\\\\s+/g, '');\n var expParts = (document.getElementById('exp').value || '').split('/');\n var expMonth = (expParts[0] || '').trim();\n var expYear = (expParts[1] || '').trim();\n if (expYear.length === 2) expYear = '20' + expYear;\n var cvn = (document.getElementById('cvn').value || '').trim();\n if (!number || !expMonth || !expYear || !cvn) {\n errBox.textContent = 'Please fill in your card details.';\n return;\n }\n if (!window.Xendit) {\n report({ event: 'failed', description: 'The payment service could not be loaded.' });\n return;\n }\n submitting = true;\n payBtn.disabled = true;\n try {\n window.Xendit.setPublishableKey(OPTS.publishableKey);\n var data = {\n amount: OPTS.amount,\n card_number: number,\n card_exp_month: expMonth,\n card_exp_year: expYear,\n card_cvn: cvn,\n is_multiple_use: false,\n should_authenticate: true,\n };\n // card_holder_* fields are ALL-OR-NOTHING peers in Xendit's validation —\n // send the group only when complete.\n if (OPTS.firstName && OPTS.lastName && OPTS.email && OPTS.phone) {\n data.card_holder_first_name = OPTS.firstName;\n data.card_holder_last_name = OPTS.lastName;\n data.card_holder_email = OPTS.email;\n data.card_holder_phone_number = OPTS.phone;\n }\n if (OPTS.onBehalfOf) data.on_behalf_of = OPTS.onBehalfOf;\n window.Xendit.card.createToken(data, handler);\n } catch (e) {\n reset((e && e.message) || 'Something went wrong. Please try again.');\n }\n });\n</script>\n</body>\n</html>`\n}\n","/**\n * Engine error helpers. Failures already arrive as `TtfError` (the transport\n * normalizes them), so these just read it: a friendly message, and whether the\n * failure is the backend rejecting an expired cart/checkout session.\n */\nimport { toTtfError } from '../client'\n\n/** The friendliest message for a failed call (the backend's own, else generic). */\nexport const errorMessage = (error: unknown): string => toTtfError(error).message\n\n/**\n * \"expired\" in the languages the backend's per-locale cart-expiry message can\n * use. Message-sniffing is a fallback — the 422 body carries no structured code.\n */\nconst EXPIRED_WORDS =\n /expir|caduc|scadut|abgelaufen|verlopen|udløbet|löpt ut|utløpt|vypršel|wygasł|истек|expirou|kedaluwarsa|hết hạn|期限切れ|已过期|已過期|만료/i\n\n/**\n * True when a failed request is the backend rejecting an expired cart/checkout\n * session (422 + an \"…expired\" message). Lets the flow show a \"restart\"\n * recovery instead of a raw error; ordinary 422 validation errors stay generic.\n */\nexport const isCartExpiredError = (error: unknown): boolean => {\n const e = toTtfError(error)\n if (e.status !== 422) return false\n return EXPIRED_WORDS.test(e.message)\n}\n","/**\n * The raw api surface — one function per endpoint, each \"just does the call\"\n * and returns typed data (or throws `TtfError`). The `ttf` facade in\n * `services.ts` is a thin, domain-grouped convenience over exactly these.\n * Power users can import them directly.\n */\nexport * from './auth'\nexport * from './profile'\nexport * from './geo'\nexport * from './engagement'\nexport * from './orders'\nexport * from './resale'\nexport * from './confirmation'\nexport * from './preRegistration'\nexport * from './delegation'\nexport * from './seatmap'\n// Checkout flow — catalog, cart/pricing, order, payment rails\nexport * from './events'\nexport * from './cart'\nexport * from './order'\nexport * from './payment'\n","/**\n * Profile reads. The signed-in user's record, straight off `/customer/profile/`.\n * (Login lives in `auth.ts`; this is imported there to resolve the profile after\n * the token lands.)\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfEnvelope, TfProfile } from '../types'\n\n/** Fetch the signed-in user's profile. Throws `TtfError` if unauthenticated. */\nexport const getProfile = async (): Promise<TfProfile> => {\n const res = await get<TfEnvelope<TfProfile>>(ENDPOINTS.profile.get, {\n withCredentials: true,\n })\n return res.data\n}\n","/**\n * Auth — the whole surface, not just login. This is the domain shared was\n * missing most: register, password reset/restore, logout, email-exists.\n *\n * Login is the platform's two-step OAuth chain (authorize-rn → access_token);\n * on success we persist the tokens via the session module and every later call\n * rides the bearer automatically.\n */\nimport { getConfig, getOriginUrl } from '../client/config'\nimport { TtfError } from '../client/errors'\nimport { del, get, patch, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { clearSession, notifyCookieSession, setTokens } from '../client/session'\nimport type { AuthRegistrationInput } from '../dtos'\nimport { buildRegistrationFields } from '../logic/auth'\nimport { TfEnvelope, TfProfile } from '../types'\nimport { getProfile } from './profile'\n\nconst toFormData = (fields: Record<string, string | Blob>): FormData => {\n const form = new FormData()\n for (const [key, value] of Object.entries(fields)) form.append(key, value)\n return form\n}\n\n/**\n * Sign in with email + password. Runs the OAuth chain, stores the tokens, and\n * resolves to the freshly-loaded profile. Throws `TtfError` on bad credentials.\n */\nexport const login = async (email: string, password: string): Promise<TfProfile> => {\n const { clientId, clientSecret, cookieAuth } = getConfig()\n\n // Web checkouts share TicketFairy's session cookie (`cookieAuth`). Sign in the\n // way the legacy checkout did — POST /auth (backend `customerLogin`) — so the\n // server issues the X-TF-ECOMMERCE session ticket and the buyer stays on the\n // SAME session that already holds their reserved cart. The OAuth bearer chain\n // below issues no such ticket and rides a separate identity, so a guest who\n // logs in mid-checkout loses the reserved cart and the next on-checkout 422s\n // with \"cart expired\". Bearerless by design (no `setTokens`), exactly like the\n // old flow — the response interceptor captures the ticket the backend returns.\n if (cookieAuth) {\n await post(`${ENDPOINTS.auth.session}?clientId=${clientId}`, { email, password })\n const profile = await getProfile()\n notifyCookieSession()\n return profile\n }\n\n if (!clientId || !clientSecret) {\n throw new TtfError('login: clientId/clientSecret are not configured.', 0)\n }\n\n const authorize = await post<{ data?: { code?: string } }>(\n ENDPOINTS.auth.authorizeRn(clientId),\n toFormData({ email, password }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n const code = authorize.data?.code\n if (!code) throw new TtfError('login: authorization code not received.', 0)\n\n const token = await post<{ access_token?: string; refresh_token?: string }>(\n ENDPOINTS.auth.accessToken,\n toFormData({\n code,\n scope: 'profile',\n grant_type: 'authorization_code',\n client_id: clientId,\n client_secret: clientSecret,\n }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n if (!token.access_token) throw new TtfError('login: no access token received.', 0)\n\n setTokens({ access: token.access_token, refresh: token.refresh_token })\n return getProfile()\n}\n\n/**\n * Create an account. Pass the registration fields as a flat record — the\n * backend endpoint (`v1/oauth/register-rn`) takes multipart form data, so field\n * names are forwarded verbatim (`email`, `password`, `first_name`, …).\n */\nexport const register = async (\n fields: Record<string, string | Blob>\n): Promise<TfProfile> => {\n const { clientId, clientSecret } = getConfig()\n const requestFields = {\n ...fields,\n client_id: fields.client_id ?? clientId,\n client_secret: fields.client_secret ?? clientSecret,\n }\n if (!requestFields.client_id || !requestFields.client_secret) {\n throw new TtfError('register: clientId/clientSecret are not configured.', 0)\n }\n const res = await post<\n | TfEnvelope<TfProfile>\n | {\n data?: {\n attributes?: {\n access_token?: string\n refresh_token?: string\n user_profile?: Record<string, unknown>\n }\n }\n }\n >(ENDPOINTS.auth.registerRn, toFormData(requestFields), {\n headers: { 'Content-Type': 'multipart/form-data' },\n })\n const data = res.data\n const attributes =\n data && typeof data === 'object' && 'attributes' in data ? data.attributes : undefined\n if (attributes?.access_token) {\n setTokens({\n access: attributes.access_token,\n refresh: attributes.refresh_token,\n })\n try {\n return await getProfile()\n } catch {\n // Some staging responses expose a reduced profile while the full profile\n // endpoint catches up. Fall through to it instead of failing a completed\n // registration.\n }\n }\n\n const candidate = (attributes?.user_profile ?? data) as Record<string, unknown>\n const firstName = String(candidate?.firstName ?? candidate?.first_name ?? '')\n const lastName = String(candidate?.lastName ?? candidate?.last_name ?? '')\n const email = String(candidate?.email ?? '')\n return {\n id: String(candidate?.id ?? ''),\n firstName,\n lastName,\n email,\n phone: candidate?.phone ? String(candidate.phone) : undefined,\n streetAddress: candidate?.streetAddress\n ? String(candidate.streetAddress)\n : candidate?.street_address\n ? String(candidate.street_address)\n : undefined,\n zipCode: candidate?.zipCode\n ? String(candidate.zipCode)\n : candidate?.zip\n ? String(candidate.zip)\n : undefined,\n countryId: String(candidate?.countryId ?? candidate?.country_id ?? ''),\n company: null,\n stateId: candidate?.stateId\n ? String(candidate.stateId)\n : candidate?.state_id\n ? String(candidate.state_id)\n : undefined,\n city: candidate?.city ? String(candidate.city) : undefined,\n username: String(candidate?.username ?? email),\n screenName: null,\n bio: null,\n shortBio: null,\n region: null,\n image: null,\n recommendedEvents: [],\n rnRoles: [],\n hasDashboardAccess: false,\n ticketHolders: [],\n linkedCryptoWallets: [],\n }\n}\n\n/** Typed registration used by platform auth flows. */\nexport const registerAccount = (input: AuthRegistrationInput): Promise<TfProfile> =>\n register(buildRegistrationFields(input))\n\n/** Kick off the \"forgot password\" email for an address. */\nexport const restorePassword = async (email: string): Promise<void> => {\n await post(ENDPOINTS.auth.restorePassword, { email })\n}\n\n/** Complete a password reset with the token from the email. */\nexport const resetPassword = async (input: {\n token: string\n password: string\n passwordConfirmation?: string\n}): Promise<void> => {\n await post(ENDPOINTS.auth.resetPassword, {\n token: input.token,\n password: input.password,\n password_confirmation: input.passwordConfirmation ?? input.password,\n })\n}\n\n/** React Native \"forgot password\" variant (`v1/oauth/restore-password-rn`). */\nexport const restorePasswordRn = async (email: string): Promise<void> => {\n await post(ENDPOINTS.auth.restorePasswordRn, { email })\n}\n\n// --- Account identity verification (Netverify/Jumio, `v1/authenticate/*`) ----\n\n/** Mint (or read) the hosted identity-verification URL for the signed-in user. */\nexport const mintVerificationUrl = async (): Promise<unknown> =>\n get(ENDPOINTS.auth.verify)\n\n/** Read the signed-in user's current identity-verification status. */\nexport const getVerificationInfo = async (): Promise<unknown> =>\n get(ENDPOINTS.auth.verificationInfo)\n\n/** Mark identity verification as PENDING after the buyer starts the provider flow. */\nexport const updateVerificationStatus = async (): Promise<unknown> =>\n patch(ENDPOINTS.auth.verify, {\n data: { attributes: { verification: { verificationStatus: 'PENDING' } } },\n })\n\n/** Sign out: tell the backend, then drop local tokens regardless of the result. */\nexport const logout = async (): Promise<void> => {\n try {\n await del(ENDPOINTS.auth.session)\n } finally {\n clearSession()\n }\n}\n\n/**\n * Whether an email already has an account. Normalizes the legacy\n * `/ajax/contact-email` response (`exists: 0|1`) to a boolean; never throws —\n * returns `{ exists: false }` on failure so callers can treat it as advisory.\n */\nexport const checkEmailExists = async (\n email: string\n): Promise<{ exists: boolean; error?: string }> => {\n try {\n const res = await post<{ exists?: number; error?: number; message?: string }>(\n `${getOriginUrl()}/${ENDPOINTS.auth.contactEmail}`,\n toFormData({ email, is_checkout_flow: 'true' }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n return {\n exists: res.exists === 1,\n error: res.error === 1 ? res.message : undefined,\n }\n } catch {\n return { exists: false, error: 'Failed to check email' }\n }\n}\n","/**\n * Geo lookups for billing selects: the country list and a country's states.\n * The states endpoint answers with an id→name map; we normalize it to an array\n * so consumers get one consistent `{ id, name }` shape.\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfCountry, TfState } from '../types'\n\n/** All selectable countries (billing `countryId` values). */\nexport const getCountries = async (): Promise<TfCountry[]> => {\n const res = await get<{ data: TfCountry[] }>(ENDPOINTS.geo.countries)\n return res.data ?? []\n}\n\n/** States/provinces for a country, normalized from the backend's id→name map. */\nexport const getStates = async (countryId: string | number): Promise<TfState[]> => {\n const res = await get<{ data: Record<string, string> }>(ENDPOINTS.geo.states(countryId))\n return Object.entries(res.data ?? {}).map(([id, name]) => ({ id, name }))\n}\n","/**\n * Pre-purchase engagement: referral attribution, sold-out waiting lists, RSVP\n * capture, and phone validation. None of these existed in shared before — they\n * lived only in the platform packages' own api layers.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport type { WaitingListEntry } from '../dtos'\n\nexport type { WaitingListEntry }\n\n/**\n * Attribute the buyer's session to a referrer/promoter (the numeric customer id\n * from a share/tracking link). The server credits it when the order completes;\n * pass `null` to clear. The endpoint always answers success, so ids can't be\n * probed.\n */\nexport const attributeReferrer = async (\n eventId: string,\n referrer: string | number | null\n): Promise<void> => {\n await post(ENDPOINTS.events.referrer(eventId), { referrer: referrer ?? '' })\n}\n\n/** Join the waiting list for a sold-out event (or one sold-out ticket type). */\nexport const joinWaitingList = async (\n eventId: string,\n entry: WaitingListEntry\n): Promise<void> => {\n await post(ENDPOINTS.events.waitingList(eventId), {\n data: { attributes: entry },\n })\n}\n\n/** Submit RSVP details for an RSVP-style event. */\nexport const sendRsvp = async (\n eventId: string,\n data: Record<string, unknown>\n): Promise<unknown> => post(ENDPOINTS.events.rsvp(eventId), data)\n\n/** Validate a phone number (Twilio-backed) before letting the buyer proceed. */\nexport const validatePhone = async (\n phone: string\n): Promise<{ valid: boolean; [key: string]: unknown }> => {\n const res = await get<{ valid?: boolean; [key: string]: unknown }>(\n ENDPOINTS.account.validatePhone(phone)\n )\n return { valid: Boolean(res?.valid), ...res }\n}\n","/**\n * Account orders — the buyer's purchase history and a single order's detail.\n * Backed by `v1/account/orders` (paginated, filterable by event/brand) and\n * `v1/account/order/:id`. New to shared; previously platform-only.\n */\nimport { get, put } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfEnvelope, TfListEnvelope } from '../types'\n\n/** A row in the order history. Fields the platform is known to return are typed;\n * the index signature keeps forward-compatible extras accessible. */\nexport interface TfOrderSummary {\n id?: string | number\n hash?: string\n status?: string\n total?: string | number\n currency?: string\n eventName?: string\n createdAt?: string\n [key: string]: unknown\n}\n\n/** A single order's full detail (tickets, buyer, totals). */\nexport interface TfOrderDetails extends TfOrderSummary {\n tickets?: unknown[]\n}\n\nexport interface OrdersQuery {\n page?: number\n limit?: number\n /** Restrict to one event by slug. */\n eventSlug?: string\n /** Restrict to a brand (and its subbrands). */\n brandSlug?: string\n}\n\n/** List the signed-in user's orders, newest first (server-paginated). */\nexport const getOrders = async (\n query: OrdersQuery = {}\n): Promise<TfListEnvelope<TfOrderSummary>> => {\n const { page = 1, limit = 10, eventSlug = '', brandSlug } = query\n const params = new URLSearchParams({\n page: String(page),\n limit: String(limit),\n 'filter[event]': eventSlug,\n })\n if (brandSlug) {\n params.set('filter[brand]', brandSlug)\n params.set('filter[subbrands]', 'true')\n }\n return get<TfListEnvelope<TfOrderSummary>>(\n `${ENDPOINTS.account.orders}?${params.toString()}`\n )\n}\n\n/** The authenticated account endpoint accepts the numeric order id. Public\n * order hashes belong to the confirmation endpoint and must be resolved first. */\nexport const getOrder = async (orderId: string): Promise<TfEnvelope<TfOrderDetails>> => {\n if (!/^\\d+$/.test(String(orderId))) {\n throw new TypeError(\n 'Account order details require a numeric order id; resolve public order hashes first.'\n )\n }\n return get<TfEnvelope<TfOrderDetails>>(ENDPOINTS.account.order(orderId))\n}\n\n/** The signed-in user's tickets (wallet), server-paginated + filterable. */\nexport const getMyTickets = async (\n query: OrdersQuery & { from?: string } = {}\n): Promise<TfListEnvelope<Record<string, unknown>>> => {\n const { page = 1, limit = 10, eventSlug = '', brandSlug, from } = query\n const params = new URLSearchParams({\n page: String(page),\n limit: String(limit),\n 'filter[event]': eventSlug,\n })\n if (brandSlug) {\n params.set('filter[brand]', brandSlug)\n params.set('filter[subbrands]', 'true')\n }\n if (from) params.set('from', from)\n return get<TfListEnvelope<Record<string, unknown>>>(\n `${ENDPOINTS.account.tickets}?${params.toString()}`\n )\n}\n\n/** Update the order-level data-capture answers shown on the order detail page. */\nexport const updateOrderCustomFields = async (\n eventId: string,\n orderId: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(`v1/event/${eventId}/order-data-capture`, {\n data: {\n attributes: {\n order_id: orderId,\n data_capture: values,\n },\n },\n })\n\n/** Update data-capture answers for one issued ticket. */\nexport const updateTicketHolderCustomFields = async (\n eventId: string,\n ticketHash: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(`v1/event/${eventId}/ticket-data-capture`, {\n data: {\n attributes: {\n ticket_hash: ticketHash,\n ticket_data_capture: {\n [ticketHash]: values,\n },\n },\n },\n })\n","/**\n * Ticket resale — list a ticket for resale, process a pending resale, or\n * decline one. Backed by `v1/ticket/:id/{sell,process,decline}`. New to shared;\n * previously only in the web package's `resale.ts`.\n */\nimport { del, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Put a ticket up for resale. `payload` carries price/recipient per the event's\n * resale rules; forwarded verbatim. */\nexport const sellTicket = async (\n ticketId: string,\n payload: Record<string, unknown> = {}\n): Promise<unknown> => post(ENDPOINTS.resale.sell(ticketId), payload)\n\n/** Remove a ticket that is currently listed for resale. */\nexport const removeTicketFromResale = async (ticketId: string): Promise<unknown> =>\n del(ENDPOINTS.resale.sell(ticketId))\n\n/** Process (accept/complete) a pending resale for a ticket. */\nexport const processResale = async (\n ticketId: string,\n payload: Record<string, unknown> = {}\n): Promise<unknown> => post(ENDPOINTS.resale.process(ticketId), payload)\n\n/** Decline a pending resale for a ticket. */\nexport const declineResale = async (ticketId: string): Promise<unknown> =>\n post(ENDPOINTS.resale.decline(ticketId))\n","/**\n * Post-purchase confirmation — the \"your order is complete\" page data, keyed by\n * order hash. Backed by `v1/order/:hash/payment/complete`. New to shared.\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Fetch the confirmation-page payload for a completed order. */\nexport const getConfirmation = async (\n orderHash: string\n): Promise<Record<string, unknown>> =>\n get<Record<string, unknown>>(ENDPOINTS.order.confirmation(orderHash))\n","/**\n * Pre-registration — the \"register your interest, then share to climb the list\"\n * flow. Confirm interest for an event, then read the post-confirm share page and\n * submit share actions (referral phases). Backed by `pre-registration/*`\n * endpoints. New to shared.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Decode the backend's lightweight pre-registration share-action token. */\nexport const decodeShareActionToken = (value: string, method?: string): string => {\n if (method === 'reverse_string') return value.split('').reverse().join('')\n if (method === 'symmetric_shuffle_string') {\n const split = Math.floor(value.length / 2)\n return value.substring(split) + value.substring(0, split)\n }\n if (method === 'shuffle_every_two_symbols_in_string') {\n let shuffled = ''\n for (let index = 0; index < value.length; index += 2) {\n shuffled += `${value[index + 1] ?? ''}${value[index] ?? ''}`\n }\n return shuffled\n }\n return value\n}\n\n/** Confirm pre-registration for an event. `attributes` carries the buyer's\n * answers; forwarded under the JSON:API `{ data: { attributes } }` envelope. */\nexport const confirmPreRegistration = async (\n eventId: string,\n attributes: Record<string, unknown>\n): Promise<unknown> =>\n post(ENDPOINTS.preRegistration.confirm(eventId), { data: { attributes } })\n\n/** Influencers/promoters available to share to for an event's pre-reg phase. */\nexport const getInfluencers = async (eventId: string): Promise<unknown> =>\n get(ENDPOINTS.preRegistration.influencers(eventId))\n\n/** The post-confirmation share page (options + the buyer's current standing). */\nexport const getConfirmationPage = async (hash: string): Promise<unknown> =>\n get(ENDPOINTS.preRegistration.confirmationPage(hash))\n\n/** Record a share action (a referral phase step) against a pre-reg hash. */\nexport const submitShareAction = async (\n hash: string,\n input: {\n eventActionId: number | string\n accessToken?: string\n shareActionToken?: string\n tokenShuffleMethod?: string\n phase?: string\n }\n): Promise<unknown> =>\n post(ENDPOINTS.preRegistration.submitAction(hash), {\n data: {\n attributes: {\n phase: input.phase ?? 'pre-registration',\n eventActionId: Number(input.eventActionId),\n accessToken:\n input.accessToken ??\n decodeShareActionToken(input.shareActionToken ?? '', input.tokenShuffleMethod),\n },\n },\n })\n","/**\n * Guest ticket delegation — the flow where someone is handed a ticket via an\n * access link and claims it without a full account. Check whether they already\n * have an account, read the claim page, and issue the ticket. Backed by\n * `v1/delegation-access/:hash/*`. New to shared.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Whether the delegated recipient already has an account. */\nexport const checkCustomerExists = async (\n accessHash: string\n): Promise<Record<string, unknown>> =>\n get(ENDPOINTS.delegation.customerExists(accessHash))\n\n/** The claim page for a delegation access link (event + ticket context). */\nexport const getConsumerPageInfo = async (accessHash: string): Promise<unknown> =>\n get(ENDPOINTS.delegation.consumerPageInfo(accessHash))\n\n/** Issue (claim) the delegated ticket. `data` carries the recipient details;\n * forwarded under the JSON:API `{ data: { attributes } }` envelope. */\nexport const issueTicket = async (\n accessHash: string,\n data: Record<string, unknown>\n): Promise<unknown> =>\n post(ENDPOINTS.delegation.issueTicket(accessHash), {\n data: { attributes: data },\n })\n","/**\n * Seated events — the wire behind the seat picker. Fetch the venue map, poll\n * live seat statuses, and reserve a selection. The seats.io / tf-seat-map-view\n * widget itself is platform UI; these are just its API calls, so they belong in\n * shared. Backed by `v1/event/:id/{seat-map-data,seats/status,seats/reserve}`.\n * New to shared.\n */\nimport { del, get, patch, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** The venue seat map for an event (optionally scoped via `params`). */\nexport const getSeatMapData = async (\n eventId: string,\n params?: Record<string, unknown>\n): Promise<unknown> => {\n const url = ENDPOINTS.seatmap.data(eventId)\n console.log('[SeatMap API] getSeatMapData called', { eventId, params, url })\n try {\n const resp = await get(url, { params })\n console.log('[SeatMap API] getSeatMapData response', JSON.stringify(resp, null, 2))\n return resp\n } catch (err) {\n console.error('[SeatMap API] getSeatMapData FAILED', err)\n throw err\n }\n}\n\n/** Live availability/status for the event's seats (poll during selection). */\nexport const getSeatStatuses = async (eventId: string): Promise<unknown> =>\n get(ENDPOINTS.seatmap.statuses(eventId))\n\n/** Reserve a seat selection, e.g. `{ tierId, seatId, ttl: 10 }` — forwarded\n * under the backend's `{ data: … }` envelope. */\nexport const reserveSeats = async (\n eventId: string,\n reservation: Record<string, unknown>\n): Promise<unknown> => post(ENDPOINTS.seatmap.reserve(eventId), { data: reservation })\n\n/** Release a held reservation (DELETE with a body). */\nexport const removeReservedSeats = async (\n eventId: string,\n tierId: string,\n seatIds: string[]\n): Promise<unknown> =>\n // axios DELETE body rides `config.data`; the web sends { tierId, seatIds } bare.\n del(ENDPOINTS.seatmap.deleteReserved(eventId), {\n data: { tierId, seatIds },\n })\n\n/** Extend a seat reservation's TTL for an in-flight order. */\nexport const refreshReservation = async (\n eventId: string,\n orderId: string\n): Promise<unknown> =>\n patch(ENDPOINTS.seatmap.refreshReservation(eventId), { order_id: orderId })\n","/**\n * Catalog — the read side of an event: tickets, seating/info, terms, time-slot\n * sessions, custom fields, add-ons, promo codes, and multi-currency. Ported\n * faithfully from the engine's api layer; this layer OWNS the wire contract\n * (JSON:API `{ data: { attributes } }` envelopes, cents-vs-units, map-vs-array)\n * so nothing above it sees those details.\n */\nimport { get, post, put } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { isSeatedEvent as coreIsSeatedEvent } from '../logic'\nimport type {\n CurrencyState,\n CurrencySyncOptions,\n EventAddon,\n EventCondition,\n EventCustomField,\n EventCustomFieldGroup,\n TicketType,\n} from '../dtos'\n\nconst mapTicket = (t: any): TicketType => ({\n id: String(t.id),\n name: t.displayName ?? '',\n groupName: t.groupName ?? t.group_name ?? null,\n optionName: t.optionName ?? '',\n price: Number(t.price ?? 0),\n // `basePrice` is the with-fees amount; fall back to price when the wire omits it.\n priceWithFees: Number(t.basePrice ?? t.price ?? 0),\n priceSymbol: t.priceSymbol ?? '',\n currency: t.priceCurrency ?? '',\n feeIncluded: Boolean(t.feeIncluded),\n // `depositPercent` arrives as a string (\"50.00\") or null.\n depositPercent: t.depositPercent != null ? Number(t.depositPercent) : null,\n soldOut: Boolean(t.soldOut),\n salesStarted: Boolean(t.salesStarted),\n salesEnded: Boolean(t.salesEnded),\n minQuantity: Number(t.minQuantity ?? 1),\n maxQuantity: Number(t.maxQuantity ?? 10),\n multiplier: Number(t.multiplier ?? 1) || 1,\n isTable: Boolean(t.isTable),\n // Tables constrain the selectable quantity by guests, not the generic\n // min/max (which stay 1/10 on the wire). Undefined for non-tables.\n minGuests: t.minGuests != null ? Number(t.minGuests) : undefined,\n maxGuests: t.maxGuests != null ? Number(t.maxGuests) : undefined,\n allowDirectPurchase: Boolean(t.allowDirectPurchase),\n waitingListEnabled: Boolean(t.waitingListEnabled),\n waitingListMaxQuantity:\n t.waitingListMaxQuantity != null ? Number(t.waitingListMaxQuantity) : undefined,\n descriptionRich: t.descriptionRich ?? null,\n})\n\n/** Purchasable ticket types for an event. */\nexport const getEventTickets = async (eventId: string): Promise<TicketType[]> => {\n const body = await get<any>(ENDPOINTS.events.tickets(eventId))\n const ticketsObj = body?.data?.attributes?.tickets ?? {}\n return Object.values(ticketsObj).map(mapTicket)\n}\n\nexport interface EventSeatingInfo {\n /** The event uses reserved seating — the buyer picks on a seat map instead of\n * choosing quantities. Render seat-map ticket types read-only and route to\n * \"Select seats\". */\n isSeatedEvent: boolean\n /** The seat map is a TABLE map (its CTA reads \"Select on map\" vs \"Select\n * seats\"). Only meaningful when `isSeatedEvent`. */\n tableMapEnabled: boolean\n /** The event sells per date/time session — pick a date, then time-slot tickets.\n * (Attribute names inferred defensively; pass dates via a prop if your page\n * data already has them.) */\n isTimeSlotEvent: boolean\n /** Selectable session dates (ISO `yyyy-mm-dd`) for a time-slot event. */\n availableDates: string[]\n /** The event lets a buyer combine MORE THAN ONE ticket type in a single order.\n * When false (the default), selecting a new type replaces the previous one —\n * the ticket screen enforces one type at a time. Tables and regular tickets\n * are mutually exclusive regardless. */\n allowMultipleTicketTypePurchases: boolean\n slug: string | null\n name: string | null\n /** ISO country code used to seed billing/phone inputs like the storefront. */\n countryCode: string | null\n}\n\n/**\n * `GET v1/event/:id` — returns what the seated-event handoff needs:\n * `isSeatedEvent` (core's helper over the event attributes), plus slug/name for\n * the event-page link. `pk` is the optional preview key for unpublished events.\n */\nexport const getEventInfo = async (\n eventId: string,\n pk?: string\n): Promise<EventSeatingInfo> => {\n const body = await get<any>(ENDPOINTS.events.info(eventId), {\n params: pk ? { pk } : undefined,\n })\n const attributes = body?.data?.attributes ?? {}\n const a = attributes as Record<string, any>\n const slotSettings = a.timeslotSettings ?? a.timeslot_settings ?? {}\n const dates =\n slotSettings.availableDates ?? slotSettings.available_dates ?? a.available_dates ?? []\n const rawCountry = a.country\n const countryCode =\n (typeof rawCountry === 'string' ? rawCountry : rawCountry?.code) ??\n a.countryCode ??\n a.country_code ??\n null\n return {\n isSeatedEvent: coreIsSeatedEvent(attributes),\n tableMapEnabled: Boolean(a.tableMapEnabled ?? a.table_map_enabled),\n isTimeSlotEvent: Boolean(\n a.isTimeSlotEvent ?? a.is_time_slot_event ?? a.time_slot_event ?? a.is_timeslot\n ),\n availableDates: Array.isArray(dates) ? dates.map(String) : [],\n allowMultipleTicketTypePurchases: Boolean(\n a.allowMultipleTicketTypePurchases ?? a.allow_multiple_ticket_type_purchases\n ),\n slug: attributes.slug ?? null,\n name: attributes.name ?? null,\n countryCode: countryCode ? String(countryCode).toUpperCase() : null,\n }\n}\n\n/**\n * Event terms/conditions (client-side gate — nothing is submitted, the server\n * already knows them). LIVE contract: `attributes` is an ARRAY OF STRINGS, each\n * a MANDATORY acknowledgement; null when none. The object form\n * `{ conditions: [{id,name,content,is_required}] }` is tolerated defensively.\n */\nexport const getEventConditions = async (eventId: string): Promise<EventCondition[]> => {\n const body = await get<any>(ENDPOINTS.events.conditions(eventId))\n const attrs = body?.data?.attributes\n const items: any[] = Array.isArray(attrs)\n ? attrs\n : Array.isArray(attrs?.conditions)\n ? attrs.conditions\n : []\n return items\n .map((c, i): EventCondition => {\n if (typeof c === 'string') {\n return { id: String(i + 1), name: '', content: c, isRequired: true }\n }\n return {\n id: String(c?.id ?? i + 1),\n name: String(c?.name ?? ''),\n content: String(c?.content ?? ''),\n isRequired: c?.is_required === true,\n }\n })\n .filter((c) => c.content || c.name)\n}\n\n/**\n * Ticket types for one DATE of a time-slot (session/calendar) event. Each\n * returned `id` (matrix_record_id) is specific to the chosen date/session — how\n * the server knows the date; no date field exists in the add-to-cart body.\n * @param date \"YYYY-MM-DD\"\n * @param options.groupIds restrict to specific slot groups; omit for all.\n */\nexport const getEventTimeSlotTickets = async (\n eventId: string,\n date: string,\n options?: { groupIds?: number[] }\n): Promise<TicketType[]> => {\n const body = await get<any>(ENDPOINTS.events.timeSlotByDate(eventId), {\n params: {\n date,\n remove_past_slots: true,\n ...(options?.groupIds?.length ? { groupIds: options.groupIds } : {}),\n },\n })\n const grouped = body?.data?.attributes?.time_grouped_slot_ticket_types ?? {}\n const out: TicketType[] = []\n for (const [slotDate, hours] of Object.entries<any>(grouped ?? {})) {\n for (const hourKey of Object.keys(hours ?? {}).sort()) {\n const times = hours[hourKey] ?? {}\n for (const timeKey of Object.keys(times).sort()) {\n for (const s of Object.values<any>(times[timeKey] ?? {})) {\n if (!s?.matrix_record_id) continue\n const stock = Number(s.in_stock ?? s.real_stock ?? 0)\n out.push({\n id: String(s.matrix_record_id),\n name: s.display_name || s.option_value || 'Ticket',\n groupName: s.group_name ?? s.groupName ?? null,\n optionName: String(s.option_key ?? ''),\n price: Number(s.base_price ?? 0),\n priceWithFees: Number(s.price_with_fees ?? s.base_price ?? 0),\n priceSymbol: s.price_symbol ?? s.priceSymbol ?? '',\n currency: '',\n feeIncluded: false,\n depositPercent: s.deposit_percent != null ? Number(s.deposit_percent) : null,\n soldOut: Boolean(s.sold_out) || stock <= 0,\n salesStarted: s.sales_started != null ? Boolean(s.sales_started) : true,\n salesEnded: Boolean(s.sales_ended),\n minQuantity: Number(s.min_quantity ?? 1) || 1,\n maxQuantity: Number(s.max_quantity ?? 10) || 10,\n multiplier: Number(s.multiplier ?? 1) || 1,\n isTable: Boolean(s.is_table),\n allowDirectPurchase: true,\n descriptionRich: s.description ?? null,\n timeSlot: { date: slotDate, time: timeKey },\n })\n }\n }\n }\n }\n return out\n}\n\n/** checkbox → '1'/null; select_multi → string[]; else → string. Matches the\n * server's `!trim(value)` required check. */\nconst normalizeDefaultValue = (type: string, raw: unknown): string | string[] | null => {\n if (type === 'checkbox') {\n if (raw === true || raw === 1 || raw === '1') return '1'\n return null\n }\n if (raw == null || raw === '') return null\n if (type === 'select_multi') {\n if (Array.isArray(raw)) return raw.map(String)\n return [String(raw)]\n }\n if (Array.isArray(raw)) return String(raw[0] ?? '')\n return String(raw)\n}\n\n/** The event's custom-field groups (order / ticket / add-on scopes). [] when\n * the event has none. */\nexport const getEventCustomFields = async (\n eventId: string\n): Promise<EventCustomFieldGroup[]> => {\n const body = await get<any>(ENDPOINTS.events.customFields(eventId))\n const items: any[] = body?.data?.attributes ?? []\n if (!Array.isArray(items)) return []\n const groups: any[] = items.flatMap((item) => {\n if (!item || typeof item !== 'object') return []\n if (item.type && Array.isArray(item.fields)) return [item]\n return Object.values<any>(item)\n .map((v) => (v && typeof v === 'object' ? v.group : undefined))\n .filter((g) => g && typeof g === 'object')\n })\n return groups\n .filter((g) => g?.type === 'order' || g?.type === 'ticket' || g?.type === 'add-on')\n .map(\n (g): EventCustomFieldGroup => ({\n id: String(g.id ?? ''),\n label: g.label ?? null,\n scope: g.type,\n fields: (Array.isArray(g.fields) ? g.fields : []).map(\n (f: any): EventCustomField => ({\n id: String(f.id ?? ''),\n name: String(f.name ?? f.id ?? ''),\n label: String(f.label || f.name || ''),\n type: f.type,\n required: f.required === true,\n description: f.description ?? null,\n defaultValue: normalizeDefaultValue(f.type, f.defaultValue),\n options: (Array.isArray(f.options) ? f.options : []).map((o: any) => ({\n id: String(o.id ?? o.value ?? ''),\n name: String(o.name ?? o.value ?? ''),\n value: String(o.value ?? o.name ?? ''),\n })),\n ticketTypeIds: Array.isArray(f.settings?.ticketTypes)\n ? f.settings.ticketTypes.map(String)\n : null,\n })\n ),\n })\n )\n}\n\n/** Labels of REQUIRED order/ticket custom fields. Fails OPEN ([]) on error. */\nexport const getRequiredCustomFieldLabels = async (\n eventId: string\n): Promise<string[]> => {\n try {\n const groups = await getEventCustomFields(eventId)\n return groups\n .filter((g) => g.scope === 'order' || g.scope === 'ticket')\n .flatMap((g) => g.fields)\n .filter((f) => f.required)\n .map((f) => f.label || f.name)\n } catch {\n return []\n }\n}\n\n/** Event add-ons (active only), prices converted from wire cents to units. */\nexport const getEventAddons = async (eventId: string): Promise<EventAddon[]> => {\n const body = await get<any>(ENDPOINTS.events.addOns(eventId))\n const items: any[] = body?.data?.attributes?.add_ons ?? []\n return items\n .map((item) => {\n const a = item.attributes ?? {}\n return {\n id: String(a.id ?? item.id),\n name: a.name ?? '',\n description: a.description ?? null,\n price: Number(a.price ?? 0) / 100,\n currency: a.currency ?? '',\n feeIncluded: Boolean(a.feeIncluded),\n imageUrl: a.imageUrl ?? a.image ?? null,\n // NEVER coerce null to 0. The wire uses null for \"untracked\" (an\n // unlimited add-on) and an explicit 0 for \"sold out\"; every consumer\n // below treats `stock === 0` as the sold-out sentinel. Collapsing the\n // two made unlimited add-ons look sold out, which hid the whole\n // section (`addons.every(a => a.stock === 0)`) and silently exempted\n // required add-ons from the pre-flight gate.\n stock: a.stock == null ? null : Number(a.stock),\n maxQuantity: a.maxQuantity == null ? null : Number(a.maxQuantity),\n // The quantity-cap inputs. Dropping these let the UI offer quantities\n // the server hard-rejects (add_on_max_quantity) — see addOnMaxQuantity.\n flagLimitToTicketQuantity: Boolean(a.flagLimitToTicketQuantity),\n limitPerTicket: a.limitPerTicket == null ? null : Number(a.limitPerTicket),\n isCheckbox: Boolean(a.isCheckbox),\n level: a.level ?? null,\n groupName: a.groupName ?? null,\n required: Boolean(a.required),\n prerequisiteTicketTypeIds: Array.isArray(a.prerequisiteTicketTypeIds)\n ? a.prerequisiteTicketTypeIds.map(String)\n : null,\n active: a.active !== false,\n }\n })\n .filter((a) => a.active)\n .map(({ active: _active, ...addon }) => addon)\n}\n\n/**\n * The web checkout's add-on visibility rule: an add-on applies iff it has no\n * prerequisite ticket types, or they intersect the cart's DECRYPTED ids. With\n * no ids yet (cart not primed), returns the list unchanged. Pure — no request.\n */\nexport const filterAddonsForTickets = (\n addons: EventAddon[],\n ticketTypeIds: string[]\n): EventAddon[] => {\n if (!ticketTypeIds.length) return addons\n const selected = new Set(ticketTypeIds.map(String))\n return addons.filter((a) => {\n const prereq = a.prerequisiteTicketTypeIds\n if (!prereq || prereq.length === 0) return true\n return prereq.some((id) => selected.has(String(id)))\n })\n}\n\nexport interface TicketCatalogPromoMeta {\n isPromotionsEnabled: boolean\n isAccessCodeEnabled: boolean\n promoCodeValid?: boolean\n promoCodeMessage?: string\n}\n\n/** Tickets plus the catalog-level promo/access metadata the same response\n * carries — the read-back half of the promo-code loop. */\nexport const getEventTicketsWithMeta = async (\n eventId: string\n): Promise<{\n tickets: TicketType[]\n promo: TicketCatalogPromoMeta\n showWaitingList: boolean\n}> => {\n const body = await get<any>(ENDPOINTS.events.tickets(eventId))\n const attrs = body?.data?.attributes ?? {}\n const ticketsObj = attrs.tickets ?? {}\n return {\n tickets: Object.values(ticketsObj).map(mapTicket),\n promo: {\n isPromotionsEnabled: attrs.isPromotionsEnabled === true,\n isAccessCodeEnabled: attrs.is_access_code === true,\n promoCodeValid:\n typeof attrs.ValidPromoCode === 'boolean' ? attrs.ValidPromoCode : undefined,\n promoCodeMessage: attrs.PromoCodeValidationMessage ?? undefined,\n },\n showWaitingList: attrs.showWaitingList === true,\n }\n}\n\n/**\n * Applies a promo/access code to the session (empty string removes it). The\n * endpoint ALWAYS answers success (anti-brute-force) — read the outcome from a\n * fresh `getEventTicketsWithMeta` (`promo.promoCodeValid`).\n */\nexport const submitPromoCode = async (eventId: string, promo: string): Promise<void> => {\n await post(ENDPOINTS.events.promo(eventId), { promo: promo.trim() })\n}\n\n/**\n * Session currency preference (multi-currency events). A bare call geo-seeds and\n * reports the resolved state; passing a code switches it (every later read\n * reprices — restart ticket selection after a switch). `{ seed: true }` replays\n * a carried-over currency without overwriting the buyer's own choice.\n */\nexport const setEventCurrency = async (\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencyState> => {\n const body = await post<any>(ENDPOINTS.events.currency(eventId), {\n data: {\n attributes: code\n ? options?.seed\n ? { currency: code, seed: true }\n : { currency: code }\n : {},\n },\n })\n return body?.data?.attributes as CurrencyState\n}\n\n/** Unlock a password-protected event. Throws `TtfError` on the wrong password. */\nexport const authenticateEvent = async (\n eventId: string,\n password: string\n): Promise<unknown> =>\n post(ENDPOINTS.events.authenticate(eventId), {\n attributes: { data: { password } },\n })\n\n/** Fire the event's tracking pixel (page view / order attribution). */\nexport const trackEvent = async (\n eventId: string,\n options: { pageUrl?: string; page?: string; orderHash?: string }\n): Promise<unknown> =>\n get(ENDPOINTS.events.track(eventId), {\n params: {\n page_url: options.pageUrl,\n page: options.page,\n order_hash: options.orderHash,\n },\n })\n\n/** Write ORDER-level custom-field values after the order exists. */\nexport const updateOrderDataCapture = async (\n eventId: string,\n orderId: string,\n dataCapture: Record<string, unknown>\n): Promise<unknown> =>\n put(ENDPOINTS.events.orderDataCapture(eventId), {\n data: { attributes: { order_id: orderId, data_capture: dataCapture } },\n })\n\n/** Write TICKET-level (per-holder) custom-field values for one ticket hash. */\nexport const updateTicketDataCapture = async (\n eventId: string,\n ticketHash: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(ENDPOINTS.events.ticketDataCapture(eventId), {\n data: {\n attributes: {\n ticket_hash: ticketHash,\n ticket_data_capture: { [ticketHash]: values },\n },\n },\n })\n","/**\n * Cart + checkout session — build the server cart, read it back (pins the\n * event's payment method into the session), price it with add-ons, and read the\n * pre-order payment config. Ported faithfully from the engine's api layer.\n */\nimport { ENV_HOSTS, getOriginUrl } from '../client/config'\nimport { get, post } from '../client/http'\nimport {\n ENDPOINTS,\n listRedirectMethods,\n XENDIT_NON_EWALLET_PROCESSORS,\n} from '../constants'\nimport {\n evaluateFieldGates,\n identifyPreOrderGateway,\n interpretContactEmail,\n paypalTabConfig,\n priceBreakdownAddOnsQuery,\n resolvePriceBreakdown,\n walletsOption,\n xenditPreOrderConfig,\n} from '../logic'\nimport type {\n AddonSelection,\n BuyerFieldVisibility,\n CheckoutBreakdown,\n CheckoutPaymentPlan,\n CheckoutPaymentPlanPreview,\n CheckoutWalletAvailability,\n ExistingAccount,\n PreOrderGateway,\n PriceBreakdown,\n SeatLine,\n StripeConfig,\n StripeWallets,\n TicketSelection,\n XenditProcessor,\n} from '../dtos'\n\n/**\n * Adds ALL selected ticket types to the server cart in ONE call. The endpoint\n * REPLACES the entire cart every call, so per-type calls would keep only the\n * last. The `{ data: { attributes } }` envelope is mandatory (the backend\n * copies data.attributes into $_POST and 422s without it).\n */\nexport const addTicketsToCart = async (\n eventId: string,\n selections: TicketSelection[]\n): Promise<{ holderNamesRequired: boolean }> => {\n const first = selections[0]\n if (!first) throw new Error('addTicketsToCart: no tickets selected.')\n const body = await post<any>(ENDPOINTS.cart.addToCart(eventId), {\n data: {\n attributes: {\n alternative_view_id: null,\n product_cart_quantity: first.quantity,\n product_options: { [first.optionName]: first.id },\n product_id: Number(eventId),\n ticket_types: Object.fromEntries(\n selections.map((t) => [\n t.id,\n {\n product_options: { [t.optionName]: t.id, ticket_price: t.price },\n quantity: t.quantity,\n },\n ])\n ),\n },\n },\n })\n return { holderNamesRequired: Boolean(body?.data?.attributes?.names_required) }\n}\n\n/**\n * Adds RESERVED SEATS to the server cart — the seat-map analogue of\n * `addTicketsToCart`, a faithful port of the legacy `getAddToCartRequestData`\n * (`seatMapContainer/utils.ts`). Kept separate because a seated order's body\n * differs from a plain-ticket one in two ways `addTicketsToCart` can't express:\n *\n * - `product_cart_quantity` is the TOTAL number of reserved seats (not the\n * first line's quantity), and\n * - when ANY line carries a guest count (tables / group tickets) the\n * `ticket_types` map is keyed by INDEX with `quantity = guests` (one line per\n * seat); otherwise it's keyed by ticket-type id with quantities aggregated.\n *\n * Seat ids never appear in the body — the server binds cart lines to seats\n * through the live reservation (held by `ttf.seatmap.reserve`).\n */\nexport const addSeatsToCart = async (\n eventId: string,\n lines: SeatLine[]\n): Promise<{ holderNamesRequired: boolean }> => {\n if (!lines.length) throw new Error('addSeatsToCart: no seats selected.')\n const hasGuests = lines.some((l) => l.guests != null)\n const product_options: Record<string, string> = {}\n const ticket_types: Record<string, unknown> = {}\n lines.forEach((l, index) => {\n // Last-write-wins over the shared option key — matches legacy utils.ts.\n product_options[l.optionName] = l.ticketTypeId\n const key = hasGuests ? index : l.ticketTypeId\n const prevQty = hasGuests\n ? 0\n : ((ticket_types[l.ticketTypeId] as { quantity?: number } | undefined)?.quantity ??\n 0)\n const quantity = hasGuests ? (l.guests as number) : prevQty + 1\n ticket_types[key] = {\n quantity,\n product_options: { [l.optionName]: l.ticketTypeId, ticket_price: l.price },\n }\n })\n const body = await post<any>(ENDPOINTS.cart.addToCart(eventId), {\n data: {\n attributes: {\n alternative_view_id: null,\n product_cart_quantity: lines.length,\n product_options,\n product_id: Number(eventId),\n ticket_types,\n },\n },\n })\n return { holderNamesRequired: Boolean(body?.data?.attributes?.names_required) }\n}\n\n/**\n * Reads the cart back. MANDATORY between add-to-cart and updateCheckout: this\n * call writes the event's payment method into the PHP session, which\n * POST v1/checkout reads. Returns reservation seconds remaining plus the raw\n * pre-order gateway string (preserved verbatim so an unknown/future gateway\n * stays fail-closed at the engine's Stripe-only guard).\n */\nexport const getCart = async (): Promise<{\n expiresInSeconds: number\n preOrderGateway: string | null\n}> => {\n const body = await get<any>(ENDPOINTS.cart.get, { params: { payment_config: 1 } })\n const attrs = body?.data?.attributes\n const raw = Number(attrs?.expiresAt)\n const gateway = attrs?.payment?.gateway\n return {\n expiresInSeconds: Number.isFinite(raw) && raw > 0 ? raw : 420,\n preOrderGateway: typeof gateway === 'string' && gateway ? gateway : null,\n }\n}\n\n/**\n * Checkout gates for the CURRENT cart session (`GET v1/checkout-configs`).\n * Session-scoped: call only after the cart exists. The reliable source for the\n * collect_names gate (staging's add-to-cart returns empty attributes).\n */\nexport const getCheckoutConfigs = async (): Promise<{\n holderNamesRequired: boolean\n fieldGates: BuyerFieldVisibility\n}> => {\n const body = await get<any>(ENDPOINTS.cart.checkoutConfigs)\n const attrs = body?.data?.attributes ?? {}\n return {\n holderNamesRequired: Boolean(attrs.names_required),\n fieldGates: evaluateFieldGates(attrs),\n }\n}\n\nexport interface CheckoutPricing {\n /** DECRYPTED ticket type ids (the tickets endpoint only has encrypted ones). */\n ticketTypeIds: string[]\n breakdown?: CheckoutBreakdown\n stripe?: StripeConfig\n paymentPlan?: CheckoutPaymentPlan\n redirectPaymentMethods?: string[]\n walletAvailability?: CheckoutWalletAvailability\n /** Server deferred-mode Stripe Elements config (mode/amount/currency) — mounts\n * the wallet-capable Payment Element exactly as the old checkout did. */\n stripeElementsConfig?: Record<string, unknown>\n}\n\n/** Parses `payment_plan_configuration` into the camelCase installment preview\n * (display-only). Undefined when absent or without an installment shape. */\nconst parsePlanPreview = (\n config: Record<string, any> | null | undefined\n): CheckoutPaymentPlanPreview | undefined => {\n if (!config || typeof config !== 'object') return undefined\n const num = (v: unknown): number | undefined =>\n v == null || v === '' || Number.isNaN(Number(v)) ? undefined : Number(v)\n const bool = (v: unknown): boolean | undefined =>\n typeof v === 'boolean' ? v : undefined\n const preview: CheckoutPaymentPlanPreview = {\n interval: num(config.interval),\n totalInstallments: num(config.total_installments),\n pricePerInstallment: num(config.price_per_installment),\n total: num(config.total),\n downPaymentEnabled:\n typeof config.down_payment_enabled === 'boolean'\n ? config.down_payment_enabled\n : undefined,\n downPaymentAmount:\n config.down_payment_amount == null ? null : num(config.down_payment_amount),\n currency: typeof config.currency === 'string' ? config.currency : undefined,\n currencySymbol:\n typeof config.currency_symbol === 'string' ? config.currency_symbol : undefined,\n customMessage: config.custom_message == null ? null : String(config.custom_message),\n terminology: typeof config.terminology === 'string' ? config.terminology : undefined,\n manufacturerName:\n typeof config.manufacturer_name === 'string' ? config.manufacturer_name : undefined,\n\n // The disclosure fields. The backend has always sent these; dropping them\n // here is what made our plan terms a three-line summary while the hosted\n // checkout states the admin fee and what the buyer forfeits on default.\n isAutoEqual: bool(config.is_auto_equal),\n hasAdminFee: bool(config.has_admin_fee),\n adminFee: config.admin_fee == null ? null : (num(config.admin_fee) ?? null),\n nonRefundableType:\n config.non_refundable_type === 'fixed' || config.non_refundable_type === 'percent'\n ? config.non_refundable_type\n : null,\n nonRefundableAmount:\n config.non_refundable_amount == null\n ? null\n : (num(config.non_refundable_amount) ?? null),\n totalNonRefundableAmount:\n config.total_non_refundable_amount == null\n ? null\n : (num(config.total_non_refundable_amount) ?? null),\n hideNonRefundableAdminFeeText: bool(config.hide_non_refundable_admin_fee_text),\n isEventAnchored: bool(config.is_event_anchored),\n finalChargeDate:\n config.final_charge_date == null ? null : String(config.final_charge_date),\n\n downPaymentMode:\n config.down_payment_mode == null ? null : String(config.down_payment_mode),\n downPaymentScope:\n config.down_payment_scope == null ? null : String(config.down_payment_scope),\n downPaymentPercent:\n config.down_payment_percent == null\n ? null\n : (num(config.down_payment_percent) ?? null),\n downPaymentPerTicketAmount:\n config.down_payment_per_ticket_amount == null\n ? null\n : (num(config.down_payment_per_ticket_amount) ?? null),\n downPaymentTicketCount:\n config.down_payment_ticket_count == null\n ? null\n : (num(config.down_payment_ticket_count) ?? null),\n }\n return preview.totalInstallments != null || preview.pricePerInstallment != null\n ? preview\n : undefined\n}\n\n/**\n * Prices the cart (+ chosen add-ons); returns the decrypted ticket type ids and\n * the Stripe config. Re-run whenever the add-on selection changes.\n *\n * paymentOption MUST be 'single_charge' — any other value makes the backend\n * reprice with a method-specific fee structure and silently drop booking fees\n * (undercharge vs. the price shown on the event page).\n */\nexport const updateCheckout = async (\n eventId: string,\n addOns: AddonSelection,\n options: { isFromResale?: boolean } = {}\n): Promise<CheckoutPricing> => {\n const body = await post<any>(ENDPOINTS.cart.checkout, {\n data: {\n attributes: {\n event_id: eventId,\n add_ons: addOns,\n is_from_resale: options.isFromResale ?? false,\n payment_information: {\n paymentSolution: 'stripe',\n paymentOption: 'single_charge',\n },\n },\n },\n })\n const attrs = body?.data?.attributes\n const cb = attrs?.cart_price_breakdown\n const api = attrs?.additional_payment_information\n const basic = api?.basic_config\n const planConfig = api?.payment_plan_configuration\n const planSavedLast4 = planConfig?.saved_card?.last_4_digits\n const redirectPaymentMethods = listRedirectMethods(\n api?.elements_config?.paymentMethodTypes\n )\n const wallets = walletsOption(api?.stripe_wallets as StripeWallets | undefined)\n\n return {\n ticketTypeIds: (cb?.tickets_price_breakdown ?? []).map((i: any) =>\n String(i.ticket_type_id)\n ),\n breakdown: cb\n ? {\n total: Number(cb.total ?? 0),\n totalAddOns: Number(cb.total_add_ons ?? 0),\n currencyCode: cb.currency?.currency ?? '',\n currencySymbol: cb.currency?.symbol ?? '',\n tickets: (cb.tickets_price_breakdown ?? []).map((t: any) => ({\n name: t.ticket_type_name,\n ticketTypeId: t.ticket_type_id != null ? String(t.ticket_type_id) : '',\n quantity: Number(t.quantity ?? 0),\n unit: String(t.price_per_ticket ?? ''),\n total: Number(t.total_price ?? 0),\n })),\n }\n : undefined,\n stripe: basic?.apiKey\n ? { publishableKey: basic.apiKey, accountId: basic.accountId || null }\n : undefined,\n paymentPlan:\n api?.payment_plan_available === true\n ? {\n available: true,\n savedCardLast4:\n typeof planSavedLast4 === 'string' ? planSavedLast4 : undefined,\n configuration: parsePlanPreview(planConfig),\n }\n : undefined,\n redirectPaymentMethods,\n walletAvailability: {\n applePay: wallets.applePay === 'auto',\n googlePay: wallets.googlePay === 'auto',\n },\n // The whole deferred block (mode/amount/currency/paymentMethodTypes). The\n // Payment Element mounts against this — server-computed amounts sidestep\n // zero-decimal-currency math. Undefined when the event isn't Stripe-deferred.\n stripeElementsConfig:\n api?.elements_config && typeof api.elements_config === 'object'\n ? (api.elements_config as Record<string, unknown>)\n : undefined,\n }\n}\n\n/**\n * Server-priced order summary (display-ready, server-formatted strings — render\n * verbatim, never recompute). Null when the backend doesn't serve the block.\n */\nexport const getPriceBreakdown = async (\n addOns?: AddonSelection\n): Promise<PriceBreakdown | null> => {\n const body = await get<any>(\n ENDPOINTS.cart.withPriceBreakdown(priceBreakdownAddOnsQuery(addOns))\n )\n return resolvePriceBreakdown(body?.data?.attributes)\n}\n\n/** Raw pre-order payment-config attributes (GET v1/cart?payment_config=1) — feed\n * to core's paypalTabConfig / xenditPreOrderConfig / walletsOption. */\nexport const getPaymentConfigAttributes = async (): Promise<Record<string, unknown>> => {\n const body = await get<any>(ENDPOINTS.cart.withPaymentConfig)\n return (body?.data?.attributes ?? {}) as Record<string, unknown>\n}\n\nexport interface PreOrderPaymentMethods {\n gateway: PreOrderGateway | null\n xenditEWallets: XenditProcessor[]\n xenditCard: boolean\n paypal: boolean\n}\n\n/** Resolves a (possibly relative) processor icon path against the host origin. */\nconst absolutizeIcon = (origin: string, icon?: string): string | undefined => {\n if (!icon) return undefined\n if (/^(https?:)?\\/\\//i.test(icon) || icon.startsWith('data:')) return icon\n if (!origin) return icon\n return `${origin}/${icon.replace(/^\\//, '')}`\n}\n\n/**\n * What this event's checkout can pay with BEFORE the order exists — read from\n * the pre-order payment config exactly as the hosted selector does.\n */\nexport const getPreOrderPaymentMethods = async (): Promise<PreOrderPaymentMethods> => {\n const attrs = await getPaymentConfigAttributes()\n const xendit = xenditPreOrderConfig(attrs)\n // The backend returns each processor icon as a RELATIVE path (e.g.\n // `/resources/images/payment/xendit/dana.png`). These are TicketFairy-global\n // brand marks served PUBLICLY from the production site — that's how the old\n // checkout loaded them (its relative paths resolved against the public host).\n // Resolve them the same way, against the public origin, so an <img> loads\n // them token-free even when the API is pointed at the access-gated staging\n // host (test.ticketfairy.com/resources 302s to a CF login, and an <img>\n // can't carry the CF-Access token). Absolute icon URLs are left untouched.\n const iconOrigin = ENV_HOSTS.PROD\n return {\n gateway: identifyPreOrderGateway(attrs),\n xenditEWallets: xendit\n ? xendit.processors\n .filter((row) => !XENDIT_NON_EWALLET_PROCESSORS.has(row.key))\n .map((row) => ({ ...row, icon: absolutizeIcon(iconOrigin, row.icon) }))\n : [],\n xenditCard: Boolean(xendit),\n paypal: Boolean(paypalTabConfig(attrs)),\n }\n}\n\n/**\n * Existing-account detection (the hosted `init_email_check`): reports whether a\n * live account owns the email so returning buyers get a sign-in prompt. Never a\n * gate — debounce it, keep typing unblocked. Origin-rooted and form-encoded.\n */\nexport const checkBuyerEmail = async (email: string): Promise<ExistingAccount> => {\n const res = await post<any>(\n `${getOriginUrl()}/${ENDPOINTS.auth.contactEmail}`,\n `email=${encodeURIComponent(email)}&is_checkout_flow=1`,\n { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }\n )\n return interpretContactEmail(res)\n}\n","/**\n * Order — create the order from the buyer/holders/add-ons, read the review\n * (gateway identity + Stripe/plan secrets), finalize (free registration or\n * success), and read ID-verification status. Ported faithfully from the\n * engine's api layer; the on-checkout body is composed by core's\n * `buildOnCheckoutBody` (the contract-pinned builder checkout-v2 also uses).\n */\nimport { post, get } from '../client/http'\nimport { TtfError } from '../client/errors'\nimport { ENDPOINTS } from '../constants'\nimport {\n buildOnCheckoutBody,\n detectGateway,\n paymentIntentIdFromClientSecret,\n savedPlanCard,\n} from '../logic'\nimport type {\n AddonSelection,\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n CustomFieldValues,\n IdVerificationStatus,\n SavedPlanCard,\n} from '../dtos'\nimport type { TfProfile } from '../types'\n\nexport interface CreatedOrder {\n hash: string\n total: string\n payNow: string\n status: string\n /** Duplicate-charge guard: true when the server answered with an\n * ALREADY-COMPLETED paid order (payment landed out-of-band). Go straight to\n * confirmation — never charge again. */\n alreadyPaid: boolean\n}\n\nexport const createOrder = async (input: {\n billing: CheckoutBilling\n holders: CheckoutHolder[]\n addOns: AddonSelection\n consent: CheckoutConsent\n /** Add-on custom-field values keyed by add-on id → add_on_data_capture. */\n addOnDataCapture?: Record<string, CustomFieldValues>\n}): Promise<CreatedOrder> => {\n const { billing, holders, addOns, consent, addOnDataCapture } = input\n\n const attributes = buildOnCheckoutBody(\n {\n buyerFields: {\n nationality: billing.nationality,\n gender: billing.gender,\n instagramHandle: billing.instagramHandle,\n },\n dataCapture: billing.dataCapture,\n ticketHolders: holders.map((h) => ({\n firstName: h.firstName,\n lastName: h.lastName,\n email: h.email,\n phone: h.phone ?? '',\n ticketTypeId: h.ticketTypeId,\n ticketDataCapture: h.ticketDataCapture,\n })),\n addOns,\n ...(addOnDataCapture\n ? {\n addOnDataCapture: Object.fromEntries(\n Object.entries(addOnDataCapture).filter(\n ([id, values]) =>\n Number(addOns[id]) > 0 && values && Object.keys(values).length > 0\n )\n ),\n }\n : {}),\n },\n {\n email: billing.email,\n confirm_email: billing.email,\n first_name: billing.firstName,\n last_name: billing.lastName,\n password: '',\n phone: billing.phone ?? '',\n ttf_opt_in: consent.ttfOptIn,\n brand_opt_in: consent.brandOptIn,\n ...(billing.streetAddress ? { street_address: billing.streetAddress } : {}),\n ...(billing.city ? { city: billing.city } : {}),\n ...(billing.zip ? { zip: billing.zip } : {}),\n ...(billing.countryId ? { country: Number(billing.countryId) } : {}),\n ...(billing.stateId ? { state: Number(billing.stateId) } : {}),\n ...(billing.dobDay && billing.dobMonth && billing.dobYear\n ? {\n dob_day: billing.dobDay,\n dob_month: billing.dobMonth,\n dob_year: billing.dobYear,\n }\n : {}),\n }\n )\n\n const body = await post<any>(ENDPOINTS.order.create, { data: { attributes } })\n const a = body?.data?.attributes\n if (!a?.hash) throw new TtfError('Order was not created (no hash in response).', 0)\n return {\n hash: String(a.hash),\n total: String(a.total ?? ''),\n payNow: String(a.pay_now ?? ''),\n status: String(a.status ?? ''),\n alreadyPaid: String(a.status ?? '') === 'paid',\n }\n}\n\nexport interface OrderReview {\n total: string\n clientSecret: string | null\n publishableKey: string | null\n connectedAccount: string | null\n expiresInSeconds?: number\n paymentAlreadyProcessed: boolean\n gateway: ReturnType<typeof detectGateway>\n orderId?: string\n currency?: string\n stripeIntentId?: string\n payNow?: string\n razorpayKeyId?: string\n xenditPublishableKey?: string\n xenditOnBehalfOf?: string | null\n paymentPlanSetupSecret?: string\n paymentPlanSavedCard: SavedPlanCard | null\n}\n\nexport const getOrderReview = async (orderHash: string): Promise<OrderReview> => {\n const body = await get<any>(ENDPOINTS.order.review(orderHash))\n const a = body?.data?.attributes\n const method = a?.payment_method ?? {}\n const rawExpiry = Number(a?.expires_at)\n return {\n total: String(a?.order_details?.total ?? ''),\n paymentAlreadyProcessed: Boolean(method.payment_already_processed),\n clientSecret: method.stripe_client_secret ?? null,\n publishableKey: method.stripe_publishable_key ?? null,\n connectedAccount: method.stripe_connected_account || null,\n expiresInSeconds: Number.isFinite(rawExpiry) && rawExpiry > 0 ? rawExpiry : undefined,\n gateway: detectGateway(method),\n orderId: a?.order_details?.id != null ? String(a.order_details.id) : undefined,\n currency: a?.order_details?.currency ?? undefined,\n stripeIntentId:\n (typeof method.stripe_intent_id === 'string' && method.stripe_intent_id) ||\n paymentIntentIdFromClientSecret(method.stripe_client_secret) ||\n undefined,\n payNow:\n a?.order_details?.pay_now != null ? String(a.order_details.pay_now) : undefined,\n razorpayKeyId: method.razorpay_key_id || method.key_id || method.api_key || undefined,\n xenditPublishableKey:\n method.xendit_publishable_key ||\n method.publishable_key ||\n method.api_key ||\n undefined,\n xenditOnBehalfOf: (method.xendit_on_behalf_of as string | undefined) ?? null,\n paymentPlanSetupSecret:\n (typeof method.stripe_payment_plan_configuration?.stripe_setup_intent_secret ===\n 'string' &&\n method.stripe_payment_plan_configuration.stripe_setup_intent_secret) ||\n undefined,\n paymentPlanSavedCard: savedPlanCard(method as Record<string, unknown>),\n }\n}\n\n/**\n * Maps a signed-in user's profile into a `CheckoutBilling` to prefill the\n * billing form. Merge over your own edits:\n * `setBilling({ ...mapProfileToBilling(profile), ...edits })`.\n */\nexport const mapProfileToBilling = (profile: TfProfile): CheckoutBilling => {\n const str = (v: string | number | null | undefined): string | undefined =>\n v == null || v === '' ? undefined : String(v)\n // 0 / '0' / '-1' are \"no selection\" sentinels for country/state ids.\n const idStr = (v: string | number | null | undefined): string | undefined => {\n const s = str(v)\n return s === undefined || s === '0' || s === '-1' ? undefined : s\n }\n // Split the ISO date by hand rather than via `new Date(...)`: that parses\n // `1990-05-01` as UTC midnight, so a buyer west of Greenwich reads their\n // birthday back a day early. `0000-00-00` is a legacy empty-date sentinel,\n // which the year test rejects along with anything else malformed.\n const dobParts = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(profile.dateOfBirth ?? '')\n const dob =\n dobParts && Number(dobParts[1]) > 1900\n ? {\n dobYear: Number(dobParts[1]),\n dobMonth: Number(dobParts[2]),\n dobDay: Number(dobParts[3]),\n }\n : {}\n return {\n firstName: profile.firstName ?? '',\n lastName: profile.lastName ?? '',\n email: profile.email ?? '',\n phone: str(profile.phone),\n streetAddress: str(profile.streetAddress),\n city: str(profile.city),\n zip: str(profile.zipCode),\n countryId: idStr(profile.countryId),\n stateId: idStr(profile.stateId),\n ...dob,\n }\n}\n\nexport const completeFreeRegistration = async (orderHash: string): Promise<void> => {\n await post(ENDPOINTS.order.completeFreeRegistration(orderHash))\n}\n\nexport const confirmOrderSuccess = async (\n orderHash: string,\n options?: {\n /** Razorpay settle token (`razorpay_payment_id`) — the server fetches +\n * captures the charge with it. */\n token?: string\n }\n): Promise<{ needIdVerification: boolean }> => {\n const body = await post<any>(\n ENDPOINTS.order.success(orderHash),\n options?.token ? { token: options.token } : undefined\n )\n return {\n needIdVerification: Boolean(\n body?.data?.attributes?.needIdVerification ?? body?.data?.needIdVerification\n ),\n }\n}\n\n/**\n * ID-verification status for a NEED_ID_VERIFICATION order. Pass `mintUrl: true`\n * on the call that OPENS the provider session (the server mints\n * `verification_url` on that call only); poll the plain form afterwards.\n */\nexport const getIdVerificationStatus = async (\n orderHash: string,\n mintUrl?: boolean\n): Promise<IdVerificationStatus> => {\n const body = await get<any>(ENDPOINTS.order.idVerification(orderHash, mintUrl))\n return (body?.data?.attributes ?? {}) as IdVerificationStatus\n}\n\n/** Whether the signed-in user owns this order (guards the confirmation page\n * against someone opening another buyer's order hash). */\nexport const verifyCustomerOrder = async (orderHash: string): Promise<unknown> =>\n get(ENDPOINTS.order.verifyCustomer(orderHash))\n","/**\n * Payment-rail transports — the per-gateway wire calls the engine dispatches to\n * after the order exists: fee re-price, redirect confirm, OXXO prepare, Xendit\n * e-wallet/card charge, MSI installments, payment plans, and PayPal Standard.\n * Ported faithfully from the engine's api layer; request/response shaping stays\n * in core's interpreters.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport {\n buildPaymentMethodTypeAttributes,\n interpretRedirectConfirm,\n resolvePayPalForm,\n} from '../logic'\nimport type {\n PaymentMethodTypeInput,\n PayPalForm,\n RedirectConfirmRequest,\n RedirectOutcome,\n} from '../dtos'\n\nconst postFormEncoded = (\n uri: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n post<Record<string, unknown>>(\n uri,\n Object.entries(fields)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join('&'),\n { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }\n ).then((data) => data ?? {})\n\nconst appendFormObject = (\n form: FormData,\n prefix: string,\n obj: Record<string, unknown>\n) => {\n Object.keys(obj).forEach((key) => {\n const value = obj[key]\n if (value === null || value === undefined) return\n if (typeof value === 'object') {\n appendFormObject(form, `${prefix}[${key}]`, value as Record<string, unknown>)\n } else {\n form.append(`${prefix}[${key}]`, String(value))\n }\n })\n}\n\n/**\n * Per-payment-method-type fee re-price (Klarna/Afterpay-class types carry their\n * own fee structures). Run BEFORE confirming a fee-mode type, then re-fetch the\n * review — charging the pre-reprice amount would undercharge.\n */\nexport const changePaymentMethodType = async (\n orderHash: string,\n input: PaymentMethodTypeInput\n): Promise<void> => {\n await post(ENDPOINTS.payment.methodType(orderHash), {\n data: { attributes: buildPaymentMethodTypeAttributes(input) },\n })\n}\n\n/** Server-side confirm for redirect-based Stripe methods — returns the provider\n * hand-off (or 'settled' when no redirect is needed). */\nexport const confirmRedirect = async (\n orderHash: string,\n request: RedirectConfirmRequest\n): Promise<RedirectOutcome> => {\n const body = await post<any>(ENDPOINTS.payment.confirmRedirect(orderHash), request)\n return interpretRedirectConfirm(body?.data?.attributes)\n}\n\n/** OXXO: move the order (and its goods) to the pending-voucher state BEFORE the\n * client confirm. Empty body; needs the registered session. */\nexport const prepareForOxxo = async (orderHash: string): Promise<void> => {\n await post(ENDPOINTS.payment.prepareOxxo(orderHash))\n}\n\n/** Xendit e-wallet charge — multipart fields from core's\n * `buildXenditEWalletChargeFields`; interpret with `interpretXenditChargeResponse`. */\nexport const submitXenditEWalletCharge = async (\n fields: Record<string, string>\n): Promise<Record<string, unknown>> => {\n const form = new FormData()\n Object.entries(fields).forEach(([key, value]) => form.append(key, value))\n const data = await post<Record<string, unknown>>(\n ENDPOINTS.payment.submitPayment(encodeURIComponent(fields.orderHash)),\n form,\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n return data ?? {}\n}\n\n/** MSI offers — between payment-method creation and the confirm; the server\n * gates to MXN carts. Fields from `buildInstallmentOffersFields`. */\nexport const getInstallmentOffers = (\n orderHash: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n postFormEncoded(ENDPOINTS.payment.installmentOffers(orderHash), fields)\n\n/** MSI confirm: the intent confirms SERVER-SIDE — when has_next_action comes\n * back, run only handleNextAction, never a second confirmPayment. */\nexport const confirmInstallments = (\n orderHash: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n postFormEncoded(ENDPOINTS.payment.confirmInstallments(orderHash), fields)\n\n/**\n * Payment plan (installments) with a NEW card: the card is saved via the\n * review's SetupIntent (confirmed on the confirmer, nothing charged), then this\n * schedules the plan server-side against the resulting PaymentMethod.\n */\nexport const createPaymentPlan = async (\n orderHash: string,\n stripePaymentMethodId: string\n): Promise<{ needIdVerification: boolean }> => {\n const body = await post<any>(ENDPOINTS.payment.paymentPlanCreate(orderHash), {\n stripe_payment_method_id: stripePaymentMethodId,\n })\n return {\n needIdVerification: Boolean(\n body?.data?.attributes?.needIdVerification ?? body?.data?.needIdVerification\n ),\n }\n}\n\n/**\n * Payment-plan saved-card shortcut: charge the plan directly to the reusable\n * card the review carries, skipping the SetupIntent round trip. The server may\n * answer `requires_action` with a client secret — run 3DS, then settle.\n */\nexport const chargeSavedCardPlan = async (\n orderHash: string,\n paymentMethodId: string\n): Promise<{ requiresAction: boolean; clientSecret?: string }> => {\n const data = await postFormEncoded(ENDPOINTS.cart.paymentPlan(orderHash), {\n paymentMethodId,\n })\n const inner = ((data.data as Record<string, unknown> | undefined) ?? data) || {}\n return {\n requiresAction: Boolean(inner.requires_action),\n clientSecret:\n typeof inner.client_secret === 'string' ? inner.client_secret : undefined,\n }\n}\n\n/** PayPal Standard step 1: switch the placed order's payment method (attributes\n * from core's `buildChangePaymentMethodAttributes`). */\nexport const changePaymentMethod = async (\n attributes: Record<string, unknown>\n): Promise<void> => {\n await post(ENDPOINTS.payment.changeMethod, {\n data: { attributes },\n })\n}\n\n/** PayPal Standard step 2: the `{action_url, fields}` document the provider page\n * auto-submits (PayPal refuses framing — top-level POST only). */\nexport const getPayPalForm = async (orderHash: string): Promise<PayPalForm | null> => {\n const body = await get<any>(ENDPOINTS.payment.paypalForm(orderHash))\n return resolvePayPalForm(body?.data?.attributes ?? null)\n}\n\n/**\n * Xendit CARD charge: the sheet tokenized the card (with 3DS) client-side; the\n * token is charged server-side (the amount is resolved from the order, the\n * token only proves the card). Success responses may still carry error:true;\n * that throws here.\n */\nexport const submitXenditCardCharge = async (\n orderId: string,\n orderHash: string,\n token: Record<string, unknown>\n): Promise<Record<string, unknown>> => {\n const form = new FormData()\n form.append('order', String(orderId))\n form.append('orderHash', orderHash)\n form.append('paymentData[paymentType]', 'credit_card')\n appendFormObject(form, 'paymentData[data]', token)\n\n const result = await post<Record<string, unknown>>(\n ENDPOINTS.payment.submitPayment(encodeURIComponent(orderHash)),\n form,\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n const data = result ?? {}\n if (data.error === true) {\n throw new Error(\n String(\n data.message ||\n data.failure_reason ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n )\n }\n return data\n}\n","/**\n * The checkout sequence — framework-free and payment-SDK-free (card/wallet\n * confirmation goes through the injected PaymentConfirmer port). Encodes the\n * traps the server contract hides:\n * - add-to-cart replaces the whole cart → ONE call with every ticket type\n * - GET /cart must run before POST /checkout (primes the session)\n * - decrypted ticket_type_ids only exist in the pricing response\n * - free strictly means order total === 0\n * - retries must never create a second order or charge twice\n */\nimport {\n addSeatsToCart,\n addTicketsToCart,\n changePaymentMethod,\n changePaymentMethodType,\n chargeSavedCardPlan,\n checkBuyerEmail as checkBuyerEmailApi,\n completeFreeRegistration,\n confirmInstallments,\n confirmOrderSuccess,\n confirmRedirect,\n createOrder,\n createPaymentPlan,\n getCart,\n getCheckoutConfigs,\n getEventAddons,\n getEventConditions,\n getEventCustomFields,\n getIdVerificationStatus,\n getInstallmentOffers,\n getOrderReview,\n getPaymentConfigAttributes,\n getPayPalForm,\n getPriceBreakdown,\n prepareForOxxo,\n setEventCurrency,\n submitXenditCardCharge,\n submitXenditEWalletCharge,\n updateCheckout,\n} from '../api'\nimport { getOriginUrl } from '../client'\nimport { clearCartGuestToken, pinCartGuestToken } from '../client/session'\nimport { XENDIT_EWALLET_EXTRA_FIELD } from '../constants'\nimport type {\n AddonSelection,\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n CheckoutOptions,\n CheckoutSnapshot,\n CurrencySync,\n CurrencySyncOptions,\n CustomFieldValues,\n EventAddon,\n EventCondition,\n EventCustomFieldGroup,\n IdVerificationCallbacks,\n IdVerificationPoller,\n IdVerificationStatus,\n InstallmentOffer,\n PlaceOrderResult,\n PreOrderGateway,\n RequiredAddOnLike,\n SeatLine,\n TicketSelection,\n} from '../dtos'\nimport {\n buildChangePaymentMethodAttributes,\n buildConfirmInstallmentsFields,\n buildInstallmentOffersFields,\n buildXenditEWalletChargeFields,\n confirmInstallmentsHasNextAction,\n createIdVerificationPoller,\n evaluateFieldGates,\n interpretXenditChargeResponse,\n missingCheckoutDetails,\n missingRequiredAddOns,\n oxxoVoucherFromNextAction,\n paypalTabConfig,\n requiresFeeReprice,\n resolveInstallmentOffers,\n} from '../logic'\nimport {\n buildAutoSubmitFormHtml,\n cleanAccountId,\n CONFIRMED_INTENT_STATUSES,\n unsupportedGatewayError,\n type CheckoutPorts,\n} from './confirmer'\nimport { errorMessage, isCartExpiredError } from './errors'\nimport { buildRazorpayCheckoutHtml, buildXenditCheckoutHtml } from './sheets'\nimport { createCheckoutStore, type CheckoutStore } from './store'\n\n/** How the shopper pays. Apple/Google Pay show the native wallet sheet; card\n * confirms the card field the consumer rendered. */\nexport type PaymentMethod = 'card' | 'applePay' | 'googlePay'\n\n/** A full payment request — the alternative rails carry parameters. The plain\n * `PaymentMethod` strings remain valid ('card' ≡ `{ method: 'card' }`). */\nexport type PaymentRequest =\n | { method: 'card' }\n /** Pay with the ORDER'S OWN gateway (the prebuilt \"just pay\" button):\n * razorpay → the Razorpay sheet, xendit → the Xendit card rail,\n * stripe/unknown → the card path (incl. MSI). */\n | { method: 'auto'; description?: string }\n | { method: 'applePay' }\n | { method: 'googlePay' }\n /** Redirect-based Stripe methods (Klarna/Afterpay/Affirm/iDEAL-class). Needs\n * ports.providerPage + ports.createRedirectPaymentMethod. */\n | { method: 'redirect'; methodType: string }\n /** OXXO cash voucher (Mexico). Needs ports.confirmOxxo; result is\n * `pending: true` + `pendingVoucherUrl`. */\n | { method: 'oxxo' }\n /** Xendit e-wallet (walletKey from the pre-order processors, e.g. 'dana';\n * Jenius Pay wants extra.cashtag, OVO extra.phoneNumber). Needs providerPage. */\n | {\n method: 'xenditEWallet'\n walletKey: string\n extra?: { cashtag?: string; phoneNumber?: string }\n }\n /** PayPal Standard (top-level form; settles via IPN — may return pending). */\n | { method: 'paypal' }\n /** Razorpay web checkout (posts razorpay_payment_id → settle token on /success). */\n | { method: 'razorpay'; description?: string }\n /** Xendit CARD: the sheet tokenizes (3DS) and posts `token`; charge server-side. */\n | { method: 'xenditCard' }\n /** Payment plan (installments, Stripe): the card is SAVED via the review's\n * SetupIntent (nothing charged now), the plan schedules server-side; a\n * reusable saved card is charged directly (opt out with useSavedCard:false). */\n | { method: 'paymentPlan'; useSavedCard?: boolean }\n\nconst normalizeRequest = (method?: PaymentMethod | PaymentRequest): PaymentRequest =>\n typeof method === 'string' ? { method } : (method ?? { method: 'card' })\n\n/** The platform capabilities + wallet/redirect options the rails run on. */\nexport interface EngineContext {\n ports: CheckoutPorts\n options: CheckoutOptions\n}\n\n// ---------------------------------------------------------------------------\n// Pre-flight helpers (pure)\n// ---------------------------------------------------------------------------\n\nconst hasValue = (v: string | string[] | undefined): boolean =>\n Array.isArray(v) ? v.length > 0 : Boolean(v && String(v).trim())\n\nconst missingRequiredAddOnCaptures = (\n groups: EventCustomFieldGroup[],\n addOns: AddonSelection,\n addOnDataCapture: Record<string, CustomFieldValues> | undefined\n): string[] => {\n const missing: string[] = []\n for (const g of groups.filter((g) => g.scope === 'add-on')) {\n if (!(Number(addOns[g.id]) > 0)) continue\n const values = addOnDataCapture?.[g.id]\n for (const f of g.fields.filter((f) => f.required && f.type !== 'image')) {\n if (!hasValue(values?.[f.name])) {\n missing.push(`${f.label || f.name}${g.label ? ` (${g.label})` : ''}`)\n }\n }\n }\n return missing\n}\n\nconst unacceptedRequiredConditions = (\n conditions: EventCondition[] | undefined,\n accepted: Record<string, boolean> | undefined\n): EventCondition[] =>\n (conditions ?? []).filter((c) => c.isRequired && accepted?.[c.id] !== true)\n\nconst assertNotBusy = (store: CheckoutStore) => {\n const { status } = store.getState()\n if (status === 'priming' || status === 'repricing' || status === 'placing') {\n throw new Error('Checkout is busy — please wait.')\n }\n}\n\n/**\n * Routes a failed call to the right terminal state: an expired-cart rejection\n * becomes 'expired' (offer a restart), anything else 'error'. Exception: once\n * the card is charged, the order MUST be finalized — even an expiry rejection\n * on the finalize call stays a recoverable 'error' (a retry replays only the\n * finalize on the same hash), never the destructive restart.\n */\nconst failCheckout = (store: CheckoutStore, e: unknown): void => {\n const expired = isCartExpiredError(e) && !store.progress.paymentConfirmed\n if (expired) clearCartGuestToken()\n store.setState({ status: expired ? 'expired' : 'error', error: errorMessage(e) })\n}\n\n// ---------------------------------------------------------------------------\n// Prime + reprice\n// ---------------------------------------------------------------------------\n\n/** Builds the server cart for a ticket selection and prices it. Idempotent per\n * selection (the server replaces the cart; the store resets for the new run). */\nexport const primeWith = (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n selections: TicketSelection[]\n): Promise<void> => {\n if (!selections.length) throw new Error('Select at least one ticket.')\n return primeCore(store, ctx, eventId, selections, () =>\n addTicketsToCart(eventId, selections)\n )\n}\n\n/** One reserved seat → one store selection, so the holder math (one holder per\n * ticket) stays correct. A guest-capable table contributes `guests` holders —\n * the server counts tickets from the `ticket_types` quantities, which for a\n * guest line equal the guest count. (If a real table-map event turns out to\n * need one holder per TABLE, drop the `?? l.guests` and use `1`.) */\nconst seatLinesToSelections = (lines: SeatLine[]): TicketSelection[] =>\n lines.map((l) => ({\n id: l.ticketTypeId,\n name: 'Seat',\n optionName: l.optionName,\n price: l.price,\n currency: '',\n quantity: l.guests ?? 1,\n }))\n\n/** Builds the server cart for RESERVED SEATS and prices it — the seat-map\n * analogue of `primeWith`. Reservations were already placed on seat click\n * (`ttf.seatmap.reserve`); this turns them into cart lines + prices the order,\n * reusing the exact same session-prime / gateway-guard / pricing pipeline. */\nexport const primeSeatsWith = (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n lines: SeatLine[]\n): Promise<void> => {\n if (!lines.length) throw new Error('Select at least one seat.')\n return primeCore(store, ctx, eventId, seatLinesToSelections(lines), () =>\n addSeatsToCart(eventId, lines)\n )\n}\n\n/**\n * Attach the engine to a cart that another supported flow already created\n * (currently resale and compatibility links). Unlike `prime`, this does not\n * add or replace ticket lines.\n */\nexport const resumeCartWith = async (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n options: { isFromResale?: boolean } = {}\n): Promise<void> => {\n assertNotBusy(store)\n store.reset()\n store.setState({ status: 'priming', eventId, selections: [] })\n\n try {\n const { expiresInSeconds, preOrderGateway } = await getCart()\n pinCartGuestToken()\n const payableGateways = ['stripe_payment_intents', 'xendit']\n if (preOrderGateway && !payableGateways.includes(preOrderGateway)) {\n throw new Error(\n \"This event's payment provider isn't supported in this checkout yet.\"\n )\n }\n\n const [pricing, customFields, configGates, priceBreakdown, addons, conditions] =\n await Promise.all([\n updateCheckout(eventId, {}, options),\n getEventCustomFields(eventId).catch((): EventCustomFieldGroup[] => []),\n getCheckoutConfigs().catch(() => ({\n holderNamesRequired: false,\n fieldGates: evaluateFieldGates(null),\n })),\n getPriceBreakdown().catch(() => null),\n getEventAddons(eventId).catch((): EventAddon[] => []),\n getEventConditions(eventId).catch((): EventCondition[] => []),\n ])\n\n store.setState({\n status: 'ready',\n gateway: (preOrderGateway ?? undefined) as PreOrderGateway | undefined,\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n stripe: pricing.stripe,\n paymentPlan: pricing.paymentPlan,\n customFields,\n requiredAddOns: addons\n .filter((addon) => addon.required)\n .map((addon) => ({\n id: addon.id,\n name: addon.name,\n required: true,\n stock: addon.stock,\n })),\n conditions,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n holderNamesRequired: configGates.holderNamesRequired,\n fieldGates: configGates.fieldGates,\n priceBreakdown,\n expiresAt: Date.now() + expiresInSeconds * 1000,\n })\n\n if (pricing.stripe) {\n await ctx.ports.confirmer\n .init({\n publishableKey: pricing.stripe.publishableKey,\n accountId: cleanAccountId(pricing.stripe.accountId),\n })\n .catch(() => undefined)\n }\n } catch (error) {\n failCheckout(store, error)\n throw error\n }\n}\n\n/** The shared prime pipeline: reset → populate the cart → session-prime +\n * gateway guard → price/custom-fields/conditions/add-ons fan-out → ready.\n * `populateCart` is the only thing that differs between tickets and seats. */\nconst primeCore = async (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n selections: TicketSelection[],\n populateCart: () => Promise<{ holderNamesRequired: boolean }>\n): Promise<void> => {\n assertNotBusy(store)\n\n // Never start a new cart on top of a CHARGED-but-unfinalized order: priming\n // resets the store, which would drop the confirmed payment and let the shopper\n // pay a second time. That order must be finalized (retry placeOrder), not replaced.\n if (store.progress.paymentConfirmed) {\n throw new Error(\n 'You already have a paid order being finalized. Please complete it before starting a new purchase.'\n )\n }\n\n store.reset()\n store.setState({ status: 'priming', eventId, selections })\n\n try {\n const { holderNamesRequired } = await populateCart()\n pinCartGuestToken()\n // Mandatory session priming — also identifies the payment gateway.\n const { expiresInSeconds, preOrderGateway } = await getCart()\n\n // Fail fast — BEFORE any order exists — on events this package can't pay.\n // Fails open when the backend doesn't identify a gateway. Xendit events are\n // payable through the e-wallet rail, so they prime.\n const PAYABLE_PRE_ORDER_GATEWAYS = ['stripe_payment_intents', 'xendit']\n if (preOrderGateway && !PAYABLE_PRE_ORDER_GATEWAYS.includes(preOrderGateway)) {\n throw new Error(\n \"This event's payment provider isn't supported in the app yet. Please complete your purchase on the event page.\"\n )\n }\n\n const [pricing, customFields, configGates, priceBreakdown, addons, conditions] =\n await Promise.all([\n updateCheckout(eventId, {}),\n getEventCustomFields(eventId).catch((): EventCustomFieldGroup[] => []),\n getCheckoutConfigs().catch(() => ({\n holderNamesRequired: false,\n fieldGates: evaluateFieldGates(null),\n })),\n getPriceBreakdown().catch(() => null),\n getEventAddons(eventId).catch((): EventAddon[] => []),\n getEventConditions(eventId).catch((): EventCondition[] => []),\n ])\n\n const requiredAddOns: RequiredAddOnLike[] = addons\n .filter((a) => a.required)\n .map((a) => ({ id: a.id, name: a.name, required: true, stock: a.stock }))\n\n store.setState({\n status: 'ready',\n // Validated payable above; the raw string narrows to the gateway union.\n gateway: (preOrderGateway ?? undefined) as PreOrderGateway | undefined,\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n stripe: pricing.stripe,\n paymentPlan: pricing.paymentPlan,\n customFields,\n requiredAddOns,\n conditions,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n holderNamesRequired: holderNamesRequired || configGates.holderNamesRequired,\n fieldGates: configGates.fieldGates,\n priceBreakdown,\n expiresAt: Date.now() + expiresInSeconds * 1000,\n })\n\n // Initialize the payment SDK as soon as the keys exist so the consumer's\n // card field is ready without any wiring on their side.\n if (pricing.stripe) {\n await ctx.ports.confirmer\n .init({\n publishableKey: pricing.stripe.publishableKey,\n accountId: cleanAccountId(pricing.stripe.accountId),\n })\n .catch(() => undefined) // re-initialized at pay time with review keys\n }\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n/** Stores the add-on selection and re-prices the cart with it. */\nexport const repriceWith = async (\n store: CheckoutStore,\n addOns: AddonSelection\n): Promise<void> => {\n const { eventId } = store.getState()\n if (!eventId) throw new Error('reprice: no active checkout.')\n assertNotBusy(store)\n\n // Changing add-ons invalidates any order created by a failed attempt.\n store.invalidateOrderProgress()\n\n store.setState({ status: 'repricing', addOns })\n try {\n const pricing = await updateCheckout(eventId, addOns)\n const priceBreakdown = await getPriceBreakdown(addOns).catch(() => null)\n store.setState({\n status: 'ready',\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n priceBreakdown,\n paymentPlan: pricing.paymentPlan,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n ...(pricing.stripe ? { stripe: pricing.stripe } : {}),\n })\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n// ---------------------------------------------------------------------------\n// Place order (create → review → rail dispatch → finalize)\n// ---------------------------------------------------------------------------\n\nexport const placeOrderWith = async (\n store: CheckoutStore,\n ctx: EngineContext,\n method: PaymentMethod | PaymentRequest = 'card'\n): Promise<PlaceOrderResult> => {\n const { ports, options } = ctx\n const { confirmer } = ports\n let request = normalizeRequest(method)\n const snap = store.getState()\n const { billing, holders, addOns, consent, selections, stripe } = snap\n\n assertNotBusy(store)\n\n const failPreflight = (message: string): Error => {\n store.setState({ status: 'error', error: message })\n return new Error(message)\n }\n\n const missingDetails = missingCheckoutDetails(snap)\n if (missingDetails.length > 0) {\n throw failPreflight(\n `Please complete the required checkout detail${missingDetails.length > 1 ? 's' : ''}: ${missingDetails\n .slice(0, 4)\n .join(', ')}${missingDetails.length > 4 ? '…' : ''}.`\n )\n }\n if (!billing) {\n // `missingCheckoutDetails` already reports this; retain the explicit guard\n // so TypeScript and non-standard callers both see billing as required.\n throw failPreflight('Billing details are incomplete.')\n }\n // Don't attempt an order the server will reject on an elapsed reservation.\n // Exception: once payment is confirmed we MUST finalize regardless of the timer.\n if (\n !store.progress.paymentConfirmed &&\n (snap.status === 'expired' ||\n (snap.expiresAt != null && Date.now() >= snap.expiresAt))\n ) {\n store.expireCart()\n throw new Error('Your cart has expired. Please choose your tickets again.')\n }\n\n // One holder entry per ticket; pad/trim to match.\n const totalTickets = selections.reduce((sum, t) => sum + t.quantity, 0) || 1\n const paddedHolders: CheckoutHolder[] = Array.from(\n { length: totalTickets },\n (_, i) => holders[i] ?? { firstName: '', lastName: '', email: '', phone: undefined }\n )\n\n const unaccepted = unacceptedRequiredConditions(\n snap.conditions,\n snap.acceptedConditions\n )\n if (unaccepted.length > 0) {\n const names = unaccepted.map((c) => c.name).filter(Boolean)\n throw failPreflight(\n `Please accept the required condition${unaccepted.length > 1 ? 's' : ''}${\n names.length ? `: ${names.join(', ')}` : ''\n }.`\n )\n }\n\n const missingCaptures = missingRequiredAddOnCaptures(\n snap.customFields,\n addOns,\n snap.addOnDataCapture\n )\n if (missingCaptures.length > 0) {\n throw failPreflight(\n `Please fill in the required field${missingCaptures.length > 1 ? 's' : ''}: ${missingCaptures\n .slice(0, 4)\n .join(', ')}${missingCaptures.length > 4 ? '…' : ''}.`\n )\n }\n\n const missingAddOns = missingRequiredAddOns(snap.requiredAddOns, addOns)\n if (missingAddOns.length > 0) {\n const names = missingAddOns.map((a) => a.name || '').filter(Boolean)\n throw failPreflight(\n `Please add the required add-on${missingAddOns.length > 1 ? 's' : ''}: ${names.join(', ')}`\n )\n }\n\n store.setState({ status: 'placing', error: undefined })\n try {\n // 1. Create the order (skip if a previous attempt already did).\n let orderHash = store.progress.orderHash\n if (!orderHash) {\n const order = await createOrder({\n billing,\n holders: paddedHolders,\n addOns,\n consent,\n addOnDataCapture: snap.addOnDataCapture,\n })\n orderHash = order.hash\n store.progress.orderHash = orderHash\n\n // Duplicate-charge guard: the server answered with the ALREADY-COMPLETED\n // paid order for this checkout — go straight to confirmation.\n if (order.alreadyPaid) {\n const result: PlaceOrderResult = {\n orderHash,\n free: false,\n needIdVerification: false,\n alreadyPaid: true,\n }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n }\n\n // 2. Review — order lock + authoritative total + Stripe secrets.\n const review = await getOrderReview(orderHash)\n if (review.expiresInSeconds != null) {\n store.setState({ expiresAt: Date.now() + review.expiresInSeconds * 1000 })\n }\n\n // 'auto' pays with the order's own gateway.\n if (request.method === 'auto') {\n request =\n review.gateway === 'razorpay'\n ? { method: 'razorpay', description: request.description }\n : review.gateway === 'xendit'\n ? { method: 'xenditCard' }\n : { method: 'card' }\n }\n\n // 3a. Free strictly means total === 0.\n if (review.total !== '' && Number(review.total) === 0) {\n await completeFreeRegistration(orderHash)\n const result: PlaceOrderResult = {\n orderHash,\n free: true,\n needIdVerification: false,\n currency: review.currency,\n }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n\n // Duplicate-charge guard: the server withholds the secret for intents that\n // already succeeded / are settling — skip charging, only replay finalize.\n if (review.paymentAlreadyProcessed) {\n store.progress.paymentConfirmed = true\n }\n\n const finish = (partial: PlaceOrderResult): PlaceOrderResult => {\n const result: PlaceOrderResult = { currency: review.currency, ...partial }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n\n let confirmedPaymentIntentId: string | undefined\n\n if (!store.progress.paymentConfirmed) {\n // ---- OXXO cash voucher (own finalize: pending result) --------------\n if (request.method === 'oxxo') {\n if (!ports.confirmOxxo) throw unsupportedGatewayError()\n if (review.gateway !== 'stripe' || !review.clientSecret) {\n throw new Error('This payment method is not available for this order')\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n await prepareForOxxo(orderHash)\n const { error: oxxoError, nextAction } = await ports.confirmOxxo(\n review.clientSecret,\n billing\n )\n const voucher = oxxoVoucherFromNextAction(\n (nextAction as Record<string, unknown>) || null\n )\n if (oxxoError && !voucher) throw new Error(oxxoError || 'Payment failed')\n if (!voucher) {\n throw new Error(\n 'We couldn’t issue the OXXO voucher. Please try again or pay with a card.'\n )\n }\n store.progress.paymentConfirmed = true\n try {\n await Promise.resolve(ports.openUrl?.(voucher.voucherUrl))\n } catch {\n // The voucher is also emailed and carried on the result.\n }\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n return finish({\n orderHash,\n free: false,\n needIdVerification,\n pending: true,\n pendingVoucherUrl: voucher.voucherUrl,\n })\n }\n\n // ---- PayPal Standard (own finalize: IPN settles asynchronously) ----\n if (request.method === 'paypal') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n const paypalConfig = paypalTabConfig(await getPaymentConfigAttributes())\n if (!paypalConfig) throw new Error('PayPal is not available for this order')\n if (!review.orderId) throw new Error('PayPal is not available for this order')\n await changePaymentMethod(\n buildChangePaymentMethodAttributes({\n paymentMethodId: paypalConfig.payment_method_id,\n paymentMethodHash: paypalConfig.payment_method_hash,\n orderId: review.orderId,\n orderHash,\n })\n )\n const paypalForm = await getPayPalForm(orderHash)\n if (!paypalForm) {\n throw new Error(\n 'We couldn’t start the PayPal payment. Please try again or pay by card.'\n )\n }\n const origin = getOriginUrl()\n const sheet = await ports.providerPage({\n html: buildAutoSubmitFormHtml(paypalForm),\n baseUrl: origin,\n returnUrlPrefix: `${origin}/store/order-complete`,\n })\n if (sheet.event === 'failed') {\n throw new Error(sheet.description || 'Payment failed')\n }\n store.progress.paymentConfirmed = true\n try {\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n return finish({ orderHash, free: false, needIdVerification })\n } catch {\n return finish({\n orderHash,\n free: false,\n needIdVerification: false,\n pending: true,\n })\n }\n }\n\n // ---- Razorpay web checkout (own finalize: settle token) ------------\n if (request.method === 'razorpay') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n if (review.gateway !== 'razorpay' || !review.razorpayKeyId) {\n throw new Error('This payment method is not available for this order')\n }\n const sheet = await ports.providerPage({\n html: buildRazorpayCheckoutHtml({\n keyId: review.razorpayKeyId,\n amountMinor: Math.round(Number(review.payNow ?? review.total) * 100),\n description: request.description ?? '',\n buyerName: `${billing.firstName} ${billing.lastName}`.trim(),\n buyerEmail: billing.email,\n orderHash,\n }),\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n if (sheet.event === 'failed') {\n throw new Error(\n sheet.description ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n }\n store.progress.paymentConfirmed = true\n const paymentId =\n typeof sheet.data?.razorpay_payment_id === 'string'\n ? sheet.data.razorpay_payment_id\n : undefined\n const { needIdVerification } = await confirmOrderSuccess(\n orderHash,\n paymentId ? { token: paymentId } : undefined\n )\n return finish({ orderHash, free: false, needIdVerification })\n }\n\n // ---- Payment plan (installments; own finalize — the plan IS the record)\n if (request.method === 'paymentPlan') {\n if (review.gateway !== 'stripe') {\n throw new Error('This payment method is not available for this order')\n }\n // The SetupIntent secret's presence IS the \"plan available\" signal.\n if (!review.paymentPlanSetupSecret) {\n throw new Error(\n \"The payment plan isn't available for this order right now. Turn off installments to pay in full.\"\n )\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n\n // Saved-card shortcut: charge the plan to the card the review carries.\n const savedCard =\n request.useSavedCard === false ? null : review.paymentPlanSavedCard\n if (savedCard) {\n const charge = await chargeSavedCardPlan(orderHash, savedCard.paymentMethodId)\n if (charge.requiresAction && charge.clientSecret) {\n if (!ports.confirmSavedCardPayment) throw unsupportedGatewayError()\n await ports.confirmSavedCardPayment(\n charge.clientSecret,\n savedCard.paymentMethodId\n )\n }\n return finish({ orderHash, free: false, needIdVerification: false })\n }\n\n // New card: SAVE it via the SetupIntent (nothing charged), then create\n // the plan against the resulting PaymentMethod.\n if (!ports.confirmPaymentPlanSetup) throw unsupportedGatewayError()\n const paymentMethodId = await ports.confirmPaymentPlanSetup(\n review.paymentPlanSetupSecret,\n billing\n )\n const { needIdVerification } = await createPaymentPlan(orderHash, paymentMethodId)\n return finish({ orderHash, free: false, needIdVerification })\n }\n\n // ---- Xendit CARD (tokenize inline or via sheet; server-side charge) -\n if (request.method === 'xenditCard') {\n if (\n review.gateway !== 'xendit' ||\n !review.xenditPublishableKey ||\n !review.orderId\n ) {\n throw new Error('This payment method is not available for this order')\n }\n let token: Record<string, unknown> | undefined\n if (ports.tokenizeXenditCard) {\n token = await ports.tokenizeXenditCard({\n publishableKey: review.xenditPublishableKey,\n amount: review.payNow ?? review.total,\n billing,\n onBehalfOf: review.xenditOnBehalfOf ?? null,\n })\n } else if (ports.providerPage) {\n const sheet = await ports.providerPage({\n html: buildXenditCheckoutHtml({\n publishableKey: review.xenditPublishableKey,\n amount: review.payNow ?? review.total,\n buyerFirstName: billing.firstName,\n buyerLastName: billing.lastName,\n buyerEmail: billing.email,\n buyerPhone: billing.phone || '',\n onBehalfOf: review.xenditOnBehalfOf ?? null,\n }),\n baseUrl: 'https://js.xendit.co',\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n const t = sheet.data?.token\n if (sheet.event === 'failed' || !t || typeof t !== 'object') {\n throw new Error(\n sheet.description ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n }\n token = t as Record<string, unknown>\n } else {\n throw unsupportedGatewayError()\n }\n await submitXenditCardCharge(review.orderId, orderHash, token)\n store.progress.paymentConfirmed = true\n }\n\n // ---- Xendit e-wallet (provider page + /success reconcile) ----------\n else if (request.method === 'xenditEWallet') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n const requiredExtra = XENDIT_EWALLET_EXTRA_FIELD[request.walletKey]\n if (requiredExtra === 'cashtag' && !request.extra?.cashtag) {\n throw new Error('Please enter your cashtag to pay with this wallet.')\n }\n if (requiredExtra === 'phoneNumber' && !request.extra?.phoneNumber) {\n throw new Error('Please enter your mobile number to pay with this wallet.')\n }\n if (review.gateway !== 'xendit' || !review.orderId) {\n throw new Error('This payment method is not available for this order')\n }\n const outcome = interpretXenditChargeResponse(\n await submitXenditEWalletCharge(\n buildXenditEWalletChargeFields({\n orderId: review.orderId,\n orderHash,\n paymentType: request.walletKey,\n cashtag: request.extra?.cashtag,\n phoneNumber: request.extra?.phoneNumber,\n })\n )\n )\n if (outcome.kind !== 'redirect') throw new Error(outcome.reason)\n const sheet = await ports.providerPage({\n uri: outcome.url,\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'failed') {\n throw new Error(sheet.description || 'Payment failed')\n }\n store.progress.paymentConfirmed = true\n }\n\n // ---- Redirect-based Stripe methods (Klarna/Afterpay/iDEAL-class) ---\n else if (request.method === 'redirect') {\n if (!ports.providerPage || !ports.createRedirectPaymentMethod) {\n throw unsupportedGatewayError()\n }\n if (review.gateway !== 'stripe') {\n throw new Error('This payment method is not available for this order')\n }\n // Klarna/Afterpay-class types carry their own fees: re-price BEFORE\n // confirming (the server confirms the re-priced intent).\n if (\n requiresFeeReprice(request.methodType) &&\n review.stripeIntentId &&\n review.orderId\n ) {\n await changePaymentMethodType(orderHash, {\n paymentMethodType: request.methodType,\n orderId: review.orderId,\n orderHash,\n stripeIntentId: review.stripeIntentId,\n })\n }\n const paymentMethodId = await ports.createRedirectPaymentMethod(\n request.methodType,\n billing\n )\n if (!paymentMethodId) throw unsupportedGatewayError()\n const returnUrl = options.redirectReturnUrl || `${getOriginUrl()}/`\n const outcome = await confirmRedirect(orderHash, {\n payment_method_id: paymentMethodId,\n return_url: returnUrl,\n })\n if (outcome.kind === 'redirect') {\n const sheet = await ports.providerPage({\n uri: outcome.url,\n returnUrlPrefix: returnUrl,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n if (sheet.event === 'failed') {\n throw new Error(\n sheet.description ||\n 'Your payment was not completed. Please try again or use a different payment method.'\n )\n }\n const redirectStatus = /[?&]redirect_status=([^&#]+)/.exec(\n sheet.returnUrl || ''\n )?.[1]\n if (redirectStatus === 'failed') {\n throw new Error(\n 'Your payment was not completed. Please try again or use a different payment method.'\n )\n }\n } else if (outcome.kind !== 'settled') {\n throw new Error(\n \"This payment method isn't available right now. Please pay with a card instead.\"\n )\n }\n store.progress.paymentConfirmed = true\n }\n\n // ---- Card / Apple Pay / Google Pay (the Stripe confirmer path, MSI) -\n else {\n if (!review.clientSecret) {\n throw new Error(\n \"This event's payment method isn't supported in the app yet. Please complete your purchase on the event page.\"\n )\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n\n // If a previous attempt already authorized this intent, reuse it rather\n // than confirming — and re-charging — again.\n const existingStatus = await confirmer.getIntentStatus(review.clientSecret)\n const alreadyConfirmed = Boolean(\n existingStatus && CONFIRMED_INTENT_STATUSES.includes(existingStatus)\n )\n\n if (!alreadyConfirmed) {\n // MSI (Mexican months without interest): offer plans between PM\n // creation and the confirm. A chosen plan confirms SERVER-SIDE — only\n // handleNextAction may run afterwards, never a second confirm.\n let confirmedViaInstallments = false\n if (\n request.method === 'card' &&\n review.currency === 'MXN' &&\n ports.onInstallmentOffers &&\n ports.createCardPaymentMethod &&\n ports.handleNextAction &&\n review.stripeIntentId\n ) {\n let offers: InstallmentOffer[] = []\n try {\n const paymentMethodId = await ports.createCardPaymentMethod(billing)\n offers = resolveInstallmentOffers(\n await getInstallmentOffers(\n orderHash,\n buildInstallmentOffersFields({\n paymentIntentId: review.stripeIntentId,\n paymentMethodId,\n })\n )\n ).installments\n } catch {\n // Offers unavailable — fall through to the normal confirm.\n }\n if (offers.length > 0) {\n const chosen = await ports.onInstallmentOffers(offers)\n if (chosen) {\n const confirmResponse = await confirmInstallments(\n orderHash,\n buildConfirmInstallmentsFields({\n paymentIntentId: review.stripeIntentId,\n offer: chosen,\n })\n )\n if (confirmInstallmentsHasNextAction(confirmResponse)) {\n await ports.handleNextAction(review.clientSecret)\n }\n confirmedViaInstallments = true\n }\n }\n }\n\n if (!confirmedViaInstallments) {\n const currencyCode = snap.breakdown?.currencyCode ?? review.currency ?? ''\n let status: string | undefined\n if (request.method === 'applePay') {\n status = await confirmer.confirmApplePay(\n review.clientSecret,\n review.total,\n currencyCode,\n {\n merchantCountryCode: options.merchantCountryCode,\n merchantName: options.merchantName,\n }\n )\n } else if (request.method === 'googlePay') {\n if (!confirmer.confirmGooglePay) throw unsupportedGatewayError()\n status = await confirmer.confirmGooglePay(\n review.clientSecret,\n review.total,\n currencyCode,\n {\n merchantCountryCode: options.merchantCountryCode,\n merchantName: options.merchantName,\n testEnv: options.googlePayTestEnv,\n }\n )\n } else {\n status = await confirmer.confirmCard(review.clientSecret, billing)\n }\n if (!status || !CONFIRMED_INTENT_STATUSES.includes(status)) {\n throw new Error(`Payment not completed (status: ${status ?? 'unknown'}).`)\n }\n }\n }\n store.progress.paymentConfirmed = true\n confirmedPaymentIntentId = review.stripeIntentId\n }\n }\n\n // 4. Record the payment server-side.\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n\n return finish({\n orderHash,\n free: false,\n needIdVerification,\n ...(confirmedPaymentIntentId ? { paymentIntentId: confirmedPaymentIntentId } : {}),\n })\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n// ---------------------------------------------------------------------------\n// Pay an order created outside the engine (retry-safe session)\n// ---------------------------------------------------------------------------\n\nexport interface OrderPaymentSession {\n /** The order to pay (from your own on-checkout call). */\n orderHash: string\n /** Buyer details for the payment legs (billing_details, wallet sheets…). */\n billing: CheckoutBilling\n /** Engine progress store — created on first payOrder call. Carry the session\n * object so a retry after a CONFIRMED charge only replays finalization. */\n store?: CheckoutStore\n}\n\n/** Pays an ALREADY-CREATED order through the engine's rails — same duplicate-\n * charge guards, same rails, same UNSUPPORTED_GATEWAY. Order creation and its\n * pre-flights are the caller's; the engine seeds a session store with the hash. */\nexport const payOrderWith = async (\n ctx: EngineContext,\n session: OrderPaymentSession,\n method: PaymentMethod | PaymentRequest = 'card'\n): Promise<PlaceOrderResult> => {\n if (!session.store) {\n session.store = createCheckoutStore()\n session.store.setState({ status: 'ready' })\n }\n session.store.setState({ billing: session.billing })\n if (!session.store.progress.orderHash) {\n session.store.progress.orderHash = session.orderHash\n }\n return placeOrderWith(session.store, ctx, method)\n}\n\n// ---------------------------------------------------------------------------\n// Currency\n// ---------------------------------------------------------------------------\n\n/** Syncs the session currency. A bare call geo-seeds; a `code` switches it —\n * after which the catalog reprices, so the engine resets the checkout (billing/\n * holders preserved) and the consumer re-runs prime with re-fetched tickets. */\nexport const syncCurrencyWith = async (\n store: CheckoutStore,\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencySync> => {\n const state = await setEventCurrency(eventId, code, options)\n const requiresCatalogRefresh = Boolean(code && !options?.seed)\n\n if (requiresCatalogRefresh) {\n if (store.progress.paymentConfirmed) {\n throw new Error(\n 'You already have a paid order being finalized. Please complete it before switching currency.'\n )\n }\n const { billing, holders } = store.getState()\n store.reset()\n store.setState({ billing, holders, currency: state })\n } else {\n store.setState({ currency: state })\n }\n\n return { state, requiresCatalogRefresh }\n}\n\n// ---------------------------------------------------------------------------\n// ID verification\n// ---------------------------------------------------------------------------\n\nexport interface RunIdVerificationOptions {\n /** Opens the provider verification URL. Omit to leave opening to the consumer. */\n openUrl?: (url: string) => void | Promise<void>\n /** Called once the check is confirmed required. Return true to TAKE OVER (the\n * engine stops — no open, no poll). */\n onRequired?: (info: {\n orderHash: string\n verificationUrl: string | null\n }) => boolean | void\n onPhase?: IdVerificationCallbacks['onPhase']\n schedule?: IdVerificationCallbacks['schedule']\n /** Fires `recheck` when the provider hand-off might have completed (e.g. the\n * app returns to the foreground). Return an unsubscribe. */\n registerForegroundListener?: (recheck: () => void) => () => void\n}\n\n/** Standalone poller for a NEED_ID_VERIFICATION order (mint + open the URL\n * first via `getIdVerificationStatus(hash, true)`, then start this). */\nexport const createIdVerificationPollerFor = (\n orderHash: string,\n onPhase: IdVerificationCallbacks['onPhase'],\n schedule?: IdVerificationCallbacks['schedule']\n): IdVerificationPoller =>\n createIdVerificationPoller({\n fetchStatus: () => getIdVerificationStatus(orderHash),\n onPhase,\n schedule,\n })\n\n/**\n * Runs ID verification end-to-end for a NEED_ID_VERIFICATION order: mint the\n * provider URL, open it, poll to completion. Already-verified → resolves now;\n * `onRequired` returns true → resolves undefined (consumer took over); verified\n * → resolves the status; timeout/error → REJECTS with a reassuring message (the\n * payment already settled — treat a rejection as a verification stall, never a\n * payment failure).\n */\nexport const runIdVerificationWith = (\n orderHash: string,\n options: RunIdVerificationOptions = {}\n): Promise<IdVerificationStatus | undefined> =>\n getIdVerificationStatus(orderHash, true).then((status) => {\n if (status.verified || status.required === false) return status\n\n if (\n options.onRequired?.({\n orderHash,\n verificationUrl: status.verification_url || null,\n }) === true\n ) {\n return undefined\n }\n if (status.verification_url && options.openUrl) {\n Promise.resolve(options.openUrl(status.verification_url)).catch(() => {\n // The consumer can still surface the URL via onRequired.\n })\n }\n\n return new Promise<IdVerificationStatus | undefined>((resolve, reject) => {\n let settled = false\n let unsubscribe: (() => void) | undefined\n const finish = (run: () => void) => {\n if (settled) return\n settled = true\n poller.stop()\n unsubscribe?.()\n run()\n }\n const poller = createIdVerificationPoller({\n fetchStatus: () => getIdVerificationStatus(orderHash),\n onPhase: (phase, fresh) => {\n options.onPhase?.(phase, fresh)\n if (phase === 'verified') {\n finish(() => resolve(fresh))\n } else if (phase === 'timeout' || phase === 'error') {\n finish(() =>\n reject(\n new Error(\n 'ID verification is taking longer than usual. Your payment is safe — your tickets will be emailed as soon as the check completes.'\n )\n )\n )\n }\n },\n schedule: options.schedule,\n })\n unsubscribe = options.registerForegroundListener?.(() => {\n getIdVerificationStatus(orderHash)\n .then((fresh) => {\n if (fresh.verified || fresh.required === false) finish(() => resolve(fresh))\n })\n .catch(() => {\n // Poller keeps running.\n })\n })\n poller.start()\n })\n })\n\n// ---------------------------------------------------------------------------\n// The engine facade\n// ---------------------------------------------------------------------------\n\nexport interface EngineConfig {\n /** Platform capabilities — confirmer (required) + optional rails. */\n ports: CheckoutPorts\n /** Wallet/redirect options (merchant identity, redirect URL, url scheme). */\n options?: CheckoutOptions\n /** Reuse an existing store; one is created otherwise. */\n store?: CheckoutStore\n}\n\nexport interface CheckoutEngine {\n /** The underlying store — subscribe/getState for non-React consumers. */\n store: CheckoutStore\n getSnapshot: () => CheckoutSnapshot\n subscribe: (listener: (s: CheckoutSnapshot) => void) => () => void\n /** Build + price the cart for a ticket selection. */\n prime: (eventId: string, selections: TicketSelection[]) => Promise<void>\n /** Build + price the cart for reserved SEATS (seat-map events). */\n primeSeats: (eventId: string, lines: SeatLine[]) => Promise<void>\n /** Resume an existing server-side cart without replacing its ticket lines. */\n resumeCart: (eventId: string, options?: { isFromResale?: boolean }) => Promise<void>\n /** Set the add-on selection and re-price. */\n setAddons: (addOns: AddonSelection) => Promise<void>\n setBilling: (billing: CheckoutBilling) => void\n setHolders: (holders: CheckoutHolder[]) => void\n setConsent: (consent: CheckoutConsent) => void\n setAcceptedConditions: (accepted: Record<string, boolean>) => void\n setAddonDataCapture: (capture: Record<string, CustomFieldValues>) => void\n /** Debounced existing-account check; sets `existingAccountEmail` on the snapshot. */\n checkBuyerEmail: (email: string) => Promise<void>\n /** Create the order and pay (or register free). */\n placeOrder: (method?: PaymentMethod | PaymentRequest) => Promise<PlaceOrderResult>\n /** Switch/seed the session currency. */\n syncCurrency: (\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n ) => Promise<CurrencySync>\n /** Run ID verification for a NEED_ID_VERIFICATION order. */\n runIdVerification: (\n orderHash: string,\n options?: RunIdVerificationOptions\n ) => Promise<IdVerificationStatus | undefined>\n reset: () => void\n /**\n * Move the cart to the terminal 'expired' state. Until now this only happened\n * reactively, when the backend rejected a call with an expired-cart 422 — so a\n * reservation that simply ran out on screen left the buyer editing a form that\n * could no longer be paid for. Consumers driving the countdown call this when\n * it reaches zero.\n */\n expireCart: () => void\n}\n\n/**\n * Binds the orchestration to a store + a platform's ports. In React, wrap this\n * with `useCheckout()`; in any other JS runtime, use it directly.\n */\nexport const createEngine = (config: EngineConfig): CheckoutEngine => {\n const store = config.store ?? createCheckoutStore()\n const ctx: EngineContext = { ports: config.ports, options: config.options ?? {} }\n\n return {\n store,\n getSnapshot: () => store.getState(),\n subscribe: (listener) => store.subscribe(listener),\n prime: (eventId, selections) => primeWith(store, ctx, eventId, selections),\n primeSeats: (eventId, lines) => primeSeatsWith(store, ctx, eventId, lines),\n resumeCart: (eventId, options) => resumeCartWith(store, ctx, eventId, options),\n setAddons: (addOns) => repriceWith(store, addOns),\n setBilling: (billing) => store.setState({ billing }),\n setHolders: (holders) => store.setState({ holders }),\n setConsent: (consent) => store.setState({ consent }),\n setAcceptedConditions: (acceptedConditions) => store.setState({ acceptedConditions }),\n setAddonDataCapture: (addOnDataCapture) => store.setState({ addOnDataCapture }),\n checkBuyerEmail: async (email) => {\n const { exists } = await checkBuyerEmailApi(email)\n store.setState({ existingAccountEmail: exists ? email : null })\n },\n placeOrder: (method) => placeOrderWith(store, ctx, method),\n syncCurrency: (eventId, code, options) =>\n syncCurrencyWith(store, eventId, code, options),\n runIdVerification: (orderHash, options) => runIdVerificationWith(orderHash, options),\n reset: () => {\n clearCartGuestToken()\n store.reset()\n },\n expireCart: () => {\n clearCartGuestToken()\n store.expireCart()\n },\n }\n}\n","/**\n * `ttf` — the facade. A domain-grouped, configured view over the raw `api/`\n * calls, so app code reads like the sentence it is:\n *\n * await ttf.auth.login(email, password)\n * const tickets = await ttf.events.tickets(eventId)\n * await ttf.cart.add(eventId, selections)\n * const review = await ttf.order.review(hash)\n * await ttf.payment.prepareOxxo(hash)\n *\n * It adds no logic of its own — every method IS the api function. One place to\n * discover the whole surface; one name to import.\n */\nimport * as auth from './api/auth'\nimport * as cart from './api/cart'\nimport * as confirmation from './api/confirmation'\nimport * as delegation from './api/delegation'\nimport * as engagement from './api/engagement'\nimport * as events from './api/events'\nimport * as geo from './api/geo'\nimport * as order from './api/order'\nimport * as orders from './api/orders'\nimport * as payment from './api/payment'\nimport * as preRegistration from './api/preRegistration'\nimport * as profile from './api/profile'\nimport * as resale from './api/resale'\nimport * as seatmap from './api/seatmap'\n\nexport const ttf = {\n auth: {\n login: auth.login,\n register: auth.register,\n registerAccount: auth.registerAccount,\n logout: auth.logout,\n restorePassword: auth.restorePassword,\n restorePasswordRn: auth.restorePasswordRn,\n resetPassword: auth.resetPassword,\n checkEmailExists: auth.checkEmailExists,\n // Account identity verification (Netverify/Jumio)\n mintVerificationUrl: auth.mintVerificationUrl,\n getVerificationInfo: auth.getVerificationInfo,\n updateVerificationStatus: auth.updateVerificationStatus,\n },\n profile: {\n get: profile.getProfile,\n },\n geo: {\n countries: geo.getCountries,\n states: geo.getStates,\n },\n\n // --- checkout flow -------------------------------------------------------\n events: {\n tickets: events.getEventTickets,\n ticketsWithMeta: events.getEventTicketsWithMeta,\n info: events.getEventInfo,\n conditions: events.getEventConditions,\n timeSlotTickets: events.getEventTimeSlotTickets,\n customFields: events.getEventCustomFields,\n requiredCustomFieldLabels: events.getRequiredCustomFieldLabels,\n addons: events.getEventAddons,\n filterAddonsForTickets: events.filterAddonsForTickets,\n submitPromoCode: events.submitPromoCode,\n setCurrency: events.setEventCurrency,\n authenticate: events.authenticateEvent,\n track: events.trackEvent,\n updateOrderDataCapture: events.updateOrderDataCapture,\n updateTicketDataCapture: events.updateTicketDataCapture,\n },\n cart: {\n add: cart.addTicketsToCart,\n addSeats: cart.addSeatsToCart,\n get: cart.getCart,\n checkoutConfigs: cart.getCheckoutConfigs,\n price: cart.updateCheckout,\n priceBreakdown: cart.getPriceBreakdown,\n paymentConfig: cart.getPaymentConfigAttributes,\n preOrderMethods: cart.getPreOrderPaymentMethods,\n checkBuyerEmail: cart.checkBuyerEmail,\n },\n order: {\n create: order.createOrder,\n review: order.getOrderReview,\n mapProfileToBilling: order.mapProfileToBilling,\n completeFreeRegistration: order.completeFreeRegistration,\n confirmSuccess: order.confirmOrderSuccess,\n idVerificationStatus: order.getIdVerificationStatus,\n verifyCustomer: order.verifyCustomerOrder,\n },\n payment: {\n changeMethodType: payment.changePaymentMethodType,\n confirmRedirect: payment.confirmRedirect,\n prepareOxxo: payment.prepareForOxxo,\n xenditEWalletCharge: payment.submitXenditEWalletCharge,\n xenditCardCharge: payment.submitXenditCardCharge,\n installmentOffers: payment.getInstallmentOffers,\n confirmInstallments: payment.confirmInstallments,\n createPaymentPlan: payment.createPaymentPlan,\n chargeSavedCardPlan: payment.chargeSavedCardPlan,\n changeMethod: payment.changePaymentMethod,\n paypalForm: payment.getPayPalForm,\n },\n\n // --- account & post-purchase --------------------------------------------\n orders: {\n list: orders.getOrders,\n get: orders.getOrder,\n myTickets: orders.getMyTickets,\n updateOrderCustomFields: orders.updateOrderCustomFields,\n updateTicketHolderCustomFields: orders.updateTicketHolderCustomFields,\n },\n engagement: {\n attributeReferrer: engagement.attributeReferrer,\n joinWaitingList: engagement.joinWaitingList,\n sendRsvp: engagement.sendRsvp,\n validatePhone: engagement.validatePhone,\n },\n resale: {\n sell: resale.sellTicket,\n remove: resale.removeTicketFromResale,\n process: resale.processResale,\n decline: resale.declineResale,\n },\n confirmation: {\n get: confirmation.getConfirmation,\n },\n preRegistration: {\n confirm: preRegistration.confirmPreRegistration,\n influencers: preRegistration.getInfluencers,\n confirmationPage: preRegistration.getConfirmationPage,\n submitShareAction: preRegistration.submitShareAction,\n },\n delegation: {\n checkCustomerExists: delegation.checkCustomerExists,\n consumerPageInfo: delegation.getConsumerPageInfo,\n issueTicket: delegation.issueTicket,\n },\n seatmap: {\n data: seatmap.getSeatMapData,\n statuses: seatmap.getSeatStatuses,\n reserve: seatmap.reserveSeats,\n removeReserved: seatmap.removeReservedSeats,\n refreshReservation: seatmap.refreshReservation,\n },\n} as const\n\nexport type Ttf = typeof ttf\n","/**\n * React hooks over the `ttf` facade — one authored copy, imported unchanged by\n * both platform packages. React and @tanstack/react-query are peer deps, so a\n * consumer supplies its own QueryClientProvider.\n */\nexport * from './auth'\nexport * from './authFlow'\nexport * from './session'\nexport * from './profile'\nexport * from './geo'\nexport * from './events'\nexport * from './orders'\nexport * from './engagement'\nexport * from './checkout'\nexport { ttfKeys } from './keys'\nexport type { QueryOpts, MutationOpts } from './types'\n","/**\n * Auth hooks — React Query mutations over the `ttf.auth` facade. Authored once\n * here; both web and RN import them unchanged. Pass `onSuccess`/`onError` (or\n * any mutation option) through the `options` argument.\n */\nimport { useMutation } from '@tanstack/react-query'\n\nimport { ttf } from '../services'\nimport { AuthRegistrationInput } from '../dtos'\nimport { TfProfile } from '../types'\nimport { MutationOpts } from './types'\n\nexport const useLogin = (\n options?: MutationOpts<TfProfile, { email: string; password: string }>\n) =>\n useMutation({\n mutationFn: ({ email, password }: { email: string; password: string }) =>\n ttf.auth.login(email, password),\n ...options,\n })\n\nexport const useRegister = (\n options?: MutationOpts<TfProfile, Record<string, string | Blob>>\n) => useMutation({ mutationFn: ttf.auth.register, ...options })\n\nexport const useRegisterAccount = (\n options?: MutationOpts<TfProfile, AuthRegistrationInput>\n) => useMutation({ mutationFn: ttf.auth.registerAccount, ...options })\n\nexport const useRestorePassword = (options?: MutationOpts<void, string>) =>\n useMutation({ mutationFn: ttf.auth.restorePassword, ...options })\n\nexport const useRestorePasswordRn = (options?: MutationOpts<void, string>) =>\n useMutation({ mutationFn: ttf.auth.restorePasswordRn, ...options })\n\nexport const useResetPassword = (\n options?: MutationOpts<\n void,\n { token: string; password: string; passwordConfirmation?: string }\n >\n) => useMutation({ mutationFn: ttf.auth.resetPassword, ...options })\n\nexport const useLogout = (options?: MutationOpts<void, void>) =>\n useMutation({ mutationFn: () => ttf.auth.logout(), ...options })\n\nexport const useCheckEmailExists = (\n options?: MutationOpts<{ exists: boolean; error?: string }, string>\n) => useMutation({ mutationFn: ttf.auth.checkEmailExists, ...options })\n","/**\n * Headless authentication flow shared by every platform UI.\n *\n * This owns validation, mutations, profile-cache/session synchronization,\n * errors, success state, and view transitions. Web renders it in a modal;\n * React Native can render the same contract as screens or a native sheet.\n */\nimport { useQueryClient } from '@tanstack/react-query'\nimport { useCallback, useState } from 'react'\n\nimport type {\n AuthFieldErrors,\n AuthFieldName,\n AuthFlowView,\n AuthLoginInput,\n AuthRegistrationInput,\n} from '../dtos'\nimport {\n normalizeAuthEmail,\n validateLoginInput,\n validatePasswordResetEmail,\n validateRegistrationInput,\n} from '../logic'\nimport type { TfProfile } from '../types'\nimport {\n useLogin,\n useLogout,\n useRegisterAccount,\n useRestorePassword,\n useRestorePasswordRn,\n} from './auth'\nimport { ttfKeys } from './keys'\nimport { useAuthSession } from './session'\n\nexport interface UseAuthFlowOptions {\n initialView?: AuthFlowView\n initialEmail?: string\n /** Match the legacy modal's full account form by default. */\n requireRegistrationAddress?: boolean\n /** Web and native use different restore-password routes on the legacy API. */\n passwordResetTransport?: 'web' | 'native'\n /** Extra backend fields for specialized registration links. */\n registrationFields?: Record<string, string>\n onAuthenticated?: (profile: TfProfile) => void\n onLoggedOut?: () => void\n}\n\nexport interface RegistrationSubmitOptions {\n /** Require state only when the selected country actually exposes states. */\n requireState?: boolean\n}\n\nconst messageFrom = (error: unknown, fallback: string): string =>\n error instanceof Error && error.message ? error.message : fallback\n\nexport const useAuthFlow = (options: UseAuthFlowOptions = {}) => {\n const queryClient = useQueryClient()\n const session = useAuthSession()\n const loginMutation = useLogin()\n const registerMutation = useRegisterAccount()\n const restoreMutation = useRestorePassword()\n const restoreNativeMutation = useRestorePasswordRn()\n const logoutMutation = useLogout()\n const [view, setViewState] = useState<AuthFlowView>(options.initialView ?? 'login')\n const [suggestedEmail, setSuggestedEmail] = useState(\n normalizeAuthEmail(options.initialEmail ?? '')\n )\n const [fieldErrors, setFieldErrors] = useState<AuthFieldErrors>({})\n const [error, setError] = useState('')\n const [successMessage, setSuccessMessage] = useState('')\n\n const clearFeedback = useCallback(() => {\n setFieldErrors({})\n setError('')\n setSuccessMessage('')\n loginMutation.reset()\n registerMutation.reset()\n restoreMutation.reset()\n restoreNativeMutation.reset()\n }, [loginMutation, registerMutation, restoreMutation, restoreNativeMutation])\n\n const clearFieldError = useCallback((field: AuthFieldName) => {\n setFieldErrors((current) => {\n if (!current[field]) return current\n const next = { ...current }\n delete next[field]\n return next\n })\n setError('')\n }, [])\n\n const setView = useCallback(\n (next: AuthFlowView, email?: string) => {\n clearFeedback()\n if (email !== undefined) setSuggestedEmail(normalizeAuthEmail(email))\n setViewState(next)\n },\n [clearFeedback]\n )\n\n const showLogin = useCallback((email?: string) => setView('login', email), [setView])\n const showRegister = useCallback(\n (email?: string) => setView('register', email),\n [setView]\n )\n const showForgotPassword = useCallback(\n (email?: string) => setView('forgot-password', email),\n [setView]\n )\n\n const authenticated = useCallback(\n (profile: TfProfile) => {\n queryClient.setQueryData(ttfKeys.profile, profile)\n setSuggestedEmail(normalizeAuthEmail(profile.email))\n clearFeedback()\n options.onAuthenticated?.(profile)\n },\n [clearFeedback, options, queryClient]\n )\n\n const submitLogin = useCallback(\n async (input: AuthLoginInput): Promise<TfProfile | null> => {\n clearFeedback()\n const validation = validateLoginInput(input)\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return null\n }\n try {\n const profile = await loginMutation.mutateAsync({\n email: normalizeAuthEmail(input.email),\n password: input.password,\n })\n authenticated(profile)\n return profile\n } catch (caught) {\n setError(messageFrom(caught, 'Unable to log in. Please try again.'))\n return null\n }\n },\n [authenticated, clearFeedback, loginMutation]\n )\n\n const submitRegistration = useCallback(\n async (\n input: AuthRegistrationInput,\n submitOptions: RegistrationSubmitOptions = {}\n ): Promise<TfProfile | null> => {\n clearFeedback()\n const validation = validateRegistrationInput(input, {\n requireAddress: options.requireRegistrationAddress ?? true,\n requireState: submitOptions.requireState,\n })\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return null\n }\n try {\n const profile = await registerMutation.mutateAsync({\n ...input,\n email: normalizeAuthEmail(input.email),\n registrationFields: options.registrationFields,\n })\n authenticated(profile)\n return profile\n } catch (caught) {\n const message = messageFrom(\n caught,\n 'Unable to create your account. Please try again.'\n )\n setError(message)\n if (/exist|already|registered/i.test(message))\n setFieldErrors({ email: 'This email already has an account.' })\n return null\n }\n },\n [\n authenticated,\n clearFeedback,\n options.registrationFields,\n options.requireRegistrationAddress,\n registerMutation,\n ]\n )\n\n const submitPasswordReset = useCallback(\n async (email: string): Promise<boolean> => {\n clearFeedback()\n const validation = validatePasswordResetEmail(email)\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return false\n }\n const normalizedEmail = normalizeAuthEmail(email)\n const mutation =\n options.passwordResetTransport === 'native'\n ? restoreNativeMutation\n : restoreMutation\n try {\n await mutation.mutateAsync(normalizedEmail)\n setSuggestedEmail(normalizedEmail)\n setSuccessMessage(\n 'If an account exists for this email, password reset instructions are on the way.'\n )\n return true\n } catch (caught) {\n setError(\n messageFrom(caught, 'Unable to send reset instructions. Please try again.')\n )\n return false\n }\n },\n [\n clearFeedback,\n options.passwordResetTransport,\n restoreMutation,\n restoreNativeMutation,\n ]\n )\n\n const logout = useCallback(async (): Promise<boolean> => {\n clearFeedback()\n try {\n await logoutMutation.mutateAsync()\n queryClient.removeQueries({ queryKey: ttfKeys.profile })\n options.onLoggedOut?.()\n return true\n } catch (caught) {\n // The API always clears local tokens in a finally block, so reflect the\n // logged-out state even if the backend session-close request failed.\n queryClient.removeQueries({ queryKey: ttfKeys.profile })\n setError(messageFrom(caught, 'You have been logged out locally.'))\n options.onLoggedOut?.()\n return true\n }\n }, [clearFeedback, logoutMutation, options, queryClient])\n\n return {\n view,\n suggestedEmail,\n fieldErrors,\n error,\n successMessage,\n isAuthenticated: session.isAuthenticated,\n isSubmitting:\n loginMutation.isPending ||\n registerMutation.isPending ||\n restoreMutation.isPending ||\n restoreNativeMutation.isPending ||\n logoutMutation.isPending,\n showLogin,\n showRegister,\n showForgotPassword,\n clearFeedback,\n clearFieldError,\n submitLogin,\n submitRegistration,\n submitPasswordReset,\n logout,\n mutations: {\n login: loginMutation,\n register: registerMutation,\n restorePassword: restoreMutation,\n restorePasswordNative: restoreNativeMutation,\n logout: logoutMutation,\n },\n }\n}\n\nexport type UseAuthFlow = ReturnType<typeof useAuthFlow>\n","/** React Query cache keys for the SDK, all namespaced under `ttf`. */\nimport { OrdersQuery } from '../api/orders'\n\nexport const ttfKeys = {\n profile: ['ttf', 'profile'] as const,\n countries: ['ttf', 'countries'] as const,\n states: (countryId: string | number) => ['ttf', 'states', countryId] as const,\n event: (eventId: string) => ['ttf', 'event', eventId] as const,\n tickets: (eventId: string) => ['ttf', 'tickets', eventId] as const,\n addons: (eventId: string) => ['ttf', 'addons', eventId] as const,\n orders: (query: OrdersQuery) => ['ttf', 'orders', query] as const,\n order: (orderId: string) => ['ttf', 'order', orderId] as const,\n}\n","/** Reactive authentication state backed by the shared token session. */\nimport { useSyncExternalStore } from 'react'\n\nimport { isAuthenticated, subscribeSession } from '../client'\n\nexport const useAuthSession = (): { isAuthenticated: boolean } => {\n const authenticated = useSyncExternalStore(\n subscribeSession,\n isAuthenticated,\n () => false\n )\n return { isAuthenticated: authenticated }\n}\n","/** Profile hook — the signed-in user's record as a React Query query. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { ttf } from '../services'\nimport { TfProfile } from '../types'\nimport { ttfKeys } from './keys'\nimport { useAuthSession } from './session'\nimport { QueryOpts } from './types'\n\nexport const useProfile = (options?: QueryOpts<TfProfile>) => {\n const session = useAuthSession()\n return useQuery({\n queryKey: ttfKeys.profile,\n queryFn: () => ttf.profile.get(),\n enabled: session.isAuthenticated,\n ...options,\n })\n}\n","/** Geo hooks — countries always, states gated on a chosen country. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { TfCountry, TfState } from '../types'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\nexport const useCountries = (options?: QueryOpts<TfCountry[]>) =>\n useQuery({\n queryKey: ttfKeys.countries,\n queryFn: () => ttf.geo.countries(),\n staleTime: Infinity,\n ...options,\n })\n\nexport const useStates = (\n countryId: string | number | undefined,\n options?: QueryOpts<TfState[]>\n) =>\n useQuery({\n queryKey: ttfKeys.states(countryId ?? ''),\n queryFn: () => ttf.geo.states(countryId as string | number),\n enabled: Boolean(countryId),\n ...options,\n })\n","/** Catalog read hooks — an event's info, purchasable tickets, and add-ons. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport type { EventAddon, TicketType } from '../dtos'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\n/** Event details (seated detection, slug, name). Gated on a chosen event id. */\nexport const useEvent = (\n eventId: string | undefined,\n options?: QueryOpts<Awaited<ReturnType<typeof ttf.events.info>>>\n) =>\n useQuery({\n queryKey: ttfKeys.event(eventId ?? ''),\n queryFn: () => ttf.events.info(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Purchasable ticket types for an event. Gated on a chosen event id. */\nexport const useTickets = (\n eventId: string | undefined,\n options?: QueryOpts<TicketType[]>\n) =>\n useQuery({\n queryKey: ttfKeys.tickets(eventId ?? ''),\n queryFn: () => ttf.events.tickets(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Tickets PLUS the catalog-level promo/access-code metadata and waiting-list\n * flag the same response carries. Use this (over `useTickets`) when the ticket\n * screen needs promo codes, access codes, or waiting lists. `refetch()` after\n * applying a code to pick up updated prices / newly-unlocked tickets. */\nexport const useTicketsWithMeta = (\n eventId: string | undefined,\n options?: QueryOpts<Awaited<ReturnType<typeof ttf.events.ticketsWithMeta>>>\n) =>\n useQuery({\n queryKey: [...ttfKeys.tickets(eventId ?? ''), 'meta'],\n queryFn: () => ttf.events.ticketsWithMeta(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Purchasable ticket types for ONE date of a time-slot / calendar event. Each\n * ticket carries its `timeSlot: { date, time }`. Gated on event id + date. */\nexport const useTimeSlotTickets = (\n eventId: string | undefined,\n date: string | undefined,\n options?: QueryOpts<TicketType[]>\n) =>\n useQuery({\n queryKey: [...ttfKeys.tickets(eventId ?? ''), 'slots', date ?? ''],\n queryFn: () => ttf.events.timeSlotTickets(eventId as string, date as string),\n enabled: Boolean(eventId && date),\n ...options,\n })\n\n/** The event's add-on catalog (upsells). Gated on a chosen event id. Filter it\n * to the primed cart with `ttf.events.filterAddonsForTickets(list, ids)`. */\nexport const useEventAddons = (\n eventId: string | undefined,\n options?: QueryOpts<EventAddon[]>\n) =>\n useQuery({\n queryKey: ttfKeys.addons(eventId ?? ''),\n queryFn: () => ttf.events.addons(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n","/** Order-history hooks — the buyer's list and one order's detail. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { OrdersQuery, TfOrderDetails, TfOrderSummary } from '../api/orders'\nimport { TfEnvelope, TfListEnvelope } from '../types'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\nexport const useOrders = (\n query: OrdersQuery = {},\n options?: QueryOpts<TfListEnvelope<TfOrderSummary>>\n) =>\n useQuery({\n queryKey: ttfKeys.orders(query),\n queryFn: () => ttf.orders.list(query),\n ...options,\n })\n\nexport const useOrder = (\n orderId: string | undefined,\n options?: QueryOpts<TfEnvelope<TfOrderDetails>>\n) =>\n useQuery({\n queryKey: ttfKeys.order(orderId ?? ''),\n queryFn: () => ttf.orders.get(orderId as string),\n enabled: Boolean(orderId),\n ...options,\n })\n","/** Engagement hooks — phone validation, waiting list, referral, RSVP. */\nimport { useMutation } from '@tanstack/react-query'\n\nimport { WaitingListEntry } from '../api/engagement'\nimport { ttf } from '../services'\nimport { MutationOpts } from './types'\n\nexport const useValidatePhone = (\n options?: MutationOpts<{ valid: boolean; [key: string]: unknown }, string>\n) => useMutation({ mutationFn: ttf.engagement.validatePhone, ...options })\n\nexport const useJoinWaitingList = (\n eventId: string,\n options?: MutationOpts<void, WaitingListEntry>\n) =>\n useMutation({\n mutationFn: (entry: WaitingListEntry) =>\n ttf.engagement.joinWaitingList(eventId, entry),\n ...options,\n })\n\nexport const useAttributeReferrer = (\n eventId: string,\n options?: MutationOpts<void, string | number | null>\n) =>\n useMutation({\n mutationFn: (referrer: string | number | null) =>\n ttf.engagement.attributeReferrer(eventId, referrer),\n ...options,\n })\n\nexport const useSendRsvp = (\n eventId: string,\n options?: MutationOpts<unknown, Record<string, unknown>>\n) =>\n useMutation({\n mutationFn: (data: Record<string, unknown>) => ttf.engagement.sendRsvp(eventId, data),\n ...options,\n })\n","/**\n * `useCheckout()` — the engine's React binding, with the shared DX every\n * platform wants baked in ONCE here (not re-written per platform):\n * - the snapshot is spread flat (`checkout.status`, `checkout.breakdown`, …)\n * - a reservation countdown (`secondsLeft`) and an `isBusy` flag\n * - `missingRequiredAddonNames`, `isLoggedIn`\n * - promo / referrer / waiting-list helpers over `ttf`\n * - `placeOrder(method, { autoRunIdVerification })`\n *\n * A platform lib only injects its `ports` (Stripe confirmer, provider page, …)\n * — it does NOT re-implement any of the above. Non-React apps use\n * `createEngine()` + `store.subscribe` directly.\n */\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'\n\nimport type {\n CheckoutSnapshot,\n PlaceOrderResult,\n SeatLine,\n TicketSelection,\n WaitingListEntry,\n} from '../dtos'\nimport {\n createCheckoutStore,\n createEngine,\n type CheckoutEngine,\n type CheckoutStore,\n type EngineConfig,\n type PaymentMethod,\n type PaymentRequest,\n type RunIdVerificationOptions,\n} from '../engine'\nimport { missingRequiredAddOns } from '../logic'\nimport { ttf } from '../services'\nimport { useAuthSession } from './session'\n\nexport interface PlaceOrderHookOptions {\n /** After a successful order needing ID verification, run it automatically\n * (mint + open + poll). The rejection is swallowed — payment already\n * settled — so it never surfaces as a payment failure. Uses the engine's\n * `openUrl` port to open the provider URL. */\n autoRunIdVerification?: boolean\n idVerification?: RunIdVerificationOptions\n}\n\n/**\n * A gated buyer field this event asks for BEYOND name/email — surfaced from the\n * server's checkout-configs so consumers render exactly what's needed instead of\n * guessing. Write the captured value straight to `billing[key]` (e.g.\n * `setBilling({ ...billing, instagramHandle })`); the engine forwards it in the\n * order body. `nationality` expects a country id (see `ttf.geo.countries()` /\n * `useCountries()`); `gender` expects `'M'` | `'F'`.\n */\nexport interface BuyerFieldSpec {\n key: 'nationality' | 'gender' | 'instagramHandle'\n label: string\n required: boolean\n /** How to render it: a country picker, an M/F choice, or a handle text box. */\n kind: 'nationality' | 'gender' | 'instagram'\n}\n\nexport interface UseCheckout extends CheckoutSnapshot {\n /** The whole snapshot object (the fields above are spread from it). */\n snapshot: CheckoutSnapshot\n /** True while a cart/order operation is in flight. */\n isBusy: boolean\n /** Whole-seconds countdown for the cart reservation (undefined when none).\n * Raw on purpose — format it however your UI wants. */\n secondsLeft?: number\n /** Required add-on names still missing (same rule the pre-flight enforces). */\n missingRequiredAddonNames: string[]\n /** Gated buyer fields this event needs beyond name/email (Instagram /\n * nationality / gender), each with its required flag — render these from\n * data. Empty when the event gates none. Pairs with `customFields` (the\n * order/ticket capture groups) for the full \"what must I collect\" picture. */\n buyerFields: BuyerFieldSpec[]\n /** Whether a signed-in access token is present. */\n isLoggedIn: boolean\n\n /** Build + price the cart for a ticket selection (alias for `prime`). */\n setTickets: (eventId: string, selections: TicketSelection[]) => Promise<void>\n /** Build + price the cart for reserved SEATS (alias for `primeSeats`). */\n setSeats: (eventId: string, lines: SeatLine[]) => Promise<void>\n /** Attach to an existing server-side cart (e.g. accepted resale invitation). */\n resumeCart: CheckoutEngine['resumeCart']\n setAddons: CheckoutEngine['setAddons']\n setBilling: CheckoutEngine['setBilling']\n setHolders: CheckoutEngine['setHolders']\n setConsent: CheckoutEngine['setConsent']\n setAcceptedConditions: CheckoutEngine['setAcceptedConditions']\n /** Accept/unaccept one condition block (merges into the map). */\n acceptCondition: (id: string, accepted: boolean) => void\n setAddonDataCapture: CheckoutEngine['setAddonDataCapture']\n checkBuyerEmail: CheckoutEngine['checkBuyerEmail']\n placeOrder: (\n method?: PaymentMethod | PaymentRequest,\n options?: PlaceOrderHookOptions\n ) => Promise<PlaceOrderResult>\n runIdVerification: CheckoutEngine['runIdVerification']\n syncCurrency: CheckoutEngine['syncCurrency']\n reset: CheckoutEngine['reset']\n applyPromoCode: (eventId: string, promo: string) => Promise<void>\n attributeReferrer: (eventId: string, referrer: string | number | null) => Promise<void>\n joinWaitingList: (eventId: string, entry: WaitingListEntry) => Promise<void>\n}\n\n// ONE app-wide checkout store. Every useCheckout() call — SignIn, Tickets, Pay,\n// each component mounting on its own — must read and write the SAME cart, with\n// no Context and no prop-drilling. Per-component engines all bind this single\n// store below. Without it, each component would get its own store: the step\n// that primes would flip ITS status to 'ready' while the step doing the gating\n// reads a different store still 'idle', so the pay UI silently never appears.\n// (Callers can still pass an explicit `config.store` to opt out.)\nlet sharedStore: CheckoutStore | null = null\n\nexport const useCheckout = (config: EngineConfig): UseCheckout => {\n const authSession = useAuthSession()\n // Create the engine exactly once — its store, subscribe, and actions must be\n // stable references for useSyncExternalStore and consumers' effects. The store\n // it binds is the app-wide singleton (unless the caller supplied their own),\n // so every useCheckout() across the tree shares one cart.\n const engineRef = useRef<CheckoutEngine | null>(null)\n if (engineRef.current === null) {\n if (sharedStore === null) sharedStore = createCheckoutStore()\n engineRef.current = createEngine({ ...config, store: config.store ?? sharedStore })\n }\n const engine = engineRef.current\n\n const snapshot = useSyncExternalStore(\n engine.subscribe,\n engine.getSnapshot,\n engine.getSnapshot // server snapshot === client (SSR-safe: idle checkout)\n )\n\n const isBusy =\n snapshot.status === 'priming' ||\n snapshot.status === 'repricing' ||\n snapshot.status === 'placing'\n\n // Whole-seconds countdown for the cart reservation.\n const [now, setNow] = useState(() => Date.now())\n useEffect(() => {\n if (snapshot.expiresAt == null) return\n const t = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(t)\n }, [snapshot.expiresAt])\n const secondsLeft =\n snapshot.expiresAt != null\n ? Math.max(0, Math.round((snapshot.expiresAt - now) / 1000))\n : undefined\n\n // The countdown used to be display-only: it sat at 0:00 while the buyer kept\n // filling in a cart the server had already released, and the truth only\n // surfaced when payment failed. Retire the cart the moment it lapses so\n // consumers can send the buyer back to ticket selection. Never while an order\n // is in flight or already paid — those own the outcome.\n useEffect(() => {\n if (secondsLeft !== 0) return\n if (snapshot.status === 'placing' || snapshot.status === 'succeeded') return\n if (snapshot.status === 'expired') return\n engine.expireCart()\n }, [engine, secondsLeft, snapshot.status])\n\n const missingRequiredAddonNames = missingRequiredAddOns(\n snapshot.requiredAddOns,\n snapshot.addOns\n )\n .map((a) => a.name || '')\n .filter(Boolean)\n\n // The event's gated buyer fields, surfaced render-ready from checkout-configs\n // so consumers stop guessing (this is what caused \"Instagram handle is\n // required\" to fail silently — the gate was in the data, just never shown).\n const gates = snapshot.fieldGates\n const buyerFields: BuyerFieldSpec[] = []\n if (gates.showNationality)\n buyerFields.push({\n key: 'nationality',\n label: 'Nationality',\n required: gates.nationalityRequired,\n kind: 'nationality',\n })\n if (gates.showGender)\n buyerFields.push({\n key: 'gender',\n label: 'Gender',\n required: gates.genderRequired,\n kind: 'gender',\n })\n if (gates.requireInstagram)\n buyerFields.push({\n key: 'instagramHandle',\n label: 'Instagram handle',\n required: true,\n kind: 'instagram',\n })\n\n const isLoggedIn = authSession.isAuthenticated\n\n // The engine's own openUrl port (the platform's) — used to open the provider\n // URL for the opt-in auto-run.\n const openUrl = config.ports.openUrl\n\n const placeOrder = useCallback(\n async (\n method?: PaymentMethod | PaymentRequest,\n options?: PlaceOrderHookOptions\n ): Promise<PlaceOrderResult> => {\n const result = await engine.placeOrder(method)\n if (options?.autoRunIdVerification && result.needIdVerification) {\n try {\n await engine.runIdVerification(result.orderHash, {\n openUrl,\n ...options.idVerification,\n })\n } catch {\n // Verification stall — payment is safe; tickets follow by email.\n }\n }\n return result\n },\n [engine, openUrl]\n )\n\n const setTickets = useCallback(\n (eventId: string, selections: TicketSelection[]) => engine.prime(eventId, selections),\n [engine]\n )\n const setSeats = useCallback(\n (eventId: string, lines: SeatLine[]) => engine.primeSeats(eventId, lines),\n [engine]\n )\n const acceptCondition = useCallback(\n (id: string, accepted: boolean) =>\n engine.setAcceptedConditions({\n ...(snapshot.acceptedConditions ?? {}),\n [id]: accepted,\n }),\n [engine, snapshot.acceptedConditions]\n )\n const applyPromoCode = useCallback(\n (eventId: string, promo: string) => ttf.events.submitPromoCode(eventId, promo),\n []\n )\n const attributeReferrer = useCallback(\n (eventId: string, referrer: string | number | null) =>\n ttf.engagement.attributeReferrer(eventId, referrer),\n []\n )\n const joinWaitingList = useCallback(\n (eventId: string, entry: WaitingListEntry) =>\n ttf.engagement.joinWaitingList(eventId, entry),\n []\n )\n\n return {\n ...snapshot,\n snapshot,\n isBusy,\n secondsLeft,\n missingRequiredAddonNames,\n buyerFields,\n isLoggedIn,\n setTickets,\n setSeats,\n resumeCart: engine.resumeCart,\n setAddons: engine.setAddons,\n setBilling: engine.setBilling,\n setHolders: engine.setHolders,\n setConsent: engine.setConsent,\n setAcceptedConditions: engine.setAcceptedConditions,\n acceptCondition,\n setAddonDataCapture: engine.setAddonDataCapture,\n checkBuyerEmail: engine.checkBuyerEmail,\n placeOrder,\n runIdVerification: engine.runIdVerification,\n syncCurrency: engine.syncCurrency,\n reset: engine.reset,\n applyPromoCode,\n attributeReferrer,\n joinWaitingList,\n }\n}\n","import type { Messages } from '../types'\n\n/**\n * English (UK) — the source of truth.\n *\n * Every key the SDK renders exists here, so a translator's job is to copy this\n * file and translate values; nothing else needs discovering. Other locales may\n * be partial and resolve missing keys through the chain in ../resolve.ts.\n *\n * Keys are namespaced by surface (`auth.`, `billing.`, `tickets.`, …) so a host\n * overriding one area does not have to know the whole catalogue. Values are the\n * strings the components previously hard-coded, moved verbatim — this file is a\n * relocation, not a rewrite, so behaviour is unchanged for anyone who never\n * sets a locale.\n */\nexport const en: Messages = {\n // --- Common ------------------------------------------------------------\n 'common.close': 'Close',\n 'common.dismiss': 'Dismiss',\n 'common.loading': 'Loading',\n 'common.required': 'Required',\n 'common.increase': 'Increase',\n 'common.decrease': 'Decrease',\n 'common.total': 'Total',\n 'common.date': 'Date',\n 'common.event': 'Event',\n 'common.currency': 'Currency',\n\n // --- Auth --------------------------------------------------------------\n 'auth.title': 'Authentication',\n 'auth.changePassword': 'Change Password',\n 'auth.email': 'Email *',\n 'auth.emailPlaceholder': 'Email',\n 'auth.password': 'Password *',\n 'auth.passwordPlaceholder': 'Password',\n 'auth.newPassword': 'New Password *',\n 'auth.confirmPassword': 'Confirm password *',\n 'auth.confirmPasswordPlaceholder': 'Confirm Password',\n 'auth.firstName': 'First name *',\n 'auth.firstNamePlaceholder': 'First Name',\n 'auth.lastName': 'Last name *',\n 'auth.lastNamePlaceholder': 'Last Name',\n 'auth.phone': 'Phone',\n 'auth.streetAddress': 'Street address *',\n 'auth.streetAddressPlaceholder': 'Street Address',\n 'auth.city': 'City *',\n 'auth.cityPlaceholder': 'City',\n 'auth.postcode': 'ZIP / postcode *',\n 'auth.postcodePlaceholder': 'Zip / Postal Code',\n 'auth.state': 'State / Province',\n 'auth.country': 'Country',\n 'auth.selectCountry': 'Select country',\n 'auth.loginSkipAhead': 'Login & skip ahead:',\n\n // --- Billing -----------------------------------------------------------\n 'billing.address': 'Billing address *',\n 'billing.email': 'Email Address *',\n 'billing.firstName': 'First Name *',\n 'billing.lastName': 'Last Name *',\n 'billing.phone': 'Phone *',\n 'billing.cityPlaceholder': 'City *',\n 'billing.streetPlaceholder': 'Street address *',\n 'billing.postcodePlaceholder': 'ZIP / Postcode *',\n 'billing.countryLabel': 'Country',\n 'billing.stateLabel': 'State / region',\n 'billing.socialPlaceholder': '@handle or profile URL',\n 'billing.male': 'Male',\n 'billing.female': 'Female',\n 'billing.ticketHolders': 'Ticket Holders',\n 'billing.emailPlaceholder': 'Email *',\n 'billing.confirmEmailPlaceholder': 'Confirm email *',\n 'billing.holderFirstName': 'First name *',\n 'billing.holderLastName': 'Last name *',\n 'billing.emailMismatch': 'The email addresses do not match.',\n\n // --- Tickets & seats ---------------------------------------------------\n 'tickets.yourTickets': 'Your Tickets',\n 'tickets.selectType': 'Please select a ticket type',\n 'tickets.soldOut': 'Sold out',\n 'tickets.guests': 'Guests',\n 'tickets.reserveTables': 'Reserve tables',\n 'tickets.noSessions': 'No sessions available on this date.',\n\n // --- Payment -----------------------------------------------------------\n 'payment.method': 'Payment method',\n 'payment.useThisCard': 'Use this card',\n 'payment.payInInstallments': 'Pay in installments?',\n 'payment.chooseInstallments': 'Choose installments',\n\n // --- Referral ----------------------------------------------------------\n 'referral.cheaperOrFree': 'Your tickets can be cheaper — or even FREE!',\n 'referral.inviteFriends': 'Invite friends',\n 'referral.howToInvite': 'How do you invite your friends?',\n 'referral.sendThisLink': 'Send them this link:',\n 'referral.howMuchCheaper': 'How much cheaper?',\n}\n","import { en } from './locales/en'\nimport type { LocaleCode, Messages, Translate, TranslatorOptions } from './types'\n\n/**\n * Locale bundles the SDK ships. English is the source of truth: every key\n * exists here, and every other locale is allowed to be partial.\n */\nconst CATALOGUES: Partial<Record<LocaleCode, Messages>> = { 'en-GB': en }\n\n/** Register a locale bundle. Used by ./locales/index to avoid a load cycle. */\nexport const registerCatalogue = (locale: LocaleCode, messages: Messages): void => {\n CATALOGUES[locale] = messages\n}\n\nexport const DEFAULT_LOCALE: LocaleCode = 'en-GB'\n\n/**\n * Per-locale fallback chains.\n *\n * en-US is an override-only layer (American spellings), so it MUST resolve\n * through en-GB rather than standing alone — the same structure the storefront\n * and the legacy platform use.\n */\nconst FALLBACKS: Record<LocaleCode, LocaleCode[]> = {\n 'en-GB': [],\n 'en-US': ['en-GB'],\n 'es-MX': ['en-GB'],\n fr: ['en-GB'],\n de: ['en-GB'],\n ru: ['en-GB'],\n id: ['en-GB'],\n}\n\n/** Map a raw device/browser language onto a locale we ship. */\nexport const resolveLocale = (raw?: string | null): LocaleCode => {\n if (!raw) return DEFAULT_LOCALE\n const lower = raw.toLowerCase()\n const base = lower.split('-')[0]\n\n if (base === 'en') return lower === 'en-us' ? 'en-US' : 'en-GB'\n if (base === 'es') return 'es-MX'\n if (base === 'fr' || base === 'de' || base === 'ru' || base === 'id') return base as LocaleCode\n return DEFAULT_LOCALE\n}\n\nconst INTERPOLATE = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g\n\n/**\n * Build a translator.\n *\n * Resolution order: host overrides -> requested locale -> its fallback chain\n * -> English -> the key itself. The last step means a missing string surfaces\n * as a visible key rather than an empty element, which is far easier to spot\n * in review than a silent blank.\n */\nexport const createTranslator = (options: TranslatorOptions = {}): Translate => {\n const locale = options.locale && FALLBACKS[options.locale] ? options.locale : DEFAULT_LOCALE\n const chain: Messages[] = []\n\n if (options.messages) chain.push(options.messages as Messages)\n const primary = CATALOGUES[locale]\n if (primary) chain.push(primary)\n for (const next of FALLBACKS[locale]) {\n const fallback = CATALOGUES[next]\n if (fallback) chain.push(fallback)\n }\n if (!chain.includes(en)) chain.push(en)\n\n return (key, vars) => {\n let template: string | undefined\n for (const source of chain) {\n const hit = source[key]\n if (typeof hit === 'string' && hit.length > 0) {\n template = hit\n break\n }\n }\n if (template === undefined) return key\n if (!vars) return template\n\n return template.replace(INTERPOLATE, (whole, name: string) => {\n const value = vars[name]\n return value === undefined || value === null ? whole : String(value)\n })\n }\n}\n","import type { Messages } from '../types'\n\n/**\n * Spanish (Mexico).\n *\n * Partial catalogues are legal — anything absent resolves through en-GB — but\n * this one is complete against ./en.ts so the checkout reads fully Spanish for\n * the storefronts that need it today.\n */\nexport const esMX: Messages = {\n // --- Common ------------------------------------------------------------\n 'common.close': 'Cerrar',\n 'common.dismiss': 'Descartar',\n 'common.loading': 'Cargando',\n 'common.required': 'Obligatorio',\n 'common.increase': 'Aumentar',\n 'common.decrease': 'Disminuir',\n 'common.total': 'Total',\n 'common.date': 'Fecha',\n 'common.event': 'Evento',\n 'common.currency': 'Moneda',\n\n // --- Auth --------------------------------------------------------------\n 'auth.title': 'Autenticación',\n 'auth.changePassword': 'Cambiar contraseña',\n 'auth.email': 'Correo electrónico *',\n 'auth.emailPlaceholder': 'Correo electrónico',\n 'auth.password': 'Contraseña *',\n 'auth.passwordPlaceholder': 'Contraseña',\n 'auth.newPassword': 'Nueva contraseña *',\n 'auth.confirmPassword': 'Confirma la contraseña *',\n 'auth.confirmPasswordPlaceholder': 'Confirma la contraseña',\n 'auth.firstName': 'Nombre *',\n 'auth.firstNamePlaceholder': 'Nombre',\n 'auth.lastName': 'Apellido *',\n 'auth.lastNamePlaceholder': 'Apellido',\n 'auth.phone': 'Teléfono',\n 'auth.streetAddress': 'Calle y número *',\n 'auth.streetAddressPlaceholder': 'Calle y número',\n 'auth.city': 'Ciudad *',\n 'auth.cityPlaceholder': 'Ciudad',\n 'auth.postcode': 'Código postal *',\n 'auth.postcodePlaceholder': 'Código postal',\n 'auth.state': 'Estado / Provincia',\n 'auth.country': 'País',\n 'auth.selectCountry': 'Selecciona un país',\n 'auth.loginSkipAhead': 'Inicia sesión y avanza más rápido:',\n\n // --- Billing -----------------------------------------------------------\n 'billing.address': 'Dirección de facturación *',\n 'billing.email': 'Correo electrónico *',\n 'billing.firstName': 'Nombre *',\n 'billing.lastName': 'Apellido *',\n 'billing.phone': 'Teléfono *',\n 'billing.cityPlaceholder': 'Ciudad *',\n 'billing.streetPlaceholder': 'Calle y número *',\n 'billing.postcodePlaceholder': 'Código postal *',\n 'billing.countryLabel': 'País',\n 'billing.stateLabel': 'Estado / región',\n 'billing.socialPlaceholder': '@usuario o URL del perfil',\n 'billing.male': 'Hombre',\n 'billing.female': 'Mujer',\n 'billing.ticketHolders': 'Titulares de los boletos',\n 'billing.emailPlaceholder': 'Correo electrónico *',\n 'billing.confirmEmailPlaceholder': 'Confirma tu correo *',\n 'billing.holderFirstName': 'Nombre *',\n 'billing.holderLastName': 'Apellido *',\n 'billing.emailMismatch': 'Los correos electrónicos no coinciden.',\n\n // --- Tickets & seats ---------------------------------------------------\n 'tickets.yourTickets': 'Tus boletos',\n 'tickets.selectType': 'Selecciona un tipo de boleto',\n 'tickets.soldOut': 'Agotado',\n 'tickets.guests': 'Invitados',\n 'tickets.reserveTables': 'Reservar mesas',\n 'tickets.noSessions': 'No hay funciones disponibles en esta fecha.',\n\n // --- Payment -----------------------------------------------------------\n 'payment.method': 'Método de pago',\n 'payment.useThisCard': 'Usar esta tarjeta',\n 'payment.payInInstallments': '¿Pagar a plazos?',\n 'payment.chooseInstallments': 'Elegir plazos',\n\n // --- Referral ----------------------------------------------------------\n 'referral.cheaperOrFree': 'Tus boletos pueden costar menos, ¡o incluso ser GRATIS!',\n 'referral.inviteFriends': 'Invita a tus amigos',\n 'referral.howToInvite': '¿Cómo invitas a tus amigos?',\n 'referral.sendThisLink': 'Envíales este enlace:',\n 'referral.howMuchCheaper': '¿Cuánto más barato?',\n}\n","import { registerCatalogue } from '../resolve'\nimport { en } from './en'\nimport { esMX } from './es-MX'\n\n/**\n * Registers every bundle the SDK ships.\n *\n * en-GB is registered by ../resolve directly (it is the fallback of last\n * resort and must exist before any lookup). The rest register here.\n *\n * Adding a locale: create ./<code>.ts exporting a Messages object, then\n * register it below. Partial catalogues are fine — missing keys resolve\n * through the fallback chain to English.\n */\nregisterCatalogue('es-MX', esMX)\n\nexport { en, esMX }\n","/**\n * Web (stripe-js) adapter of the SDK's PaymentConfirmer port — the proof that\n * the engine in `tf-checkout-shared` is genuinely platform-free. Bind it via\n * `useCheckout({ ports: { confirmer: webConfirmer, ...webPorts } })` to run the\n * exact same cart → order → charge → finalize sequence React Native runs (same\n * retry-safety invariants, same duplicate-charge guards, same tests).\n *\n * Card payments on the web confirm against a Stripe Element the consumer\n * renders: register it via `confirmer.registerCardElement(element)` before\n * placing the order. Apple Pay is not bound on web yet (the web equivalent is\n * the Payment Request button, a different integration) — `confirmApplePay`\n * throws with a clear message.\n */\nimport {\n loadStripe,\n type Stripe,\n type StripeCardElement,\n type StripeElements,\n} from '@stripe/stripe-js'\nimport type {\n CheckoutBilling,\n CheckoutPorts,\n PaymentConfirmer,\n} from 'tf-checkout-shared'\n\nimport type { WebXenditTokenizer } from './xendit'\n\n/**\n * stripe-js reports PaymentIntent statuses in snake_case; the port's\n * vocabulary is the RN SDK's PascalCase. Normalize so\n * CONFIRMED_INTENT_STATUSES matches on both platforms.\n */\nconst normalizeStatus = (status?: string): string | undefined => {\n if (!status) return undefined\n const map: Record<string, string> = {\n succeeded: 'Succeeded',\n requires_capture: 'RequiresCapture',\n processing: 'Processing',\n requires_payment_method: 'RequiresPaymentMethod',\n requires_confirmation: 'RequiresConfirmation',\n requires_action: 'RequiresAction',\n canceled: 'Canceled',\n }\n return map[status] ?? status\n}\n\nexport interface WebStripeConfirmer extends PaymentConfirmer {\n /** The card Element the consumer rendered — required before confirmCard. */\n registerCardElement(element: StripeCardElement | null): void\n /** The currently registered card Element (null before registration) —\n * the MSI port creates its PaymentMethod from it. */\n getCardElement(): StripeCardElement | null\n /**\n * The Elements GROUP backing a `<StripePaymentElement/>` (deferred mode).\n * This is how the old checkout did wallets: when a Payment Element is\n * registered, `confirmCard` confirms card + Apple Pay + Google Pay through it\n * (`elements.submit()` + `stripe.confirmPayment`), exactly as the old\n * `useStripePayment.processPayment` did. Null when only a bare card is rendered.\n */\n registerPaymentElement(elements: StripeElements | null): void\n getPaymentElement(): StripeElements | null\n /**\n * The live Stripe instance (null before the flow calls init). Elements MUST\n * be created from this instance — stripe-js rejects confirming with an\n * Element born from a different one:\n * `confirmer.getStripe()!.elements().create('card')`.\n */\n getStripe(): Stripe | null\n /** Resolves with the Stripe instance as soon as init() has run — mount UI\n * against this instead of polling getStripe(). */\n whenReady(): Promise<Stripe>\n}\n\nexport const createWebStripeConfirmer = (): WebStripeConfirmer => {\n let stripe: Stripe | null = null\n let initKey: string | null = null\n let cardElement: StripeCardElement | null = null\n let paymentElements: StripeElements | null = null\n let readyResolve: (s: Stripe) => void\n let ready = new Promise<Stripe>((r) => (readyResolve = r))\n\n const requireStripe = (): Stripe => {\n if (!stripe) {\n throw new Error(\n 'Stripe is not initialized — the flow calls confirmer.init() first.'\n )\n }\n return stripe\n }\n\n return {\n registerCardElement: (element) => {\n cardElement = element\n },\n\n getCardElement: () => cardElement,\n\n registerPaymentElement: (elements) => {\n paymentElements = elements\n },\n\n getPaymentElement: () => paymentElements,\n\n getStripe: () => stripe,\n\n whenReady: () => ready,\n\n init: async ({ publishableKey, accountId }) => {\n // Re-init only when the key/account pair changes (events on connected\n // accounts each need their own instance).\n const key = `${publishableKey}:${accountId ?? ''}`\n if (stripe && initKey === key) return\n stripe = await loadStripe(\n publishableKey,\n accountId ? { stripeAccount: accountId } : undefined\n )\n if (!stripe) throw new Error('Failed to load Stripe.js.')\n initKey = key\n readyResolve(stripe)\n // subsequent inits (new key) refresh the promise for late mounts\n ready = Promise.resolve(stripe)\n },\n\n getIntentStatus: async (clientSecret) => {\n const { paymentIntent } = await requireStripe().retrievePaymentIntent(clientSecret)\n return normalizeStatus(paymentIntent?.status)\n },\n\n confirmCard: async (clientSecret, billing: CheckoutBilling) => {\n // Wallet-capable path — the way the OLD checkout confirmed. When a\n // `<StripePaymentElement/>` is mounted, the buyer may have picked card OR\n // Apple/Google Pay INSIDE the widget; a single `elements.submit()` +\n // `stripe.confirmPayment({ elements, clientSecret })` settles whichever it\n // is (`useStripePayment.processPayment`). Billing is left to the element —\n // matching old, and avoiding Stripe's \"collected in both places\" error.\n if (paymentElements) {\n const { error: submitError } = await paymentElements.submit()\n if (submitError) throw new Error(submitError.message || 'Payment failed.')\n const returnUrl =\n window.location.href +\n (window.location.href.includes('?') ? '&' : '?') +\n 'payment_return=true'\n const { error, paymentIntent } = await requireStripe().confirmPayment({\n clientSecret,\n elements: paymentElements,\n confirmParams: { return_url: returnUrl },\n // Card + wallets settle in place; only a redirect method navigates away.\n redirect: 'if_required',\n })\n if (error) throw new Error(error.message || 'Payment failed.')\n return normalizeStatus(paymentIntent?.status)\n }\n\n // Bare-card fallback (no wallets / MSI events): the current CardElement path.\n if (!cardElement) {\n throw new Error(\n 'No card element registered — call confirmer.registerCardElement(element) with the CardElement you rendered.'\n )\n }\n const { error, paymentIntent } = await requireStripe().confirmCardPayment(\n clientSecret,\n {\n payment_method: {\n card: cardElement,\n billing_details: {\n email: billing.email,\n name: `${billing.firstName} ${billing.lastName}`.trim(),\n phone: billing.phone || undefined,\n },\n },\n }\n )\n if (error) throw new Error(error.message || 'Payment failed.')\n return normalizeStatus(paymentIntent?.status)\n },\n\n confirmApplePay: async () => {\n throw new Error(\n 'Apple Pay is not bound on web yet — use the card flow, or bind a Payment Request confirmer.'\n )\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Web bindings of the engine's alternative-rail ports\n// ---------------------------------------------------------------------------\n\nconst stripeBillingDetails = (billing: CheckoutBilling) => ({\n email: billing.email,\n name: `${billing.firstName} ${billing.lastName}`.trim(),\n phone: billing.phone || undefined,\n address: {\n line1: billing.streetAddress || undefined,\n city: billing.city || undefined,\n postal_code: billing.zip || undefined,\n // Stripe wants ISO-2 — CheckoutBilling.countryCode/stateCode carry it when\n // the consumer resolved them (backend countryId/stateId are numeric);\n // providers that require it still collect it on their own page otherwise.\n country: billing.countryCode || undefined,\n state: billing.stateCode || undefined,\n },\n})\n\n/**\n * The web half of the engine's `CheckoutPorts`:\n *\n * - `providerPage` runs the provider in a POPUP and resolves when navigation\n * lands back on `returnUrlPrefix` (same-origin, so the URL is readable);\n * a closed popup resolves as 'dismiss'. Call `placeOrder` from a click\n * handler, or the browser's popup blocker will refuse the window.\n * - `confirmOxxo` / `createCardPaymentMethod` / `createRedirectPaymentMethod`\n * / `handleNextAction` bind the same Stripe legs the RN ports bind.\n *\n * MSI's `onInstallmentOffers` picker stays consumer-supplied (pass it via\n * `placeOrder(request, ports)`).\n */\nexport const createWebPorts = (\n confirmer: WebStripeConfirmer,\n /** The Xendit card tokenizer `<XenditCardInput/>` binds to. When given, the\n * engine tokenizes Xendit cards inline instead of in a popup. */\n xenditTokenizer?: WebXenditTokenizer\n): Omit<CheckoutPorts, 'confirmer'> => {\n const requireStripe = (): Stripe => {\n const stripe = confirmer.getStripe()\n if (!stripe) {\n throw new Error(\n 'Stripe is not initialized — the flow calls confirmer.init() first.'\n )\n }\n return stripe\n }\n\n return {\n ...(xenditTokenizer\n ? {\n tokenizeXenditCard: (params) =>\n xenditTokenizer.tokenize({\n publishableKey: params.publishableKey,\n amount: params.amount,\n billing: {\n firstName: params.billing.firstName,\n lastName: params.billing.lastName,\n email: params.billing.email,\n phone: params.billing.phone,\n },\n onBehalfOf: params.onBehalfOf,\n }),\n }\n : {}),\n\n openUrl: (url: string) => {\n window.open(url, '_blank', 'noopener')\n },\n\n providerPage: ({ uri, html, returnUrlPrefix }) =>\n new Promise((resolve) => {\n const popup = window.open(\n uri ?? '',\n 'tf-checkout-gateway',\n 'width=480,height=720'\n )\n if (!popup) {\n resolve({\n event: 'failed',\n description: 'Please allow pop-ups to continue this payment.',\n })\n return\n }\n\n let settled = false\n let timer = 0\n const settle = (outcome: {\n event: 'success' | 'dismiss' | 'failed'\n returnUrl?: string\n data?: Record<string, unknown>\n description?: string\n }) => {\n if (settled) return\n settled = true\n window.clearInterval(timer)\n window.removeEventListener('message', onMessage)\n if (!popup.closed) popup.close()\n resolve(outcome)\n }\n\n // Data-driven sheets (Razorpay, Xendit card) post lifecycle JSON via\n // ReactNativeWebView.postMessage — the shim below forwards it to this\n // window, same protocol as checkout-v2's WebView onMessage.\n const onMessage = (e: MessageEvent) => {\n if (e.source !== popup) return\n const raw = (e.data as { __tfGatewaySheet?: string } | null)?.__tfGatewaySheet\n if (typeof raw !== 'string') return\n let parsed: {\n event?: string\n razorpay_payment_id?: string\n token?: Record<string, unknown>\n description?: string\n } | null = null\n try {\n parsed = JSON.parse(raw)\n } catch {\n return\n }\n if (!parsed || typeof parsed.event !== 'string') return\n if (parsed.event === 'success') {\n settle({\n event: 'success',\n data: {\n ...(parsed.razorpay_payment_id\n ? { razorpay_payment_id: parsed.razorpay_payment_id }\n : {}),\n ...(parsed.token ? { token: parsed.token } : {}),\n },\n })\n } else if (parsed.event === 'dismiss') {\n settle({ event: 'dismiss' })\n } else if (parsed.event === 'failed') {\n settle({ event: 'failed', description: parsed.description })\n }\n }\n window.addEventListener('message', onMessage)\n\n if (!uri && html) {\n const shim =\n '<script>window.ReactNativeWebView={postMessage:function(m){' +\n \"window.opener&&window.opener.postMessage({__tfGatewaySheet:m},'*')}}</script>\"\n popup.document.open()\n popup.document.write(shim + html)\n popup.document.close()\n }\n\n timer = window.setInterval(() => {\n if (popup.closed) {\n settle({ event: 'dismiss' })\n return\n }\n try {\n const href = popup.location.href\n if (href && href.startsWith(returnUrlPrefix)) {\n settle({ event: 'success', returnUrl: href })\n }\n } catch {\n // Cross-origin while on the provider's page — keep polling.\n }\n }, 500)\n }),\n\n createCardPaymentMethod: async (billing: CheckoutBilling) => {\n const card = confirmer.getCardElement()\n if (!card) {\n throw new Error(\n 'No card element registered — render <CardInput/> before placing the order.'\n )\n }\n const { paymentMethod, error } = await requireStripe().createPaymentMethod({\n type: 'card',\n card,\n billing_details: stripeBillingDetails(billing),\n })\n if (error || !paymentMethod?.id) {\n throw new Error(error?.message || 'Payment failed')\n }\n return paymentMethod.id\n },\n\n createRedirectPaymentMethod: async (methodType: string, billing: CheckoutBilling) => {\n const { paymentMethod, error } = await requireStripe().createPaymentMethod({\n type: methodType,\n billing_details: stripeBillingDetails(billing),\n } as unknown as Parameters<Stripe['createPaymentMethod']>[0])\n // An unknown/unsupported type is the platform saying \"can't express\n // this\" — the engine turns null into a typed UNSUPPORTED_GATEWAY.\n if (error) return null\n return paymentMethod?.id ?? null\n },\n\n handleNextAction: async (clientSecret: string) => {\n const stripe = requireStripe() as Stripe & {\n handleNextAction?: (options: {\n clientSecret: string\n }) => Promise<{ error?: { message?: string } }>\n }\n if (!stripe.handleNextAction) {\n throw new Error('This Stripe.js version cannot run the payment’s next step.')\n }\n const { error } = await stripe.handleNextAction({ clientSecret })\n if (error) throw new Error(error.message || 'Payment failed')\n },\n\n confirmOxxo: async (clientSecret: string, billing: CheckoutBilling) => {\n const { error, paymentIntent } = await requireStripe().confirmOxxoPayment(\n clientSecret,\n { payment_method: { billing_details: stripeBillingDetails(billing) } }\n )\n return {\n error: error?.message,\n // stripe-js reports snake_case next_action — exactly the shape the\n // shared logic's oxxoVoucherFromNextAction parses.\n nextAction: paymentIntent?.next_action as unknown,\n }\n },\n\n // Payment plan (new card): confirm the SetupIntent against the registered\n // CardElement to SAVE the card (nothing charged), returning its\n // PaymentMethod id for the server-side plan.\n confirmPaymentPlanSetup: async (clientSecret: string, billing: CheckoutBilling) => {\n const card = confirmer.getCardElement()\n if (!card) {\n throw new Error(\n 'No card element registered — render <CardInput/> before placing the order.'\n )\n }\n const { setupIntent, error } = await requireStripe().confirmCardSetup(\n clientSecret,\n {\n payment_method: { card, billing_details: stripeBillingDetails(billing) },\n }\n )\n // payment_method is a string id (or an expanded object on some responses).\n const pm = setupIntent?.payment_method\n const paymentMethodId =\n typeof pm === 'string' ? pm : (pm as { id?: string } | null)?.id\n if (error || !paymentMethodId) {\n throw new Error(error?.message || 'Card setup failed')\n }\n return paymentMethodId\n },\n\n // Payment plan (saved-card 3DS): confirm the pending charge against the\n // existing PaymentMethod when the plan comes back requires_action.\n confirmSavedCardPayment: async (clientSecret: string, paymentMethodId: string) => {\n const { error } = await requireStripe().confirmCardPayment(clientSecret, {\n payment_method: paymentMethodId,\n })\n if (error) throw new Error(error.message || 'Payment failed')\n },\n }\n}\n","/**\n * Web (xendit.js) binding for Xendit CARD tokenization — the inline,\n * natively-styled equivalent of the React Native WebView sheet. It loads\n * xendit.js into the page, tokenizes the card the consumer rendered via\n * `<XenditCardInput/>`, and runs the 3DS challenge in a full-screen overlay.\n * The engine charges the returned token server-side.\n *\n * The consumer's app must allow `https://js.xendit.co` in its CSP.\n */\n\nconst XENDIT_JS = 'https://js.xendit.co/v1/xendit.min.js'\n\n/** How long to wait for xendit.js to call our callback even ONCE before giving\n * up. The SDK can stall after its `payer/init` + `fingerprint/scans` warmup\n * without ever POSTing `/v2/credit_card_tokens`; without this the promise\n * never settles and the buyer stares at a blank 3DS overlay forever. */\nconst FIRST_RESPONSE_TIMEOUT_MS = 45_000\n\ninterface XenditToken {\n status: 'VERIFIED' | 'IN_REVIEW' | 'FAILED' | string\n payer_authentication_url?: string\n [k: string]: unknown\n}\n\ninterface XenditGlobal {\n setPublishableKey(key: string): void\n card: {\n createToken(\n data: Record<string, unknown>,\n cb: (err: XenditError | null, token: XenditToken) => void\n ): void\n /** xendit.js ships its own validators — use them so the rules match exactly\n * what `createToken` will accept, instead of re-deriving them here. */\n validateCardNumber(number: string): boolean\n validateExpiry(month: string, year: string): boolean\n validateCvn(cvn: string): boolean\n }\n}\n\n/** Luhn — the fallback used only before xendit.js has finished loading. */\nconst luhn = (digits: string): boolean => {\n let sum = 0\n let double = false\n for (let i = digits.length - 1; i >= 0; i -= 1) {\n let d = digits.charCodeAt(i) - 48\n if (d < 0 || d > 9) return false\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\nconst xenditGlobal = (): XenditGlobal | undefined =>\n typeof window === 'undefined'\n ? undefined\n : (window as unknown as { Xendit?: XenditGlobal }).Xendit\n\n/**\n * Field-level card checks, matching what `createToken` enforces. Prefers\n * xendit.js's own validators and falls back to equivalent local rules while the\n * script is still loading, so a form can validate on blur from the first\n * keystroke. `expYear` accepts \"YY\" or \"YYYY\".\n */\nexport const xenditCardChecks = {\n number: (value: string): boolean => {\n const digits = value.replace(/\\D/g, '')\n if (digits.length < 12) return false\n const X = xenditGlobal()\n return X?.card?.validateCardNumber\n ? X.card.validateCardNumber(digits)\n : digits.length <= 19 && luhn(digits)\n },\n expiry: (month: string, year: string): boolean => {\n const mm = month.trim()\n const yyyy = year.trim().length === 2 ? `20${year.trim()}` : year.trim()\n if (!/^\\d{1,2}$/.test(mm) || !/^\\d{4}$/.test(yyyy)) return false\n const X = xenditGlobal()\n if (X?.card?.validateExpiry) return X.card.validateExpiry(mm, yyyy)\n const m = Number(mm)\n const y = Number(yyyy)\n if (m < 1 || m > 12) return false\n const now = new Date()\n return y > now.getFullYear() || (y === now.getFullYear() && m >= now.getMonth() + 1)\n },\n cvn: (value: string): boolean => {\n const digits = value.replace(/\\D/g, '')\n const X = xenditGlobal()\n return X?.card?.validateCvn\n ? X.card.validateCvn(digits)\n : digits.length >= 3 && digits.length <= 4\n },\n}\n\n/**\n * Human copy for Xendit's `failure_reason` codes — the same map the hosted PHP\n * checkout shows (`XenditHelper::FAILURE_REASONS`). Without it a decline\n * surfaces as a bare code like `INVALID_CVV`, which means nothing to a buyer.\n */\nexport const XENDIT_FAILURE_REASONS: Record<string, string> = {\n EXPIRED_CARD: 'This card has expired. Please use a different card.',\n ISSUER_SUSPECT_FRAUD:\n 'Your bank declined this card as a suspected fraud risk. Please use a different card.',\n DECLINED_BY_PROCESSOR:\n 'This card was declined by the payment processor. Please use a different card.',\n INSUFFICIENT_BALANCE: 'This card does not have enough balance to complete the payment.',\n STOLEN_CARD: 'This card has been reported lost or stolen.',\n INACTIVE_OR_UNAUTHORIZED_CARD:\n 'This card is inactive, or not authorised for this type of payment.',\n PROCESSOR_ERROR:\n 'The payment could not be processed by your bank. Please try again shortly.',\n INVALID_CVV: 'The security code (CVC) does not match this card.',\n DECLINED_BY_ISSUER: 'Your bank declined this payment. Please use a different card.',\n AUTHENTICATION_FAILED:\n 'Card authentication failed. Please try again or use a different card.',\n ENROLLMENT_STATUS_UNAVAILABLE:\n 'Your bank could not verify this card right now. Please try again or use a different card.',\n DEFAULT: 'Your payment was not accepted. Please try again or use a different card.',\n}\n\n/**\n * Xendit accepts only ASCII + Latin-1 in `card_holder_*` names, and requires a\n * letter first:\n * /^[A-Za-z][\\x20-\\x7EÀ-ÖØ-öø-ÿ]*$/\n * A name with an emoji or non-Latin script (\"Babken 🇦🇲\", \"Բաբկեն\") is rejected\n * with API_VALIDATION_ERROR and the whole payment fails. Strip what Xendit\n * can't take and keep the rest; the group is optional, so a name that reduces\n * to nothing is dropped instead of blocking the buyer.\n */\nconst XENDIT_NAME_BODY = /[^\\x20-\\x7EÀ-ÖØ-öø-ÿ]/g\n\nexport const sanitizeXenditHolderName = (value: string): string => {\n const stripped = (value ?? '').replace(XENDIT_NAME_BODY, '').trim()\n // Must begin with a plain A–Z letter — trim any leading punctuation/digits.\n const fromFirstLetter = stripped.replace(/^[^A-Za-z]+/, '')\n return fromFirstLetter.trim()\n}\n\n/** The error shape xendit.js hands back, including per-field validation rows. */\ninterface XenditError {\n message?: string\n error_code?: string\n errors?: Array<{\n message?: string\n path?: string[]\n context?: { key?: string }\n }>\n}\n\n/** Field key → buyer-facing sentence, for API_VALIDATION_ERROR responses. */\nconst VALIDATION_FIELD_COPY: Record<string, string> = {\n card_number: 'Card number is invalid',\n card_exp_month: 'Card expiry date is invalid',\n card_exp_year: 'Card expiry date is invalid',\n card_cvn: 'Card security code is invalid',\n card_holder_first_name: 'Please check the first name on the card.',\n card_holder_last_name: 'Please check the last name on the card.',\n card_holder_email: 'Please check the email address.',\n card_holder_phone_number: 'Please check the phone number.',\n amount: 'This order could not be charged. Please refresh and try again.',\n}\n\n/**\n * Turn a raw xendit.js error into something a buyer can act on. Xendit's own\n * `message` for a rejected field is \"There was an error with the format\n * submitted to the server\", which says nothing — the useful detail is in\n * `errors[].context.key`.\n */\nexport const describeXenditError = (err: XenditError): string => {\n const first = Array.isArray(err.errors) ? err.errors[0] : undefined\n const key = first?.context?.key ?? first?.path?.[first.path.length - 1]\n if (key && VALIDATION_FIELD_COPY[key]) return VALIDATION_FIELD_COPY[key]\n if (err.error_code && XENDIT_FAILURE_REASONS[err.error_code]) {\n return XENDIT_FAILURE_REASONS[err.error_code]\n }\n // Xendit's generic format message is noise — prefer our own wording.\n if (!err.message || /format submitted to the server/i.test(err.message)) {\n return XENDIT_FAILURE_REASONS.DEFAULT\n }\n return err.message\n}\n\n/** Raw card field values, read at tokenize time (never held in JS state). */\nexport interface XenditCardFields {\n number: string\n /** \"MM\" */\n expMonth: string\n /** \"YY\" or \"YYYY\" — 2-digit is expanded to 20YY. */\n expYear: string\n cvn: string\n}\n\nexport interface WebXenditTokenizer {\n /** `<XenditCardInput/>` registers a getter for its live field values (or\n * null on unmount). */\n registerFields(getFields: (() => XenditCardFields) | null): void\n /** Tokenizes the registered card (running inline 3DS when the bank asks) and\n * resolves with the token the engine charges. Rejects on validation error,\n * decline, or a failed 3DS challenge. */\n tokenize(params: {\n publishableKey: string\n amount: string | number\n billing: { firstName: string; lastName: string; email: string; phone?: string }\n onBehalfOf?: string | null\n }): Promise<Record<string, unknown>>\n}\n\nlet scriptPromise: Promise<XenditGlobal> | null = null\n\nconst loadXendit = (): Promise<XenditGlobal> => {\n if (scriptPromise) return scriptPromise\n scriptPromise = new Promise<XenditGlobal>((resolve, reject) => {\n const w = window as unknown as { Xendit?: XenditGlobal }\n if (w.Xendit) {\n return resolve(w.Xendit)\n }\n const script = document.createElement('script')\n script.src = XENDIT_JS\n script.async = true\n script.onload = () => {\n if (w.Xendit) {\n resolve(w.Xendit)\n } else {\n reject(new Error('The payment service could not be loaded.'))\n }\n }\n script.onerror = () => {\n reject(new Error('The payment service could not be loaded.'))\n }\n document.head.appendChild(script)\n })\n return scriptPromise\n}\n\n/** Warm xendit.js so field validation uses Xendit's own rules immediately. */\nexport const preloadXendit = (): void => {\n void loadXendit().catch(() => {\n // Pre-warming is best-effort; tokenize() surfaces a real load failure.\n })\n}\n\nexport const createWebXenditTokenizer = (): WebXenditTokenizer => {\n let getFields: (() => XenditCardFields) | null = null\n\n /**\n * Full-screen overlay hosting the 3DS challenge iframe. Returns a disposer.\n *\n * The iframe is layered OVER a status strip rather than shown bare: an\n * issuer page that is slow, blank (frictionless auth), or blocked would\n * otherwise leave the buyer staring at a plain white rectangle with no way\n * out — indistinguishable from a crash. `onCancel` gives them that way out.\n */\n const showThreeDs = (url: string, onCancel: () => void): (() => void) => {\n const overlay = document.createElement('div')\n overlay.setAttribute(\n 'style',\n 'position:fixed;inset:0;z-index:2147483647;background:#fff;display:flex;flex-direction:column'\n )\n\n const bar = document.createElement('div')\n bar.setAttribute(\n 'style',\n 'display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid #e7e7f0;font:14px system-ui,sans-serif;color:#16162e;flex:none'\n )\n const status = document.createElement('span')\n status.textContent = 'Verifying with your bank…'\n const cancel = document.createElement('button')\n cancel.type = 'button'\n cancel.textContent = 'Cancel'\n cancel.setAttribute(\n 'style',\n 'margin-left:auto;padding:6px 14px;border:1px solid #e7e7f0;border-radius:8px;background:#fff;font:inherit;cursor:pointer'\n )\n cancel.onclick = () => {\n onCancel()\n }\n bar.append(status, cancel)\n\n const frame = document.createElement('iframe')\n frame.setAttribute('style', 'width:100%;flex:1;border:0')\n // Assigning src is what starts the challenge — it must run unconditionally.\n frame.src = url\n\n overlay.append(bar, frame)\n document.body.appendChild(overlay)\n return () => overlay.remove()\n }\n\n return {\n registerFields: (fn) => {\n getFields = fn\n },\n\n tokenize: async ({ publishableKey, amount, billing, onBehalfOf }) => {\n if (!getFields) {\n throw new Error('Render <XenditCardInput/> before paying with a Xendit card.')\n }\n const f = getFields()\n const number = f.number.replace(/\\s+/g, '')\n const expMonth = f.expMonth.trim()\n let expYear = f.expYear.trim()\n if (expYear.length === 2) expYear = '20' + expYear\n const cvn = f.cvn.trim()\n if (!number || !expMonth || !expYear || !cvn) {\n throw new Error('Please fill in your card details.')\n }\n\n const Xendit = await loadXendit()\n Xendit.setPublishableKey(publishableKey)\n\n // Check the fields with Xendit's own validators before spending a network\n // round trip, so the buyer is told WHICH field is wrong rather than\n // getting a generic decline back from the API.\n if (!xenditCardChecks.number(number)) {\n throw new Error('Card number is invalid')\n }\n if (!xenditCardChecks.expiry(expMonth, expYear)) {\n throw new Error('Card expiry date is invalid')\n }\n if (!xenditCardChecks.cvn(cvn)) {\n throw new Error('Card security code is invalid')\n }\n\n return new Promise<Record<string, unknown>>((resolve, reject) => {\n let dismissThreeDs: (() => void) | null = null\n let settled = false\n let answered = false\n const finish = (fn: () => void) => {\n if (settled) return\n settled = true\n clearTimeout(watchdog)\n dismissThreeDs?.()\n fn()\n }\n\n // xendit.js can complete its `payer/init` + `fingerprint/scans` warmup\n // and then never POST /v2/credit_card_tokens — no callback, no error.\n // Fail loudly instead of hanging on a blank overlay forever.\n const watchdog = setTimeout(() => {\n if (answered) return\n finish(() =>\n reject(\n new Error(\n 'The payment service did not respond. Please try again — if it keeps happening, try a different card or browser.'\n )\n )\n )\n }, FIRST_RESPONSE_TIMEOUT_MS)\n\n // The Xendit SDK re-invokes this handler after the 3DS challenge, so\n // IN_REVIEW then VERIFIED/FAILED all flow through here.\n const handler = (err: XenditError | null, token: XenditToken) => {\n answered = true\n if (err) {\n finish(() => reject(new Error(describeXenditError(err))))\n return\n }\n // A callback with neither an error nor a token would throw on\n // `token.status` INSIDE xendit.js, where the try/catch below can't\n // reach it — leaving the promise permanently unsettled.\n if (!token || typeof token !== 'object') {\n finish(() =>\n reject(new Error('The payment service returned an unexpected response.'))\n )\n return\n }\n if (token.status === 'VERIFIED') {\n finish(() => resolve(token as Record<string, unknown>))\n return\n }\n if (token.status === 'IN_REVIEW' && token.payer_authentication_url) {\n // The buyer now drives the bank's challenge — no fixed deadline.\n clearTimeout(watchdog)\n dismissThreeDs?.()\n dismissThreeDs = showThreeDs(token.payer_authentication_url, () =>\n finish(() => reject(new Error('Payment was cancelled')))\n )\n return\n }\n // Translate Xendit's failure_reason the way the hosted checkout does\n // — a bare code like INVALID_CVV tells the buyer nothing.\n const code =\n typeof token.failure_reason === 'string' ? token.failure_reason : ''\n finish(() =>\n reject(\n new Error(XENDIT_FAILURE_REASONS[code] ?? XENDIT_FAILURE_REASONS.DEFAULT)\n )\n )\n }\n try {\n // card_holder_* fields are ALL-OR-NOTHING peers in Xendit's\n // validation (\"card_holder_first_name missing required peer\n // card_holder_phone_number\" — observed live): send the group only\n // when every field is present, else omit it entirely (it's optional\n // as a whole).\n // …and the names must additionally satisfy Xendit's Latin-only\n // pattern, so strip anything it rejects (emoji, non-Latin scripts).\n const holderFirst = sanitizeXenditHolderName(billing.firstName)\n const holderLast = sanitizeXenditHolderName(billing.lastName)\n const holder =\n holderFirst && holderLast && billing.email && billing.phone\n ? {\n card_holder_first_name: holderFirst,\n card_holder_last_name: holderLast,\n card_holder_email: billing.email,\n card_holder_phone_number: billing.phone,\n }\n : {}\n Xendit.card.createToken(\n {\n amount: String(amount),\n card_number: number,\n card_exp_month: expMonth,\n card_exp_year: expYear,\n card_cvn: cvn,\n is_multiple_use: false,\n should_authenticate: true,\n ...holder,\n ...(onBehalfOf ? { on_behalf_of: onBehalfOf } : {}),\n },\n handler\n )\n } catch (e) {\n finish(() =>\n reject(\n e instanceof Error\n ? e\n : new Error('Something went wrong. Please try again.')\n )\n )\n }\n })\n },\n }\n}\n","/**\n * The package-level web platform instances. Created once at module load\n * (SSR-safe — nothing touches the DOM until `init()` / `tokenize()` run), so the\n * hook and the UI components all bind to the SAME confirmer/tokenizer.\n */\nimport {\n createWebPorts,\n createWebStripeConfirmer,\n type WebStripeConfirmer,\n} from './confirmer'\nimport { createWebXenditTokenizer, type WebXenditTokenizer } from './xendit'\n\n/** The confirmer every `useCheckout`/`<CardInput/>` binds to. */\nexport const webConfirmer: WebStripeConfirmer = createWebStripeConfirmer()\n\n/** The Xendit card tokenizer `<XenditCardInput/>` binds to. */\nexport const webXenditTokenizer: WebXenditTokenizer = createWebXenditTokenizer()\n\n/** The web ports the alternative rails run on: the popup provider page, OXXO /\n * MSI Stripe legs, and inline Xendit tokenization. */\nexport const webPorts = createWebPorts(webConfirmer, webXenditTokenizer)\n","/**\n * Web `useCheckout` — a thin injector: the SDK's `useCheckout` with the web\n * platform ports pre-wired (Stripe confirmer, popup provider page, inline\n * Xendit). ALL the DX (countdown, isBusy, promo/referrer/waiting-list, auto ID\n * verification, the flat snapshot) lives in the SDK's hook, so web and React\n * Native share it — this file only supplies what's browser-specific.\n *\n * configureCheckout({ env: 'PROD', clientId, clientSecret }) // once, at app start\n * const checkout = useCheckout()\n * await checkout.setTickets(eventId, selections)\n * checkout.setBilling(b)\n * await checkout.placeOrder('card') // <CardInput/> rendered\n */\nimport {\n useCheckout as useSharedCheckout,\n type CheckoutOptions,\n type CheckoutPorts,\n type UseCheckout,\n} from 'tf-checkout-shared'\n\nimport { webConfirmer, webPorts } from './instance'\n\nexport interface UseCheckoutOptions {\n /** Extra platform ports merged over the web defaults — e.g. MSI's\n * `onInstallmentOffers` picker. Read once, at first render. */\n ports?: Omit<CheckoutPorts, 'confirmer'>\n /** Wallet/redirect engine options (merchant identity, redirect URL). */\n options?: CheckoutOptions\n}\n\nexport const useCheckout = (opts: UseCheckoutOptions = {}): UseCheckout =>\n useSharedCheckout({\n ports: { confirmer: webConfirmer, ...webPorts, ...opts.ports },\n options: opts.options,\n })\n","/**\n * One-time SDK setup for the web. Wraps the shared `configure()` and defaults\n * the storage adapter to `localStorage` (SSR-safe — no-ops on the server). Call\n * once at app start, before any `useCheckout`/`ttf` call:\n *\n * configureCheckout({ env: 'PROD', clientId, clientSecret })\n */\nimport {\n configure,\n type StorageAdapter,\n type TtfConfig,\n} from 'tf-checkout-shared'\n\nconst isBrowser =\n typeof window !== 'undefined' && typeof window.localStorage !== 'undefined'\n\n/** localStorage-backed token storage. No-ops on the server (SSR). */\nexport const localStorageAdapter: StorageAdapter = {\n getItem: (key) => (isBrowser ? window.localStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (isBrowser) window.localStorage.setItem(key, value)\n },\n removeItem: (key) => {\n if (isBrowser) window.localStorage.removeItem(key)\n },\n}\n\nexport const configureCheckout = (config: TtfConfig): void =>\n configure({ storage: localStorageAdapter, ...config })\n","/**\n * The card fields. `<CardInput/>` mounts a Stripe Element as soon as the engine\n * has initialized Stripe (via the confirmer's `whenReady()` — no races, renders\n * before or after init) and registers it with the confirmer. `<XenditCardInput/>`\n * is the inline, formatted equivalent for Xendit events.\n */\nimport React, { useEffect, useRef, useState, type CSSProperties, type FC } from 'react'\nimport type {\n StripeCardElementOptions,\n StripeElements,\n StripeElementsOptionsMode,\n StripePaymentElementOptions,\n} from '@stripe/stripe-js'\n\nimport { webConfirmer, webXenditTokenizer } from './instance'\nimport { preloadXendit, xenditCardChecks } from './xendit'\n\ntype Field = 'number' | 'expiry' | 'cvc'\n\n/**\n * The Stripe card field. Mounts against the engine's Stripe instance and\n * registers itself with the confirmer; unregisters on unmount.\n *\n * Stripe Elements live in a cross-origin iframe and DON'T inherit page CSS, so\n * by default they render black text — invisible on a dark surface. We read the\n * host element's computed color/font and feed them to the Element so it matches\n * whatever theme the consumer uses, no config needed. Pass `style` to override.\n */\nexport const CardInput: FC<{\n className?: string\n /** Stripe base-style overrides, merged onto the inherited color/font. */\n style?: StripeCardElementOptions['style']\n}> = ({ className, style }) => {\n const hostRef = useRef<HTMLDivElement | null>(null)\n\n useEffect(() => {\n let element: { mount: (el: HTMLElement) => void; unmount: () => void } | null = null\n let cancelled = false\n webConfirmer.whenReady().then((stripe) => {\n if (cancelled || !hostRef.current) return\n const cs = getComputedStyle(hostRef.current)\n const color = cs.color || '#ffffff'\n const fontSize = cs.fontSize && parseFloat(cs.fontSize) > 0 ? cs.fontSize : '16px'\n // Stripe's Element style parser only accepts hex / rgb / rgba / hsl / named\n // colors — NOT color-mix() or CSS vars (it silently drops the whole style,\n // leaving a blank, dead field). Derive a muted placeholder as a plain rgba\n // of the inherited text color.\n const rgb = color.match(/\\d+(?:\\.\\d+)?/g)\n const placeholder =\n rgb && rgb.length >= 3 ? `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, 0.5)` : color\n const card = stripe.elements().create('card', {\n style: {\n ...style,\n base: {\n color,\n fontFamily: cs.fontFamily,\n fontSize,\n iconColor: color,\n '::placeholder': { color: placeholder },\n ...style?.base,\n },\n },\n })\n card.mount(hostRef.current)\n webConfirmer.registerCardElement(card)\n element = card\n })\n return () => {\n cancelled = true\n if (element) {\n webConfirmer.registerCardElement(null)\n element.unmount()\n }\n }\n }, [])\n\n return <div ref={hostRef} className={className} />\n}\n\n/**\n * Build a Stripe Appearance from the live `--tf-checkout-*` tokens on the host\n * element. This is what keeps the Payment Element CONSISTENT with the rest of the\n * checkout: it inherits the same surface / text / accent / border / radius / font\n * a consumer set — via the provider `theme`, their own CSS, or the default\n * light/dark — so retheming the checkout (flat, branded, whatever) reflows the\n * Stripe widget too, instead of it being a generic Stripe `night`/`stripe` box.\n */\nconst checkoutAppearance = (host: HTMLElement) => {\n const cs = getComputedStyle(host)\n const v = (name: string) => cs.getPropertyValue(name).trim() || undefined\n const surface = v('--tf-checkout-surface')\n const text = v('--tf-checkout-text')\n const muted = v('--tf-checkout-muted')\n const border = v('--tf-checkout-border')\n const accent = v('--tf-checkout-accent')\n const danger = v('--tf-checkout-error')\n const font = v('--tf-checkout-font')\n const radius = v('--tf-checkout-radius-control')\n\n // Pick the closest Stripe base theme from the surface luminance, then override\n // its palette with our tokens so it matches exactly.\n const bgRgb = ((surface ?? cs.backgroundColor).match(/\\d+(?:\\.\\d+)?/g) ?? []).map(\n Number\n )\n const isDark =\n bgRgb.length >= 3 &&\n (0.299 * bgRgb[0] + 0.587 * bgRgb[1] + 0.114 * bgRgb[2]) / 255 < 0.5\n\n const variables: Record<string, string> = {}\n const set = (k: string, val?: string) => {\n if (val) variables[k] = val\n }\n set('colorPrimary', accent)\n set('colorBackground', surface)\n set('colorText', text)\n set('colorTextSecondary', muted)\n set('colorTextPlaceholder', muted)\n set('colorDanger', danger)\n set('fontFamily', font)\n set('borderRadius', radius)\n\n const rules: Record<string, Record<string, string>> = {}\n if (border) {\n rules['.Input'] = { border: `1px solid ${border}` }\n rules['.Input:focus'] = {\n border: `1px solid ${accent ?? border}`,\n boxShadow: 'none',\n }\n rules['.Tab'] = { border: `1px solid ${border}` }\n rules['.Block'] = { border: `1px solid ${border}` }\n }\n\n return {\n theme: isDark ? 'night' : 'stripe',\n ...(Object.keys(variables).length ? { variables } : {}),\n ...(Object.keys(rules).length ? { rules } : {}),\n }\n}\n\n/**\n * The wallet-capable card widget — a Stripe **Payment Element** in DEFERRED mode,\n * exactly how the OLD checkout rendered payment. It shows the card fields AND,\n * when the event's `stripe_wallets` gate is on, the Apple Pay / Google Pay\n * buttons that the buyer picks *inside* the widget. There is no separate \"Apple\n * Pay\" method row — wallets are a property of the card widget, as in old.\n *\n * Confirmation rides the same `placeOrder({ method: 'card' })` rail: this mounts\n * the Elements group and registers it with the confirmer, whose `confirmCard`\n * then runs `elements.submit()` + `stripe.confirmPayment` (old\n * `useStripePayment.processPayment`). Mount this instead of `<CardInput/>` for a\n * Stripe event with wallets available — see `<Payment/>`. It needs the server's\n * deferred Elements config (`checkout.stripeElementsConfig`: mode/amount/currency).\n */\nexport const StripePaymentElement: FC<{\n className?: string\n /** Server deferred Elements config from `checkout.stripeElementsConfig`. */\n elementsConfig?: Record<string, unknown>\n /** Wallet gate from `checkout.walletAvailability`. */\n wallets?: { applePay?: boolean; googlePay?: boolean }\n /** Extra Payment Element options, merged over the wallet gate. */\n options?: StripePaymentElementOptions\n}> = ({ className, elementsConfig, wallets, options }) => {\n const hostRef = useRef<HTMLDivElement | null>(null)\n\n // Re-mount when the deferred amount/currency or the wallet gate changes.\n const configKey = JSON.stringify(elementsConfig ?? null)\n const applePay = Boolean(wallets?.applePay)\n const googlePay = Boolean(wallets?.googlePay)\n\n useEffect(() => {\n let group: StripeElements | null = null\n let element: { unmount: () => void } | null = null\n let cancelled = false\n\n webConfirmer.whenReady().then((stripe) => {\n if (cancelled || !hostRef.current) return\n // Deferred mode — the same `{ mode, amount, currency }` shape the old\n // `<Elements options={elements_config}>` used.\n const mode = (elementsConfig ?? {\n mode: 'payment',\n amount: 0,\n currency: 'usd',\n }) as unknown as StripeElementsOptionsMode\n // Theme the widget from the checkout's own tokens (read live off the host)\n // so it matches whatever the consumer set — not a generic Stripe preset.\n // (The server sends `theme:'automatic'`, which isn't a real Stripe theme and\n // just defaults to light — hence the white box on a dark checkout.)\n group = stripe.elements({\n ...mode,\n appearance: checkoutAppearance(hostRef.current),\n } as unknown as StripeElementsOptionsMode)\n const pe = group.create('payment', {\n ...options,\n wallets: {\n applePay: applePay ? 'auto' : 'never',\n googlePay: googlePay ? 'auto' : 'never',\n ...(options?.wallets ?? {}),\n },\n })\n pe.mount(hostRef.current)\n webConfirmer.registerPaymentElement(group)\n element = pe\n })\n\n return () => {\n cancelled = true\n if (element) {\n webConfirmer.registerPaymentElement(null)\n element.unmount()\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [configKey, applePay, googlePay])\n\n return <div ref={hostRef} className={className} />\n}\n\nconst onlyDigits = (v: string) => v.replace(/\\D/g, '')\n/** \"1234567812345678\" → \"1234 5678 1234 5678\" (max 19 digits). */\nconst formatCardNumber = (v: string) =>\n onlyDigits(v)\n .slice(0, 19)\n .replace(/(\\d{4})(?=\\d)/g, '$1 ')\n/**\n * Digits → \"MM/YY\" (max 4 digits), inserting the slash after the month.\n * A leading digit above 1 can only be a single-digit month, so it's expanded\n * (\"4\" → \"04/\"); a two-digit month is clamped to 12. Without this the field\n * happily accepted \"44/44\" and only Xendit ever objected.\n */\nconst formatExpiry = (v: string) => {\n let d = onlyDigits(v).slice(0, 4)\n if (d.length === 1 && Number(d) > 1) d = `0${d}`\n if (d.length >= 2) {\n const mm = Math.min(Math.max(Number(d.slice(0, 2)), 1), 12)\n d = String(mm).padStart(2, '0') + d.slice(2)\n }\n return d.length > 2 ? `${d.slice(0, 2)}/${d.slice(2)}` : d\n}\nconst formatCvc = (v: string) => onlyDigits(v).slice(0, 4)\n\n/**\n * Inline card field for a Xendit event — the formatted, no-popup equivalent of\n * `<CardInput/>`. Render it when the gateway is Xendit and the buyer picks card,\n * then `placeOrder({ method: 'xenditCard' })`: the engine tokenizes these fields\n * with xendit.js (3DS inline) and charges server-side.\n */\nexport const XenditCardInput: FC<{\n className?: string\n inputClassName?: string\n /**\n * Reports the current field-level problem (or null when the fields are fine).\n * The message is deliberately NOT rendered here: this component is mounted\n * inside the consumer's bordered card box, and an error printed in there sits\n * inside the border instead of beneath it. The consumer places it — see\n * `<Payment/>`, which renders it under the box like every other field error.\n */\n onValidationChange?: (message: string | null) => void\n}> = ({ className, inputClassName, onValidationChange }) => {\n const [number, setNumber] = useState('')\n const [expiry, setExpiry] = useState('')\n const [cvc, setCvc] = useState('')\n // Per-field messages, revealed on blur so the buyer isn't scolded mid-typing.\n const [touched, setTouched] = useState<Record<Field, boolean>>({\n number: false,\n expiry: false,\n cvc: false,\n })\n\n const [mm = '', yy = ''] = expiry.split('/')\n const errors: Record<Field, string | null> = {\n number: number && !xenditCardChecks.number(number) ? 'Card number is invalid' : null,\n expiry:\n expiry.length >= 5 && !xenditCardChecks.expiry(mm, yy)\n ? 'Expiry date is invalid'\n : null,\n cvc: cvc && !xenditCardChecks.cvn(cvc) ? 'Security code is invalid' : null,\n }\n const show = (f: Field) => (touched[f] ? errors[f] : null)\n const markTouched = (f: Field) => setTouched((t) => ({ ...t, [f]: true }))\n\n // The tokenizer reads the live values at pay time via this ref (registered\n // once) — no stale closure over state.\n const latest = useRef({ number, expiry, cvc })\n latest.current = { number, expiry, cvc }\n\n useEffect(() => {\n // Warm xendit.js so the checks above use Xendit's own rules from the first\n // blur, not just the local fallback.\n preloadXendit()\n webXenditTokenizer.registerFields(() => {\n const [m = '', y = ''] = latest.current.expiry.split('/')\n return {\n number: latest.current.number,\n expMonth: m.trim(),\n expYear: y.trim(),\n cvn: latest.current.cvc,\n }\n })\n return () => webXenditTokenizer.registerFields(null)\n }, [])\n\n // Borderless inner inputs (unless the consumer styles them) so the three\n // fields read as one card field inside `className`.\n const blend: CSSProperties = inputClassName\n ? {}\n : {\n border: 0,\n background: 'transparent',\n outline: 'none',\n padding: 0,\n color: 'inherit',\n font: 'inherit',\n }\n\n // First message wins. Reported upward (never rendered here) so the consumer\n // can place it below its card box.\n const message = show('number') || show('expiry') || show('cvc')\n\n const reportRef = useRef(onValidationChange)\n reportRef.current = onValidationChange\n useEffect(() => {\n // Re-report on every EDIT, not just when the message text changes. A field\n // that was never blurred has no message of its own, so if the consumer is\n // showing a pay-time failure (\"Card number is invalid\" from the submit\n // attempt) a message-only dependency would never fire again and that error\n // would sit there while the buyer types a perfectly good number.\n //\n // The callback identity is deliberately NOT a dependency — a consumer's\n // inline arrow changes every render and would loop.\n reportRef.current?.(message)\n }, [message, number, expiry, cvc])\n\n return (\n <div\n className={className}\n style={{ display: 'flex', alignItems: 'center', gap: 10 }}\n data-checkout-invalid={message ? 'true' : undefined}\n >\n <input\n className={inputClassName}\n style={{ ...blend, flex: 1, minWidth: 0 }}\n inputMode=\"numeric\"\n autoComplete=\"cc-number\"\n placeholder=\"Card number\"\n aria-invalid={Boolean(show('number'))}\n value={number}\n onChange={(e) => setNumber(formatCardNumber(e.target.value))}\n onBlur={() => markTouched('number')}\n />\n <input\n className={inputClassName}\n style={{ ...blend, width: 64, textAlign: 'center' }}\n inputMode=\"numeric\"\n autoComplete=\"cc-exp\"\n placeholder=\"MM / YY\"\n aria-invalid={Boolean(show('expiry'))}\n value={expiry}\n onChange={(e) => setExpiry(formatExpiry(e.target.value))}\n onBlur={() => markTouched('expiry')}\n />\n <input\n className={inputClassName}\n style={{ ...blend, width: 44, textAlign: 'center' }}\n inputMode=\"numeric\"\n autoComplete=\"cc-csc\"\n placeholder=\"CVC\"\n aria-invalid={Boolean(show('cvc'))}\n value={cvc}\n onChange={(e) => setCvc(formatCvc(e.target.value))}\n onBlur={() => markTouched('cvc')}\n />\n </div>\n )\n}\n","/**\n * `<CheckoutProvider>` — wrap your checkout UI once. It:\n * - provides the checkout to every section via context — so `<Tickets/>`,\n * `<Payment/>`, … just read it, no prop-drilling. By default it runs\n * `useCheckout()` for you (the web-wired engine: Stripe/Xendit + shared\n * store); pass your own instance as `value` to bring your own;\n * - applies the `theme` as `--tf-checkout-*` CSS variables on its root and\n * scopes all styles under `.tf-checkout`.\n *\n * This is the single styling + context boundary shared by all three usage\n * tiers: the batteries-included `<EmbeddedCheckout/>`, à-la-carte sections, and (via\n * `value`) a consumer who already holds a `useCheckout()` of their own.\n *\n * Styles load automatically from the package entry point.\n */\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport type { LocaleCode, Messages, UseCheckout } from 'tf-checkout-shared'\n\nimport { useCheckout } from '../useCheckout'\nimport { cx } from './cx'\nimport { I18nProvider } from './I18nProvider'\nimport { useInstallmentPicker } from './InstallmentPicker'\nimport { themeToVars, type CheckoutTheme } from './theme'\n\nconst CheckoutCtx = createContext<UseCheckout | null>(null)\nconst CheckoutValidationCtx = createContext<{\n attempt: number\n requestValidation: () => void\n} | null>(null)\n\nexport interface CheckoutProviderProps {\n /**\n * Bring your own checkout instance (from a top-level `useCheckout()`). Omit\n * and the provider runs `useCheckout()` itself. Either way the sections read\n * the same shared cart (the engine store is a module singleton).\n */\n value?: UseCheckout\n /** Retheme via design tokens. */\n theme?: CheckoutTheme\n /**\n * Language for the checkout's own copy. Defaults to `en-GB`, so omitting it\n * leaves every existing consumer's rendering byte-for-byte unchanged.\n */\n locale?: LocaleCode\n /**\n * Per-key overrides merged over the locale, for brands that need to reword\n * individual strings without shipping a whole catalogue.\n */\n messages?: Partial<Messages>\n /** Extra class on the `.tf-checkout` root. */\n className?: string\n children: ReactNode\n}\n\n/** The `.tf-checkout` root + context — given a resolved checkout instance. */\nconst CheckoutRoot: FC<{\n checkout: UseCheckout\n theme?: CheckoutTheme\n className?: string\n children: ReactNode\n}> = ({ checkout, theme, className, children }) => {\n const rootRef = useRef<HTMLDivElement | null>(null)\n const [attempt, setAttempt] = useState(0)\n const requestValidation = useCallback(() => setAttempt((current) => current + 1), [])\n\n // Every section marks its own invalid controls. Keeping the navigation here\n // makes validation work for EmbeddedCheckout and for consumers composing the\n // sections themselves.\n useEffect(() => {\n if (attempt === 0) return\n const frame = window.requestAnimationFrame(() => {\n const invalid = rootRef.current?.querySelector<HTMLElement>(\n '[data-checkout-invalid=\"true\"]'\n )\n if (!invalid) return\n const behavior = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n ? 'auto'\n : 'smooth'\n invalid.scrollIntoView({ behavior, block: 'center' })\n const focusTarget = invalid.matches('input, select, textarea, button')\n ? invalid\n : invalid.querySelector<HTMLElement>('input, select, textarea, button')\n focusTarget?.focus({ preventScroll: true })\n })\n return () => window.cancelAnimationFrame(frame)\n }, [attempt])\n\n return (\n <CheckoutCtx.Provider value={checkout}>\n <CheckoutValidationCtx.Provider value={{ attempt, requestValidation }}>\n <div\n ref={rootRef}\n className={cx(\n 'tf-checkout',\n // No colorScheme → auto-follow the OS/browser (prefers-color-scheme).\n // Set it to force one: 'dark' → --dark, 'light' → --light (opt out of auto-dark).\n theme?.colorScheme === 'dark' && 'tf-checkout--dark',\n theme?.colorScheme === 'light' && 'tf-checkout--light',\n className\n )}\n style={themeToVars(theme)}\n >\n {children}\n </div>\n </CheckoutValidationCtx.Provider>\n </CheckoutCtx.Provider>\n )\n}\n\n/** Default path: the provider owns the `useCheckout()` call. Wires the MSI\n * installment picker so Mexican card payments can split into installments. */\nconst SelfProvidedCheckout: FC<Omit<CheckoutProviderProps, 'value'>> = ({\n children,\n ...rest\n}) => {\n const { onInstallmentOffers, picker } = useInstallmentPicker()\n const checkout = useCheckout({ ports: { onInstallmentOffers } })\n return (\n <CheckoutRoot checkout={checkout} {...rest}>\n {children}\n {picker}\n </CheckoutRoot>\n )\n}\n\nexport const CheckoutProvider: FC<CheckoutProviderProps> = ({\n value,\n locale,\n messages,\n ...rest\n}) => (\n // I18n wraps the whole checkout tree so every section can call `useT()`.\n // Outside CheckoutRoot so the translator is in scope for the provider's own\n // children as well as the sections.\n <I18nProvider locale={locale} messages={messages}>\n {\n // `value` present ⇒ don't call `useCheckout()` at all (no second\n // binding); absent ⇒ the self-providing branch owns it. The choice is\n // static per mount, so the two branches never swap and violate the rules\n // of hooks.\n value ? <CheckoutRoot checkout={value} {...rest} /> : <SelfProvidedCheckout {...rest} />\n }\n </I18nProvider>\n)\n\n/** Read the shared checkout inside any component under `<CheckoutProvider>`. */\nexport const useCheckoutContext = (): UseCheckout => {\n const ctx = useContext(CheckoutCtx)\n if (!ctx) {\n throw new Error('useCheckoutContext must be used within <CheckoutProvider>.')\n }\n return ctx\n}\n\n/** Coordinate submit-attempt validation across separately composed sections. */\nexport const useCheckoutValidation = () => {\n const ctx = useContext(CheckoutValidationCtx)\n if (!ctx) {\n throw new Error('useCheckoutValidation must be used within <CheckoutProvider>.')\n }\n return ctx\n}\n","/** Join truthy class names (tiny, dependency-free). */\nexport const cx = (...parts: Array<string | false | null | undefined>): string =>\n parts.filter(Boolean).join(' ')\n","import React, { createContext, useContext, useMemo, type FC, type ReactNode } from 'react'\nimport {\n createTranslator,\n DEFAULT_LOCALE,\n type LocaleCode,\n type Messages,\n type Translate,\n} from 'tf-checkout-shared'\n\n/**\n * React binding for the shared core's translator.\n *\n * The resolution itself lives in `tf-checkout-shared` so native gets the same\n * behaviour; this file only carries it through React context.\n *\n * The default context value is a real English translator, not null, so any\n * component calling `useT()` outside a provider still renders correct copy.\n * That keeps this change backwards compatible: a host that never passes\n * `locale` sees exactly the strings it saw before.\n */\nconst I18nCtx = createContext<Translate>(createTranslator({ locale: DEFAULT_LOCALE }))\n\nexport interface I18nProviderProps {\n locale?: LocaleCode\n /** Per-key overrides, merged over the locale. */\n messages?: Partial<Messages>\n children?: ReactNode\n}\n\nexport const I18nProvider: FC<I18nProviderProps> = ({ locale, messages, children }) => {\n const t = useMemo(() => createTranslator({ locale, messages }), [locale, messages])\n return <I18nCtx.Provider value={t}>{children}</I18nCtx.Provider>\n}\n\n/** Returns the active translator. Safe to call anywhere in the SDK tree. */\nexport const useT = (): Translate => useContext(I18nCtx)\n","/**\n * MSI (meses sin intereses) picker. Mexican card payments can be split into\n * interest-free installments: mid-payment the engine calls `onInstallmentOffers`\n * with the available plans and waits for the buyer's choice. This hook bridges\n * that callback to an overlay — `<CheckoutProvider>` wires it by default, so\n * `<EmbeddedCheckout/>` gets MSI for free. Returns the port + the overlay to render.\n */\nimport React, { useCallback, useState } from 'react'\n\nimport type { InstallmentOffer } from 'tf-checkout-shared'\n\nimport { Button } from './Button'\n\nexport const useInstallmentPicker = () => {\n const [pending, setPending] = useState<{\n offers: InstallmentOffer[]\n resolve: (o: InstallmentOffer | null) => void\n } | null>(null)\n\n // Stable across renders (useCheckout reads ports once) — resolves when the\n // buyer picks a plan (or declines) below.\n const onInstallmentOffers = useCallback(\n (offers: InstallmentOffer[]) =>\n new Promise<InstallmentOffer | null>((resolve) => setPending({ offers, resolve })),\n []\n )\n\n const choose = (o: InstallmentOffer | null) => {\n pending?.resolve(o)\n setPending(null)\n }\n\n const picker = pending ? (\n <div\n className=\"tf-checkout-installments\"\n role=\"dialog\"\n aria-label=\"Choose installments\"\n >\n <div className=\"tf-checkout-installments__box\">\n <strong>Pay in installments?</strong>\n <div className=\"tf-checkout-installments__list\">\n {pending.offers.map((o, i) => (\n <button\n key={i}\n type=\"button\"\n className=\"tf-checkout-installments__opt\"\n onClick={() => choose(o)}\n >\n <span>\n {o.count} × {o.per_installment_formatted ?? o.per_installment}\n </span>\n <span className=\"tf-checkout-installments__meta\">\n {o.total_formatted ? `${o.total_formatted} total` : ''}\n {o.diff_from_original_formatted\n ? ` · ${o.diff_from_original_formatted}`\n : ''}\n </span>\n </button>\n ))}\n </div>\n <Button variant=\"ghost\" block onClick={() => choose(null)}>\n Pay in full instead\n </Button>\n </div>\n </div>\n ) : null\n\n return { onInstallmentOffers, picker }\n}\n","import React, { forwardRef, type ButtonHTMLAttributes } from 'react'\n\nimport { cx } from './cx'\nimport { Loader } from './Loader'\n\nexport interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n /** Visual weight. */\n variant?: 'primary' | 'secondary' | 'ghost'\n /** Stretch to full width. */\n block?: boolean\n /** Show a spinner and disable. */\n loading?: boolean\n}\n\n/** The one shared button — token-driven variants, loading state, `className`. */\nexport const Button = forwardRef<HTMLButtonElement, ButtonProps>(\n (\n { variant = 'primary', block, loading, className, disabled, children, ...rest },\n ref\n ) => (\n <button\n ref={ref}\n type=\"button\"\n className={cx(\n 'tf-checkout-button',\n `tf-checkout-button--${variant}`,\n block && 'tf-checkout-button--block',\n className\n )}\n disabled={disabled || loading}\n {...rest}\n >\n {loading && <Loader />}\n {children}\n </button>\n )\n)\nButton.displayName = 'Button'\n","import React, { type FC } from 'react'\n\nimport { cx } from './cx'\n\n/** A spinner that inherits `currentColor` (so it works inside buttons/text). */\nexport const Loader: FC<{ className?: string }> = ({ className }) => (\n <span\n className={cx('tf-checkout-loader', className)}\n role=\"status\"\n aria-label=\"Loading\"\n />\n)\n","/**\n * The checkout theme — a structured, documented token set. Pass any subset to\n * `<CheckoutProvider theme={…}>`; each token maps to a `--tf-checkout-*` CSS\n * custom property that `checkout.css` (and every component) reads. Anything you\n * omit falls back to the stylesheet default.\n */\nimport type { CSSProperties } from 'react'\n\nexport interface CheckoutTheme {\n /** `'dark'` adds the `tf-checkout--dark` class (dark default palette). */\n colorScheme?: 'light' | 'dark'\n\n // color\n /** Primary color — buttons, step badges, focus ring, links. */\n accent?: string\n /** Hover state for `accent` (defaults near `accent`). */\n accentHover?: string\n /** Text/icon color on top of `accent`. */\n accentContrast?: string\n /** Card background. */\n surface?: string\n /** Subtle fill (summary rows, muted pills). */\n surfaceMuted?: string\n /** Primary text. */\n text?: string\n /** Secondary text (labels, \"incl. fees\", hints). */\n muted?: string\n /** Borders + dividers. */\n border?: string\n /** Error text + invalid field borders. */\n error?: string\n /** Success (confirmation check). */\n success?: string\n\n // shape\n /** Corner radius for cards. */\n radiusCard?: string\n /** Corner radius for inputs / buttons. */\n radiusControl?: string\n /** Card shadow. */\n shadow?: string\n\n // type\n /** Font family for the whole component tree. */\n font?: string\n /** Base font size (e.g. `15px`). */\n fontSize?: string\n\n // layout\n /** Max width of the checkout column. */\n maxWidth?: string\n}\n\nconst MAP: Record<keyof Omit<CheckoutTheme, 'colorScheme'>, string> = {\n accent: '--tf-checkout-accent',\n accentHover: '--tf-checkout-accent-hover',\n accentContrast: '--tf-checkout-accent-contrast',\n surface: '--tf-checkout-surface',\n surfaceMuted: '--tf-checkout-surface-muted',\n text: '--tf-checkout-text',\n muted: '--tf-checkout-muted',\n border: '--tf-checkout-border',\n error: '--tf-checkout-error',\n success: '--tf-checkout-success',\n radiusCard: '--tf-checkout-radius-card',\n radiusControl: '--tf-checkout-radius-control',\n shadow: '--tf-checkout-shadow',\n font: '--tf-checkout-font',\n fontSize: '--tf-checkout-font-size',\n maxWidth: '--tf-checkout-max-width',\n}\n\n/** Turn a theme into inline `--tf-checkout-*` custom properties for the root. */\nexport const themeToVars = (theme?: CheckoutTheme): CSSProperties => {\n const out: Record<string, string> = {}\n if (theme) {\n for (const key of Object.keys(MAP) as (keyof typeof MAP)[]) {\n const value = theme[key]\n if (value != null) out[MAP[key]] = value\n }\n }\n return out as CSSProperties\n}\n","/**\n * `Card` + `SectionHeader` — the shell every checkout section shares: a rounded\n * surface with a numbered step badge, a title, and optional right-aligned pills\n * (totals, a countdown, a loading chip). Keeps all sections visually identical\n * without each re-authoring the header markup.\n */\nimport React, { type FC, type HTMLAttributes, type ReactNode } from 'react'\n\nimport { cx } from './cx'\n\nexport interface CardProps extends HTMLAttributes<HTMLDivElement> {\n className?: string\n}\n\n/** A themed surface (`.tf-checkout-card`). Spreads through any div props. */\nexport const Card: FC<CardProps> = ({ className, children, ...rest }) => (\n <div className={cx('tf-checkout-card', className)} {...rest}>\n {children}\n </div>\n)\n\nexport interface SectionHeaderProps {\n /** Badge content — a step number, an icon, `✓`. Omit for no badge. */\n step?: ReactNode\n title: ReactNode\n /** Right-aligned chips (total, timer, \"loading…\"). */\n pills?: ReactNode\n className?: string\n}\n\nexport const SectionHeader: FC<SectionHeaderProps> = ({\n step,\n title,\n pills,\n className,\n}) => (\n <div className={cx('tf-checkout-card__header', className)}>\n {step != null && <span className=\"tf-checkout-card__step\">{step}</span>}\n <span className=\"tf-checkout-card__title\">{title}</span>\n {pills != null && <span className=\"tf-checkout-card__pills\">{pills}</span>}\n </div>\n)\n\n/** A single right-aligned chip for a `SectionHeader`'s `pills`. */\nexport const Pill: FC<{ muted?: boolean; children: ReactNode }> = ({\n muted,\n children,\n}) => (\n <span\n className={cx('tf-checkout-card__pill', muted && 'tf-checkout-card__pill--muted')}\n >\n {children}\n </span>\n)\n","import React, {\n forwardRef,\n type FC,\n type InputHTMLAttributes,\n type ReactNode,\n type SelectHTMLAttributes,\n type TextareaHTMLAttributes,\n} from 'react'\n\nimport { cx } from './cx'\n\n/** Labeled wrapper — owns the label + error row so controls stay consistent. */\nexport const Field: FC<{\n label?: ReactNode\n error?: ReactNode\n invalid?: boolean\n className?: string\n children: ReactNode\n}> = ({ label, error, invalid, className, children }) => (\n <label\n className={cx(\n 'tf-checkout-field',\n invalid && 'tf-checkout-field--invalid',\n className\n )}\n data-checkout-invalid={invalid || undefined}\n >\n {label != null && <span className=\"tf-checkout-field__label\">{label}</span>}\n {children}\n {error != null && (\n <span className=\"tf-checkout-field__error\" role=\"alert\">\n {error}\n </span>\n )}\n </label>\n)\n\n/** Lay out two fields side by side. */\nexport const FieldRow: FC<{ className?: string; children: ReactNode }> = ({\n className,\n children,\n}) => (\n <div className={cx('tf-checkout-field', 'tf-checkout-field--row', className)}>\n {children}\n </div>\n)\n\nexport interface InputProps extends InputHTMLAttributes<HTMLInputElement> {\n invalid?: boolean\n}\nexport const Input = forwardRef<HTMLInputElement, InputProps>(\n ({ invalid, className, ...rest }, ref) => (\n <input\n ref={ref}\n className={cx(\n 'tf-checkout-input',\n invalid && 'tf-checkout-input--invalid',\n className\n )}\n {...rest}\n />\n )\n)\nInput.displayName = 'Input'\n\nexport interface TextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {\n invalid?: boolean\n}\nexport const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(\n ({ invalid, className, ...rest }, ref) => (\n <textarea\n ref={ref}\n className={cx(\n 'tf-checkout-input',\n 'tf-checkout-textarea',\n invalid && 'tf-checkout-input--invalid',\n className\n )}\n {...rest}\n />\n )\n)\nTextarea.displayName = 'Textarea'\n\nexport interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {\n invalid?: boolean\n}\nexport const Select = forwardRef<HTMLSelectElement, SelectProps>(\n ({ invalid, className, children, ...rest }, ref) => (\n <select\n ref={ref}\n className={cx(\n 'tf-checkout-select',\n invalid && 'tf-checkout-select--invalid',\n className\n )}\n {...rest}\n >\n {children}\n </select>\n )\n)\nSelect.displayName = 'Select'\n\nexport interface CheckboxProps extends InputHTMLAttributes<HTMLInputElement> {\n label?: ReactNode\n}\n/** A checkbox is its own label — don't wrap it in `<Field>`. */\nexport const Checkbox: FC<CheckboxProps> = ({ label, className, ...rest }) => (\n <label className={cx('tf-checkout-checkbox', className)}>\n <input type=\"checkbox\" className=\"tf-checkout-checkbox__box\" {...rest} />\n {label != null && <span className=\"tf-checkout-checkbox__label\">{label}</span>}\n </label>\n)\n","/**\n * Data-driven custom fields. The event describes what to collect\n * (`EventCustomField[]`, order- / ticket- / add-on-scoped); these render it —\n * text, textarea, phone, email, select, radio, checkbox, multi-select — and\n * report values back. No per-brand form code: pass the group, hold the values.\n *\n * const [vals, setVals] = useState<CustomFieldValues>({})\n * <CustomFieldGroupFields group={group} values={vals}\n * onChange={(name, v) => setVals(s => ({ ...s, [name]: v }))} />\n */\nimport React, { type FC, type ReactNode } from 'react'\n\nimport type {\n CustomFieldValues,\n EventCustomField,\n EventCustomFieldGroup,\n} from 'tf-checkout-shared'\nimport { ticketFieldsFor } from 'tf-checkout-shared'\n\nimport { Checkbox, Field, Input, Select, Textarea } from './Field'\n\ntype FieldValue = string | string[]\n\nconst asString = (v: FieldValue | undefined): string =>\n Array.isArray(v) ? (v[0] ?? '') : (v ?? '')\nconst asArray = (v: FieldValue | undefined): string[] =>\n Array.isArray(v) ? v : v ? [v] : []\n\nexport interface CustomFieldInputProps {\n field: EventCustomField\n value: FieldValue | undefined\n onChange: (value: FieldValue) => void\n error?: ReactNode\n}\n\n/** Render one custom field by its declared `type`. */\nexport const CustomFieldInput: FC<CustomFieldInputProps> = ({\n field,\n value,\n onChange,\n error,\n}) => {\n const label = `${field.label}${field.required ? ' *' : ''}`\n const invalid = error != null\n const desc = field.description ? (\n <span className=\"tf-checkout-field__hint\">{field.description}</span>\n ) : undefined\n\n switch (field.type) {\n case 'textarea':\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <Textarea\n value={asString(value)}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(e) => onChange(e.target.value)}\n />\n </Field>\n )\n case 'select':\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <Select\n value={asString(value)}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(e) => onChange(e.target.value)}\n >\n <option value=\"\">— select —</option>\n {field.options.map((o) => (\n <option key={o.id} value={o.value}>\n {o.name}\n </option>\n ))}\n </Select>\n </Field>\n )\n case 'radio':\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <div className=\"tf-checkout-choices\">\n {field.options.map((o) => (\n <label key={o.id} className=\"tf-checkout-choice\">\n <input\n type=\"radio\"\n name={field.name}\n checked={asString(value) === o.value}\n onChange={() => onChange(o.value)}\n />\n <span>{o.name}</span>\n </label>\n ))}\n </div>\n </Field>\n )\n case 'select_multi': {\n const picked = asArray(value)\n const toggle = (v: string, on: boolean) =>\n onChange(on ? [...picked, v] : picked.filter((x) => x !== v))\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <div className=\"tf-checkout-choices\">\n {field.options.map((o) => (\n <Checkbox\n key={o.id}\n checked={picked.includes(o.value)}\n onChange={(e) => toggle(o.value, e.target.checked)}\n label={o.name}\n />\n ))}\n </div>\n </Field>\n )\n }\n case 'checkbox':\n return (\n <div\n className={invalid ? 'tf-checkout-consent--error' : undefined}\n data-checkout-invalid={invalid || undefined}\n >\n <Checkbox\n checked={asString(value) === '1'}\n aria-invalid={invalid}\n onChange={(e) => onChange(e.target.checked ? '1' : '')}\n label={label}\n />\n {error != null && <div className=\"tf-checkout-consent__error\">{error}</div>}\n </div>\n )\n case 'image':\n // File capture needs an upload rail the SDK doesn't own yet — surface it\n // rather than silently dropping a required field.\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <span className=\"tf-checkout-note\">\n Image upload isn’t supported in this build.\n </span>\n </Field>\n )\n default:\n // text / phone / email\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <Input\n type={\n field.type === 'email' ? 'email' : field.type === 'phone' ? 'tel' : 'text'\n }\n value={asString(value)}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(e) => onChange(e.target.value)}\n />\n </Field>\n )\n }\n}\n\nexport interface CustomFieldGroupFieldsProps {\n group: EventCustomFieldGroup\n values: CustomFieldValues\n onChange: (name: string, value: FieldValue) => void\n /** Restrict to fields scoped to this holder's ticket type (ticket groups). */\n ticketTypeId?: string\n}\n\n/** Render every field in a group, wired to a values map. */\nexport const CustomFieldGroupFields: FC<CustomFieldGroupFieldsProps> = ({\n group,\n values,\n onChange,\n ticketTypeId,\n}) => (\n <>\n {ticketFieldsFor(group.fields, ticketTypeId).map((f) => (\n <CustomFieldInput\n key={f.id}\n field={f}\n value={values[f.name]}\n onChange={(v) => onChange(f.name, v)}\n />\n ))}\n </>\n)\n\n/** True when every required field in the group has a non-empty value.\n * Re-exported from the SDK so web, native and the engine preflight all apply\n * one rule (including its \"image uploads are server-authoritative\" carve-out). */\nexport { customFieldsComplete } from 'tf-checkout-shared'\n","/**\n * `<PaymentMethods>` — a controlled radio-list of payment methods (icon + label\n * per row), matching the hosted checkout's iconed selector. Presentational only:\n * it renders the choices + the selected row's extra input (and hosts a card\n * field in the card row via `children`/`inputSlotFor`). It does NOT own the Pay\n * button or `placeOrder` — `<Payment/>` builds the options and maps a selection\n * back to a `placeOrder` request.\n */\nimport React, { type FC, type ReactNode } from 'react'\n\nimport { cx } from './cx'\nimport { Field, Input } from './Field'\n\n// The method descriptor + row shape live in the SDK so both platforms render\n// the SAME option list. Imported for local use and re-exported for consumers\n// that already import them from here.\nimport type {\n PaymentMethodId,\n PaymentMethodOption,\n} from 'tf-checkout-shared'\n\nexport type { PaymentMethodId, PaymentMethodOption }\n\nexport interface PaymentMethodsProps {\n options: PaymentMethodOption[]\n /** Selected `option.value` (controlled). */\n selected: string\n onSelect: (value: string) => void\n /** Extra-field values keyed by `option.value`. */\n extraValues: Record<string, { cashtag?: string; phoneNumber?: string }>\n onExtraChange: (\n value: string,\n patch: { cashtag?: string; phoneNumber?: string }\n ) => void\n /** Reveal required extra-field errors after the buyer attempts payment. */\n showValidation?: boolean\n /** Rendered inside the row whose `value === inputSlotFor` (e.g. `<CardInput/>`). */\n children?: ReactNode\n inputSlotFor?: string\n className?: string\n}\n\nconst EXTRA_LABEL: Record<'cashtag' | 'phoneNumber', string> = {\n cashtag: 'Jenius $cashtag',\n phoneNumber: 'OVO phone number',\n}\n\nexport const PaymentMethods: FC<PaymentMethodsProps> = ({\n options,\n selected,\n onSelect,\n extraValues,\n onExtraChange,\n showValidation = false,\n children,\n inputSlotFor,\n className,\n}) => (\n <div\n className={cx('tf-checkout-payment__methods', className)}\n role=\"radiogroup\"\n aria-label=\"Payment method\"\n >\n {options.map((o) => {\n const isSelected = o.value === selected\n const extraValue =\n o.extra === 'phoneNumber'\n ? extraValues[o.value]?.phoneNumber\n : extraValues[o.value]?.cashtag\n const extraInvalid =\n Boolean(isSelected && o.extra && showValidation) && !extraValue?.trim()\n return (\n <label\n key={o.value}\n className={cx(\n 'tf-checkout-payment__method',\n isSelected && 'tf-checkout-payment__method--selected'\n )}\n >\n <span className=\"tf-checkout-payment__method-head\">\n <input\n type=\"radio\"\n name=\"tf-pay-method\"\n className=\"tf-checkout-payment__method-radio\"\n checked={isSelected}\n onChange={() => onSelect(o.value)}\n />\n {o.iconUrl && (\n <img className=\"tf-checkout-payment__method-icon\" src={o.iconUrl} alt=\"\" />\n )}\n <span className=\"tf-checkout-payment__method-label\">{o.label}</span>\n </span>\n\n {isSelected && (o.value === inputSlotFor || o.extra) && (\n <div className=\"tf-checkout-payment__method-body\">\n {o.value === inputSlotFor && children}\n {o.extra && (\n <Field\n label={`${EXTRA_LABEL[o.extra]} *`}\n error={extraInvalid ? 'This field is required.' : undefined}\n invalid={extraInvalid}\n >\n <Input\n inputMode={o.extra === 'phoneNumber' ? 'tel' : 'text'}\n required\n invalid={extraInvalid}\n aria-invalid={extraInvalid}\n placeholder={\n o.extra === 'phoneNumber' ? 'e.g. 081234567890' : '$cashtag'\n }\n value={\n o.extra === 'phoneNumber'\n ? (extraValues[o.value]?.phoneNumber ?? '')\n : (extraValues[o.value]?.cashtag ?? '')\n }\n onChange={(e) =>\n onExtraChange(\n o.value,\n o.extra === 'phoneNumber'\n ? { phoneNumber: e.target.value }\n : { cashtag: e.target.value }\n )\n }\n />\n </Field>\n )}\n </div>\n )}\n </label>\n )\n })}\n </div>\n)\n","import React, { type FC } from 'react'\n\nimport { cx } from './cx'\n\n/** Quantity ± control (ticket / add-on quantities). */\nexport const Stepper: FC<{\n value: number\n onChange: (value: number) => void\n min?: number\n max?: number\n step?: number\n disabled?: boolean\n className?: string\n}> = ({ value, onChange, min = 0, max = Infinity, step = 1, disabled, className }) => (\n <div className={cx('tf-checkout-stepper', className)}>\n <button\n type=\"button\"\n className=\"tf-checkout-stepper__btn\"\n aria-label=\"Decrease\"\n disabled={disabled || value <= min}\n onClick={() => onChange(Math.max(min, value - step))}\n >\n −\n </button>\n <span className=\"tf-checkout-stepper__value\">{value}</span>\n <button\n type=\"button\"\n className=\"tf-checkout-stepper__btn\"\n aria-label=\"Increase\"\n disabled={disabled || value >= max}\n onClick={() => onChange(Math.min(max, value + step))}\n >\n +\n </button>\n </div>\n)\n","/**\n * `<QuantitySelect>` — a compact quantity dropdown (0…max), the control the old\n * checkout used for tickets and add-ons (not a +/- stepper).\n */\nimport React, { type FC } from 'react'\n\nimport { cx } from './cx'\n\nexport interface QuantitySelectProps {\n value: number\n onChange: (value: number) => void\n /** Minimum purchasable quantity when buying (0 = none is always allowed). */\n min?: number\n max?: number\n /** Step between options (the old checkout's `multiplier`). */\n step?: number\n disabled?: boolean\n className?: string\n}\n\nexport const QuantitySelect: FC<QuantitySelectProps> = ({\n value,\n onChange,\n min = 0,\n max = 10,\n step = 1,\n disabled,\n className,\n}) => {\n // 0 (buy none) is always offered; the first non-zero option honors the ticket's\n // minimum, then steps up to the cap — so a min-2 type offers 0, 2, 3, … not 1.\n const cap = Math.min(max, 50)\n const lo = Math.max(1, min)\n const options: number[] = [0]\n for (let n = lo; n <= cap; n += step) options.push(n)\n return (\n <select\n className={cx('tf-checkout-qty', className)}\n value={value}\n disabled={disabled}\n onChange={(e) => onChange(Number(e.target.value))}\n >\n {options.map((n) => (\n <option key={n} value={n}>\n {n}\n </option>\n ))}\n </select>\n )\n}\n","import React, { type FC, type ReactNode } from 'react'\n\nimport { cx } from './cx'\n\n/** A price with optional struck-through original + a fees/deposit note. */\nexport const PriceLine: FC<{\n currency?: string\n amount: number | string\n /** Struck-through pre-discount price. */\n original?: number | string\n /** e.g. \"incl. fees\" or \"50% deposit\". */\n note?: ReactNode\n className?: string\n}> = ({ currency, amount, original, note, className }) => (\n <span className={cx('tf-checkout-price', className)}>\n {original != null && (\n <span className=\"tf-checkout-price__original\">\n {currency} {original}\n </span>\n )}\n {currency} {amount}\n {note != null && <span className=\"tf-checkout-price__fees\">{note}</span>}\n </span>\n)\n","import React, { type FC, type ReactNode } from 'react'\n\nimport { cx } from './cx'\n\nconst clock = (s: number) => {\n const v = Math.max(0, Math.floor(s))\n return v >= 3600\n ? `${Math.floor(v / 3600)}:${String(Math.floor((v % 3600) / 60)).padStart(\n 2,\n '0'\n )}:${String(v % 60).padStart(2, '0')}`\n : `${Math.floor(v / 60)}:${String(v % 60).padStart(2, '0')}`\n}\n\n/** Reservation countdown. Pass `checkout.secondsLeft`. */\nexport const Timer: FC<{\n seconds: number\n /** Below this many seconds it turns urgent (default 60). */\n urgentAt?: number\n /** Text before the clock, e.g. \"Reserved for\". */\n label?: ReactNode\n className?: string\n}> = ({ seconds, urgentAt = 60, label, className }) => (\n <span\n className={cx(\n 'tf-checkout-timer',\n seconds <= urgentAt && 'tf-checkout-timer--urgent',\n className\n )}\n >\n {label != null && <span>{label}</span>}\n {clock(seconds)}\n </span>\n)\n","/**\n * `<TimerBanner>` — the reservation countdown banner the old checkout showed at\n * the top of the add-ons / billing / payment steps: \"Please complete your\n * purchase before the timer reaches zero.\" + mm:ss, with a dismiss X. Feed it\n * `checkout.secondsLeft`. Renders nothing when there's no live reservation.\n */\nimport React, { useState, type FC } from 'react'\n\nimport { cx } from './cx'\n\nconst clock = (s: number) => {\n const m = String(Math.floor(s / 60)).padStart(2, '0')\n const ss = String(s % 60).padStart(2, '0')\n return `${m}:${ss}`\n}\n\nexport interface TimerBannerProps {\n seconds?: number\n /** Show red styling at/under this many seconds. Default 60. */\n urgentAt?: number\n message?: string\n className?: string\n}\n\nexport const TimerBanner: FC<TimerBannerProps> = ({\n seconds,\n urgentAt = 60,\n message = 'Please complete your purchase before the timer reaches zero.',\n className,\n}) => {\n const [dismissed, setDismissed] = useState(false)\n if (seconds === undefined || seconds <= 0 || dismissed) return null\n const urgent = seconds <= urgentAt\n return (\n <div\n role=\"status\"\n className={cx(\n 'tf-checkout-timerbanner',\n urgent && 'tf-checkout-timerbanner--urgent',\n className\n )}\n >\n <span className=\"tf-checkout-timerbanner__msg\">{message}</span>\n <span className=\"tf-checkout-timerbanner__clock\">{clock(seconds)}</span>\n <button\n type=\"button\"\n className=\"tf-checkout-timerbanner__close\"\n aria-label=\"Dismiss\"\n onClick={() => setDismissed(true)}\n >\n ×\n </button>\n </div>\n )\n}\n","import { useT } from '../ui/I18nProvider'\nimport React, { useCallback, useEffect, useRef, type FC, type MouseEvent } from 'react'\n\nimport { hooks, type AuthFlowView, type TfProfile } from 'tf-checkout-shared'\n\nimport { cx } from '../ui/cx'\nimport { ForgotPasswordForm } from './ForgotPasswordForm'\nimport { LoginForm } from './LoginForm'\nimport { RegisterForm } from './RegisterForm'\n\nconst DEFAULT_LOGO = 'https://www.ticketfairy.com/resources/images/logo-ttf-black.svg'\n\nexport interface AuthModalProps {\n open: boolean\n onClose: () => void\n initialView?: AuthFlowView\n initialEmail?: string\n /** Optional context shown above the active form. */\n message?: string\n allowRegistration?: boolean\n allowPasswordReset?: boolean\n requireRegistrationAddress?: boolean\n /** Extra backend fields for specialized registrations such as delegations. */\n registrationFields?: Record<string, string>\n logoUrl?: string\n onAuthenticated?: (profile: TfProfile) => void\n className?: string\n}\n\n/** Accessible web presentation over `hooks.useAuthFlow()`. Render it inside\n * `<CheckoutProvider>` so it inherits the checkout theme tokens. */\nexport const AuthModal: FC<AuthModalProps> = ({\n open,\n onClose,\n initialView = 'login',\n initialEmail,\n message,\n allowRegistration = true,\n allowPasswordReset = true,\n requireRegistrationAddress = true,\n registrationFields,\n logoUrl = DEFAULT_LOGO,\n onAuthenticated,\n className,\n}) => {\n const t = useT()\n const closeAfterAuth = useCallback(\n (profile: TfProfile) => {\n onAuthenticated?.(profile)\n onClose()\n },\n [onAuthenticated, onClose]\n )\n const auth = hooks.useAuthFlow({\n initialView: initialView === 'register' && !allowRegistration ? 'login' : initialView,\n initialEmail,\n requireRegistrationAddress,\n registrationFields,\n onAuthenticated: closeAfterAuth,\n })\n const dialogRef = useRef<HTMLDivElement | null>(null)\n const previouslyFocused = useRef<HTMLElement | null>(null)\n const submittingRef = useRef(auth.isSubmitting)\n submittingRef.current = auth.isSubmitting\n // Consumers pass `onClose` as an inline arrow, so its identity changes on\n // every parent render — and the parent re-renders once a second while the\n // reservation timer counts down. Held in a ref so the setup effect below can\n // depend on `open` alone; with `onClose` in its deps it tore down and re-ran\n // each tick, stealing focus back to the first field mid-typing.\n const onCloseRef = useRef(onClose)\n onCloseRef.current = onClose\n\n useEffect(() => {\n if (!open) return\n previouslyFocused.current = document.activeElement as HTMLElement | null\n const previousOverflow = document.body.style.overflow\n document.body.style.overflow = 'hidden'\n const focusable = () =>\n Array.from(\n dialogRef.current?.querySelectorAll<HTMLElement>(\n 'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex=\"-1\"])'\n ) ?? []\n ).filter((element) => element.offsetParent !== null)\n const initialFocus =\n dialogRef.current?.querySelector<HTMLElement>(\n 'input:not([disabled]), select:not([disabled]), textarea:not([disabled])'\n ) ??\n focusable()[0] ??\n dialogRef.current\n initialFocus?.focus()\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape' && !submittingRef.current) onCloseRef.current()\n if (event.key !== 'Tab') return\n const elements = focusable()\n if (elements.length === 0) {\n event.preventDefault()\n dialogRef.current?.focus()\n return\n }\n const first = elements[0]\n const last = elements[elements.length - 1]\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault()\n last.focus()\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault()\n first.focus()\n }\n }\n document.addEventListener('keydown', onKeyDown)\n return () => {\n document.removeEventListener('keydown', onKeyDown)\n document.body.style.overflow = previousOverflow\n previouslyFocused.current?.focus()\n }\n }, [open])\n\n if (!open) return null\n\n const closeFromBackdrop = (event: MouseEvent<HTMLDivElement>) => {\n if (event.target === event.currentTarget && !auth.isSubmitting) onClose()\n }\n const isPasswordReset = auth.view === 'forgot-password'\n const title = isPasswordReset ? 'Password reset' : 'Ticket Fairy account'\n\n return (\n <div className={cx('tf-checkout-auth', className)} onMouseDown={closeFromBackdrop}>\n <div\n ref={dialogRef}\n className=\"tf-checkout-auth__dialog\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={isPasswordReset ? undefined : title}\n aria-labelledby={isPasswordReset ? 'tf-checkout-auth-title' : undefined}\n tabIndex={-1}\n >\n <button\n type=\"button\"\n className=\"tf-checkout-auth__close\"\n aria-label={t('common.close')}\n disabled={auth.isSubmitting}\n onClick={onClose}\n >\n ×\n </button>\n {allowRegistration && !isPasswordReset && (\n <div\n className=\"tf-checkout-auth__tabs\"\n role=\"tablist\"\n aria-label={t('auth.title')}\n >\n <button\n type=\"button\"\n role=\"tab\"\n aria-selected={auth.view === 'login'}\n className={cx(\n 'tf-checkout-auth__tab',\n auth.view === 'login' && 'tf-checkout-auth__tab--active'\n )}\n onClick={() => auth.showLogin(auth.suggestedEmail)}\n >\n Login\n </button>\n <button\n type=\"button\"\n role=\"tab\"\n aria-selected={auth.view === 'register'}\n className={cx(\n 'tf-checkout-auth__tab',\n auth.view === 'register' && 'tf-checkout-auth__tab--active'\n )}\n onClick={() => auth.showRegister(auth.suggestedEmail)}\n >\n Sign Up\n </button>\n </div>\n )}\n\n {logoUrl && (\n <div className=\"tf-checkout-auth__logo-wrap\">\n <img\n className=\"tf-checkout-auth__logo\"\n src={logoUrl}\n alt=\"The Ticket Fairy\"\n />\n </div>\n )}\n\n {isPasswordReset && (\n <h2 id=\"tf-checkout-auth-title\" className=\"tf-checkout-auth__title\">\n {title}\n </h2>\n )}\n\n {message && !isPasswordReset && (\n <p className=\"tf-checkout-auth__message\">{message}</p>\n )}\n\n {auth.view === 'login' && (\n <LoginForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n loading={auth.isSubmitting}\n allowPasswordReset={allowPasswordReset}\n onSubmit={auth.submitLogin}\n onForgotPassword={auth.showForgotPassword}\n onFieldChange={auth.clearFieldError}\n />\n )}\n {auth.view === 'register' && allowRegistration && (\n <RegisterForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n loading={auth.isSubmitting}\n requireAddress={requireRegistrationAddress}\n onSubmit={auth.submitRegistration}\n onFieldChange={auth.clearFieldError}\n />\n )}\n {auth.view === 'forgot-password' && (\n <ForgotPasswordForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n successMessage={auth.successMessage}\n loading={auth.isSubmitting}\n onSubmit={auth.submitPasswordReset}\n onBackToLogin={auth.showLogin}\n onFieldChange={() => auth.clearFieldError('email')}\n />\n )}\n </div>\n </div>\n )\n}\n","import { useT } from '../ui/I18nProvider'\nimport React, { useEffect, useState, type FC, type FormEvent } from 'react'\n\nimport type { AuthFieldErrors } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Field, Input } from '../ui/Field'\n\nexport interface ForgotPasswordFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n successMessage?: string\n loading?: boolean\n onSubmit: (email: string) => void | Promise<unknown>\n onBackToLogin: (email: string) => void\n onFieldChange?: () => void\n}\n\n/** Password-recovery presentation over the shared auth-flow controller. */\nexport const ForgotPasswordForm: FC<ForgotPasswordFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n successMessage,\n loading = false,\n onSubmit,\n onBackToLogin,\n onFieldChange,\n}) => {\n const t = useT()\n const [email, setEmail] = useState(initialEmail)\n\n useEffect(() => {\n if (initialEmail && !email) setEmail(initialEmail)\n }, [email, initialEmail])\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n void onSubmit(email)\n }\n\n if (successMessage) {\n return (\n <div className=\"tf-checkout-auth__form\">\n <div className=\"tf-checkout-auth__success\" role=\"status\">\n {successMessage}\n </div>\n <Button type=\"button\" block onClick={() => onBackToLogin(email)}>\n Back to log in\n </Button>\n </div>\n )\n }\n\n return (\n <form className=\"tf-checkout-auth__form\" onSubmit={submit} noValidate>\n <p className=\"tf-checkout-auth__intro\">\n Enter your email and we’ll send you instructions to reset your password.\n </p>\n {error && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {error}\n </div>\n )}\n <Field label={t('auth.email')} error={errors.email}>\n <Input\n type=\"email\"\n name=\"email\"\n autoComplete=\"email\"\n autoFocus\n required\n value={email}\n invalid={Boolean(errors.email)}\n onChange={(event) => {\n setEmail(event.target.value)\n onFieldChange?.()\n }}\n />\n </Field>\n <Button type=\"submit\" block loading={loading}>\n Send reset instructions\n </Button>\n <button\n type=\"button\"\n className=\"tf-checkout-auth__text-button tf-checkout-auth__back\"\n onClick={() => onBackToLogin(email)}\n >\n Back to log in\n </button>\n </form>\n )\n}\n","import { useT } from '../ui/I18nProvider'\nimport React, { useEffect, useState, type FC, type FormEvent } from 'react'\n\nimport type { AuthFieldErrors, AuthLoginInput } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Field, Input } from '../ui/Field'\nimport { PasswordInput } from './PasswordInput'\n\nexport interface LoginFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n loading?: boolean\n allowPasswordReset?: boolean\n onSubmit: (input: AuthLoginInput) => void | Promise<unknown>\n onForgotPassword?: (email: string) => void\n onFieldChange?: (field: keyof AuthLoginInput) => void\n}\n\n/** Pure web form: it renders fields and delegates all auth work to its caller. */\nexport const LoginForm: FC<LoginFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n loading = false,\n allowPasswordReset = true,\n onSubmit,\n onForgotPassword,\n onFieldChange,\n}) => {\n const t = useT()\n const [email, setEmail] = useState(initialEmail)\n const [password, setPassword] = useState('')\n\n useEffect(() => {\n if (initialEmail && !email) setEmail(initialEmail)\n }, [email, initialEmail])\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n void onSubmit({ email, password })\n }\n\n return (\n <form className=\"tf-checkout-auth__form\" onSubmit={submit} noValidate>\n {error && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {error}\n </div>\n )}\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.email')}\n error={errors.email}\n >\n <Input\n type=\"email\"\n name=\"email\"\n placeholder={t('auth.emailPlaceholder')}\n autoComplete=\"email\"\n autoFocus\n required\n value={email}\n invalid={Boolean(errors.email)}\n onChange={(event) => {\n setEmail(event.target.value)\n onFieldChange?.('email')\n }}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.password')}\n error={errors.password}\n >\n <PasswordInput\n name=\"password\"\n placeholder={t('auth.passwordPlaceholder')}\n autoComplete=\"current-password\"\n required\n value={password}\n invalid={Boolean(errors.password)}\n onChange={(event) => {\n setPassword(event.target.value)\n onFieldChange?.('password')\n }}\n />\n </Field>\n <Button type=\"submit\" block loading={loading}>\n Login\n </Button>\n {allowPasswordReset && onForgotPassword && (\n <button\n type=\"button\"\n className=\"tf-checkout-auth__text-button tf-checkout-auth__forgot\"\n onClick={() => onForgotPassword(email)}\n >\n Forgot password?\n </button>\n )}\n </form>\n )\n}\n","import React, { forwardRef, useState } from 'react'\n\nimport { Input, type InputProps } from '../ui/Field'\n\n/** Password control with the same reveal affordance as the legacy checkout. */\nexport const PasswordInput = forwardRef<HTMLInputElement, InputProps>(\n ({ className, ...props }, ref) => {\n const [visible, setVisible] = useState(false)\n\n return (\n <span className=\"tf-checkout-auth__password\">\n <Input\n {...props}\n ref={ref}\n className={className}\n type={visible ? 'text' : 'password'}\n />\n <button\n type=\"button\"\n className=\"tf-checkout-auth__password-toggle\"\n aria-label={visible ? 'Hide password' : 'Show password'}\n aria-pressed={visible}\n onClick={() => setVisible((current) => !current)}\n >\n <svg aria-hidden=\"true\" viewBox=\"0 0 24 24\">\n <path d=\"M12 5c5.3 0 9.3 4.8 10.5 6.4a1 1 0 0 1 0 1.2C21.3 14.2 17.3 19 12 19S2.7 14.2 1.5 12.6a1 1 0 0 1 0-1.2C2.7 9.8 6.7 5 12 5Zm0 2c-3.8 0-7 3.2-8.4 5 1.4 1.8 4.6 5 8.4 5s7-3.2 8.4-5C19 10.2 15.8 7 12 7Zm0 2.1a2.9 2.9 0 1 1 0 5.8 2.9 2.9 0 0 1 0-5.8Z\" />\n </svg>\n </button>\n </span>\n )\n }\n)\nPasswordInput.displayName = 'PasswordInput'\n","import { useT } from '../ui/I18nProvider'\nimport React, { useEffect, useMemo, useState, type FC, type FormEvent } from 'react'\nimport { PhoneInput, type CountryIso2 } from 'react-international-phone'\n\nimport {\n hooks,\n type AuthFieldErrors,\n type AuthFieldName,\n type AuthRegistrationInput,\n} from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Field, FieldRow, Input, Select } from '../ui/Field'\nimport { PasswordInput } from './PasswordInput'\n\nexport interface RegisterFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n loading?: boolean\n requireAddress?: boolean\n onSubmit: (\n input: AuthRegistrationInput,\n options: { requireState: boolean }\n ) => void | Promise<unknown>\n onFieldChange?: (field: AuthFieldName) => void\n}\n\nconst emptyRegistration = (email: string): AuthRegistrationInput => ({\n firstName: '',\n lastName: '',\n email,\n password: '',\n passwordConfirmation: '',\n phone: '',\n streetAddress: '',\n city: '',\n zip: '',\n countryId: '',\n stateId: '',\n})\n\n/** Legacy-compatible account fields with no API or validation logic inside. */\nexport const RegisterForm: FC<RegisterFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n loading = false,\n requireAddress = true,\n onSubmit,\n onFieldChange,\n}) => {\n const t = useT()\n const [values, setValues] = useState<AuthRegistrationInput>(() =>\n emptyRegistration(initialEmail)\n )\n const countriesQuery = hooks.useCountries()\n const countries = useMemo(() => countriesQuery.data ?? [], [countriesQuery.data])\n const statesQuery = hooks.useStates(values.countryId, {\n enabled: requireAddress && Boolean(values.countryId),\n })\n const states = useMemo(() => statesQuery.data ?? [], [statesQuery.data])\n\n useEffect(() => {\n if (initialEmail && !values.email)\n setValues((current) => ({ ...current, email: initialEmail }))\n }, [initialEmail, values.email])\n\n // The old form defaults to the US. Resolve it by ISO code rather than the\n // old hard-coded country id so this remains backend/environment safe.\n useEffect(() => {\n if (!requireAddress || values.countryId || countries.length === 0) return\n const preferred =\n countries.find((country) => country.code?.toLowerCase() === 'us') ?? countries[0]\n setValues((current) => ({\n ...current,\n countryId: String(preferred.id),\n phone:\n current.phone || (preferred.code?.toLowerCase() === 'us' ? '+1' : current.phone),\n }))\n }, [countries, requireAddress, values.countryId])\n\n const patch = (next: Partial<AuthRegistrationInput>) =>\n setValues((current) => ({ ...current, ...next }))\n const setField = (field: AuthFieldName, value: string) => {\n setValues((current) => ({ ...current, [field]: value }))\n onFieldChange?.(field)\n }\n\n const selectedCountry = countries.find(\n (country) => String(country.id) === String(values.countryId)\n )\n const phoneCountry = (selectedCountry?.code?.toLowerCase() ?? 'us') as CountryIso2\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n void onSubmit(values, { requireState: states.length > 0 })\n }\n\n return (\n <form\n className=\"tf-checkout-auth__form tf-checkout-auth__form--register\"\n onSubmit={submit}\n noValidate\n >\n {error && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {error}\n </div>\n )}\n\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.firstName')}\n error={errors.firstName}\n >\n <Input\n name=\"firstName\"\n placeholder={t('auth.firstNamePlaceholder')}\n autoComplete=\"given-name\"\n autoFocus\n required\n value={values.firstName}\n invalid={Boolean(errors.firstName)}\n onChange={(event) => setField('firstName', event.target.value)}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.lastName')}\n error={errors.lastName}\n >\n <Input\n name=\"lastName\"\n placeholder={t('auth.lastNamePlaceholder')}\n autoComplete=\"family-name\"\n required\n value={values.lastName}\n invalid={Boolean(errors.lastName)}\n onChange={(event) => setField('lastName', event.target.value)}\n />\n </Field>\n </FieldRow>\n\n {requireAddress ? (\n <>\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.email')}\n error={errors.email}\n >\n <Input\n type=\"email\"\n name=\"email\"\n placeholder={t('auth.emailPlaceholder')}\n autoComplete=\"email\"\n required\n value={values.email}\n invalid={Boolean(errors.email)}\n onChange={(event) => setField('email', event.target.value)}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.streetAddress')}\n error={errors.streetAddress}\n >\n <Input\n name=\"streetAddress\"\n placeholder={t('auth.streetAddressPlaceholder')}\n autoComplete=\"street-address\"\n required\n value={values.streetAddress}\n invalid={Boolean(errors.streetAddress)}\n onChange={(event) => setField('streetAddress', event.target.value)}\n />\n </Field>\n </FieldRow>\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.postcode')}\n error={errors.zip}\n >\n <Input\n name=\"zip\"\n placeholder={t('auth.postcodePlaceholder')}\n autoComplete=\"postal-code\"\n required\n value={values.zip}\n invalid={Boolean(errors.zip)}\n onChange={(event) => setField('zip', event.target.value)}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__select-field\"\n label={t('auth.country')}\n error={errors.countryId}\n >\n <Select\n name=\"countryId\"\n autoComplete=\"country\"\n required\n value={values.countryId}\n invalid={Boolean(errors.countryId)}\n onChange={(event) => {\n patch({ countryId: event.target.value, stateId: '' })\n onFieldChange?.('countryId')\n onFieldChange?.('stateId')\n }}\n >\n <option value=\"\">{t('auth.selectCountry')}</option>\n {countries.map((country) => (\n <option key={country.id} value={country.id}>\n {country.name}\n </option>\n ))}\n </Select>\n </Field>\n </FieldRow>\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__select-field\"\n label={t('auth.state')}\n error={errors.stateId}\n >\n <Select\n name=\"stateId\"\n autoComplete=\"address-level1\"\n value={values.stateId}\n disabled={!values.countryId || states.length === 0}\n required={states.length > 0}\n invalid={Boolean(errors.stateId)}\n onChange={(event) => setField('stateId', event.target.value)}\n >\n <option value=\"\">\n {states.length > 0 ? 'Select state / region' : 'Not required'}\n </option>\n {states.map((state) => (\n <option key={state.id} value={state.id}>\n {state.name}\n </option>\n ))}\n </Select>\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.city')}\n error={errors.city}\n >\n <Input\n name=\"city\"\n placeholder={t('auth.cityPlaceholder')}\n autoComplete=\"address-level2\"\n required\n value={values.city}\n invalid={Boolean(errors.city)}\n onChange={(event) => setField('city', event.target.value)}\n />\n </Field>\n </FieldRow>\n </>\n ) : (\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.email')}\n error={errors.email}\n >\n <Input\n type=\"email\"\n name=\"email\"\n placeholder={t('auth.emailPlaceholder')}\n autoComplete=\"email\"\n required\n value={values.email}\n invalid={Boolean(errors.email)}\n onChange={(event) => setField('email', event.target.value)}\n />\n </Field>\n )}\n\n <Field className=\"tf-checkout-auth__phone-field\" label={t('auth.phone')}>\n <PhoneInput\n className=\"tf-checkout-phone\"\n inputClassName=\"tf-checkout-input tf-checkout-phone__input\"\n defaultCountry={phoneCountry}\n value={values.phone ?? ''}\n placeholder=\"\"\n inputProps={{ autoComplete: 'tel', 'aria-label': 'Phone' }}\n onChange={(phone) => setField('phone', phone)}\n />\n </Field>\n\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.password')}\n error={errors.password}\n >\n <PasswordInput\n name=\"password\"\n placeholder={t('auth.passwordPlaceholder')}\n autoComplete=\"new-password\"\n required\n value={values.password}\n invalid={Boolean(errors.password)}\n onChange={(event) => setField('password', event.target.value)}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.confirmPassword')}\n error={errors.passwordConfirmation}\n >\n <PasswordInput\n name=\"passwordConfirmation\"\n placeholder={t('auth.confirmPasswordPlaceholder')}\n autoComplete=\"new-password\"\n required\n value={values.passwordConfirmation}\n invalid={Boolean(errors.passwordConfirmation)}\n onChange={(event) => setField('passwordConfirmation', event.target.value)}\n />\n </Field>\n </FieldRow>\n <Button type=\"submit\" block loading={loading}>\n Create Account\n </Button>\n </form>\n )\n}\n","import { useT } from '../ui/I18nProvider'\nimport React, { useMemo, useState, type FC, type FormEvent } from 'react'\n\nimport { errorMessage, hooks } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Field, Input } from '../ui/Field'\n\nexport interface ResetPasswordFormProps {\n /** Token from the password-reset email. */\n token: string\n onSuccess?: () => void\n onBackToLogin?: () => void\n}\n\n/** Complete the password-reset flow started by `<ForgotPasswordForm/>`. */\nexport const ResetPasswordForm: FC<ResetPasswordFormProps> = ({\n token,\n onSuccess,\n onBackToLogin,\n}) => {\n const t = useT()\n const [password, setPassword] = useState('')\n const [confirmation, setConfirmation] = useState('')\n const [submitted, setSubmitted] = useState(false)\n const [success, setSuccess] = useState(false)\n\n const validation = useMemo(() => {\n if (!submitted) return {}\n return {\n token: token ? '' : 'This password-reset link is missing its token.',\n password:\n password.length < 8\n ? 'Password must have at least 8 characters.'\n : !/[@$!%*#?&]/.test(password)\n ? 'Password must contain at least one special character.'\n : '',\n confirmation: password !== confirmation ? 'Passwords must match.' : '',\n }\n }, [confirmation, password, submitted, token])\n\n const reset = hooks.useResetPassword({\n onSuccess: () => {\n setSuccess(true)\n onSuccess?.()\n },\n })\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n setSubmitted(true)\n const passwordValid = password.length >= 8 && /[@$!%*#?&]/.test(password)\n if (!token || !passwordValid || password !== confirmation) return\n reset.mutate({ token, password, passwordConfirmation: confirmation })\n }\n\n if (success) {\n return (\n <div className=\"tf-checkout-auth__form\">\n <div className=\"tf-checkout-auth__success\" role=\"status\">\n Your password has been changed. You can now log in.\n </div>\n {onBackToLogin && (\n <Button type=\"button\" block onClick={onBackToLogin}>\n Log in\n </Button>\n )}\n </div>\n )\n }\n\n return (\n <form className=\"tf-checkout-auth__form\" onSubmit={submit} noValidate>\n <h2 className=\"tf-checkout-auth__title\">{t('auth.changePassword')}</h2>\n {validation.token && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {validation.token}\n </div>\n )}\n {reset.error && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {errorMessage(reset.error)}\n </div>\n )}\n <Field label={t('auth.newPassword')} error={validation.password}>\n <Input\n type=\"password\"\n name=\"password\"\n autoComplete=\"new-password\"\n required\n value={password}\n invalid={Boolean(validation.password)}\n onChange={(event) => setPassword(event.target.value)}\n />\n </Field>\n <Field label={t('auth.confirmPassword')} error={validation.confirmation}>\n <Input\n type=\"password\"\n name=\"password_confirmation\"\n autoComplete=\"new-password\"\n required\n value={confirmation}\n invalid={Boolean(validation.confirmation)}\n onChange={(event) => setConfirmation(event.target.value)}\n />\n </Field>\n <Button type=\"submit\" block loading={reset.isPending} disabled={!token}>\n Submit\n </Button>\n </form>\n )\n}\n","/**\n * `<Tickets/>` — ticket selection. Lists the event's ticket types with a\n * quantity dropdown, applies promo / access codes (re-pricing + unlocking\n * tickets), offers a waiting-list sign-up on sold-out types, and primes the\n * cart. Matches the old checkout: no running total, a `GET TICKETS` CTA.\n */\nimport React, {\n Fragment,\n useEffect,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport {\n errorMessage,\n hooks,\n ticketQuantityRange,\n type TicketType,\n type WaitingListEntry,\n} from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { cx } from '../ui/cx'\nimport { Field, FieldRow, Input } from '../ui/Field'\nimport { Loader } from '../ui/Loader'\nimport { QuantitySelect } from '../ui/QuantitySelect'\n\n/** Inline waiting-list sign-up for a sold-out type. */\nconst WaitingListForm: FC<{\n ticket: TicketType\n onJoin: (entry: WaitingListEntry) => Promise<void>\n}> = ({ ticket, onJoin }) => {\n const [form, setForm] = useState({ firstName: '', lastName: '', email: '' })\n const [state, setState] = useState<'idle' | 'busy' | 'done' | 'error'>('idle')\n const [error, setError] = useState('')\n const ok = form.firstName.trim() && form.lastName.trim() && form.email.trim()\n\n if (state === 'done')\n return (\n <p className=\"tf-checkout-note tf-checkout-tickets__wl-done\">\n You’re on the waiting list — we’ll email you if a spot opens.\n </p>\n )\n\n return (\n <div className=\"tf-checkout-tickets__wl\">\n <FieldRow>\n <Field>\n <Input\n placeholder=\"First name\"\n value={form.firstName}\n onChange={(e) => setForm((f) => ({ ...f, firstName: e.target.value }))}\n />\n </Field>\n <Field>\n <Input\n placeholder=\"Last name\"\n value={form.lastName}\n onChange={(e) => setForm((f) => ({ ...f, lastName: e.target.value }))}\n />\n </Field>\n </FieldRow>\n <Field>\n <Input\n placeholder=\"Email\"\n value={form.email}\n onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}\n />\n </Field>\n <Button\n onClick={() => {\n setState('busy')\n setError('')\n onJoin({ ...form, ticketTypeId: ticket.id })\n .then(() => setState('done'))\n .catch((e) => {\n setState('error')\n setError(errorMessage(e))\n })\n }}\n loading={state === 'busy'}\n disabled={!ok || state === 'busy'}\n variant=\"secondary\"\n >\n Join the waiting list\n </Button>\n {error && <p className=\"tf-checkout-error-text\">{error}</p>}\n </div>\n )\n}\n\nexport interface TicketsProps {\n eventId: string\n /** Optional heading above the catalog. The legacy storefront does not show\n * one, so the default is intentionally hidden. */\n title?: ReactNode | false\n /** Fired once the cart is primed (tickets added) — e.g. reveal `<AddOns/>`. */\n onContinue?: () => void\n /** CTA label. Old storefront uses \"Get tickets\". */\n buttonLabel?: string\n /** Force time-slot mode + supply the selectable session dates (ISO yyyy-mm-dd).\n * Omit to auto-detect from the event (`isTimeSlotEvent` / `availableDates`). */\n timeSlotDates?: string[]\n /** Optional numbered badge (old checkout shows none — omitted by default). */\n step?: ReactNode\n /** SEATED events: fired when the buyer clicks \"Select seats\". Wire this to\n * reveal `<SeatMap/>`. Without it the seat CTA is hidden (the seat-map ticket\n * types then have no way to be bought — provide it for seated events). */\n onSelectSeats?: () => void\n /** Apply this code once when the ticket catalog mounts. */\n initialPromoCode?: string\n /** Attribute this visit once. URL values use `ttf_r` / `referrer_id`. */\n referrer?: string | number\n /** Also read promo/referral values from the current URL. Defaults true. */\n readAttributionFromUrl?: boolean\n className?: string\n}\n\nexport const Tickets: FC<TicketsProps> = ({\n eventId,\n title = false,\n onContinue,\n buttonLabel = 'Get tickets',\n timeSlotDates,\n step,\n onSelectSeats,\n initialPromoCode,\n referrer,\n readAttributionFromUrl = true,\n className,\n}) => {\n const checkout = useCheckoutContext()\n const ticketsQuery = hooks.useTicketsWithMeta(eventId)\n const promoMeta = ticketsQuery.data?.promo\n const showWaitingList = ticketsQuery.data?.showWaitingList ?? false\n\n const [qty, setQty] = useState<Record<string, number>>({})\n const [slotDate, setSlotDate] = useState('')\n\n // Time-slot / calendar events: pick a date, then buy from that session's slots.\n const eventInfo = hooks.useEvent(eventId).data\n const isTimeSlot = Boolean(timeSlotDates?.length || eventInfo?.isTimeSlotEvent)\n const dates = timeSlotDates ?? eventInfo?.availableDates ?? []\n useEffect(() => {\n if (isTimeSlot && !slotDate && dates.length) setSlotDate(dates[0])\n }, [isTimeSlot, slotDate, dates])\n const slotQuery = hooks.useTimeSlotTickets(eventId, isTimeSlot ? slotDate : undefined)\n\n const tickets = isTimeSlot ? (slotQuery.data ?? []) : (ticketsQuery.data?.tickets ?? [])\n const [error, setError] = useState('')\n const [code, setCode] = useState('')\n const [codeState, setCodeState] = useState<'idle' | 'busy'>('idle')\n const [promoOpen, setPromoOpen] = useState(false)\n const [wlOpen, setWlOpen] = useState<Record<string, boolean>>({})\n const [visibleDescription, setVisibleDescription] = useState<string | null>(null)\n const attributionEvent = useRef<string | null>(null)\n\n // Match hosted links: attribute referral visits and apply a carried promo\n // once per event. Explicit props win; URL support can be disabled by hosts\n // that manage routing/attribution themselves.\n useEffect(() => {\n if (attributionEvent.current === eventId) return\n attributionEvent.current = eventId\n\n let promo = initialPromoCode?.trim() ?? ''\n let referral: string | number | undefined = referrer\n if (readAttributionFromUrl && typeof window !== 'undefined') {\n const params = new URLSearchParams(window.location.search)\n promo ||= params.get('promo')?.trim() || params.get('promo_code')?.trim() || ''\n referral ??= params.get('ttf_r') || params.get('referrer_id') || undefined\n }\n\n if (referral !== undefined && String(referral).trim()) {\n checkout.attributeReferrer(eventId, referral).catch(() => undefined)\n }\n if (promo) {\n setCode(promo)\n setPromoOpen(true)\n setCodeState('busy')\n checkout\n .applyPromoCode(eventId, promo)\n .catch(() => undefined)\n .finally(() => {\n ticketsQuery.refetch().finally(() => setCodeState('idle'))\n })\n }\n // Checkout actions and query functions are stable; this effect is scoped to\n // one attribution pass per event rather than every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [eventId, initialPromoCode, referrer, readAttributionFromUrl])\n\n // Seed the currency state once so a multi-currency event can offer a switcher\n // on the ticket screen (before the cart is primed). No-op for single-currency.\n useEffect(() => {\n checkout.syncCurrency(eventId, undefined, { seed: true }).catch(() => undefined)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [eventId])\n\n const changeCurrency = (code: string) => {\n checkout\n .syncCurrency(eventId, code)\n .then((res) => {\n if (res.requiresCatalogRefresh) {\n setQty({})\n ticketsQuery.refetch()\n }\n })\n .catch(() => undefined)\n }\n\n // Remember each type's first-seen (pre-promo) price so a discount can strike it.\n const originals = useRef<Record<string, number>>({})\n useEffect(() => {\n for (const t of tickets)\n if (originals.current[t.id] == null) originals.current[t.id] = t.price\n }, [tickets])\n\n const selected = tickets.filter((t) => (qty[t.id] ?? 0) > 0)\n // The current selection's kind — drives the CTA label and the mutual-exclusion\n // rule below (a table order and a ticket order can't be combined).\n const selectionIsTable = selected.some((t) => t.isTable)\n const allowMultiple = eventInfo?.allowMultipleTicketTypePurchases === true\n\n // Ported from the old checkout's `handleTicketSelect`: unless the event opts\n // into multiple types (`allowMultipleTicketTypePurchases`), a new selection\n // REPLACES the previous one — one ticket type per order. Even when multiple\n // are allowed, switching between a table and a regular ticket clears the rest.\n const selectQty = (t: TicketType, value: number) =>\n setQty((prev) => {\n const activeIds = Object.keys(prev).filter((k) => (prev[k] ?? 0) > 0)\n const prevIsTable = activeIds.length\n ? Boolean(tickets.find((x) => x.id === activeIds[0])?.isTable)\n : t.isTable\n const switchingKind = activeIds.length > 0 && prevIsTable !== t.isTable\n\n if (!allowMultiple) return value > 0 ? { [t.id]: value } : {}\n if (switchingKind && value > 0) return { [t.id]: value }\n const next = { ...prev }\n if (value > 0) next[t.id] = value\n else delete next[t.id]\n return next\n })\n\n const money = (sym: string, n: number) => `${sym} ${Number(n).toFixed(2)}`\n\n // Seated events: the buyer picks on a seat map, so seat-map ticket types show\n // read-only (no quantity dropdown) and the CTA becomes \"Select seats\". A type\n // with `allowDirectPurchase` opts out and keeps its dropdown.\n const isSeated = eventInfo?.isSeatedEvent ?? false\n const seatMapRow = (t: TicketType) => isSeated && !t.allowDirectPurchase\n const hasSeatMapTickets = tickets.some(seatMapRow)\n // Types that can still be bought with a quantity dropdown (all of them for a\n // non-seated event). When empty on a seated event, only \"Select seats\" shows.\n const directPurchasable = tickets.filter((t) => !seatMapRow(t))\n const seatCtaLabel = eventInfo?.tableMapEnabled ? 'Select on map' : 'Select seats'\n\n // A \"Tables\" divider before the first table type — only when regular tickets\n // actually precede it (a tables-first list gets no stray divider).\n const firstTableIndex = tickets.findIndex((t) => t.isTable)\n const firstTableId =\n firstTableIndex > 0 && tickets.slice(0, firstTableIndex).some((t) => !t.isTable)\n ? tickets[firstTableIndex].id\n : undefined\n\n const prime = () => {\n setError('')\n checkout\n .setTickets(\n eventId,\n selected.map((t) => ({ ...t, quantity: qty[t.id] }))\n )\n .then(() => onContinue?.())\n .catch((e) => setError(errorMessage(e)))\n }\n\n const applyCode = () => {\n if (!code.trim()) return\n setCodeState('busy')\n checkout\n .applyPromoCode(eventId, code.trim())\n .catch(() => undefined)\n .finally(() => {\n ticketsQuery.refetch().finally(() => setCodeState('idle'))\n })\n }\n\n const isAccess = promoMeta?.isAccessCodeEnabled\n const showCodeInput = promoMeta?.isPromotionsEnabled || isAccess\n const listQuery = isTimeSlot ? slotQuery : ticketsQuery\n\n const renderRow = (t: TicketType) => {\n const notStarted = !t.salesStarted\n const unavailable = t.soldOut || t.salesEnded || notStarted\n const original = originals.current[t.id]\n const discounted = original != null && original > t.price\n const canWaitlist =\n t.soldOut && (t.waitingListEnabled || showWaitingList) && !t.salesEnded\n const isFree = Number(t.price) === 0\n const sym = t.priceSymbol || t.currency\n const range = ticketQuantityRange(t)\n const ticketIndex = tickets.findIndex((candidate) => candidate.id === t.id)\n const previousTicket = ticketIndex > 0 ? tickets[ticketIndex - 1] : undefined\n const startsNamedGroup =\n Boolean(t.groupName) && t.groupName !== previousTicket?.groupName\n return (\n <Fragment key={t.id}>\n {startsNamedGroup ? (\n <div className=\"tf-checkout-tickets__group\">{t.groupName}</div>\n ) : (\n t.id === firstTableId && (\n <div className=\"tf-checkout-tickets__group\">Reserve tables</div>\n )\n )}\n <div className=\"tf-checkout-tickets__row-wrap\">\n <div className=\"tf-checkout-tickets__row\">\n <div className=\"tf-checkout-tickets__info\">\n <div className=\"tf-checkout-tickets__name\">\n <span>{t.name}</span>\n {t.descriptionRich && (\n <button\n type=\"button\"\n className=\"tf-checkout-tickets__description-toggle\"\n aria-expanded={visibleDescription === t.id}\n aria-controls={`ticket-description-${t.id}`}\n onClick={() =>\n setVisibleDescription((current) => (current === t.id ? null : t.id))\n }\n >\n {visibleDescription === t.id ? 'Hide info' : 'View info'}\n </button>\n )}\n </div>\n <div className=\"tf-checkout-tickets__price\">\n {discounted && (\n <span className=\"tf-checkout-tickets__old\">\n {money(sym, original!)}\n </span>\n )}\n <span\n className={cx(\n 'tf-checkout-tickets__amount',\n isFree && 'tf-checkout-tickets__amount--free'\n )}\n >\n {isFree ? 'FREE' : money(sym, t.price)}\n </span>\n {/* Fees sub-line (the \"(… with fees)\" the old checkout shows) —\n omitted for free/sold-out types. */}\n {!isFree && !t.soldOut && (\n <span className=\"tf-checkout-tickets__fees\">\n ({money(sym, t.priceWithFees)} with fees)\n </span>\n )}\n {t.depositPercent != null && (\n <span className=\"tf-checkout-tickets__deposit\">\n {t.depositPercent.toFixed(2)}% DEPOSIT\n </span>\n )}\n </div>\n </div>\n {/* Seat-map types are read-only here — no quantity control; the buyer\n picks them on the map via \"Select seats\". */}\n {seatMapRow(t) ? null : unavailable ? (\n <span className=\"tf-checkout-tickets__soldout\">\n {t.soldOut\n ? 'Sold out'\n : notStarted\n ? 'Sales not started'\n : 'Sales Ended'}\n </span>\n ) : (\n <div className=\"tf-checkout-tickets__qty\">\n {/* Tables pick a number of GUESTS (bounded by minGuests/maxGuests),\n not a count of tickets — the label makes that explicit, matching\n the old checkout's \"GUESTS\" affordance. */}\n {t.isTable && <span className=\"tf-checkout-tickets__guests\">Guests</span>}\n <QuantitySelect\n value={qty[t.id] ?? 0}\n min={range.min}\n max={range.max}\n step={range.step}\n onChange={(v) => selectQty(t, v)}\n />\n </div>\n )}\n </div>\n {t.descriptionRich && visibleDescription === t.id && (\n <div\n id={`ticket-description-${t.id}`}\n className=\"tf-checkout-tickets__description\"\n dangerouslySetInnerHTML={{ __html: t.descriptionRich }}\n />\n )}\n {canWaitlist &&\n (wlOpen[t.id] ? (\n <WaitingListForm\n ticket={t}\n onJoin={(entry) => checkout.joinWaitingList(eventId, entry)}\n />\n ) : (\n <button\n type=\"button\"\n className=\"tf-checkout-tickets__wl-toggle\"\n onClick={() => setWlOpen((w) => ({ ...w, [t.id]: true }))}\n >\n Join the waiting list\n </button>\n ))}\n </div>\n </Fragment>\n )\n }\n\n // Time-slot layout groups the date's tickets under their time heading.\n const timeGroups: { time: string; items: TicketType[] }[] = []\n if (isTimeSlot)\n for (const t of tickets) {\n const time = t.timeSlot?.time ?? ''\n const g = timeGroups.find((x) => x.time === time)\n if (g) g.items.push(t)\n else timeGroups.push({ time, items: [t] })\n }\n\n return (\n <Card className={cx('tf-checkout-tickets', className)}>\n {(title !== false || step != null) && (\n <SectionHeader\n step={step}\n title={title || ''}\n pills={listQuery.isFetching && !listQuery.isLoading ? <Loader /> : undefined}\n />\n )}\n\n {listQuery.isLoading && (\n <div className=\"tf-checkout-tickets__loading\">\n <Loader className=\"tf-checkout-tickets__loading-spinner\" />\n </div>\n )}\n\n {listQuery.error && (\n <p className=\"tf-checkout-error-text\">{(listQuery.error as Error).message}</p>\n )}\n\n {isTimeSlot && dates.length > 0 && (\n <div className=\"tf-checkout-tickets__currency\">\n <span className=\"tf-checkout-tickets__currency-label\">Date</span>\n <select\n className=\"tf-checkout-select\"\n value={slotDate}\n onChange={(e) => {\n setSlotDate(e.target.value)\n setQty({})\n }}\n >\n {dates.map((d) => (\n <option key={d} value={d}>\n {d}\n </option>\n ))}\n </select>\n </div>\n )}\n\n {checkout.currency && checkout.currency.available.length > 1 && (\n <div className=\"tf-checkout-tickets__currency\">\n <span className=\"tf-checkout-tickets__currency-label\">Currency</span>\n <select\n className=\"tf-checkout-select\"\n value={checkout.currency.currency}\n onChange={(e) => changeCurrency(e.target.value)}\n >\n {checkout.currency.available.map((c) => (\n <option key={c.code} value={c.code}>\n {c.name} ({c.code})\n </option>\n ))}\n </select>\n </div>\n )}\n\n {isTimeSlot && !slotQuery.isLoading && tickets.length === 0 && slotDate && (\n <p className=\"tf-checkout-note\">No sessions available on this date.</p>\n )}\n\n {isTimeSlot\n ? timeGroups.map((g) => (\n <Fragment key={g.time}>\n {g.time && <div className=\"tf-checkout-tickets__slot-time\">{g.time}</div>}\n {g.items.map(renderRow)}\n </Fragment>\n ))\n : tickets.map(renderRow)}\n\n {/* Promo / access code */}\n {showCodeInput && (\n <div className=\"tf-checkout-tickets__promo\">\n {!isAccess && !promoOpen ? (\n <button\n type=\"button\"\n className=\"tf-checkout-tickets__promo-toggle\"\n onClick={() => setPromoOpen(true)}\n >\n Got a promo code? Click here\n </button>\n ) : (\n <>\n <FieldRow>\n <Field>\n <Input\n placeholder={isAccess ? 'Access code' : 'Promo code'}\n value={code}\n onChange={(e) => setCode(e.target.value)}\n onKeyDown={(e) => e.key === 'Enter' && applyCode()}\n />\n </Field>\n <Button\n variant=\"secondary\"\n onClick={applyCode}\n loading={codeState === 'busy'}\n disabled={codeState === 'busy' || !code.trim()}\n >\n {isAccess ? 'ENTER' : 'APPLY'}\n </Button>\n </FieldRow>\n {promoMeta?.promoCodeMessage && (\n <p\n className={cx(\n 'tf-checkout-note',\n promoMeta.promoCodeValid === false && 'tf-checkout-error-text'\n )}\n >\n {promoMeta.promoCodeMessage}\n </p>\n )}\n </>\n )}\n </div>\n )}\n\n {/* Direct-purchase CTA — hidden on a fully-seated event (nothing to buy by\n quantity; the seat map is the only path). */}\n {directPurchasable.length > 0 && (\n <Button\n block\n onClick={prime}\n loading={checkout.isBusy}\n disabled={checkout.isBusy || selected.length === 0}\n >\n {checkout.isBusy\n ? 'Reserving…'\n : selectionIsTable\n ? 'Reserve tables'\n : buttonLabel}\n </Button>\n )}\n\n {/* Seated events: hand off to the seat map instead of quantity selection. */}\n {hasSeatMapTickets && (\n <Button block onClick={() => onSelectSeats?.()}>\n {seatCtaLabel}\n </Button>\n )}\n\n {(error || checkout.error) && (\n <p className=\"tf-checkout-error-text\">{error || checkout.error}</p>\n )}\n </Card>\n )\n}\n","/**\n * `<SeatMap/>` — the venue seat picker for seated events, rebuilt to match the\n * legacy `seatMapContainer` exactly (the REAL seat wire, not the earlier\n * inferred mapping):\n *\n * 1. Fetch the chart (`seat-map-data`) → `seatData`, `ticketTypeTierRelations`,\n * `eventSeats`, `seatReservationTime`, `seatMapType`, `tierPrices`,\n * `predefinedSeats`. Poll `seats/status` every 3s and derive the seats this\n * buyer owns (status `'OR'`).\n * 2. Clicking a seat reserves it (`ttf.seatmap.reserve`, one seat per call);\n * clicking a held seat releases it (`ttf.seatmap.removeReserved`). Blocked /\n * reserved-by-others seats and the 10-seat cap are enforced like legacy.\n * 3. Each held seat gets a ticket-type dropdown (auto-selected when its tier\n * offers only one) and, for table/group types, a guest-count dropdown.\n * 4. \"Get tickets\" turns the held seats into `SeatLine`s and calls\n * `checkout.setSeats(eventId, lines)` → the seat-aware add-to-cart + price.\n *\n * Boundaries (documented, not hidden):\n * - `tf-seat-map-view` is an OPTIONAL peer dependency. Install it and import its\n * CSS (`import 'tf-seat-map-view/dist/index.css'`) to use this section; it is\n * lazy-loaded + externalized, so it never weighs on the base SDK.\n * - Guest-count → cart shape follows the spec's model: a `SeatLine` carries\n * `guests` ONLY for guest-capable (table) types, so plain seated events post\n * aggregated per-type quantities and table events post one indexed line per\n * seat with `quantity = guests`. Validate against a real table-map event.\n */\nimport React, {\n useCallback,\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport { errorMessage, ttf, type SeatLine } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { Field, Select } from '../ui/Field'\nimport { Loader } from '../ui/Loader'\nimport { Timer } from '../ui/Timer'\nimport {\n getOwnReservationsBasedOnStatuses,\n getTierIdBasedOnSeatId,\n getTierRelationsArray,\n isGuestCapable,\n MAX_SEATS,\n ticketTypesForTier,\n UNSELECTABLE_STATUSES,\n type EventSeatLike,\n type ReservedSeat,\n type SeatRelation,\n type SeatStatuses,\n type TierRelations,\n} from './seatMap.utils'\n\n// tf-seat-map-view ships no types (see src/.d.ts ambient module) — treat the\n// default export as an opaque component rendered with the legacy prop contract.\ntype SeatMapWidget = ComponentType<Record<string, unknown>>\n\n/** The seat click payload the widget emits: `{ seat: { tierId, seatId, status } }`. */\ninterface SeatClick {\n seat: { tierId: string; seatId: string; status: string }\n}\n\ninterface Chart {\n seatData: unknown\n ticketTypeTierRelations: TierRelations\n eventSeats: EventSeatLike[]\n seatReservationTime: number\n seatMapType: string | null\n tierPrices: unknown\n predefinedSeats: unknown\n}\n\ntype Load<T> =\n | { state: 'loading' }\n | { state: 'ready'; data: T }\n | { state: 'empty' }\n | { state: 'error' }\n\nexport interface SeatMapProps {\n eventId: string\n /** Fired once seats are added to the cart + priced — e.g. reveal billing. */\n onContinue?: () => void\n /** Badge content. Defaults to a seat glyph. */\n step?: ReactNode\n className?: string\n}\n\nexport const SeatMap: FC<SeatMapProps> = ({\n eventId,\n onContinue,\n step = '💺',\n className,\n}) => {\n const checkout = useCheckoutContext()\n const [chart, setChart] = useState<Load<Chart>>({ state: 'loading' })\n const [Widget, setWidget] = useState<SeatMapWidget | null>(null)\n const [widgetMissing, setWidgetMissing] = useState(false)\n\n const [statuses, setStatuses] = useState<SeatStatuses>({})\n const [reserved, setReserved] = useState<ReservedSeat[]>([])\n const [selectedTypes, setSelectedTypes] = useState<Record<string, string>>({})\n const [guestCounts, setGuestCounts] = useState<Record<string, number>>({})\n const [reserving, setReserving] = useState(false)\n const [adding, setAdding] = useState(false)\n const [error, setError] = useState('')\n const [deadline, setDeadline] = useState<number | null>(null)\n const [nowTick, setNowTick] = useState(0)\n\n // The poll's setInterval closure reads these without re-subscribing.\n const eventSeatsRef = useRef<EventSeatLike[]>([])\n const relationsRef = useRef<TierRelations>({})\n const reservationTimeRef = useRef(0)\n const canvasRef = useRef<HTMLDivElement | null>(null)\n\n // Lazy-load the optional widget; a consumer who never installed it just gets\n // the \"unavailable\" note instead of a hard module-resolution crash.\n useEffect(() => {\n let active = true\n import('tf-seat-map-view')\n .then((m) => active && setWidget(() => (m.default ?? m) as SeatMapWidget))\n .catch(() => active && setWidgetMissing(true))\n return () => {\n active = false\n }\n }, [])\n\n // Fetch the chart. `get()` returns the JSON:API envelope, so read\n // `.data.attributes`; `seatData` is a JSON string the widget wants parsed.\n useEffect(() => {\n let active = true\n setChart({ state: 'loading' })\n console.log('[SeatMap] Fetching chart for eventId:', eventId)\n ttf.seatmap\n .data(eventId)\n .then((resp) => {\n if (!active) return\n console.log('[SeatMap] Raw response from ttf.seatmap.data:', resp)\n console.log('[SeatMap] typeof resp:', typeof resp)\n console.log('[SeatMap] resp?.data:', (resp as any)?.data)\n console.log('[SeatMap] resp?.data?.attributes:', (resp as any)?.data?.attributes)\n const attrs = (resp as { data?: { attributes?: Record<string, unknown> } })?.data\n ?.attributes\n console.log('[SeatMap] Parsed attrs:', attrs)\n console.log('[SeatMap] attrs?.seatData:', attrs?.seatData)\n console.log('[SeatMap] attrs?.seatData == null:', attrs?.seatData == null)\n if (!attrs || attrs.seatData == null) {\n console.warn(\n '[SeatMap] Setting chart to EMPTY because:',\n !attrs ? 'attrs is falsy' : 'seatData is null/undefined'\n )\n setChart({ state: 'empty' })\n return\n }\n const rawSeatData = attrs.seatData\n let seatData: unknown = rawSeatData\n if (typeof rawSeatData === 'string') {\n try {\n seatData = JSON.parse(rawSeatData)\n } catch {\n seatData = rawSeatData\n }\n }\n const relations = (attrs.ticketTypeTierRelations ?? {}) as TierRelations\n const eventSeats = (attrs.eventSeats ?? []) as EventSeatLike[]\n eventSeatsRef.current = eventSeats\n relationsRef.current = relations\n reservationTimeRef.current = Number(attrs.seatReservationTime) || 0\n // The widget reads tier prices off a global (legacy \"temp solution\").\n if (typeof window !== 'undefined') {\n ;(window as unknown as { tierPrices?: unknown }).tierPrices = attrs.tierPrices\n }\n console.log('[SeatMap] Setting chart to READY', {\n seatMapType: attrs.seatMapType,\n seatReservationTime: reservationTimeRef.current,\n eventSeatsCount: eventSeats.length,\n relationsKeys: Object.keys(relations),\n seatDataType: typeof seatData,\n })\n setChart({\n state: 'ready',\n data: {\n seatData,\n ticketTypeTierRelations: relations,\n eventSeats,\n seatReservationTime: reservationTimeRef.current,\n seatMapType: (attrs.seatMapType ?? null) as string | null,\n tierPrices: attrs.tierPrices,\n predefinedSeats: attrs.predefinedSeats,\n },\n })\n })\n .catch((err) => {\n console.error('[SeatMap] Fetch FAILED — setting chart to ERROR', err)\n if (active) setChart({ state: 'error' })\n })\n return () => {\n active = false\n }\n }, [eventId])\n\n // Poll live statuses every 3s (like legacy) once the chart is ready: derive the\n // seats this buyer owns, auto-select single-type tiers, prune released seats.\n const refreshStatuses = useCallback(async () => {\n try {\n const resp = await ttf.seatmap.statuses(eventId)\n const attrs = ((resp as { data?: { attributes?: SeatStatuses } })?.data\n ?.attributes ?? {}) as SeatStatuses\n const own = getOwnReservationsBasedOnStatuses(attrs) // mutates 'H' → 'BLOCKED'\n const nextReserved: ReservedSeat[] = own.map((seatId) => ({\n seatId,\n tierId: getTierIdBasedOnSeatId(seatId, eventSeatsRef.current),\n }))\n setStatuses(attrs)\n setReserved(nextReserved)\n const ownSet = new Set(own)\n setSelectedTypes((prev) => {\n const next: Record<string, string> = {}\n for (const r of nextReserved) {\n if (prev[r.seatId] != null) {\n next[r.seatId] = prev[r.seatId]\n } else {\n const types = ticketTypesForTier(relationsRef.current, r.tierId)\n next[r.seatId] = types.length === 1 ? types[0].ticket_type_id : ''\n }\n }\n return next\n })\n setGuestCounts((prev) => {\n const next: Record<string, number> = {}\n for (const seatId of Object.keys(prev))\n if (ownSet.has(seatId)) next[seatId] = prev[seatId]\n return next\n })\n } catch {\n // A transient status poll failure is non-fatal — keep the last snapshot.\n }\n }, [eventId])\n\n useEffect(() => {\n if (chart.state !== 'ready') return\n refreshStatuses()\n const id = setInterval(refreshStatuses, 3000)\n return () => clearInterval(id)\n }, [chart.state, refreshStatuses])\n\n // Reservation countdown: arm it when the first seat is held; clear when none\n // remain. The server is the source of truth — expiry drops seats via the poll.\n useEffect(() => {\n if (reserved.length && deadline == null && reservationTimeRef.current) {\n setDeadline(Date.now() + reservationTimeRef.current * 60000)\n } else if (!reserved.length && deadline != null) {\n setDeadline(null)\n }\n }, [reserved.length, deadline])\n useEffect(() => {\n if (deadline == null) return\n const id = setInterval(() => setNowTick((n) => n + 1), 1000)\n return () => clearInterval(id)\n }, [deadline])\n const secondsLeft =\n deadline != null ? Math.max(0, Math.round((deadline - Date.now()) / 1000)) : undefined\n // referenced so the 1s tick re-renders the timer\n void nowTick\n\n const reserve = async (tierId: string, seatId: string) => {\n setError('')\n setReserving(true)\n try {\n await ttf.seatmap.reserve(eventId, { tierId, seatId, ttl: 10 })\n await refreshStatuses()\n // Auto-select the tier's type if it's the only one (legacy behaviour).\n const types = ticketTypesForTier(relationsRef.current, tierId)\n if (types.length === 1) {\n setSelectedTypes((s) => ({ ...s, [seatId]: types[0].ticket_type_id }))\n }\n } catch (e) {\n setError(errorMessage(e))\n } finally {\n setReserving(false)\n }\n }\n\n const cancel = async (tierId: string, seatId: string) => {\n setError('')\n setReserving(true)\n try {\n await ttf.seatmap.removeReserved(eventId, tierId, [seatId])\n await refreshStatuses()\n } catch (e) {\n setError(errorMessage(e))\n } finally {\n setReserving(false)\n }\n }\n\n const onSeatClick = (info: SeatClick) => {\n const { tierId, seatId, status } = info.seat\n if (UNSELECTABLE_STATUSES.has(status)) return\n if (reserved.some((r) => r.seatId === seatId)) {\n cancel(tierId, seatId)\n } else if (reserved.length >= MAX_SEATS) {\n setError(`You can hold at most ${MAX_SEATS} seats.`)\n } else {\n reserve(tierId, seatId)\n }\n }\n\n const relationFor = (seatId: string): SeatRelation | undefined => {\n const seat = reserved.find((r) => r.seatId === seatId)\n const typeId = selectedTypes[seatId]\n if (!seat || !typeId) return undefined\n return ticketTypesForTier(relationsRef.current, seat.tierId).find(\n (t) => t.ticket_type_id === typeId\n )\n }\n\n // \"Get tickets\" is enabled only once every held seat has a type chosen.\n const allChosen =\n reserved.length > 0 && reserved.every((r) => Boolean(selectedTypes[r.seatId]))\n\n const getTickets = () => {\n setError('')\n const lines: SeatLine[] = []\n for (const r of reserved) {\n const rel = relationFor(r.seatId)\n if (!rel) continue\n const guestCapable = isGuestCapable(rel)\n const min = Number(rel.ticket_type_min_number_of_guests) || 0\n lines.push({\n seatId: r.seatId,\n tierId: r.tierId,\n ticketTypeId: rel.ticket_type_id,\n optionName: rel.ticket_type_option,\n price: Number(rel.ticket_type_price),\n ...(guestCapable ? { guests: guestCounts[r.seatId] ?? min } : {}),\n })\n }\n if (!lines.length) {\n setError('Please choose a ticket type for each seat.')\n return\n }\n setAdding(true)\n checkout\n .setSeats(eventId, lines)\n .then(() => onContinue?.())\n .catch((e) => setError(errorMessage(e)))\n .finally(() => setAdding(false))\n }\n\n const symbol = checkout.breakdown?.currencySymbol ?? ''\n\n return (\n <Card className={className}>\n <SectionHeader\n step={step}\n title=\"Select your seats\"\n pills={secondsLeft != null ? <Timer seconds={secondsLeft} /> : undefined}\n />\n\n {chart.state === 'loading' && (\n <div className=\"tf-checkout-seatmap__loading\">\n <Loader />\n </div>\n )}\n\n {chart.state === 'empty' && (\n <p className=\"tf-checkout-note\">\n This event has no seating chart — choose tickets above instead.\n </p>\n )}\n\n {chart.state === 'error' && (\n <p className=\"tf-checkout-note\">\n This seat map is currently unavailable in the checkout widget. If this event\n uses Seats.io, please return to the main event page to pick your seats.\n </p>\n )}\n\n {chart.state === 'ready' && widgetMissing && (\n <p className=\"tf-checkout-note\">\n Seat map unavailable — install <code>tf-seat-map-view</code> and import its CSS\n to enable the picker.\n </p>\n )}\n\n {chart.state === 'ready' && !widgetMissing && (\n <>\n <div className=\"tf-checkout-seatmap__canvas\" ref={canvasRef}>\n {Widget ? (\n <Widget\n seatData={chart.data.seatData}\n statuses={statuses}\n isSelectionOn={false}\n disabled={reserving}\n loading={reserving}\n events={{ onSeatClick }}\n ticketTypeTireRelationsArray={getTierRelationsArray(\n chart.data.ticketTypeTierRelations\n )}\n width={Math.min(canvasRef.current?.clientWidth || 800, 800)}\n height={Math.min(canvasRef.current?.clientWidth || 800, 800)}\n isBlockMap={chart.data.seatMapType === 'block'}\n isTableMap={chart.data.seatMapType === 'table'}\n predefinedSeats={chart.data.predefinedSeats}\n />\n ) : (\n <Loader />\n )}\n </div>\n\n {reserved.length > 0 && (\n <div className=\"tf-checkout-seatmap__seats\">\n {reserved.map((r) => {\n const types = ticketTypesForTier(relationsRef.current, r.tierId)\n const rel = relationFor(r.seatId)\n const guestCapable = isGuestCapable(rel)\n const min = Number(rel?.ticket_type_min_number_of_guests) || 0\n const max = Number(rel?.ticket_type_max_number_of_guests) || 0\n const guests = guestCounts[r.seatId] ?? min\n const unitPrice = Number(rel?.ticket_type_price ?? 0)\n const guestPrice = guestCapable\n ? (guests - min) * Number(rel?.guest_price ?? 0)\n : 0\n const total = (unitPrice + guestPrice).toFixed(2)\n return (\n <div key={r.seatId} className=\"tf-checkout-seatmap__seat\">\n <Field label={`Seat ${r.seatId}`}>\n <Select\n value={selectedTypes[r.seatId] || ''}\n onChange={(e) =>\n setSelectedTypes((s) => ({ ...s, [r.seatId]: e.target.value }))\n }\n >\n <option value=\"\">Please select a ticket type</option>\n {types.map((t) => (\n <option key={t.ticket_type_id} value={t.ticket_type_id}>\n {t.ticket_type_name}\n </option>\n ))}\n </Select>\n </Field>\n\n {guestCapable && (\n <Field label=\"Guests\">\n <Select\n value={guests}\n onChange={(e) =>\n setGuestCounts((g) => ({\n ...g,\n [r.seatId]: Number(e.target.value),\n }))\n }\n >\n {Array.from(\n { length: Math.max(0, max - min + 1) },\n (_, i) => min + i\n ).map((n) => (\n <option key={n} value={n}>\n {n}\n </option>\n ))}\n </Select>\n </Field>\n )}\n\n <div className=\"tf-checkout-seatmap__seat-foot\">\n {rel && (\n <span className=\"tf-checkout-seatmap__seat-price\">\n {symbol}\n {total}\n <span className=\"tf-checkout-note\">\n {rel.fee_included ? ' incl. fees' : ' excl. fees'}\n </span>\n </span>\n )}\n <button\n type=\"button\"\n className=\"tf-checkout-seatmap__seat-remove\"\n onClick={() => cancel(r.tierId, r.seatId)}\n disabled={reserving}\n >\n Remove\n </button>\n </div>\n </div>\n )\n })}\n\n <Button\n block\n onClick={getTickets}\n loading={adding}\n disabled={adding || reserving || !allChosen}\n >\n {adding\n ? 'Reserving…'\n : `Get ${reserved.length} seat${reserved.length > 1 ? 's' : ''}`}\n </Button>\n </div>\n )}\n {error && <p className=\"tf-checkout-error-text\">{error}</p>}\n </>\n )}\n </Card>\n )\n}\n","/**\n * Seat-wire helpers — a faithful port of the legacy `seatMapContainer/utils.ts`\n * (the real seat-map logic), rewritten in dependency-free TS. These translate\n * the `seat-map-data` + `seats/status` responses into the shapes `<SeatMap/>`\n * and the `tf-seat-map-view` widget need.\n */\n\n/** `{ [tierId]: { [ticketTypeId]: Relation } }` — from `seat-map-data`. */\nexport interface SeatRelation {\n ticket_type_id: string\n ticket_type_option: string\n ticket_type_price: number\n ticket_type_name: string\n ticket_type_min_number_of_guests?: string | number | null\n ticket_type_max_number_of_guests?: string | number | null\n ticket_type_deposit?: string\n guest_price?: string\n fee_included?: boolean\n description?: string | null\n}\nexport type TierRelations = Record<string, Record<string, SeatRelation>>\n\n/** `{ [groupRowId]: { [seatIndex]: statusCode } }` — from `seats/status`. */\nexport type SeatStatuses = Record<string, Record<string, string>>\n\n/** `seat-map-data`'s `eventSeats` — used only to resolve seatId → tierId. */\nexport interface EventSeatLike {\n tier_id: number | string\n seats: Record<string, number>\n}\n\n/** A seat the buyer holds: its id + resolved tier. */\nexport interface ReservedSeat {\n seatId: string\n tierId: string\n}\n\n/** Statuses the widget won't let the buyer act on (blocked / reserved-by-others). */\nexport const UNSELECTABLE_STATUSES = new Set(['B', 'R', 'BLOCKED', 'RE'])\n\n/** Max seats a single order may hold (legacy cap). */\nexport const MAX_SEATS = 10\n\n/**\n * `seatId` (`\"rowId:seatIndex\"`) → its tier id, by finding the `eventSeats`\n * group whose `seats[rowId]` covers `seatIndex`. Port of legacy\n * `getTierIdBasedOnSeatId`.\n */\nexport const getTierIdBasedOnSeatId = (\n seatId: string,\n eventSeats: EventSeatLike[]\n): string => {\n const [rowId, seatIndex] = seatId.split(':')\n for (const group of eventSeats ?? []) {\n for (const [row, count] of Object.entries(group.seats ?? {})) {\n if (row === rowId && Number(seatIndex) <= Number(count)) {\n return String(group.tier_id)\n }\n }\n }\n return ''\n}\n\n/**\n * Statuses → the seat ids the buyer currently OWNS (status `'OR'`). Also rewrites\n * `'H'` (held by someone else) to `'BLOCKED'` so the widget greys it out — the\n * mutation the legacy container did in place. Pass a status object you own\n * (freshly fetched), not shared React state.\n */\nexport const getOwnReservationsBasedOnStatuses = (statuses: SeatStatuses): string[] => {\n const own: string[] = []\n for (const groupRowId of Object.keys(statuses ?? {})) {\n const row = statuses[groupRowId]\n for (const seatIndex of Object.keys(row ?? {})) {\n if (row[seatIndex] === 'OR') own.push(`${groupRowId}:${seatIndex}`)\n else if (row[seatIndex] === 'H') row[seatIndex] = 'BLOCKED'\n }\n }\n return own\n}\n\n/**\n * Tier→type relations → the flat relation array the `tf-seat-map-view` widget\n * wants (its prop is the legacy-typo'd `ticketTypeTireRelationsArray`). Port of\n * legacy `getTierRelationsArray`.\n */\nexport const getTierRelationsArray = (relations: TierRelations): SeatRelation[] => {\n const out: SeatRelation[] = []\n for (const tier of Object.values(relations ?? {})) out.push(...Object.values(tier))\n return out\n}\n\n/** The ticket types a tier offers (dropdown options for its seats). */\nexport const ticketTypesForTier = (\n relations: TierRelations,\n tierId: string\n): SeatRelation[] => (relations[tierId] ? Object.values(relations[tierId]) : [])\n\n/** Whether a relation is guest-capable (a table / group ticket): it declares a\n * real min AND max guest count. Only then does a SeatLine carry `guests`. */\nexport const isGuestCapable = (rel: SeatRelation | undefined): boolean => {\n const min = Number(rel?.ticket_type_min_number_of_guests)\n const max = Number(rel?.ticket_type_max_number_of_guests)\n return Boolean(min && max)\n}\n","/**\n * `<AddOns/>` — optional upsells for the primed cart. Lists the event's add-ons\n * (filtered to the tickets in the cart), lets the buyer pick quantities, and\n * captures any per-add-on custom fields. On continue it writes the selection\n * (`setAddons`, which reprices) and the captured fields (`setAddonDataCapture`).\n *\n * Renders nothing when the event has no applicable add-ons, so it's safe to\n * always place between `<Tickets/>` and `<BillingInfo/>`.\n */\nimport React, { Fragment, useEffect, useMemo, useState, type FC } from 'react'\n\nimport {\n addOnMaxQuantity,\n errorMessage,\n hooks,\n ttf,\n type CustomFieldValues,\n type EventAddon,\n} from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { CustomFieldGroupFields } from '../ui/CustomFields'\nimport { Loader } from '../ui/Loader'\nimport { PriceLine } from '../ui/PriceLine'\nimport { QuantitySelect } from '../ui/QuantitySelect'\n\nexport interface AddOnsProps {\n eventId: string\n /** Fired once add-ons are saved to the cart — e.g. reveal `<BillingInfo/>`. */\n onContinue?: () => void\n /** Fired when the buyer skips add-ons. Hidden when a required add-on exists. */\n onSkip?: () => void\n /** CTA label. Old checkout uses \"CONFIRM SELECTION\". */\n buttonLabel?: string\n /** Eyebrow above the title. Old checkout uses \"Get Your Tickets\". */\n eyebrow?: string\n /** Section heading. Old checkout uses \"UPGRADES & ADD-ONS\". */\n heading?: string\n className?: string\n}\n\nexport const AddOns: FC<AddOnsProps> = ({\n eventId,\n onContinue,\n onSkip,\n buttonLabel = 'CONFIRM SELECTION',\n eyebrow = 'Get Your Tickets',\n heading = 'UPGRADES & ADD-ONS',\n className,\n}) => {\n const checkout = useCheckoutContext()\n // No onContinue ⇒ combined form (inside <EmbeddedCheckout/>): apply the selection live\n // (no \"confirm\" click) — the old checkout applied add-ons at checkout too.\n const combined = !onContinue\n const addonsQuery = hooks.useEventAddons(eventId)\n const all = addonsQuery.data ?? []\n const addons = ttf.events.filterAddonsForTickets(all, checkout.ticketTypeIds)\n // Tickets reserved in the cart — the bound for ticket-scoped add-on caps\n // (the hosted partial's `selectedTotalQty()`).\n const ticketQuantity = (checkout.breakdown?.tickets ?? []).reduce(\n (total, line) => total + (line.quantity || 0),\n 0\n )\n\n const [qty, setQty] = useState<Record<string, number>>(checkout.addOns ?? {})\n const [capture, setCapture] = useState<Record<string, CustomFieldValues>>(\n checkout.addOnDataCapture ?? {}\n )\n const [error, setError] = useState('')\n\n // Custom-field groups keyed by add-on id (scope 'add-on', group id = add-on id).\n const fieldGroups = useMemo(() => {\n const map: Record<string, (typeof checkout.customFields)[number]> = {}\n for (const g of checkout.customFields) if (g.scope === 'add-on') map[g.id] = g\n return map\n }, [checkout.customFields])\n\n // Combined mode: debounce-apply the selection to the cart (which reprices)\n // as it changes, instead of gating behind a \"confirm\" button.\n useEffect(() => {\n if (!combined) return\n const selection = Object.fromEntries(Object.entries(qty).filter(([, n]) => n > 0))\n if (JSON.stringify(selection) === JSON.stringify(checkout.addOns ?? {})) return\n const captureForSelected = Object.fromEntries(\n Object.entries(capture).filter(([id]) => (selection[id] ?? 0) > 0)\n )\n const t = setTimeout(() => {\n checkout.setAddonDataCapture(captureForSelected)\n checkout.setAddons(selection).catch((e) => setError(errorMessage(e)))\n }, 500)\n return () => clearTimeout(t)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [combined, qty, capture])\n\n const hasRequired = (checkout.requiredAddOns ?? []).some((a) => a.required)\n const head = (\n <div className=\"tf-checkout-addons__head\">\n {eyebrow && <span className=\"tf-checkout-addons__eyebrow\">{eyebrow}</span>}\n <span className=\"tf-checkout-addons__heading\">{heading}</span>\n {onSkip && !hasRequired && (\n <button type=\"button\" className=\"tf-checkout-addons__skip\" onClick={onSkip}>\n Skip\n </button>\n )}\n </div>\n )\n\n if (addonsQuery.isLoading) {\n return (\n <Card className={className}>\n {head}\n <div className=\"tf-checkout-section-loader\">\n <Loader />\n </div>\n </Card>\n )\n }\n if (addons.length === 0) return null\n // A catalog containing only unavailable rows is not a useful checkout step.\n // Required sold-out add-ons are already exempted by the engine preflight.\n if (addons.every((addon) => addon.stock === 0)) return null\n\n // The hosted cap — ticket-quantity / per-ticket / max-quantity bounds. The\n // server hard-rejects anything above it, so never offer a larger number.\n const max = (a: EventAddon) => addOnMaxQuantity(a, ticketQuantity)\n const soldOut = (a: EventAddon) => a.stock === 0\n\n // Group add-ons under their groupName heading (nulls fall under no heading).\n const groups: { heading: string | null; items: EventAddon[] }[] = []\n for (const a of addons) {\n const last = groups[groups.length - 1]\n if (last && last.heading === (a.groupName ?? null)) last.items.push(a)\n else groups.push({ heading: a.groupName ?? null, items: [a] })\n }\n\n const missing = checkout.missingRequiredAddonNames\n const save = () => {\n setError('')\n const selection = Object.fromEntries(Object.entries(qty).filter(([, n]) => n > 0))\n // Only keep captured fields for add-ons that are actually selected.\n const captureForSelected = Object.fromEntries(\n Object.entries(capture).filter(([id]) => (selection[id] ?? 0) > 0)\n )\n checkout.setAddonDataCapture(captureForSelected)\n checkout\n .setAddons(selection)\n .then(() => onContinue?.())\n .catch((e) => setError(errorMessage(e)))\n }\n\n const selectedCount = Object.values(qty).filter((n) => n > 0).length\n\n return (\n <Card className={className}>\n {head}\n <p className=\"tf-checkout-addons__subtitle\">\n PLEASE SELECT FROM THE OPTIONAL ADD-ONS BELOW\n </p>\n\n {groups.map((g, gi) => (\n <Fragment key={g.heading ?? `g${gi}`}>\n {g.heading && <div className=\"tf-checkout-addons__group\">{g.heading}</div>}\n {g.items.map((a) => {\n const n = qty[a.id] ?? 0\n const group = fieldGroups[a.id]\n return (\n <div key={a.id} className=\"tf-checkout-addons__item\">\n <div className=\"tf-checkout-addons__row\">\n <div className=\"tf-checkout-addons__info\">\n <div className=\"tf-checkout-addons__name\">\n {a.name}\n {a.required && (\n <span className=\"tf-checkout-addons__req\"> · required</span>\n )}\n </div>\n <div className=\"tf-checkout-addons__meta\">\n <PriceLine\n currency={a.currency}\n amount={a.price}\n note={a.feeIncluded ? 'incl. fees' : undefined}\n />\n </div>\n {a.description && (\n <div\n className=\"tf-checkout-addons__desc\"\n dangerouslySetInnerHTML={{ __html: a.description }}\n />\n )}\n </div>\n {soldOut(a) ? (\n <span className=\"tf-checkout-tickets__soldout\">Sold out</span>\n ) : (\n <QuantitySelect\n value={n}\n min={0}\n max={max(a)}\n onChange={(v) => setQty((q) => ({ ...q, [a.id]: v }))}\n />\n )}\n </div>\n {n > 0 && group && (\n <div className=\"tf-checkout-addons__fields\">\n <CustomFieldGroupFields\n group={group}\n values={capture[a.id] ?? {}}\n onChange={(name, val) =>\n setCapture((c) => ({\n ...c,\n [a.id]: { ...(c[a.id] ?? {}), [name]: val },\n }))\n }\n />\n </div>\n )}\n </div>\n )\n })}\n </Fragment>\n ))}\n\n {!combined && (\n <Button\n block\n onClick={save}\n loading={checkout.isBusy}\n disabled={checkout.isBusy || selectedCount === 0}\n >\n {checkout.isBusy ? 'Updating…' : buttonLabel}\n </Button>\n )}\n {missing.length > 0 && (\n <p className=\"tf-checkout-note\">Required add-on: {missing.join(', ')}.</p>\n )}\n {(error || checkout.error) && (\n <p className=\"tf-checkout-error-text\">{error || checkout.error}</p>\n )}\n </Card>\n )\n}\n","/**\n * `<BillingInfo/>` — the buyer + attendee details step. Collects: the buyer's\n * name/email + event-gated buyer fields (Instagram/nationality/gender), any\n * ORDER-level custom fields, PER-HOLDER name + ticket-level custom fields (when\n * the event requires holder names or has ticket-scoped fields), and marketing\n * opt-ins. Writes it all into the engine (`setBilling` with `dataCapture`,\n * `setHolders` with `ticketDataCapture`, `setConsent`) so `<Payment/>`'s\n * pre-flight passes. Use it alongside `<Payment/>`, or set those yourself.\n */\nimport React, {\n Fragment,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ChangeEvent,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport {\n hooks,\n mapProfileToBilling,\n missingCheckoutDetails,\n isEmail,\n ticketFieldsFor,\n type CheckoutBilling,\n type CheckoutHolder,\n type CustomFieldValues,\n type EventCustomFieldGroup,\n} from 'tf-checkout-shared'\nimport { PhoneInput, type CountryIso2 } from 'react-international-phone'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext, useCheckoutValidation } from '../ui/CheckoutProvider'\nimport { CustomFieldInput } from '../ui/CustomFields'\nimport { Checkbox, Field, FieldRow, Input } from '../ui/Field'\nimport { BillingAddressFields } from './billing/BillingAddressFields'\nimport { BuyerField } from './billing/BuyerField'\nimport { DOB_MIN, isBlankPhone, toDateInputValue, todayISO } from './billing/fieldRules'\nimport { TicketHoldersCard } from './billing/TicketHoldersCard'\nimport type { BillingDraft, HolderDraft } from './billing/types'\n\nexport interface BillingInfoProps {\n /** Event context is used to default the country and phone dial code. */\n eventId?: string\n /** Fired once billing is saved to the engine — e.g. reveal `<Payment/>`. */\n onContinue?: () => void\n /** Section heading. Old checkout uses \"Billing Information\". */\n heading?: string\n /** CTA label. */\n buttonLabel?: string\n /** When provided and the buyer isn't signed in, shows a \"Login & skip ahead\"\n * row. The current email is passed when login follows an account match. */\n onLogin?: (email?: string) => void\n /** Hide this card only after a signed-in profile satisfies every ordinary\n * billing requirement and the event needs no extra buyer/holder answers. */\n skipWhenProfileComplete?: boolean\n /** Ask guests to repeat their email and require an exact match. */\n requireEmailConfirmation?: boolean\n /** Always collect one named holder per selected ticket. EmbeddedCheckout uses\n * this to match tf-sports; standalone sections default to backend gates. */\n collectTicketHolders?: boolean\n /** When holder details are enabled, also collect each holder's email and phone. */\n collectHolderContact?: boolean\n /** Marketing opt-in labels. Render a checkbox for each provided (unchecked). */\n ttfOptInLabel?: string\n brandOptInLabel?: string\n /** Required host privacy acknowledgement. The URL is supplied by the consumer. */\n privacyPolicy?: CheckoutPrivacyPolicy\n /** Show the legacy inline \"Required\" error after a failed payment attempt. */\n showPrivacyError?: boolean\n /** Optional numbered badge (old checkout shows none — omitted by default). */\n step?: ReactNode\n className?: string\n}\n\nexport interface CheckoutPrivacyPolicy {\n url: string\n brandName: string\n linkLabel?: string\n}\n\nexport const BillingInfo: FC<BillingInfoProps> = ({\n eventId,\n onContinue,\n heading = 'Billing Information',\n buttonLabel = 'Continue to payment',\n onLogin,\n skipWhenProfileComplete = false,\n requireEmailConfirmation = false,\n collectTicketHolders = false,\n collectHolderContact = false,\n ttfOptInLabel = 'Keep me updated about future events from The Ticket Fairy',\n brandOptInLabel,\n privacyPolicy,\n showPrivacyError = false,\n step,\n className,\n}) => {\n const checkout = useCheckoutContext()\n const validation = useCheckoutValidation()\n const profile = hooks.useProfile({ retry: false })\n const event = hooks.useEvent(eventId)\n // No onContinue ⇒ this is one combined form (inside <EmbeddedCheckout/>): mirror the\n // fields into the engine live and drop the \"continue\" button, so the buyer\n // fills billing + pays with ONE button — the way the old checkout flowed.\n const combined = !onContinue\n\n const [billing, setBilling] = useState<BillingDraft>({\n firstName: checkout.billing?.firstName ?? '',\n lastName: checkout.billing?.lastName ?? '',\n email: checkout.billing?.email ?? '',\n confirmEmail: checkout.billing?.confirmEmail ?? '',\n phone: checkout.billing?.phone,\n streetAddress: checkout.billing?.streetAddress,\n city: checkout.billing?.city,\n zip: checkout.billing?.zip,\n countryId: checkout.billing?.countryId,\n stateId: checkout.billing?.stateId,\n countryCode: checkout.billing?.countryCode,\n stateCode: checkout.billing?.stateCode,\n nationality: checkout.billing?.nationality,\n gender: checkout.billing?.gender,\n instagramHandle: checkout.billing?.instagramHandle,\n })\n const [dataCapture, setDataCapture] = useState<CustomFieldValues>(\n checkout.billing?.dataCapture ?? {}\n )\n const [holders, setHolders] = useState<HolderDraft[]>(() =>\n checkout.holders.map((holder) => ({\n firstName: holder.firstName,\n lastName: holder.lastName,\n email: holder.email,\n phone: holder.phone ?? '',\n ticketTypeId: holder.ticketTypeId,\n ticketDataCapture: holder.ticketDataCapture ?? {},\n }))\n )\n const [consent, setConsent] = useState({ ttfOptIn: false, brandOptIn: false })\n const [dob, setDob] = useState(() => {\n const b = checkout.billing\n if (!b?.dobDay || !b.dobMonth || !b.dobYear) return ''\n return `${b.dobYear}-${String(b.dobMonth).padStart(2, '0')}-${String(\n b.dobDay\n ).padStart(2, '0')}`\n }) // ISO yyyy-mm-dd\n const restoredHolders = useRef(checkout.holders)\n const profileSeeded = useRef(false)\n const countryDefaultApplied = useRef(Boolean(checkout.billing?.countryId))\n\n const gates = checkout.fieldGates\n\n // Custom-field groups by scope.\n const orderGroups = useMemo(\n () => checkout.customFields.filter((g) => g.scope === 'order'),\n [checkout.customFields]\n )\n const ticketGroups = useMemo(\n () => checkout.customFields.filter((g) => g.scope === 'ticket'),\n [checkout.customFields]\n )\n const ticketFields = useMemo(\n () => ticketGroups.flatMap((g) => g.fields),\n [ticketGroups]\n )\n const holderNamesRequired = checkout.holderNamesRequired || collectTicketHolders\n const showHolders = holderNamesRequired || ticketFields.length > 0\n\n // One holder slot per ticket, tagged with its ticket type (drives ticket-field\n // scoping + the engine's per-holder validation).\n const slots = useMemo(() => {\n const out: { ticketTypeId?: string; ticketName?: string }[] = []\n const lines = checkout.breakdown?.tickets ?? []\n for (const line of lines)\n for (let i = 0; i < line.quantity; i++)\n out.push({ ticketTypeId: line.ticketTypeId, ticketName: line.name })\n if (!out.length) {\n const total = checkout.selections.reduce((n, s) => n + s.quantity, 0)\n for (let i = 0; i < total; i++) out.push({})\n }\n return out\n }, [checkout.breakdown, checkout.selections])\n\n // The initial state above restores anything already on the engine. A profile\n // that arrives later may fill blanks ONCE, but must never be consulted again\n // while the buyer edits — otherwise clearing the final character restores the\n // previous engine value on the next live commit.\n useEffect(() => {\n const p = profile.data\n if (!p || profileSeeded.current) return\n profileSeeded.current = true\n const profileBilling = mapProfileToBilling(p)\n setBilling((prev) => {\n const next = {\n ...prev,\n firstName: prev.firstName || profileBilling.firstName || '',\n lastName: prev.lastName || profileBilling.lastName || '',\n email: prev.email || profileBilling.email || '',\n confirmEmail:\n prev.confirmEmail || (checkout.isLoggedIn ? profileBilling.email : '') || '',\n phone:\n (isBlankPhone(prev.phone) ? undefined : prev.phone) || profileBilling.phone,\n streetAddress: prev.streetAddress || profileBilling.streetAddress,\n city: prev.city || profileBilling.city,\n zip: prev.zip || profileBilling.zip,\n countryId: prev.countryId || profileBilling.countryId,\n stateId: prev.stateId || profileBilling.stateId,\n }\n const keys = Object.keys(next) as (keyof BillingDraft)[]\n return keys.every((k) => next[k] === prev[k]) ? prev : next\n })\n // Date of birth lives outside `billing`, so it has to be seeded here too —\n // and it has to be here rather than in its own effect or in the useState\n // initialiser: the initialiser runs before the profile resolves, and a\n // separate effect would re-fire and overwrite the buyer, since the live\n // commit below depends on `dob`. This effect already runs exactly once.\n setDob((prev) => {\n if (prev) return prev\n const { dobYear, dobMonth, dobDay } = profileBilling\n return toDateInputValue(dobYear, dobMonth, dobDay) ?? prev\n })\n }, [profile.data, checkout.isLoggedIn])\n\n // Resize holders to the slot count, preserving typed values; tag ticket type.\n useEffect(() => {\n setHolders((prev) =>\n slots.map((s, i) => ({\n firstName: prev[i]?.firstName ?? restoredHolders.current[i]?.firstName ?? '',\n lastName: prev[i]?.lastName ?? restoredHolders.current[i]?.lastName ?? '',\n email: prev[i]?.email ?? restoredHolders.current[i]?.email ?? '',\n phone: prev[i]?.phone ?? restoredHolders.current[i]?.phone ?? '',\n ticketDataCapture:\n prev[i]?.ticketDataCapture ??\n restoredHolders.current[i]?.ticketDataCapture ??\n {},\n ticketTypeId: s.ticketTypeId,\n ticketName: s.ticketName,\n }))\n )\n }, [slots])\n\n // Match the storefront: ticket 1 silently starts as the buyer. The legacy\n // checkout has no extra \"use buyer details\" control.\n useEffect(() => {\n if (!showHolders) return\n setHolders((prev) =>\n prev.map((holder, index) =>\n index === 0\n ? {\n ...holder,\n firstName: billing.firstName,\n lastName: billing.lastName,\n email: billing.email,\n phone: billing.phone ?? '',\n }\n : holder\n )\n )\n }, [showHolders, billing.firstName, billing.lastName, billing.email, billing.phone])\n\n // Debounced \"this email already has an account\" check → nudges the buyer to\n // sign in (autofill + avoid duplicate accounts). Skips signed-in buyers.\n useEffect(() => {\n const email = billing.email.trim()\n if (checkout.isLoggedIn || !isEmail(email)) return\n const t = setTimeout(\n () => checkout.checkBuyerEmail(email).catch(() => undefined),\n 600\n )\n return () => clearTimeout(t)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [billing.email, checkout.isLoggedIn])\n const emailTaken =\n !checkout.isLoggedIn && checkout.existingAccountEmail === billing.email.trim()\n\n const needsNationality = checkout.buyerFields.some((f) => f.kind === 'nationality')\n const countriesQuery = hooks.useCountries({\n enabled: needsNationality || gates.showAddress,\n })\n const countries = useMemo(() => countriesQuery.data ?? [], [countriesQuery.data])\n const statesQuery = hooks.useStates(billing.countryId, {\n enabled: Boolean(billing.countryId),\n })\n const states = useMemo(() => statesQuery.data ?? [], [statesQuery.data])\n\n // Event country → signed-in profile → US, matching the hosted checkout's\n // country preference order. Also retain the ISO code for Stripe + phone UI.\n useEffect(() => {\n if (\n countryDefaultApplied.current ||\n billing.countryId ||\n countries.length === 0 ||\n profile.isLoading ||\n (eventId && event.isLoading)\n ) {\n return\n }\n const eventCode = event.data?.countryCode?.toLowerCase()\n const preferred =\n countries.find((country) => country.code?.toLowerCase() === eventCode) ??\n countries.find(\n (country) =>\n profile.data?.countryId !== null &&\n profile.data?.countryId !== undefined &&\n String(country.id) === String(profile.data.countryId)\n ) ??\n countries.find((country) => country.code?.toLowerCase() === 'us')\n if (!preferred) return\n countryDefaultApplied.current = true\n setBilling((current) => {\n // The profile-seed effect above can run in this same commit, so the\n // `billing` this effect closed over is stale — it still shows no country\n // even though the seed just supplied one (with its state). Re-check the\n // live value here: without it the default overwrote the seeded country\n // and blanked `stateId`, which is why a returning buyer's State/County\n // came back empty while every other saved field prefilled.\n if (current.countryId) return current\n return {\n ...current,\n countryId: String(preferred.id),\n countryCode: preferred.code?.toUpperCase(),\n stateId: undefined,\n stateCode: undefined,\n }\n })\n }, [\n billing.countryId,\n countries,\n profile.isLoading,\n profile.data?.countryId,\n eventId,\n event.isLoading,\n event.data?.countryCode,\n ])\n\n useEffect(() => {\n if (!billing.countryId) return\n const country = countries.find(\n (candidate) => String(candidate.id) === String(billing.countryId)\n )\n const countryCode = country?.code?.toUpperCase()\n if (countryCode && countryCode !== billing.countryCode) {\n setBilling((current) => ({ ...current, countryCode }))\n }\n }, [billing.countryId, billing.countryCode, countries])\n\n useEffect(() => {\n if (!billing.stateId) return\n const state = states.find(\n (candidate) => String(candidate.id) === String(billing.stateId)\n )\n const stateCode = state?.code\n if (stateCode && stateCode !== billing.stateCode) {\n setBilling((current) => ({ ...current, stateCode }))\n }\n }, [billing.stateId, billing.stateCode, states])\n\n const setB = (k: keyof BillingDraft) => (e: ChangeEvent<HTMLInputElement>) =>\n setBilling((b) => ({ ...b, [k]: e.target.value }))\n\n const patchHolder = (i: number, patch: Partial<HolderDraft>) =>\n setHolders((hs) => hs.map((h, j) => (j === i ? { ...h, ...patch } : h)))\n\n const dobMax = useMemo(todayISO, [])\n const [dobYear, dobMonth, dobDay] = dob ? dob.split('-').map(Number) : []\n // A dial code on its own is not a phone number — see `isBlankPhone`.\n const buyerPhone = isBlankPhone(billing.phone) ? undefined : billing.phone\n const committedBilling: CheckoutBilling = {\n ...checkout.billing,\n ...billing,\n phone: buyerPhone,\n stateRequired: gates.showAddress && Boolean(billing.countryId) && states.length > 0,\n dataCapture,\n dobDay,\n dobMonth,\n dobYear,\n }\n const committedHolders: CheckoutHolder[] = holders.map((holder) => {\n const holderPhone = isBlankPhone(holder.phone) ? '' : holder.phone\n return {\n firstName: holderNamesRequired\n ? holder.firstName\n : holder.firstName || billing.firstName,\n lastName: holderNamesRequired\n ? holder.lastName\n : holder.lastName || billing.lastName,\n email:\n showHolders && collectHolderContact\n ? holder.email\n : holder.email || billing.email,\n phone:\n showHolders && collectHolderContact\n ? holderPhone\n : holderPhone || buyerPhone || '',\n ticketTypeId: holder.ticketTypeId,\n ticketDataCapture: holder.ticketDataCapture,\n }\n })\n const missingDetails = missingCheckoutDetails(\n {\n billing: committedBilling,\n holders: committedHolders,\n selections: checkout.selections,\n breakdown: checkout.breakdown,\n holderNamesRequired: checkout.holderNamesRequired,\n fieldGates: checkout.fieldGates,\n customFields: checkout.customFields,\n },\n {\n requireEmailConfirmation,\n collectTicketHolders,\n requireHolderContact: collectHolderContact,\n }\n )\n const complete = missingDetails.length === 0\n const showValidation = validation.attempt > 0\n const missingSet = new Set(missingDetails)\n const fieldError = (key: string, message = 'This field is required.') =>\n showValidation && missingSet.has(key) ? message : undefined\n const dobError = showValidation\n ? missingDetails.find(\n (detail) => detail === 'Date of birth' || detail.startsWith('Age ')\n )\n : undefined\n const phoneCountry = (\n billing.countryCode ??\n event.data?.countryCode ??\n 'US'\n )?.toLowerCase() as CountryIso2\n\n const commit = () => {\n checkout.setBilling(committedBilling)\n checkout.setHolders(committedHolders)\n if (ttfOptInLabel || brandOptInLabel) checkout.setConsent(consent)\n }\n\n // Combined mode: keep the engine in sync as the form is filled, so <Payment/>\n // is always chargeable without a separate \"continue\" click.\n useEffect(() => {\n if (combined) commit()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [combined, billing, holders, consent, dob, dataCapture])\n\n const renderGroupFields = (\n group: EventCustomFieldGroup,\n values: CustomFieldValues,\n onChange: (name: string, v: string | string[]) => void,\n ticketTypeId?: string,\n ticketIndex?: number\n ) =>\n ticketFieldsFor(group.fields, ticketTypeId).map((f) => {\n const label = f.label || f.name\n const missingKey =\n ticketIndex === undefined ? label : `${label} (ticket ${ticketIndex + 1})`\n return (\n <CustomFieldInput\n key={f.id}\n field={f}\n value={values[f.name]}\n error={fieldError(missingKey)}\n onChange={(v) => onChange(f.name, v)}\n />\n )\n })\n\n const hasEventSpecificDetails =\n checkout.buyerFields.length > 0 ||\n checkout.customFields.some((group) => group.fields.length > 0) ||\n showHolders ||\n gates.showDob\n const skipBilling =\n skipWhenProfileComplete &&\n checkout.isLoggedIn &&\n profile.isSuccess &&\n complete &&\n !hasEventSpecificDetails\n\n // This is the safe EmbeddedCheckout interpretation of legacy\n // `skip_billing_page`: payment remains visible; only a fully satisfied,\n // ordinary billing card disappears.\n if (skipBilling) return null\n\n return (\n <>\n <Card className={className}>\n <SectionHeader step={step} title={heading} />\n\n {onLogin && !checkout.isLoggedIn && (\n <div className=\"tf-checkout-billing__login\">\n <span>Login & skip ahead:</span>\n <button\n type=\"button\"\n className=\"tf-checkout-billing__login-btn\"\n onClick={() => onLogin()}\n >\n Login\n </button>\n </div>\n )}\n\n <FieldRow>\n <Field\n error={fieldError('First name', 'First name is required.')}\n invalid={Boolean(fieldError('First name'))}\n >\n <Input\n placeholder=\"First name *\"\n value={billing.firstName}\n required\n invalid={Boolean(fieldError('First name'))}\n aria-invalid={Boolean(fieldError('First name'))}\n onChange={setB('firstName')}\n />\n </Field>\n <Field\n error={fieldError('Last name', 'Last name is required.')}\n invalid={Boolean(fieldError('Last name'))}\n >\n <Input\n placeholder=\"Last name *\"\n value={billing.lastName}\n required\n invalid={Boolean(fieldError('Last name'))}\n aria-invalid={Boolean(fieldError('Last name'))}\n onChange={setB('lastName')}\n />\n </Field>\n </FieldRow>\n <FieldRow>\n <Field\n error={fieldError('Valid email address', 'Enter a valid email address.')}\n invalid={Boolean(fieldError('Valid email address'))}\n >\n <Input\n type=\"email\"\n autoComplete=\"email\"\n placeholder=\"Email *\"\n value={billing.email}\n required\n invalid={Boolean(fieldError('Valid email address'))}\n aria-invalid={Boolean(fieldError('Valid email address'))}\n onChange={setB('email')}\n />\n </Field>\n {requireEmailConfirmation && !checkout.isLoggedIn && (\n <Field\n error={fieldError(\n 'Matching email confirmation',\n 'Email addresses must match.'\n )}\n invalid={Boolean(fieldError('Matching email confirmation'))}\n >\n <Input\n type=\"email\"\n autoComplete=\"email\"\n placeholder=\"Confirm email *\"\n value={billing.confirmEmail ?? ''}\n required\n invalid={Boolean(fieldError('Matching email confirmation'))}\n aria-invalid={Boolean(fieldError('Matching email confirmation'))}\n onChange={setB('confirmEmail')}\n />\n </Field>\n )}\n </FieldRow>\n {!showValidation &&\n requireEmailConfirmation &&\n billing.confirmEmail &&\n billing.confirmEmail.trim().toLowerCase() !==\n billing.email.trim().toLowerCase() && (\n <p className=\"tf-checkout-error-text\">The email addresses do not match.</p>\n )}\n {emailTaken && (\n <p className=\"tf-checkout-note tf-checkout-billing__email-taken\">\n This email is already registered.{' '}\n {onLogin ? (\n <button\n type=\"button\"\n className=\"tf-checkout-billing__login-link\"\n onClick={() => onLogin(billing.email)}\n >\n Log in to autofill your details\n </button>\n ) : (\n 'Log in to autofill your details.'\n )}\n </p>\n )}\n\n {checkout.buyerFields.map((f) => (\n <BuyerField\n key={f.key}\n field={f}\n value={String(billing[f.key] ?? '')}\n onChange={(v) => setBilling((b) => ({ ...b, [f.key]: v }))}\n countries={countries}\n error={fieldError(\n f.kind === 'nationality'\n ? 'Nationality'\n : f.kind === 'gender'\n ? 'Gender'\n : 'Instagram handle'\n )}\n />\n ))}\n\n {gates.showPhone && (\n <Field\n label={`Phone${gates.phoneRequired ? ' *' : ''}`}\n error={fieldError('Valid phone number', 'Enter a valid phone number.')}\n invalid={Boolean(fieldError('Valid phone number'))}\n >\n <PhoneInput\n className=\"tf-checkout-phone\"\n inputClassName={`tf-checkout-input tf-checkout-phone__input${\n fieldError('Valid phone number') ? ' tf-checkout-input--invalid' : ''\n }`}\n defaultCountry={phoneCountry}\n // The flag owns the country; the input holds the national number\n // only. Without `disableDialCodeAndPrefix` the empty field still\n // expects a full international number, so a Mexican buyer typing\n // \"5512345678\" has it read as a dial code and the country guess\n // flips them to Brazil (+55) — submitting the wrong code.\n disableDialCodeAndPrefix\n showDisabledDialCodeAndPrefix\n disableDialCodePrefill\n value={billing.phone ?? ''}\n required={gates.phoneRequired}\n placeholder=\"Phone number\"\n inputProps={{\n autoComplete: 'tel',\n 'aria-label': 'Phone',\n 'aria-invalid': Boolean(fieldError('Valid phone number')),\n }}\n onChange={(phone) => setBilling((current) => ({ ...current, phone }))}\n />\n </Field>\n )}\n\n {gates.showDob && (\n <Field\n label={`Date of birth *${\n gates.minimumAge ? ` (must be ${gates.minimumAge}+)` : ''\n }`}\n error={\n dobError === 'Date of birth'\n ? 'Date of birth is required.'\n : dobError\n ? `You must be ${gates.minimumAge} or older.`\n : undefined\n }\n invalid={Boolean(dobError)}\n >\n <Input\n type=\"date\"\n value={dob}\n required\n // A date input with no bounds lets the browser's year segment run\n // to six digits (\"202555\") and accept dates in the future. The\n // range both caps the year at four digits and keeps the value a\n // date someone could actually have been born on.\n min={DOB_MIN}\n max={dobMax}\n invalid={Boolean(dobError)}\n aria-invalid={Boolean(dobError)}\n onChange={(e) => setDob(e.target.value)}\n />\n </Field>\n )}\n\n {gates.showAddress && (\n <BillingAddressFields\n billing={billing}\n countries={countries}\n states={states}\n fieldError={fieldError}\n setBilling={setBilling}\n />\n )}\n\n {/* Order-level custom fields */}\n {orderGroups.map((g) => (\n <Fragment key={g.id}>\n {g.label && (\n <div className=\"tf-checkout-billing__section-label\">{g.label}</div>\n )}\n {renderGroupFields(g, dataCapture, (name, v) =>\n setDataCapture((d) => ({ ...d, [name]: v }))\n )}\n </Fragment>\n ))}\n\n {/* Marketing opt-ins (optional) */}\n {brandOptInLabel && (\n <Checkbox\n checked={consent.brandOptIn}\n onChange={(e) => setConsent((c) => ({ ...c, brandOptIn: e.target.checked }))}\n className=\"tf-checkout-checkbox--consent\"\n label={brandOptInLabel}\n />\n )}\n {privacyPolicy ? (\n <div\n className={\n (showPrivacyError || showValidation) && !consent.ttfOptIn\n ? 'tf-checkout-consent--error'\n : ''\n }\n data-checkout-invalid={\n ((showPrivacyError || showValidation) && !consent.ttfOptIn) || undefined\n }\n >\n <Checkbox\n required\n checked={consent.ttfOptIn}\n aria-invalid={(showPrivacyError || showValidation) && !consent.ttfOptIn}\n onChange={(e) => setConsent((c) => ({ ...c, ttfOptIn: e.target.checked }))}\n className=\"tf-checkout-checkbox--consent\"\n label={\n <>\n I have read and agree to {privacyPolicy.brandName}{' '}\n <a href={privacyPolicy.url} target=\"_blank\" rel=\"noreferrer\">\n {privacyPolicy.linkLabel || 'Privacy Policy.'}\n </a>\n {' *'}\n </>\n }\n />\n {(showPrivacyError || showValidation) && !consent.ttfOptIn && (\n <div className=\"tf-checkout-consent__error\">Required</div>\n )}\n </div>\n ) : ttfOptInLabel ? (\n <Checkbox\n checked={consent.ttfOptIn}\n onChange={(e) => setConsent((c) => ({ ...c, ttfOptIn: e.target.checked }))}\n className=\"tf-checkout-checkbox--consent\"\n label={ttfOptInLabel}\n />\n ) : null}\n {!combined && (\n <>\n <Button\n block\n onClick={() => {\n if (!complete) {\n validation.requestValidation()\n return\n }\n commit()\n onContinue?.()\n }}\n >\n {buttonLabel}\n </Button>\n </>\n )}\n </Card>\n {showHolders && (\n <TicketHoldersCard\n holders={holders}\n holderNamesRequired={holderNamesRequired}\n collectHolderContact={collectHolderContact}\n phoneCountry={phoneCountry}\n fieldError={fieldError}\n patchHolder={patchHolder}\n renderCustomFields={(holder, index) =>\n ticketGroups.map((group) =>\n renderGroupFields(\n group,\n holder.ticketDataCapture,\n (name, value) =>\n patchHolder(index, {\n ticketDataCapture: {\n ...holder.ticketDataCapture,\n [name]: value,\n },\n }),\n holder.ticketTypeId,\n index\n )\n )\n }\n />\n )}\n </>\n )\n}\n","import React, { type Dispatch, type FC, type SetStateAction } from 'react'\n\nimport { Field, FieldRow, Input, Select } from '../../ui/Field'\nimport type { BillingDraft, BillingFieldError, LocationOption } from './types'\n\ninterface BillingAddressFieldsProps {\n billing: BillingDraft\n countries: LocationOption[]\n states: LocationOption[]\n fieldError: BillingFieldError\n setBilling: Dispatch<SetStateAction<BillingDraft>>\n}\n\n/** Address fields shared by the embedded and stepped billing experiences. */\nexport const BillingAddressFields: FC<BillingAddressFieldsProps> = ({\n billing,\n countries,\n states,\n fieldError,\n setBilling,\n}) => {\n const setValue =\n (key: keyof BillingDraft) => (event: React.ChangeEvent<HTMLInputElement>) =>\n setBilling((current) => ({ ...current, [key]: event.target.value }))\n\n return (\n <>\n <div className=\"tf-checkout-billing__section-label\">Billing address *</div>\n <Field\n error={fieldError('Street address', 'Street address is required.')}\n invalid={Boolean(fieldError('Street address'))}\n >\n <Input\n placeholder=\"Street address *\"\n autoComplete=\"street-address\"\n value={billing.streetAddress ?? ''}\n required\n invalid={Boolean(fieldError('Street address'))}\n aria-invalid={Boolean(fieldError('Street address'))}\n onChange={setValue('streetAddress')}\n />\n </Field>\n <FieldRow>\n <Field\n error={fieldError('City', 'City is required.')}\n invalid={Boolean(fieldError('City'))}\n >\n <Input\n placeholder=\"City *\"\n autoComplete=\"address-level2\"\n value={billing.city ?? ''}\n required\n invalid={Boolean(fieldError('City'))}\n aria-invalid={Boolean(fieldError('City'))}\n onChange={setValue('city')}\n />\n </Field>\n <Field\n error={fieldError('ZIP / postcode', 'ZIP / postcode is required.')}\n invalid={Boolean(fieldError('ZIP / postcode'))}\n >\n <Input\n placeholder=\"ZIP / Postcode *\"\n autoComplete=\"postal-code\"\n value={billing.zip ?? ''}\n required\n invalid={Boolean(fieldError('ZIP / postcode'))}\n aria-invalid={Boolean(fieldError('ZIP / postcode'))}\n onChange={setValue('zip')}\n />\n </Field>\n </FieldRow>\n <FieldRow>\n <Field\n error={fieldError('Country', 'Country is required.')}\n invalid={Boolean(fieldError('Country'))}\n >\n <Select\n value={billing.countryId ?? ''}\n aria-label=\"Country\"\n required\n invalid={Boolean(fieldError('Country'))}\n aria-invalid={Boolean(fieldError('Country'))}\n onChange={(event) => {\n const country = countries.find(\n (candidate) => String(candidate.id) === event.target.value\n )\n setBilling((current) => ({\n ...current,\n countryId: event.target.value,\n countryCode: country?.code?.toUpperCase(),\n stateId: undefined,\n stateCode: undefined,\n }))\n }}\n >\n <option value=\"\">— country * —</option>\n {countries.map((country) => (\n <option key={country.id} value={country.id}>\n {country.name}\n </option>\n ))}\n </Select>\n </Field>\n <Field\n error={fieldError('State / county', 'State / county is required.')}\n invalid={Boolean(fieldError('State / county'))}\n >\n <Select\n value={billing.stateId ?? ''}\n disabled={!billing.countryId || states.length === 0}\n aria-label=\"State / region\"\n required={states.length > 0}\n invalid={Boolean(fieldError('State / county'))}\n aria-invalid={Boolean(fieldError('State / county'))}\n onChange={(event) => {\n const state = states.find(\n (candidate) => String(candidate.id) === event.target.value\n )\n setBilling((current) => ({\n ...current,\n stateId: event.target.value,\n stateCode: state?.code,\n }))\n }}\n >\n <option value=\"\">— state / county{states.length > 0 ? ' *' : ''} —</option>\n {states.map((state) => (\n <option key={state.id} value={state.id}>\n {state.name}\n </option>\n ))}\n </Select>\n </Field>\n </FieldRow>\n </>\n )\n}\n","import React, { type FC, type ReactNode } from 'react'\n\nimport type { BuyerFieldSpec } from 'tf-checkout-shared'\n\nimport { Field, Input, Select } from '../../ui/Field'\nimport type { LocationOption } from './types'\n\ninterface BuyerFieldProps {\n field: BuyerFieldSpec\n value: string\n countries: LocationOption[]\n error?: ReactNode\n onChange: (value: string) => void\n}\n\n/** Renders one backend-configured buyer field without owning form state. */\nexport const BuyerField: FC<BuyerFieldProps> = ({\n field,\n value,\n countries,\n error,\n onChange,\n}) => {\n const label = `${field.label}${field.required ? ' *' : ''}`\n const invalid = error !== undefined && error !== null\n\n if (field.kind === 'gender') {\n return (\n <Field label={label} error={error} invalid={invalid}>\n <Select\n value={value}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(event) => onChange(event.target.value)}\n >\n <option value=\"\">— select —</option>\n <option value=\"M\">Male</option>\n <option value=\"F\">Female</option>\n </Select>\n </Field>\n )\n }\n\n if (field.kind === 'nationality') {\n return (\n <Field label={label} error={error} invalid={invalid}>\n <Select\n value={value}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(event) => onChange(event.target.value)}\n >\n <option value=\"\">— select —</option>\n {countries.map((country) => (\n <option key={country.id} value={country.id}>\n {country.name}\n </option>\n ))}\n </Select>\n </Field>\n )\n }\n\n return (\n <Field label={label} error={error} invalid={invalid}>\n <Input\n placeholder=\"@handle or profile URL\"\n value={value}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(event) => onChange(event.target.value)}\n />\n </Field>\n )\n}\n","/**\n * Small value rules shared by the billing form's inputs. They live here rather\n * than in `../BillingInfo.tsx` so that file stays inside the checkout\n * architecture budget, and because each one encodes a non-obvious constraint\n * worth stating once.\n */\n\n/**\n * The phone control keeps the dial code outside the input, so it reports a bare\n * `\"+52\"` the moment it mounts — before the buyer has typed anything. A string\n * that short is a country prefix, not a number, so treat it as blank: it must\n * not out-rank a saved profile number, and it must never reach the API as a\n * phone in its own right.\n */\nexport const isBlankPhone = (phone?: string) =>\n !phone || /^\\+?\\d{0,4}$/.test(phone.trim())\n\n/** Earliest date of birth the form accepts. Nobody alive predates it. */\nexport const DOB_MIN = '1900-01-01'\n\n/**\n * Today as `yyyy-mm-dd` in the buyer's own timezone. Built from the local\n * calendar parts rather than `toISOString()`, which would roll over to\n * tomorrow's date for anyone east of Greenwich late in the day.\n */\nexport const todayISO = () => {\n const now = new Date()\n return [\n now.getFullYear(),\n String(now.getMonth() + 1).padStart(2, '0'),\n String(now.getDate()).padStart(2, '0'),\n ].join('-')\n}\n\n/** `dobDay/dobMonth/dobYear` → the `yyyy-mm-dd` a date input expects. */\nexport const toDateInputValue = (\n year?: number,\n month?: number,\n day?: number\n): string | undefined =>\n year && month && day\n ? `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`\n : undefined\n","import React, { type FC, type ReactNode } from 'react'\nimport { PhoneInput, type CountryIso2 } from 'react-international-phone'\n\nimport { Card, SectionHeader } from '../../ui/Card'\nimport { Field, FieldRow, Input } from '../../ui/Field'\nimport type { BillingFieldError, HolderDraft } from './types'\n\ninterface TicketHoldersCardProps {\n holders: HolderDraft[]\n holderNamesRequired: boolean\n collectHolderContact: boolean\n phoneCountry: CountryIso2\n fieldError: BillingFieldError\n renderCustomFields: (holder: HolderDraft, index: number) => ReactNode\n patchHolder: (index: number, patch: Partial<HolderDraft>) => void\n}\n\n/** Ticket-holder card kept separate from buyer billing for parity and reuse. */\nexport const TicketHoldersCard: FC<TicketHoldersCardProps> = ({\n holders,\n holderNamesRequired,\n collectHolderContact,\n phoneCountry,\n fieldError,\n renderCustomFields,\n patchHolder,\n}) => (\n <Card className=\"tf-checkout-billing__holders-card\">\n <SectionHeader title=\"Ticket Holders\" />\n {holders.map((holder, index) => {\n const firstNameKey = `Ticket ${index + 1} holder first name`\n const lastNameKey = `Ticket ${index + 1} holder last name`\n const emailKey = `Ticket ${index + 1} holder email`\n const phoneKey = `Ticket ${index + 1} holder phone`\n\n return (\n <div key={index} className=\"tf-checkout-billing__holder\">\n <div className=\"tf-checkout-billing__holder-title\">Ticket {index + 1}</div>\n {holderNamesRequired && (\n <FieldRow>\n <Field\n label=\"First Name *\"\n error={fieldError(firstNameKey, 'First name is required.')}\n invalid={Boolean(fieldError(firstNameKey))}\n >\n <Input\n value={holder.firstName}\n required\n invalid={Boolean(fieldError(firstNameKey))}\n aria-invalid={Boolean(fieldError(firstNameKey))}\n onChange={(event) =>\n patchHolder(index, { firstName: event.target.value })\n }\n />\n </Field>\n <Field\n label=\"Last Name *\"\n error={fieldError(lastNameKey, 'Last name is required.')}\n invalid={Boolean(fieldError(lastNameKey))}\n >\n <Input\n value={holder.lastName}\n required\n invalid={Boolean(fieldError(lastNameKey))}\n aria-invalid={Boolean(fieldError(lastNameKey))}\n onChange={(event) =>\n patchHolder(index, { lastName: event.target.value })\n }\n />\n </Field>\n </FieldRow>\n )}\n {collectHolderContact && (\n <FieldRow>\n <Field\n label=\"Email Address *\"\n error={fieldError(emailKey, 'Enter a valid email address.')}\n invalid={Boolean(fieldError(emailKey))}\n >\n <Input\n type=\"email\"\n autoComplete=\"email\"\n value={holder.email}\n required\n invalid={Boolean(fieldError(emailKey))}\n aria-invalid={Boolean(fieldError(emailKey))}\n onChange={(event) => patchHolder(index, { email: event.target.value })}\n />\n </Field>\n <Field\n label=\"Phone *\"\n error={fieldError(phoneKey, 'Enter a valid phone number.')}\n invalid={Boolean(fieldError(phoneKey))}\n >\n <PhoneInput\n className=\"tf-checkout-phone\"\n inputClassName={`tf-checkout-input tf-checkout-phone__input${\n fieldError(phoneKey) ? ' tf-checkout-input--invalid' : ''\n }`}\n defaultCountry={phoneCountry}\n // Matches the buyer phone field in ../BillingInfo.tsx — see\n // the note there on why the dial code must stay out of the\n // input.\n disableDialCodeAndPrefix\n showDisabledDialCodeAndPrefix\n disableDialCodePrefill\n value={holder.phone}\n required\n inputProps={{\n autoComplete: 'tel',\n 'aria-label': phoneKey,\n 'aria-invalid': Boolean(fieldError(phoneKey)),\n }}\n onChange={(phone) => patchHolder(index, { phone })}\n />\n </Field>\n </FieldRow>\n )}\n {renderCustomFields(holder, index)}\n </div>\n )\n })}\n </Card>\n)\n","/**\n * `<Payment/>` — order review + payment-method selection + T&C, then place the\n * order. Buyer details come from `<BillingInfo/>` (read back off the shared\n * checkout). The method list is built from the event's gateway + `preOrderMethods()`\n * + the priced snapshot, and each selection maps to the right `placeOrder` rail\n * (Stripe card, Xendit card/e-wallet, PayPal, redirect rails, payment plan).\n */\nimport React, { useEffect, useMemo, useRef, useState, type FC } from 'react'\n\nimport {\n XENDIT_EWALLET_EXTRA_FIELD,\n errorMessage,\n missingCheckoutDetails,\n paymentPlanTerms,\n planConfirmLabel,\n planTermsTitle,\n ttf,\n type EventCondition,\n type PaymentRequest,\n type PlaceOrderResult,\n} from 'tf-checkout-shared'\n\nimport { CardInput, StripePaymentElement, XenditCardInput } from '../CardInput'\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext, useCheckoutValidation } from '../ui/CheckoutProvider'\nimport { Checkbox } from '../ui/Field'\nimport { cx } from '../ui/cx'\nimport { Loader } from '../ui/Loader'\nimport { PaymentMethods, type PaymentMethodOption } from '../ui/PaymentMethods'\nimport { OrderSummary } from './OrderSummary'\n\ntype PreOrderMethods = Awaited<ReturnType<typeof ttf.cart.preOrderMethods>>\n\n/** Server spellings → display labels for Stripe redirect rails. */\nconst REDIRECT_LABELS: Record<string, string> = {\n klarna: 'Klarna',\n afterpay_clearpay: 'Afterpay / Clearpay',\n affirm: 'Affirm',\n ideal: 'iDEAL',\n bancontact: 'Bancontact',\n eps: 'EPS',\n giropay: 'giropay',\n p24: 'Przelewy24',\n alipay: 'Alipay',\n grabpay: 'GrabPay',\n cashapp: 'Cash App Pay',\n paypal: 'PayPal',\n}\nconst redirectLabel = (t: string) =>\n REDIRECT_LABELS[t] ?? t.replace(/_/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase())\n\nconst isCardFieldError = (message: string) =>\n /(?:card|expiry|expiration|security code|cvc).*(?:incomplete|required|invalid)|(?:incomplete|required|invalid).*(?:card|expiry|expiration|security code|cvc)/i.test(\n message\n )\n\n/**\n * Anything the buyer would fix AT THE CARD FIELD — a bad number, a wrong CVC,\n * an expired or declined card, missing details. These belong beside the card\n * box; only order-level problems (conditions, billing, network) belong down by\n * the pay button, where a card message is easy to miss entirely.\n */\nconst isCardAreaError = (message: string) =>\n isCardFieldError(message) ||\n /card details|security code|cvc|cvv|expired|declined|not accepted|balance|stolen|inactive|authentication failed|name on the card|different card/i.test(\n message\n )\n\nexport interface PaymentProps {\n onComplete?: (order: PlaceOrderResult) => void\n /** Optional event context adds the event name to the order review. */\n eventId?: string\n /** Must match the policy used by the paired `<BillingInfo/>`. */\n requireEmailConfirmation?: boolean\n /** Must match the holder policy used by the paired `<BillingInfo/>`. */\n collectTicketHolders?: boolean\n /** Must match the holder-contact policy used by the paired `<BillingInfo/>`. */\n requireHolderContact?: boolean\n /** Host-owned acknowledgements such as a brand privacy policy. */\n additionalConditions?: EventCondition[]\n /** Require the privacy checkbox managed by BillingInfo before payment. */\n requirePrivacyPolicy?: boolean\n /** Called when payment is attempted before required privacy consent. */\n onPrivacyRequired?: () => void\n /** Test card copy is useful in examples, but should never appear by default. */\n showTestCardHint?: boolean\n className?: string\n}\n\nexport const Payment: FC<PaymentProps> = ({\n onComplete,\n eventId,\n requireEmailConfirmation = false,\n collectTicketHolders = false,\n requireHolderContact = false,\n additionalConditions = [],\n requirePrivacyPolicy = false,\n onPrivacyRequired,\n showTestCardHint = false,\n className,\n}) => {\n const checkout = useCheckoutContext()\n const validation = useCheckoutValidation()\n const [error, setError] = useState('')\n /** Field-level problem reported by `<XenditCardInput/>` (it renders none). */\n const [cardFieldError, setCardFieldError] = useState<string | null>(null)\n /** Card problem from the last pay attempt (declined, wrong CVC, expired…). */\n const [payCardError, setPayCardError] = useState<string | null>(null)\n /** True once the buyer edits the card after a failed attempt — their fix\n * supersedes both our message and the engine's stale one. */\n const [cardEditedSincePay, setCardEditedSincePay] = useState(true)\n const [methods, setMethods] = useState<PreOrderMethods | null>(null)\n const [selected, setSelected] = useState('')\n const [extras, setExtras] = useState<\n Record<string, { cashtag?: string; phoneNumber?: string }>\n >({})\n const [useSavedCard, setUseSavedCard] = useState(true)\n const cardSectionRef = useRef<HTMLDivElement | null>(null)\n\n useEffect(() => {\n let active = true\n ttf.cart\n .preOrderMethods()\n .then((m) => active && setMethods(m))\n .catch(() => active && setMethods(null))\n return () => {\n active = false\n }\n }, [])\n\n const bd = checkout.breakdown\n const isFree = bd != null && Number(bd.total) === 0\n const isXendit = checkout.gateway === 'xendit'\n\n // Whether the server put OXXO on the deferred Elements config. This is\n // `Checkout::get_payment_method_types()`'s verdict — the event's own OXXO\n // flag, the voucher-expiry window against the event date, an MX Stripe\n // account, a MXN 10–10,000 total, and no manual capture. Several of those\n // inputs (the Stripe account's country, per-ticket ID verification, the\n // event's timezone) have no client-side equivalent, so this must never be\n // re-derived here. Absent config (free carts, Xendit, Razorpay) → false,\n // which is what the legacy checkout does too.\n const serverMethodTypes = (\n checkout.stripeElementsConfig as { paymentMethodTypes?: unknown } | undefined\n )?.paymentMethodTypes\n const offersOxxo =\n Array.isArray(serverMethodTypes) && serverMethodTypes.includes('oxxo')\n\n // Build the selectable method rows from gateway + probe + snapshot.\n const options = useMemo<PaymentMethodOption[]>(() => {\n if (isFree || !methods) return []\n const out: PaymentMethodOption[] = []\n if (isXendit) {\n if (methods.xenditCard)\n out.push({ id: { kind: 'xenditCard' }, value: 'xenditCard', label: 'Card' })\n for (const w of methods.xenditEWallets)\n out.push({\n id: { kind: 'xenditEWallet', walletKey: w.key },\n value: `ew:${w.key}`,\n label: w.label,\n iconUrl: w.icon,\n extra: (XENDIT_EWALLET_EXTRA_FIELD[w.key] as 'cashtag' | 'phoneNumber') ?? null,\n })\n } else if (checkout.gateway === 'razorpay') {\n out.push({ id: { kind: 'razorpay' }, value: 'razorpay', label: 'Razorpay' })\n } else {\n // Stripe (or unknown → fail open to card).\n out.push({ id: { kind: 'card' }, value: 'card', label: 'Card' })\n for (const t of checkout.redirectPaymentMethods ?? []) {\n if (t === 'paypal' && methods.paypal) continue // dedupe vs PayPal Standard\n out.push({\n id: { kind: 'redirect', methodType: t },\n value: `rd:${t}`,\n label: redirectLabel(t),\n })\n }\n if (checkout.paymentPlan?.available)\n out.push({\n id: { kind: 'paymentPlan' },\n value: 'paymentPlan',\n label: 'Payment plan',\n })\n // OXXO cash voucher. `oxxo` is deliberately absent from\n // SUPPORTED_REDIRECT_METHODS, so it never arrives via the loop above.\n if (offersOxxo)\n out.push({ id: { kind: 'oxxo' }, value: 'oxxo', label: 'OXXO (pay in cash)' })\n }\n if (methods.paypal)\n out.push({ id: { kind: 'paypal' }, value: 'paypal', label: 'PayPal' })\n return out\n }, [\n isFree,\n methods,\n isXendit,\n checkout.gateway,\n checkout.redirectPaymentMethods,\n checkout.paymentPlan,\n offersOxxo,\n ])\n\n // Default the selection to the first row once options exist.\n useEffect(() => {\n if (options.length && !options.some((o) => o.value === selected))\n setSelected(options[0].value)\n }, [options, selected])\n\n const cardValue = isXendit ? 'xenditCard' : 'card'\n const selectedOption = options.find((o) => o.value === selected)\n const isCardSelected = selected === cardValue\n const isPlanSelected = selectedOption?.id.kind === 'paymentPlan'\n const savedLast4 = checkout.paymentPlan?.savedCardLast4\n /**\n * \"Reuse the card on file\" only means something when there IS one. The raw\n * `useSavedCard` toggle defaults to true (matching the hosted default-checked\n * box), so reading it directly made a first-time buyer look like a returning\n * one: `inputSlotFor` collapsed to undefined, the card field and the plan\n * terms never mounted, and \"Confirm Payment Plan\" then failed in the\n * confirmer with \"No card element registered\". Always gate on the card.\n */\n const reuseSavedCard = Boolean(savedLast4) && useSavedCard\n const usesCardDetails =\n !isFree && (isCardSelected || (isPlanSelected && !reuseSavedCard))\n // Stripe's CardElement renders its own inline \"Card number is invalid\" text, so\n // the pay handler can stay quiet and just scroll to it. Xendit's card form is\n // three plain inputs with no error slot — there, the message MUST be shown or\n // a declined/invalid card looks like the button simply did nothing.\n const cardWidgetReportsItsOwnError = usesCardDetails && !isXendit\n\n // Wallets the old-checkout way: when the event's `stripe_wallets` gate is on,\n // render the Payment Element (card + Apple/Google Pay in one widget) instead of\n // the bare card field. Held back for MXN so the CardElement-based MSI path\n // (Mexican months-without-interest) keeps working — matching old, which didn't\n // run MSI off its web Payment Element either.\n const hasWallets = Boolean(\n checkout.walletAvailability?.applePay || checkout.walletAvailability?.googlePay\n )\n // A payment plan NEVER rides the wallet element, matching the hosted flow's\n // `wallets: planMode ? { applePay: 'never', googlePay: 'never' }`. Two\n // reasons, both load-bearing:\n // 1. A plan charges installments off-session, so it needs a REUSABLE card.\n // Wallet tokens are typically single-use and can't be charged later.\n // 2. Mechanically: the plan rail confirms via `confirmer.getCardElement()`,\n // which only exists for `<CardInput/>`. The Payment Element registers\n // itself through `registerPaymentElement` instead, so mounting it here\n // made `confirmPaymentPlanSetup` throw \"No card element registered\" —\n // the plan could never be completed on a wallet-enabled event.\n const useWalletElement =\n !isXendit &&\n !isPlanSelected &&\n hasWallets &&\n checkout.breakdown?.currencyCode !== 'MXN' &&\n Boolean((checkout.stripeElementsConfig as { mode?: unknown } | undefined)?.mode)\n\n // When there's only ONE way to pay and it's a card, there's nothing to\n // *choose* — the old checkout just showed the card form, no radio wrapper.\n // Render the field directly; keep the radio list only when there's a choice.\n const onlyOption = options.length === 1 ? options[0] : undefined\n const singleCard =\n onlyOption?.id.kind === 'card' || onlyOption?.id.kind === 'xenditCard'\n\n // Gating: buyer + every configured holder/custom field complete, required\n // conditions accepted, and payment-method extras filled.\n const b = checkout.billing\n const missingDetails = missingCheckoutDetails(\n {\n billing: b,\n holders: checkout.holders,\n selections: checkout.selections,\n breakdown: checkout.breakdown,\n holderNamesRequired: checkout.holderNamesRequired,\n fieldGates: checkout.fieldGates,\n customFields: checkout.customFields,\n },\n { requireEmailConfirmation, collectTicketHolders, requireHolderContact }\n )\n const billingReady = missingDetails.length === 0\n const conditions = [...(checkout.conditions ?? []), ...additionalConditions]\n const requiredConditions = conditions.filter((c) => c.isRequired)\n const conditionsOk = requiredConditions.every(\n (c) => checkout.acceptedConditions?.[c.id]\n )\n const extra = selectedOption?.extra\n const extrasOk =\n !extra ||\n (extra === 'cashtag'\n ? Boolean(extras[selected]?.cashtag?.trim())\n : Boolean(extras[selected]?.phoneNumber?.trim()))\n const privacyOk = !requirePrivacyPolicy || checkout.consent.ttfOptIn\n // The plan CTA carries the brand's terminology (\"Confirm Layaway\"), and the\n // terms sentence quotes this same label — they must agree.\n const payLabel = isFree\n ? 'Complete Registration'\n : isPlanSelected\n ? planConfirmLabel(checkout.paymentPlan?.configuration)\n : 'Submit Payment'\n const planTerms = paymentPlanTerms(checkout.paymentPlan?.configuration)\n // 'placing' → order in flight; 'succeeded' → placed, host navigating away.\n // Both keep the CTA busy so it can't be re-clicked during the handoff.\n const finalizing = checkout.status === 'placing' || checkout.status === 'succeeded'\n\n const pay = () => {\n setError('')\n setPayCardError(null)\n setCardEditedSincePay(false)\n if (!billingReady || !conditionsOk || !extrasOk || !privacyOk) {\n if (!privacyOk) onPrivacyRequired?.()\n validation.requestValidation()\n return\n }\n // Backfill one holder per ticket if billing was set without holders.\n if (checkout.holders.length === 0 && b) {\n const n = checkout.selections.reduce((acc, s) => acc + s.quantity, 0) || 1\n checkout.setHolders(\n Array.from({ length: n }, () => ({\n firstName: b.firstName,\n lastName: b.lastName,\n email: b.email,\n }))\n )\n }\n let req: PaymentRequest = { method: 'auto' }\n const id = selectedOption?.id\n if (isFree || !id) req = { method: 'auto' }\n else if (id.kind === 'xenditEWallet')\n req = { method: 'xenditEWallet', walletKey: id.walletKey, extra: extras[selected] }\n else if (id.kind === 'redirect')\n req = { method: 'redirect', methodType: id.methodType }\n else if (id.kind === 'paymentPlan')\n req = { method: 'paymentPlan', useSavedCard: reuseSavedCard }\n else req = { method: id.kind } as PaymentRequest\n // NOTE: called synchronously in the click handler — popup rails (e-wallet,\n // redirect, razorpay, paypal) need the user gesture or the browser blocks them.\n checkout\n .placeOrder(req)\n .then((order) => onComplete?.(order))\n .catch((e) => {\n const message = errorMessage(e)\n if (usesCardDetails && isCardAreaError(message)) {\n const behavior = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n ? 'auto'\n : 'smooth'\n cardSectionRef.current?.scrollIntoView({ behavior, block: 'center' })\n // Stripe's CardElement prints the message inside its own widget, so\n // scrolling to it is enough. Ours doesn't — show it AT the card box,\n // not down by the button where it reads as an unrelated failure.\n if (cardWidgetReportsItsOwnError) return\n setPayCardError(message)\n return\n }\n setError(message)\n })\n }\n\n // A card problem surfaced by the engine belongs at the box too, not under the\n // pay button — same rule as the ones we catch in `pay()`.\n // Whether the engine's error is a CARD problem at all. This must not depend on\n // whether the buyer has since edited: the edit decides if we still SHOW it, it\n // must never decide whether it may fall through to the button (it may not — a\n // card error belongs at the card, always).\n const engineErrorIsCardArea = Boolean(\n isXendit && checkout.error && isCardAreaError(checkout.error)\n )\n const engineCardError =\n engineErrorIsCardArea && !cardEditedSincePay ? checkout.error : ''\n // The buyer's live field state wins over a stale decline from a past attempt.\n const cardAreaError = cardFieldError || payCardError || engineCardError\n const checkoutError =\n checkout.error &&\n !(cardWidgetReportsItsOwnError && isCardFieldError(checkout.error)) &&\n !engineErrorIsCardArea\n ? checkout.error\n : ''\n // Single gate for the message under the pay button: whatever the source, a\n // card problem is shown at the card and NEVER duplicated down here.\n const bottomMessage = error || checkoutError\n const bottomError =\n bottomMessage && isXendit && isCardAreaError(bottomMessage) ? '' : bottomMessage\n\n // The card/plan field + its note + plan terms. Rendered inside the selected\n // method row when there's a choice, or directly when there's only a card.\n const paymentInput = (\n <>\n {(isCardSelected || (isPlanSelected && !reuseSavedCard)) && (\n <>\n {useWalletElement ? (\n // The Payment Element frames itself — don't box it again.\n <div ref={cardSectionRef} className=\"tf-checkout-payment__element\">\n <StripePaymentElement\n elementsConfig={checkout.stripeElementsConfig}\n wallets={checkout.walletAvailability}\n />\n </div>\n ) : (\n <div\n ref={cardSectionRef}\n className={cx(\n 'tf-checkout-payment__cardbox',\n isXendit && cardAreaError && 'tf-checkout-payment__cardbox--invalid'\n )}\n >\n {isXendit ? (\n <XenditCardInput\n onValidationChange={(m) => {\n setCardFieldError(m)\n // Any edit supersedes the previous attempt's verdict — the\n // buyer shouldn't be told a number is invalid while they're\n // typing a valid one.\n setPayCardError(null)\n setCardEditedSincePay(true)\n }}\n />\n ) : (\n <CardInput />\n )}\n </div>\n )}\n {/* Below the box, not inside it — Stripe prints its own message within\n its iframe, but the Xendit fields are ours to caption. */}\n {isXendit && cardAreaError && (\n <p className=\"tf-checkout-error-text\">{cardAreaError}</p>\n )}\n {showTestCardHint && (\n <p className=\"tf-checkout-note\">\n {isXendit\n ? 'Test card: 4000 0000 0000 0002 · any future date · any CVC'\n : 'Test card: 4242 4242 4242 4242 · any future date · any CVC'}\n </p>\n )}\n </>\n )}\n {/* The full hosted terms block. Composed in the SDK so web and native\n state the identical schedule, admin fee and non-refundable clause —\n these are disclosures, not summary copy. */}\n {isPlanSelected && planTerms.length > 0 && (\n <div className=\"tf-checkout-payment__plan\">\n <strong>{planTermsTitle(checkout.paymentPlan!.configuration!)}</strong>\n {planTerms.map((part) => (\n <p key={part.id} className=\"tf-checkout-note\">\n {part.text}\n </p>\n ))}\n </div>\n )}\n {/* Returning plan buyer with a reusable card on file. Ticked by default,\n and when it stays ticked the card fields never mount — the plan is\n created straight off the saved payment method, like the hosted flow. */}\n {isPlanSelected && savedLast4 && (\n <div className=\"tf-checkout-payment__plan-savedcard\">\n <p className=\"tf-checkout-note\">\n Your payment will proceed with the card ending in{' '}\n <strong>**** {savedLast4}</strong>\n </p>\n <Checkbox\n checked={useSavedCard}\n onChange={(e) => setUseSavedCard(e.target.checked)}\n label=\"Use this card\"\n />\n </div>\n )}\n </>\n )\n\n return (\n <div className={['tf-checkout-payment-stack', className].filter(Boolean).join(' ')}>\n <Card>\n <SectionHeader title=\"Payment\" />\n\n {/* Payment method */}\n {!isFree && (\n <>\n {!singleCard && (\n <div className=\"tf-checkout-payment__label\">Payment method</div>\n )}\n {!methods ? (\n <div className=\"tf-checkout-payment__cardbox\">\n <Loader />\n </div>\n ) : singleCard ? (\n paymentInput\n ) : (\n <PaymentMethods\n options={options}\n selected={selected}\n onSelect={setSelected}\n extraValues={extras}\n onExtraChange={(v, patch) =>\n setExtras((s) => ({ ...s, [v]: { ...s[v], ...patch } }))\n }\n showValidation={validation.attempt > 0}\n /**\n * The plan row ALWAYS owns the slot when it's selected. This\n * used to be conditional on needing a card field, which meant a\n * returning buyer reusing their saved card got `undefined` — and\n * `undefined` renders the children nowhere, so the plan terms\n * AND the \"card ending in ****\" block both vanished. The card\n * field inside is separately gated on `!reuseSavedCard`, so the\n * slot itself never needs to be.\n */\n inputSlotFor={isPlanSelected ? 'paymentPlan' : cardValue}\n >\n {paymentInput}\n </PaymentMethods>\n )}\n </>\n )}\n\n {/* Conditions */}\n {conditions.map((c) => {\n const invalid =\n validation.attempt > 0 && c.isRequired && !checkout.acceptedConditions?.[c.id]\n return (\n <div\n key={c.id}\n className={invalid ? 'tf-checkout-consent--error' : undefined}\n data-checkout-invalid={invalid || undefined}\n >\n <Checkbox\n required={c.isRequired}\n checked={Boolean(checkout.acceptedConditions?.[c.id])}\n aria-invalid={invalid}\n onChange={(e) => checkout.acceptCondition(c.id, e.target.checked)}\n label={\n <>\n <span dangerouslySetInnerHTML={{ __html: c.content || c.name }} />\n {c.isRequired && ' *'}\n </>\n }\n />\n {invalid && (\n <div className=\"tf-checkout-consent__error\">\n You must accept this condition to continue.\n </div>\n )}\n </div>\n )\n })}\n </Card>\n\n <OrderSummary eventId={eventId} />\n\n <div className=\"tf-checkout-payment__cta\">\n <Button\n onClick={pay}\n // Stay busy through 'succeeded' too: in redirect mode the checkout\n // remains mounted while the host navigates away, so the button must\n // not flicker back to a clickable state before the redirect lands.\n loading={finalizing}\n disabled={checkout.isBusy || finalizing || (!isFree && !methods)}\n >\n {finalizing ? 'Placing…' : payLabel}\n </Button>\n </div>\n {bottomError && <p className=\"tf-checkout-error-text\">{bottomError}</p>}\n </div>\n )\n}\n","import React, { type FC } from 'react'\n\nimport { hooks } from 'tf-checkout-shared'\n\nimport { Card } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\n\nexport interface OrderSummaryProps {\n eventId?: string\n className?: string\n}\n\n/** Storefront-compatible order summary shown after the checkout controls. */\nexport const OrderSummary: FC<OrderSummaryProps> = ({ eventId, className }) => {\n const checkout = useCheckoutContext()\n const event = hooks.useEvent(eventId)\n const breakdown = checkout.breakdown\n const detailed = checkout.priceBreakdown\n\n if (!breakdown || breakdown.tickets.length === 0) return null\n\n return (\n <Card className={['tf-checkout-order-summary', className].filter(Boolean).join(' ')}>\n {event.data?.name && (\n <div className=\"tf-checkout-order-summary__group\">\n <div className=\"tf-checkout-order-summary__label\">Event</div>\n <div className=\"tf-checkout-order-summary__event\">{event.data.name}</div>\n </div>\n )}\n\n <div className=\"tf-checkout-order-summary__group\">\n <div className=\"tf-checkout-order-summary__label\">Your Tickets</div>\n {breakdown.tickets.map((ticket, index) => {\n const detail = detailed?.tickets[index]\n return (\n <div\n key={`${ticket.ticketTypeId}-${index}`}\n className=\"tf-checkout-order-summary__item\"\n >\n <div className=\"tf-checkout-order-summary__ticket\">\n {ticket.quantity} x {ticket.name} - {detail?.unit_price ?? ticket.unit}{' '}\n each\n </div>\n {detail?.line_total && detail.line_total !== detail.unit_price && (\n <div className=\"tf-checkout-order-summary__fees\">\n ({detail.line_total} with fees)\n </div>\n )}\n </div>\n )\n })}\n </div>\n\n {(detailed?.add_ons.length ?? 0) > 0 && (\n <div className=\"tf-checkout-order-summary__group\">\n <div className=\"tf-checkout-order-summary__label\">\n {detailed?.add_ons_title || 'Add-ons'}\n </div>\n {detailed?.add_ons.map((addOn, index) => (\n <div\n key={`${addOn.name}-${index}`}\n className=\"tf-checkout-order-summary__item\"\n >\n <div className=\"tf-checkout-order-summary__ticket\">\n {addOn.quantity} x {addOn.name}\n {addOn.show_price ? ` - ${addOn.unit_price} each` : ''}\n </div>\n </div>\n ))}\n </div>\n )}\n\n <div className=\"tf-checkout-order-summary__total\">\n <div className=\"tf-checkout-order-summary__label\">Total</div>\n <div className=\"tf-checkout-order-summary__amount\">\n {detailed?.total ??\n `${breakdown.currencySymbol || `${breakdown.currencyCode} `}${Number(\n breakdown.total\n ).toFixed(2)}`}\n </div>\n </div>\n </Card>\n )\n}\n","/**\n * `<IDVerification/>` — shown after an order that needs identity verification\n * (`order.needIdVerification`). Kicks off the engine's verify flow: mint the\n * provider URL, open it, and poll to completion, reflecting each phase. The\n * order is already paid — a stall here never means a failed payment.\n *\n * If you place your order with `placeOrder(method, { autoRunIdVerification:true })`\n * the engine runs this for you; this section is the manual, visible counterpart.\n */\nimport React, { useState, type FC } from 'react'\n\nimport { errorMessage, type IdVerificationPhase } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { cx } from '../ui/cx'\n\ntype UiPhase = IdVerificationPhase | 'starting'\n\nconst MESSAGE: Record<UiPhase, string> = {\n idle: 'To complete the purchase, please verify your identity.',\n starting: 'Opening the verification page…',\n polling: 'Waiting for verification to complete in the other tab…',\n verified: 'Identity verified — your tickets are on their way.',\n timeout: 'Still not confirmed. Finish in the other tab, then check again.',\n error: 'We couldn’t reach the verification service. Try again.',\n}\n\nexport interface IDVerificationProps {\n className?: string\n}\n\nexport const IDVerification: FC<IDVerificationProps> = ({ className }) => {\n const checkout = useCheckoutContext()\n const order = checkout.order\n const [phase, setPhase] = useState<UiPhase>('idle')\n const [error, setError] = useState('')\n\n if (!order?.needIdVerification) return null\n\n const done = phase === 'verified'\n const running = phase === 'starting' || phase === 'polling'\n\n const run = () => {\n setError('')\n setPhase('starting')\n checkout\n .runIdVerification(order.orderHash, {\n openUrl: (url) => {\n if (url) window.open(url, '_blank', 'noopener,noreferrer')\n },\n onPhase: (p) => setPhase(p),\n })\n .then((status) => setPhase(status?.verified ? 'verified' : 'polling'))\n .catch((e) => {\n setPhase('error')\n setError(errorMessage(e))\n })\n }\n\n return (\n <Card className={cx('tf-checkout-idverify', className)}>\n <SectionHeader title=\"Account Verification\" />\n <p className={cx('tf-checkout-note', done && 'tf-checkout-idverify__done')}>\n {MESSAGE[phase]}\n </p>\n {!done && (\n <Button block onClick={run} loading={running} disabled={running}>\n {phase === 'idle' ? 'Verify' : running ? 'Verifying…' : 'Check again'}\n </Button>\n )}\n {error && <p className=\"tf-checkout-error-text\">{error}</p>}\n </Card>\n )\n}\n","/**\n * `<Confirmation/>` — the order-placed receipt + a referral/share growth block\n * (invite friends → cheaper/free tickets). Reads the settled order off the\n * shared checkout; returns null until an order exists.\n *\n * Fire purchase tracking (Meta Pixel / GTM) from the `onComplete(order)` callback\n * you already pass to `<Payment/>` / `<EmbeddedCheckout/>` — the SDK stays analytics-\n * agnostic. The referral REWARD ladder (\"how much cheaper\") needs the order\n * confirmation payload, which is left to the consumer (pass `children`); the\n * share affordances below need no backend data.\n */\nimport React, { useState, type FC, type ReactNode } from 'react'\n\nimport { Button } from '../ui/Button'\nimport { Card } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { cx } from '../ui/cx'\n\nexport interface ConfirmationProps {\n /** URL friends land on (referral/event page). Defaults to the current page. */\n shareUrl?: string\n /** Message prefilled into social shares. */\n shareMessage?: string\n /** Link to the buyer's tickets/order — renders a \"View my tickets\" button. */\n viewOrderUrl?: string\n /** Extra content (e.g. your own referral-reward ladder from the order payload). */\n children?: ReactNode\n className?: string\n}\n\nexport const Confirmation: FC<ConfirmationProps> = ({\n shareUrl,\n shareMessage = 'I just got my tickets — grab yours!',\n viewOrderUrl,\n children,\n className,\n}) => {\n const checkout = useCheckoutContext()\n const order = checkout.order\n const [copied, setCopied] = useState(false)\n\n if (!order) return null\n const pending = order.pending\n\n const url = shareUrl ?? (typeof window !== 'undefined' ? window.location.href : '')\n const enc = encodeURIComponent\n const shares: { label: string; href: string }[] = url\n ? [\n {\n label: 'Facebook',\n href: `https://www.facebook.com/sharer/sharer.php?u=${enc(url)}`,\n },\n {\n label: 'X',\n href: `https://twitter.com/intent/tweet?url=${enc(url)}&text=${enc(\n shareMessage\n )}`,\n },\n {\n label: 'WhatsApp',\n href: `https://wa.me/?text=${enc(`${shareMessage} ${url}`)}`,\n },\n ]\n : []\n\n const copy = () => {\n if (!url || typeof navigator === 'undefined' || !navigator.clipboard) return\n navigator.clipboard.writeText(url).then(\n () => {\n setCopied(true)\n setTimeout(() => setCopied(false), 1500)\n },\n () => undefined\n )\n }\n\n return (\n <Card className={cx('tf-checkout-confirmation', className)}>\n <span className=\"tf-checkout-confirmation__check\">{pending ? '⏳' : '✓'}</span>\n <strong className=\"tf-checkout-confirmation__title\">\n {pending ? 'Payment pending' : 'Your Tickets are Confirmed!'}\n </strong>\n <p className=\"tf-checkout-note\">\n {pending\n ? 'We’ll email your tickets as soon as the payment settles.'\n : order.alreadyPaid\n ? 'This order was already paid — nothing was charged again.'\n : 'Your tickets are available in the My Tickets section — please bring them with you to the event.'}\n </p>\n {order.orderHash && (\n <p className=\"tf-checkout-confirmation__ref\">Reference: {order.orderHash}</p>\n )}\n\n {pending && order.pendingVoucherUrl && (\n <a\n className=\"tf-checkout-button tf-checkout-button--secondary tf-checkout-button--block\"\n href={order.pendingVoucherUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n View payment voucher\n </a>\n )}\n\n {viewOrderUrl && (\n <a\n className=\"tf-checkout-button tf-checkout-button--secondary tf-checkout-button--block\"\n href={viewOrderUrl}\n >\n View my tickets\n </a>\n )}\n\n {children}\n\n {/* Referral / share — invite friends for cheaper (or free) tickets. */}\n {!pending && url && (\n <div className=\"tf-checkout-confirmation__share\">\n <strong>Your tickets can be cheaper — or even FREE!</strong>\n <p className=\"tf-checkout-note\">\n Invite friends with your link. When they buy, you get rewarded.\n </p>\n <div className=\"tf-checkout-confirmation__share-link\">\n <input className=\"tf-checkout-input\" readOnly value={url} />\n <Button variant=\"secondary\" onClick={copy}>\n {copied ? 'Copied!' : 'Copy link'}\n </Button>\n </div>\n <div className=\"tf-checkout-confirmation__socials\">\n {shares.map((s) => (\n <a\n key={s.label}\n className=\"tf-checkout-button tf-checkout-button--ghost\"\n href={s.href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n {s.label}\n </a>\n ))}\n </div>\n </div>\n )}\n </Card>\n )\n}\n","import React, { useEffect, useRef, useState, type FC, type ReactNode } from 'react'\n\nimport { errorMessage, ttf } from 'tf-checkout-shared'\n\nimport { cx } from '../ui/cx'\nimport { Loader } from '../ui/Loader'\n\ntype ConfirmationData = Record<string, any>\ntype ReferralPrice = {\n label: string\n subLabel?: string\n price: string\n}\n\nconst attributesOf = (response: Record<string, unknown>): ConfirmationData => {\n const data = response?.data as Record<string, unknown> | undefined\n const attributes = data?.attributes\n if (attributes && typeof attributes === 'object') return attributes as ConfirmationData\n if (data && typeof data === 'object') return data as ConfirmationData\n return response\n}\n\nexport interface OrderConfirmationProps {\n orderHash: string\n title?: ReactNode\n message?: ReactNode\n helper?: ReactNode\n eventTitle?: ReactNode\n eventDate?: ReactNode\n eventLocation?: ReactNode\n viewOrderUrl?: string | ((data: ConfirmationData) => string)\n showReferral?: boolean\n showShareButtons?: boolean\n onLoaded?: (data: ConfirmationData) => void\n onError?: (error: unknown) => void\n className?: string\n}\n\n/**\n * Reloadable post-purchase confirmation. Its markup intentionally preserves\n * the proven legacy checkout class contract so existing white-label themes do\n * not lose their confirmation-page UX when they adopt Checkout Kit.\n */\nexport const OrderConfirmation: FC<OrderConfirmationProps> = ({\n orderHash,\n title = 'Your order has been confirmed!',\n message,\n helper,\n eventTitle,\n eventDate,\n eventLocation,\n viewOrderUrl,\n showReferral = true,\n showShareButtons = true,\n onLoaded,\n onError,\n className,\n}) => {\n const [data, setData] = useState<ConfirmationData | null>(null)\n const [failure, setFailure] = useState('')\n const [copied, setCopied] = useState(false)\n const loadedRef = useRef(onLoaded)\n const errorRef = useRef(onError)\n\n useEffect(() => {\n loadedRef.current = onLoaded\n errorRef.current = onError\n }, [onError, onLoaded])\n\n useEffect(() => {\n if (!orderHash) {\n setFailure('The order reference is missing.')\n return\n }\n\n let active = true\n ttf.confirmation.get(orderHash).then(\n (response) => {\n if (!active) return\n const attributes = attributesOf(response)\n if (!attributes.order_hash) attributes.order_hash = orderHash\n setData(attributes)\n loadedRef.current?.(attributes)\n },\n (error) => {\n if (!active) return\n setFailure(errorMessage(error))\n errorRef.current?.(error)\n }\n )\n\n return () => {\n active = false\n }\n }, [orderHash])\n\n if (failure) {\n return (\n <div className={cx('confirmation-page tf-checkout-confirmation-page', className)}>\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {failure}\n </div>\n </div>\n )\n }\n\n if (!data) {\n return (\n <div className=\"tf-checkout-confirmation-page__loading\">\n <Loader className=\"tf-checkout-loader--page\" />\n </div>\n )\n }\n\n const customText = String(data.custom_confirmation_page_text ?? '')\n const customReplacement = Boolean(data.custom_confirmation_page_text_full_replacement)\n const attachTickets = Boolean(data.attach_tickets)\n const shareUrl = String(data.personal_share_link ?? '')\n const orderUrl = typeof viewOrderUrl === 'function' ? viewOrderUrl(data) : viewOrderUrl\n const sales = Array.isArray(data.personal_share_sales) ? data.personal_share_sales : []\n const symbol = String(data.currency?.symbol ?? '')\n const currentPrice = Number(data.product_price)\n const pricing: ReferralPrice[] = [\n ...(Number.isFinite(currentPrice)\n ? [\n {\n label: 'Your ticket is currently',\n price: `${symbol}${currentPrice.toFixed(2)}`,\n },\n ]\n : []),\n ...sales.map((sale: ConfirmationData) => ({\n label: `If your friends buy ${sale.sales} tickets`,\n subLabel:\n Number(sale.price) === 0 ? 'Your ticket becomes' : 'Your ticket goes down to',\n price:\n Number(sale.price) === 0 ? 'FREE!' : `${symbol}${Number(sale.price).toFixed(2)}`,\n })),\n ]\n\n const copy = () => {\n if (!shareUrl || typeof navigator === 'undefined' || !navigator.clipboard) return\n void navigator.clipboard.writeText(shareUrl).then(() => {\n setCopied(true)\n window.setTimeout(() => setCopied(false), 1500)\n })\n }\n\n return (\n <div className={cx('confirmation-page tf-checkout-confirmation-page', className)}>\n <div className=\"header-container\">\n <div className=\"header-product-text\">\n <p className=\"title\">{title}</p>\n {(eventTitle || eventDate || eventLocation) && (\n <div className=\"event-details\">\n {eventTitle && <div className=\"event-title\">{eventTitle}</div>}\n {eventDate && <div className=\"event-date\">{eventDate}</div>}\n {eventLocation && <div className=\"event-location\">{eventLocation}</div>}\n </div>\n )}\n <div className=\"share-message-section\">\n {customReplacement ? (\n <div dangerouslySetInnerHTML={{ __html: customText }} />\n ) : (\n <>\n <span className=\"main\">\n {attachTickets\n ? 'Your tickets have been emailed to you'\n : (message ?? 'Your tickets are available in My Tickets.')}\n </span>\n <span className=\"helper\">\n {attachTickets ? 'Please bring them with you to the event' : helper}\n </span>\n </>\n )}\n </div>\n </div>\n </div>\n\n {customText && !customReplacement && (\n <div\n className=\"custom-confirmation-page-text tf-checkout-confirmation-page__custom\"\n dangerouslySetInnerHTML={{ __html: customText }}\n />\n )}\n\n {orderUrl && (\n <div className=\"order-details-button-container\">\n <a className=\"view-order-button\" href={orderUrl}>\n View Order\n </a>\n </div>\n )}\n\n {showReferral && data.disable_referral === false && shareUrl && (\n <>\n <div className=\"referral_text_image_section\">\n <div className=\"referral_text_section\">\n <div className=\"referral_title_text\">\n Your ticket can become\n <span className=\"strong-text\"> cheaper </span>\n or even\n <span className=\"strong-text\"> FREE!</span>\n </div>\n <div className=\"referral_text\">\n <span className=\"strong-text\">Invite friends </span>\n and we'll refund up to\n <span className=\"strong-text\"> 100% </span>\n of your ticket money, if they buy tickets as well!\n </div>\n </div>\n </div>\n <div className=\"share_wrapper\">\n <div className=\"share_section\">\n <div className=\"invitation_section\">\n <div className=\"invitation_title\">How do you invite your friends?</div>\n <div className=\"share_buttons\">\n <div className=\"share-by-link\">\n <h5 className=\"share-by-link label\">Send them this link:</h5>\n <div className=\"share-btn-inner\">\n <input className=\"share-input\" readOnly value={shareUrl} />\n <button\n className=\"share-by-link-copy-icon\"\n type=\"button\"\n onClick={copy}\n >\n <span className=\"copy-icon\">{copied ? 'Copied!' : 'Copy'}</span>\n </button>\n </div>\n </div>\n {showShareButtons && (\n <div className=\"social-media-btns\">\n <a\n className=\"social-media-sharing\"\n href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(\n shareUrl\n )}`}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n Facebook\n </a>\n <a\n className=\"social-media-sharing\"\n href={`https://wa.me/?text=${encodeURIComponent(shareUrl)}`}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n WhatsApp\n </a>\n </div>\n )}\n </div>\n </div>\n </div>\n {pricing.length > 0 && (\n <div className=\"pricing-section\">\n <div className=\"invitation_title\">How much cheaper?</div>\n {pricing.map((item, index) => (\n <div className=\"pricing-section_wrapper\" key={`${item.label}-${index}`}>\n <div className=\"pricing-section_label\">\n {item.label}\n {item.subLabel && (\n <div className=\"pricing-section_sublabel\">{item.subLabel}</div>\n )}\n </div>\n <div className=\"pricing-section_price\">{item.price}</div>\n </div>\n ))}\n </div>\n )}\n </div>\n </>\n )}\n </div>\n )\n}\n","import React, { useEffect, useState, type FC } from 'react'\n\nimport {\n errorMessage,\n runIdVerificationWith,\n ttf,\n type IdVerificationPhase,\n} from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { cx } from '../ui/cx'\n\ntype UiPhase = IdVerificationPhase | 'checking' | 'starting'\n\nconst PHASE_MESSAGE: Record<UiPhase, string> = {\n checking: 'Checking your verification status…',\n idle: 'To complete the purchase, please verify your identity.',\n starting: 'Opening the verification page…',\n polling: 'Waiting for verification to complete in the other tab…',\n verified: 'Identity verified — your tickets are on their way.',\n timeout: 'Verification is taking longer than usual. Your payment is safe.',\n error: 'We couldn’t reach the verification service. Try again.',\n}\n\nexport interface OrderIDVerificationProps {\n orderHash: string\n onVerified?: () => void\n className?: string\n}\n\n/** Routed ID-verification UI that survives a full page navigation. */\nexport const OrderIDVerification: FC<OrderIDVerificationProps> = ({\n orderHash,\n onVerified,\n className,\n}) => {\n const [phase, setPhase] = useState<UiPhase>('checking')\n const [failure, setFailure] = useState('')\n\n useEffect(() => {\n if (!orderHash) {\n setPhase('error')\n setFailure('The order reference is missing.')\n return\n }\n let active = true\n ttf.order.idVerificationStatus(orderHash).then(\n (status) => {\n if (!active) return\n if (status.verified || status.required === false) {\n setPhase('verified')\n onVerified?.()\n } else {\n setPhase('idle')\n }\n },\n (error) => {\n if (!active) return\n setPhase('error')\n setFailure(errorMessage(error))\n }\n )\n return () => {\n active = false\n }\n }, [onVerified, orderHash])\n\n const running = phase === 'checking' || phase === 'starting' || phase === 'polling'\n const run = () => {\n setFailure('')\n setPhase('starting')\n runIdVerificationWith(orderHash, {\n openUrl: (url) => {\n window.open(url, '_blank', 'noopener,noreferrer')\n },\n onPhase: (next) => setPhase(next),\n registerForegroundListener: (recheck) => {\n const listener = () => {\n if (document.visibilityState === 'visible') recheck()\n }\n document.addEventListener('visibilitychange', listener)\n return () => document.removeEventListener('visibilitychange', listener)\n },\n }).then(\n (status) => {\n if (status?.verified || status?.required === false) {\n setPhase('verified')\n onVerified?.()\n }\n },\n (error) => {\n setPhase('error')\n setFailure(errorMessage(error))\n }\n )\n }\n\n return (\n <Card className={cx('tf-checkout-idverify', className)}>\n <SectionHeader title=\"Account Verification\" />\n <p\n className={cx(\n 'tf-checkout-note',\n phase === 'verified' && 'tf-checkout-idverify__done'\n )}\n >\n {failure || PHASE_MESSAGE[phase]}\n </p>\n {phase !== 'verified' && orderHash && (\n <Button block onClick={run} loading={running} disabled={running || !orderHash}>\n {phase === 'idle' ? 'Verify' : running ? 'Verifying…' : 'Try again'}\n </Button>\n )}\n </Card>\n )\n}\n","/**\n * `<EmbeddedCheckout eventId=\"…\" />` — the batteries-included checkout. It\n * follows the legacy storefront UX: ticket selection and checkout are separate\n * views, with a compact selection summary + Edit action once the cart is\n * reserved. Want a different layout? Compose the sections yourself — they all\n * read the same `useCheckout()` from the provider.\n */\nimport React, { useCallback, useEffect, useRef, useState, type FC } from 'react'\n\nimport type {\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n EventCondition,\n LocaleCode,\n Messages,\n PlaceOrderResult,\n TfProfile,\n} from 'tf-checkout-shared'\n\nimport { AuthModal } from './auth/AuthModal'\nimport { AddOns } from './sections/AddOns'\nimport { BillingInfo } from './sections/BillingInfo'\nimport type { CheckoutPrivacyPolicy } from './sections/BillingInfo'\nimport { Confirmation } from './sections/Confirmation'\nimport { IDVerification } from './sections/IDVerification'\nimport { Payment } from './sections/Payment'\nimport { SeatMap } from './sections/SeatMap'\nimport { Tickets } from './sections/Tickets'\nimport { CheckoutProvider, useCheckoutContext } from './ui/CheckoutProvider'\nimport { TimerBanner } from './ui/TimerBanner'\nimport type { CheckoutTheme } from './ui/theme'\n\nexport interface EmbeddedCheckoutProps {\n /** The event whose tickets to sell. */\n eventId: string\n /** Called with the placed order once payment settles. */\n onComplete?: (order: PlaceOrderResult) => void\n /**\n * `inline` renders verification/confirmation inside the checkout. `redirect`\n * leaves completion routing to `onComplete` and shows a short transition\n * state while the host navigates. Defaults to `inline`.\n */\n confirmationMode?: 'inline' | 'redirect'\n /** Initial checkout screen. Useful for preserving an existing `/seat-map` route. */\n initialView?: 'tickets' | 'seats'\n /** Reports the visible flow view so host storefronts can coordinate mobile UI. */\n onViewChange?: (view: CheckoutView) => void\n /** Smooth-scroll to buyer details after tickets/seats are reserved. Default true. */\n autoScroll?: boolean\n /** Require guests to repeat their email. Defaults to storefront-compatible true. */\n requireEmailConfirmation?: boolean\n /** Collect one named holder per ticket. Defaults true to match tf-sports. */\n collectTicketHolders?: boolean\n /** Collect email/phone when ticket-holder details are required. Defaults true. */\n collectHolderContact?: boolean\n /** Open the host application's login UI instead of the built-in modal. The\n * current buyer email is passed when an existing account was detected. */\n onLogin?: (email?: string) => void\n /** Configure the built-in login/create-account/password-reset modal, or set\n * false to remove auth UI. Ignored when `onLogin` is provided. */\n auth?: false | EmbeddedCheckoutAuthOptions\n /** Legacy skip-billing equivalent for complete signed-in profiles. Payment is\n * never skipped. Defaults false; incompatible holder/custom fields prevent it. */\n skipBillingWhenProfileComplete?: boolean\n /** Optional marketing copy controlled by the embedding brand. */\n ttfOptInLabel?: string\n brandOptInLabel?: string\n /** Consumer-owned privacy policy link and brand name. Required when provided. */\n privacyPolicy?: CheckoutPrivacyPolicy\n /** Host-owned required/optional acknowledgements, e.g. a privacy policy. */\n additionalConditions?: EventCondition[]\n /** Apply/attribute hosted links without requiring a custom Tickets section. */\n initialPromoCode?: string\n referrer?: string | number\n readAttributionFromUrl?: boolean\n /** Opt into sandbox card copy in demos. Defaults false. */\n showTestCardHint?: boolean\n /** Recolor via design tokens. */\n theme?: CheckoutTheme\n /**\n * Language for the checkout's own copy. Defaults to `en-GB`, so existing\n * consumers that never set it render exactly as before.\n */\n locale?: LocaleCode\n /** Per-key copy overrides, merged over the locale. */\n messages?: Partial<Messages>\n className?: string\n}\n\nexport interface EmbeddedCheckoutAuthOptions {\n allowRegistration?: boolean\n allowPasswordReset?: boolean\n requireRegistrationAddress?: boolean\n logoUrl?: string\n onAuthenticated?: (profile: TfProfile) => void\n}\n\ntype SelectionView = 'tickets' | 'seats'\nexport type CheckoutView = SelectionView | 'checkout'\ntype FlowView = CheckoutView\ninterface PreservedDetails {\n billing?: CheckoutBilling\n holders: CheckoutHolder[]\n consent: CheckoutConsent\n}\n\nconst Flow: FC<{\n eventId: string\n onComplete?: (o: PlaceOrderResult) => void\n confirmationMode: 'inline' | 'redirect'\n initialView: SelectionView\n onViewChange?: (view: CheckoutView) => void\n autoScroll: boolean\n requireEmailConfirmation: boolean\n collectTicketHolders: boolean\n collectHolderContact: boolean\n onLogin?: (email?: string) => void\n auth?: false | EmbeddedCheckoutAuthOptions\n skipBillingWhenProfileComplete: boolean\n ttfOptInLabel?: string\n brandOptInLabel?: string\n privacyPolicy?: CheckoutPrivacyPolicy\n additionalConditions: EventCondition[]\n initialPromoCode?: string\n referrer?: string | number\n readAttributionFromUrl: boolean\n showTestCardHint: boolean\n}> = ({\n eventId,\n onComplete,\n confirmationMode,\n initialView,\n onViewChange,\n autoScroll,\n requireEmailConfirmation,\n collectTicketHolders,\n collectHolderContact,\n onLogin,\n auth,\n skipBillingWhenProfileComplete,\n ttfOptInLabel,\n brandOptInLabel,\n privacyPolicy,\n additionalConditions,\n initialPromoCode,\n referrer,\n readAttributionFromUrl,\n showTestCardHint,\n}) => {\n const checkout = useCheckoutContext()\n const [view, setView] = useState<FlowView>(initialView)\n const [selectionView, setSelectionView] = useState<SelectionView>(initialView)\n const checkoutViewRef = useRef<HTMLDivElement | null>(null)\n const editedDetailsRef = useRef<PreservedDetails | null>(null)\n const [authRequest, setAuthRequest] = useState<{\n email?: string\n key: number\n } | null>(null)\n const [privacyAttempted, setPrivacyAttempted] = useState(false)\n\n const openBuiltInAuth = useCallback((email?: string) => {\n setAuthRequest((current) => ({\n email,\n key: (current?.key ?? 0) + 1,\n }))\n }, [])\n const requestLogin = onLogin ?? (auth !== false ? openBuiltInAuth : undefined)\n\n // The engine store is intentionally shared across SDK consumers.\n // Never let state from another event/run select this component's UI view.\n const checkoutBelongsToEvent = checkout.eventId === eventId\n const checkoutViewAvailable = checkoutBelongsToEvent && checkout.status !== 'expired'\n const visibleView: FlowView =\n view === 'checkout' && !checkoutViewAvailable ? 'tickets' : view\n\n useEffect(() => {\n if (\n view === 'checkout' &&\n (!checkoutBelongsToEvent || checkout.status === 'expired')\n ) {\n setView('tickets')\n setSelectionView('tickets')\n }\n }, [checkout.status, checkoutBelongsToEvent, view])\n\n useEffect(() => {\n if (!autoScroll || visibleView !== 'checkout') return\n const timeout = window.setTimeout(() => {\n const behavior = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n ? 'auto'\n : 'smooth'\n checkoutViewRef.current?.scrollIntoView({ behavior, block: 'start' })\n }, 0)\n return () => window.clearTimeout(timeout)\n }, [autoScroll, visibleView])\n\n useEffect(() => {\n onViewChange?.(visibleView)\n }, [onViewChange, visibleView])\n\n const enterCheckout = (from: SelectionView) => {\n const preserved = editedDetailsRef.current\n if (preserved) {\n if (preserved.billing) checkout.setBilling(preserved.billing)\n checkout.setHolders(preserved.holders)\n checkout.setConsent(preserved.consent)\n editedDetailsRef.current = null\n }\n setSelectionView(from)\n setView('checkout')\n }\n\n const editSelection = () => {\n editedDetailsRef.current = {\n billing: checkout.billing,\n holders: checkout.holders,\n consent: checkout.consent,\n }\n setView(selectionView)\n }\n\n const breakdown = checkout.breakdown\n const selectedCount =\n breakdown?.tickets.reduce((total, ticket) => total + ticket.quantity, 0) ??\n checkout.selections.reduce((total, ticket) => total + ticket.quantity, 0)\n // Match the storefront summary: show the reserved tickets' amount, not a\n // moving order total that changes while the buyer picks add-ons.\n const selectedTicketsTotal = breakdown?.tickets.reduce(\n (total, ticket) => total + Number(ticket.total),\n 0\n )\n const formattedTotal = breakdown\n ? breakdown.currencySymbol\n ? `${breakdown.currencySymbol}${Number(selectedTicketsTotal).toFixed(2)}`\n : `${breakdown.currencyCode} ${Number(selectedTicketsTotal).toFixed(2)}`\n : null\n\n // Inline mode renders the receipt in place. Redirect mode intentionally does\n // NOT swap the UI on success — it keeps the checkout mounted (the pay button\n // stays busy) while the host navigates to its own confirmation page, so the\n // checkout never flashes an empty card during the handoff.\n if (\n visibleView === 'checkout' &&\n checkout.status === 'succeeded' &&\n checkout.order &&\n confirmationMode === 'inline'\n ) {\n return (\n <>\n <IDVerification />\n <Confirmation />\n </>\n )\n }\n\n return (\n <>\n {/* Keep Tickets mounted while hidden so Edit restores the buyer's exact\n quantities, promo state, date, and currency instead of starting over. */}\n <div hidden={visibleView !== 'tickets'}>\n <Tickets\n eventId={eventId}\n onContinue={() => enterCheckout('tickets')}\n onSelectSeats={() => setView('seats')}\n initialPromoCode={initialPromoCode}\n referrer={referrer}\n readAttributionFromUrl={readAttributionFromUrl}\n />\n </div>\n\n {visibleView === 'seats' && (\n <div className=\"tf-checkout-flow__seat-view\">\n <button\n type=\"button\"\n className=\"tf-checkout-flow__back\"\n onClick={() => setView('tickets')}\n >\n ← Back to tickets\n </button>\n <SeatMap eventId={eventId} onContinue={() => enterCheckout('seats')} />\n </div>\n )}\n\n {visibleView === 'checkout' && (\n <div ref={checkoutViewRef} className=\"tf-checkout-flow__checkout\">\n <TimerBanner seconds={checkout.secondsLeft} />\n <div className=\"tf-checkout-flow__selection\">\n <span className=\"tf-checkout-flow__selection-text\">\n {selectedCount} {selectedCount === 1 ? 'ticket' : 'tickets'} selected\n {formattedTotal ? ` · ${formattedTotal}` : ''}\n </span>\n <button\n type=\"button\"\n className=\"tf-checkout-flow__edit\"\n onClick={editSelection}\n >\n Edit\n </button>\n </div>\n <AddOns eventId={eventId} />\n <BillingInfo\n eventId={eventId}\n onLogin={requestLogin}\n skipWhenProfileComplete={skipBillingWhenProfileComplete}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n collectHolderContact={collectHolderContact}\n ttfOptInLabel={ttfOptInLabel}\n brandOptInLabel={brandOptInLabel}\n privacyPolicy={privacyPolicy}\n showPrivacyError={privacyAttempted}\n />\n <Payment\n onComplete={onComplete}\n eventId={eventId}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n requireHolderContact={collectHolderContact}\n additionalConditions={additionalConditions}\n requirePrivacyPolicy={Boolean(privacyPolicy)}\n onPrivacyRequired={() => setPrivacyAttempted(true)}\n showTestCardHint={showTestCardHint}\n />\n </div>\n )}\n {authRequest && auth !== false && !onLogin && (\n <AuthModal\n key={authRequest.key}\n open\n initialEmail={authRequest.email}\n message={\n authRequest.email\n ? 'This email already has an account. Log in to autofill your checkout details.'\n : undefined\n }\n allowRegistration={auth?.allowRegistration}\n allowPasswordReset={auth?.allowPasswordReset}\n requireRegistrationAddress={auth?.requireRegistrationAddress}\n logoUrl={auth?.logoUrl}\n onAuthenticated={auth?.onAuthenticated}\n onClose={() => setAuthRequest(null)}\n />\n )}\n </>\n )\n}\n\nexport const EmbeddedCheckout: FC<EmbeddedCheckoutProps> = ({\n eventId,\n onComplete,\n confirmationMode = 'inline',\n initialView = 'tickets',\n onViewChange,\n autoScroll = true,\n requireEmailConfirmation = true,\n collectTicketHolders = true,\n collectHolderContact = true,\n onLogin,\n auth,\n skipBillingWhenProfileComplete = false,\n ttfOptInLabel,\n brandOptInLabel,\n privacyPolicy,\n additionalConditions = [],\n initialPromoCode,\n referrer,\n readAttributionFromUrl = true,\n showTestCardHint = false,\n theme,\n locale,\n messages,\n className,\n}) => (\n <CheckoutProvider theme={theme} locale={locale} messages={messages} className={className}>\n <Flow\n key={eventId}\n eventId={eventId}\n onComplete={onComplete}\n confirmationMode={confirmationMode}\n initialView={initialView}\n onViewChange={onViewChange}\n autoScroll={autoScroll}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n collectHolderContact={collectHolderContact}\n onLogin={onLogin}\n auth={auth}\n skipBillingWhenProfileComplete={skipBillingWhenProfileComplete}\n ttfOptInLabel={ttfOptInLabel}\n brandOptInLabel={brandOptInLabel}\n privacyPolicy={privacyPolicy}\n additionalConditions={additionalConditions}\n initialPromoCode={initialPromoCode}\n referrer={referrer}\n readAttributionFromUrl={readAttributionFromUrl}\n showTestCardHint={showTestCardHint}\n />\n </CheckoutProvider>\n)\n","import React, { useEffect, useRef, useState, type FC } from 'react'\n\nimport {\n errorMessage,\n type EventCondition,\n type PlaceOrderResult,\n} from 'tf-checkout-shared'\n\nimport { AuthModal } from './auth/AuthModal'\nimport { BillingInfo, type CheckoutPrivacyPolicy } from './sections/BillingInfo'\nimport { Confirmation } from './sections/Confirmation'\nimport { IDVerification } from './sections/IDVerification'\nimport { Payment } from './sections/Payment'\nimport { CheckoutProvider, useCheckoutContext } from './ui/CheckoutProvider'\nimport { Loader } from './ui/Loader'\nimport { TimerBanner } from './ui/TimerBanner'\nimport type { CheckoutTheme } from './ui/theme'\n\nexport interface ResumedCheckoutProps {\n eventId: string\n isFromResale?: boolean\n onComplete?: (order: PlaceOrderResult) => void\n confirmationMode?: 'inline' | 'redirect'\n requireEmailConfirmation?: boolean\n collectTicketHolders?: boolean\n collectHolderContact?: boolean\n privacyPolicy?: CheckoutPrivacyPolicy\n brandOptInLabel?: string\n additionalConditions?: EventCondition[]\n theme?: CheckoutTheme\n className?: string\n}\n\nconst ResumedFlow: FC<Omit<ResumedCheckoutProps, 'theme' | 'className'>> = ({\n eventId,\n isFromResale = false,\n onComplete,\n confirmationMode = 'redirect',\n requireEmailConfirmation = true,\n collectTicketHolders = true,\n collectHolderContact = true,\n privacyPolicy,\n brandOptInLabel,\n additionalConditions = [],\n}) => {\n const checkout = useCheckoutContext()\n const started = useRef(false)\n const [failure, setFailure] = useState('')\n const [authRequest, setAuthRequest] = useState<{ email?: string; key: number } | null>(\n null\n )\n const [privacyAttempted, setPrivacyAttempted] = useState(false)\n\n useEffect(() => {\n if (started.current) return\n started.current = true\n checkout.resumeCart(eventId, { isFromResale }).catch((error) => {\n setFailure(errorMessage(error))\n })\n }, [checkout, eventId, isFromResale])\n\n if (failure) return <p className=\"tf-checkout-error-text\">{failure}</p>\n if (checkout.status === 'idle' || checkout.status === 'priming') {\n return (\n <div className=\"tf-checkout-flow__redirecting\">\n <Loader className=\"tf-checkout-loader--page\" />\n </div>\n )\n }\n if (checkout.status === 'succeeded' && checkout.order) {\n if (confirmationMode === 'redirect') {\n return (\n <div className=\"tf-checkout-flow__redirecting\">\n <Loader className=\"tf-checkout-loader--page\" />\n </div>\n )\n }\n return (\n <>\n <IDVerification />\n <Confirmation />\n </>\n )\n }\n\n return (\n <div className=\"tf-checkout-flow__checkout\">\n <TimerBanner seconds={checkout.secondsLeft} />\n <BillingInfo\n eventId={eventId}\n onLogin={(email) =>\n setAuthRequest((current) => ({ email, key: (current?.key ?? 0) + 1 }))\n }\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n collectHolderContact={collectHolderContact}\n privacyPolicy={privacyPolicy}\n brandOptInLabel={brandOptInLabel}\n showPrivacyError={privacyAttempted}\n />\n <Payment\n eventId={eventId}\n onComplete={onComplete}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n requireHolderContact={collectHolderContact}\n additionalConditions={additionalConditions}\n requirePrivacyPolicy={Boolean(privacyPolicy)}\n onPrivacyRequired={() => setPrivacyAttempted(true)}\n />\n {authRequest && (\n <AuthModal\n key={authRequest.key}\n open\n initialEmail={authRequest.email}\n onClose={() => setAuthRequest(null)}\n />\n )}\n </div>\n )\n}\n\n/** Checkout UI for a cart created by a preceding server flow, such as resale. */\nexport const ResumedCheckout: FC<ResumedCheckoutProps> = ({\n theme,\n className,\n ...props\n}) => (\n <CheckoutProvider theme={theme} className={className}>\n <ResumedFlow {...props} />\n </CheckoutProvider>\n)\n"],"mappings":";;;;;;;AAWA,OAAO;AACP,OAAO;;;ACMA,IAAM,sBAAsB,MAAsB;AACvD,QAAM,MAAM,oBAAI,IAAoB;AACpC,SAAO;AAAA,IACL,SAAS,CAAC,QAAS,IAAI,IAAI,GAAG,IAAK,IAAI,IAAI,GAAG,IAAe;AAAA,IAC7D,SAAS,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CACb,gBAAAA,QAAA,cAAC,UAAO,WAAU,4BAA2B,CAC/C;AAAA,IAEJ;AACA,WACE,gBAAAA,QAAA,cAAAA,QAAA,gBACE,gBAAAA,QAAA,cAAC,oBAAe,GAChB,gBAAAA,QAAA,cAAC,kBAAa,CAChB;AAAA,EAEJ;AAEA,SACE,gBAAAA,QAAA,cAAC,SAAI,WAAU,gCACb,gBAAAA,QAAA,cAAC,eAAY,SAAS,SAAS,aAAa,GAC5C,gBAAAA,QAAA;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA,SAAS,CAAC,UACR,eAAe,CAACC,aAAS;AA3FnC;AA2FuC,iBAAE,OAAO,OAAM,KAAAA,YAAA,gBAAAA,SAAS,QAAT,YAAgB,KAAK,EAAE;AAAA,OAAE;AAAA,MAEvE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,kBAAkB;AAAA;AAAA,EACpB,GACA,gBAAAD,QAAA;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,sBAAsB;AAAA,MACtB;AAAA,MACA,sBAAsB,QAAQ,aAAa;AAAA,MAC3C,mBAAmB,MAAM,oBAAoB,IAAI;AAAA;AAAA,EACnD,GACC,eACC,gBAAAA,QAAA;AAAA,IAAC;AAAA;AAAA,MACC,KAAK,YAAY;AAAA,MACjB,MAAI;AAAA,MACJ,cAAc,YAAY;AAAA,MAC1B,SAAS,MAAM,eAAe,IAAI;AAAA;AAAA,EACpC,CAEJ;AAEJ;AAGO,IAAM,kBAA4C,CAAC;AAAA,EACxD;AAAA,EACA;AAAA,EACA,GAAG;AACL,MACE,gBAAAA,QAAA,cAAC,oBAAiB,OAAc,aAC9B,gBAAAA,QAAA,cAAC,eAAa,GAAG,OAAO,CAC1B;","names":["_a","_b","listeners","patch","_a","_b","_c","_d","_e","_a","_b","_c","_a","result","hasValue","g","f","_a","result","needIdVerification","messageFrom","current","_a","logout","_b","useQuery","useQuery","useQuery","useQuery","useQuery","useQuery","useMutation","useMutation","useCallback","useState","useSyncExternalStore","useSyncExternalStore","useState","useCallback","result","_a","attributeReferrer","joinWaitingList","error","paymentIntent","e","useCheckout","useEffect","useRef","useState","useRef","useEffect","useState","React","createContext","useCallback","useContext","useEffect","useRef","useState","React","React","React","useCallback","useState","React","React","React","React","useState","useCallback","React","createContext","useRef","useState","useCallback","current","useEffect","React","useCheckout","useContext","React","React","React","forwardRef","React","forwardRef","React","React","React","React","React","React","React","React","React","React","React","React","React","useState","clock","useState","React","React","useCallback","useEffect","useRef","React","useEffect","useState","useState","useEffect","React","React","useEffect","useState","React","forwardRef","useState","forwardRef","useState","React","current","useState","useEffect","React","React","useEffect","useMemo","useState","useState","useMemo","_a","useEffect","current","patch","React","useCallback","useRef","useEffect","_a","_b","React","React","useMemo","useState","useState","useMemo","React","React","useEffect","useRef","useState","useState","React","useEffect","useRef","_a","_b","_c","code","current","React","useCallback","useEffect","useRef","useState","useState","useRef","useEffect","_a","_b","_c","_d","useCallback","React","React","Fragment","useEffect","useMemo","useState","useState","useMemo","useEffect","_a","React","Fragment","_b","React","Fragment","useEffect","useMemo","useRef","useState","PhoneInput","React","current","React","_a","React","React","React","PhoneInput","React","PhoneInput","useState","_a","_b","useRef","useMemo","useEffect","dobYear","dobMonth","dobDay","_c","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","_p","_q","_r","_s","_t","current","patch","React","PhoneInput","Fragment","React","useEffect","useMemo","useRef","useState","React","React","_a","useState","useRef","useEffect","useMemo","_a","_b","_c","React","patch","React","useState","useState","React","React","useState","useState","React","React","useEffect","useRef","useState","useState","useRef","useEffect","_a","React","React","useEffect","useState","useState","useEffect","React","React","useCallback","useEffect","useRef","useState","useState","useRef","useCallback","current","_a","useEffect","React","React","useEffect","useRef","useState","useRef","useState","useEffect","React","current"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../../tf-checkout-shared/src/client/storage.ts","../../tf-checkout-shared/src/client/config.ts","../../tf-checkout-shared/src/client/errors.ts","../../tf-checkout-shared/src/client/cookies.ts","../../tf-checkout-shared/src/client/session.ts","../../tf-checkout-shared/src/client/http.ts","../../tf-checkout-shared/src/constants/endpoints.ts","../../tf-checkout-shared/src/constants/gateways.ts","../../tf-checkout-shared/src/constants/redirectMethods.ts","../../tf-checkout-shared/src/logic/gateway.ts","../../tf-checkout-shared/src/logic/pricing.ts","../../tf-checkout-shared/src/logic/checkout.ts","../../tf-checkout-shared/src/logic/payment.ts","../../tf-checkout-shared/src/logic/paymentPlan.ts","../../tf-checkout-shared/src/logic/account.ts","../../tf-checkout-shared/src/logic/auth.ts","../../tf-checkout-shared/src/logic/verification.ts","../../tf-checkout-shared/src/engine/store.ts","../../tf-checkout-shared/src/engine/confirmer.ts","../../tf-checkout-shared/src/engine/sheets.ts","../../tf-checkout-shared/src/engine/errors.ts","../../tf-checkout-shared/src/api/index.ts","../../tf-checkout-shared/src/api/profile.ts","../../tf-checkout-shared/src/api/auth.ts","../../tf-checkout-shared/src/api/geo.ts","../../tf-checkout-shared/src/api/engagement.ts","../../tf-checkout-shared/src/api/orders.ts","../../tf-checkout-shared/src/api/resale.ts","../../tf-checkout-shared/src/api/confirmation.ts","../../tf-checkout-shared/src/api/preRegistration.ts","../../tf-checkout-shared/src/api/delegation.ts","../../tf-checkout-shared/src/api/seatmap.ts","../../tf-checkout-shared/src/api/events.ts","../../tf-checkout-shared/src/api/cart.ts","../../tf-checkout-shared/src/api/order.ts","../../tf-checkout-shared/src/api/payment.ts","../../tf-checkout-shared/src/engine/engine.ts","../../tf-checkout-shared/src/services.ts","../../tf-checkout-shared/src/hooks/index.ts","../../tf-checkout-shared/src/hooks/auth.ts","../../tf-checkout-shared/src/hooks/authFlow.ts","../../tf-checkout-shared/src/hooks/keys.ts","../../tf-checkout-shared/src/hooks/session.ts","../../tf-checkout-shared/src/hooks/profile.ts","../../tf-checkout-shared/src/hooks/geo.ts","../../tf-checkout-shared/src/hooks/events.ts","../../tf-checkout-shared/src/hooks/orders.ts","../../tf-checkout-shared/src/hooks/engagement.ts","../../tf-checkout-shared/src/hooks/checkout.ts","../../tf-checkout-shared/src/i18n/locales/en.ts","../../tf-checkout-shared/src/i18n/resolve.ts","../../tf-checkout-shared/src/i18n/locales/es-MX.ts","../../tf-checkout-shared/src/i18n/locales/index.ts","../src/confirmer.ts","../src/xendit.ts","../src/instance.ts","../src/useCheckout.ts","../src/configure.ts","../src/CardInput.tsx","../src/ui/CheckoutProvider.tsx","../src/ui/cx.ts","../src/ui/I18nProvider.tsx","../src/ui/InstallmentPicker.tsx","../src/ui/Button.tsx","../src/ui/Loader.tsx","../src/ui/theme.ts","../src/ui/Card.tsx","../src/ui/Field.tsx","../src/ui/CustomFields.tsx","../src/ui/PaymentMethods.tsx","../src/ui/Stepper.tsx","../src/ui/QuantitySelect.tsx","../src/ui/PriceLine.tsx","../src/ui/Timer.tsx","../src/ui/TimerBanner.tsx","../src/auth/AuthModal.tsx","../src/auth/ForgotPasswordForm.tsx","../src/auth/LoginForm.tsx","../src/auth/PasswordInput.tsx","../src/auth/RegisterForm.tsx","../src/auth/ResetPasswordForm.tsx","../src/sections/Tickets.tsx","../src/sections/SeatMap.tsx","../src/sections/seatMap.utils.ts","../src/sections/AddOns.tsx","../src/sections/BillingInfo.tsx","../src/sections/billing/BillingAddressFields.tsx","../src/sections/billing/BuyerField.tsx","../src/sections/billing/fieldRules.ts","../src/sections/billing/TicketHoldersCard.tsx","../src/sections/Payment.tsx","../src/sections/OrderSummary.tsx","../src/sections/IDVerification.tsx","../src/sections/Confirmation.tsx","../src/sections/OrderConfirmation.tsx","../src/sections/OrderIDVerification.tsx","../src/EmbeddedCheckout.tsx","../src/ResumedCheckout.tsx"],"sourcesContent":["/**\n * tf-checkout-react — the web checkout, built on `tf-checkout-shared`.\n *\n * One import gives you the whole SDK (ttf, ENDPOINTS, dtos, logic, the engine)\n * PLUS the web platform layer: a `useCheckout` with Stripe + popup + inline\n * Xendit pre-wired, `<CardInput/>` / `<XenditCardInput/>`, and `configureCheckout`.\n *\n * import { configureCheckout, useCheckout, CardInput, ttf } from 'tf-checkout-react'\n */\n\n// Load the SDK styles once. Consumers do not need a separate CSS import.\nimport 'react-international-phone/style.css'\nimport './checkout.css'\n\n// The entire shared SDK (the web `useCheckout` below overrides the SDK's).\nexport * from 'tf-checkout-shared'\n\n// Web platform layer\nexport { useCheckout, type UseCheckoutOptions } from './useCheckout'\nexport { configureCheckout, localStorageAdapter } from './configure'\nexport { CardInput, StripePaymentElement, XenditCardInput } from './CardInput'\n\n// Component library: the themeable provider + primitives + section components.\nexport * from './ui'\nexport * from './auth'\nexport * from './sections'\nexport {\n EmbeddedCheckout,\n type EmbeddedCheckoutProps,\n type EmbeddedCheckoutAuthOptions,\n} from './EmbeddedCheckout'\nexport { ResumedCheckout, type ResumedCheckoutProps } from './ResumedCheckout'\n\nexport { webConfirmer, webPorts, webXenditTokenizer } from './instance'\nexport {\n createWebStripeConfirmer,\n createWebPorts,\n type WebStripeConfirmer,\n} from './confirmer'\nexport {\n createWebXenditTokenizer,\n type WebXenditTokenizer,\n type XenditCardFields,\n} from './xendit'\n","/**\n * The one platform seam the SDK's transport needs: somewhere to keep tokens.\n *\n * Web passes a `localStorage`-backed adapter, React Native an MMKV-backed one.\n * If a consumer configures nothing, we fall back to an in-memory map so the SDK\n * still works in tests and SSR (tokens just don't survive a reload).\n *\n * Deliberately synchronous — web `localStorage` and RN MMKV are both sync, and\n * a sync contract keeps the axios interceptors trivial. If you only have an\n * async store (AsyncStorage), wrap it with a small sync mirror.\n */\nexport interface StorageAdapter {\n getItem(key: string): string | null | undefined\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\n/** Process-lifetime fallback store. Not persisted — good enough for tests/SSR. */\nexport const createMemoryStorage = (): StorageAdapter => {\n const map = new Map<string, string>()\n return {\n getItem: (key) => (map.has(key) ? (map.get(key) as string) : null),\n setItem: (key, value) => void map.set(key, value),\n removeItem: (key) => void map.delete(key),\n }\n}\n","/**\n * One-time setup for the SDK. Call `configure()` at app start, before any\n * `ttf.*` call or hook runs. Everything downstream (transport, session, api)\n * reads this single record — there is no other global state.\n */\nimport { createMemoryStorage, StorageAdapter } from './storage'\n\nexport type TtfEnv = 'PROD' | 'STAG' | 'DEV'\n\n/** Host origins (NO /api suffix) — the one base-URL notion every layer derives\n * from. '' is valid: same-origin (e.g. behind a dev proxy). */\nexport const ENV_HOSTS: Record<TtfEnv, string> = {\n PROD: 'https://www.ticketfairy.com',\n STAG: 'https://test.ticketfairy.com',\n DEV: 'https://sandbox.ticketfairy.com',\n}\n\n/** Explicit `baseUrl` wins (even ''); otherwise the env host (default PROD).\n * A value in the old full-base form (…/api) is accepted — the /api suffix is\n * stripped here and re-appended for the transport. */\nexport const resolveHost = (env?: TtfEnv, baseUrl?: string): string => {\n if (baseUrl === undefined) return ENV_HOSTS[env ?? 'PROD']\n const trimmed = baseUrl.replace(/\\/+$/, '')\n return /\\/api$/.test(trimmed) ? trimmed.replace(/\\/api$/, '') : trimmed\n}\n\n/**\n * Extra auth material the consumer hands us — called on EVERY request; whatever\n * headers it returns are merged in last (they win over the SDK's own). Pass a\n * bearer token, a session cookie, an API key — anything. This is the flexible\n * \"bring your own auth\" seam. Return `undefined` to add nothing this request.\n */\nexport type AuthProvider = () => Record<string, string> | undefined\n\nexport interface TtfConfig {\n /** Host origin, e.g. `https://www.ticketfairy.com` — the `/api` path is\n * appended internally. `''` = same-origin. Omit to use `env`. */\n baseUrl?: string\n /** Picks the TicketFairy host when `baseUrl` is omitted. Defaults to PROD. */\n env?: TtfEnv\n /** OAuth client id issued to your brand. */\n clientId: string\n /** OAuth client secret issued to your brand. */\n clientSecret: string\n /** Value for the `X-Source-Origin` header (your domain). Optional. */\n sourceOrigin?: string\n /** Where tokens live. Defaults to an in-memory store (not persisted). */\n storage?: StorageAdapter\n /** Bring-your-own auth: return headers to attach to every request (token,\n * cookie, custom). Merged last, so it overrides the SDK's own headers. */\n auth?: AuthProvider\n /** Cookie-based session auth: forward the `X-TF-ECOMMERCE` login ticket (+\n * browser cookies where they exist) as headers, and capture the rotating\n * ones back from responses. Sign-in rides the legacy `/auth` session flow —\n * no bearer is minted, so the backend session that holds a reserved cart\n * survives a mid-checkout login. Enable when the app shares a session cookie\n * with TicketFairy (same-domain / SSO), runs anonymous cookie carts, or is a\n * native app (React Native persists the ticket via the storage adapter —\n * the RN `configureCheckout` turns this on by default). */\n cookieAuth?: boolean\n}\n\n/** Fully-resolved config — `storage`, `host`, and `apiBaseUrl` always present. */\nexport interface ResolvedTtfConfig extends TtfConfig {\n storage: StorageAdapter\n /** Host origin, no `/api` (e.g. `https://www.ticketfairy.com`). '' = same-origin. */\n host: string\n /** The transport base: `<host>/api`. */\n apiBaseUrl: string\n}\n\nlet current: ResolvedTtfConfig | null = null\n\n/** Wire the SDK. Idempotent — the last call wins. */\nexport const configure = (config: TtfConfig): void => {\n const host = resolveHost(config.env, config.baseUrl)\n current = {\n ...config,\n storage: config.storage ?? createMemoryStorage(),\n host,\n apiBaseUrl: `${host}/api`,\n }\n}\n\n/** Read the active config, or throw a pointed error if `configure()` was skipped. */\nexport const getConfig = (): ResolvedTtfConfig => {\n if (!current) {\n throw new Error(\n 'TicketFairy SDK is not configured — call configure({ baseUrl, clientId, clientSecret }) once at app start.'\n )\n }\n return current\n}\n\n/** The host origin (no `/api`) — for the few endpoints served off the root\n * (e.g. `/ajax/contact-email`) and for absolutizing icon paths. */\nexport const getOriginUrl = (): string => getConfig().host\n\n/** True once `configure()` has run. Lets callers branch without catching. */\nexport const isConfigured = (): boolean => current !== null\n","/**\n * One error shape for the whole SDK. Every api function rejects with a\n * `TtfError`, so callers (and hooks) branch on `.status` / `.code` instead of\n * digging through axios internals. `message` is always safe to show a user.\n */\nimport { AxiosError } from 'axios'\n\nexport class TtfError extends Error {\n /** HTTP status, or 0 for network/transport failures. */\n readonly status: number\n /** Backend error code when present (e.g. `INVALID_CREDENTIALS`). */\n readonly code?: string\n /** The raw payload, for callers that need more than the message. */\n readonly data?: unknown\n\n constructor(message: string, status: number, code?: string, data?: unknown) {\n super(message)\n this.name = 'TtfError'\n this.status = status\n this.code = code\n this.data = data\n }\n}\n\nconst flattenMessages = (value: unknown): string[] => {\n if (typeof value === 'string') return value.trim() ? [value.trim()] : []\n if (Array.isArray(value)) return value.flatMap(flattenMessages)\n if (value && typeof value === 'object')\n return Object.values(value).flatMap(flattenMessages)\n return []\n}\n\n/** Pull the friendliest message the backend gave us, including the legacy\n * `{ message: { email: [\"already registered\"] } }` validation shape. */\nconst messageFrom = (payload: unknown, fallback: string): string => {\n if (typeof payload === 'string' && payload.trim()) return payload\n if (payload && typeof payload === 'object') {\n const record = payload as Record<string, unknown>\n const candidate =\n record.message ??\n record.error ??\n record.error_description ??\n (Array.isArray(record.errors) ? (record.errors[0] as any)?.message : undefined)\n if (typeof candidate === 'string' && candidate.trim()) return candidate\n const messages = flattenMessages(candidate)\n if (messages.length > 0) return messages.join('\\n')\n }\n return fallback\n}\n\nconst codeFrom = (payload: unknown): string | undefined => {\n if (payload && typeof payload === 'object') {\n const code = (payload as Record<string, unknown>).code\n if (typeof code === 'string') return code\n }\n return undefined\n}\n\n/** Normalize any thrown value into a `TtfError`. Never throws itself. */\nexport const toTtfError = (\n error: unknown,\n fallback = 'Something went wrong'\n): TtfError => {\n if (error instanceof TtfError) return error\n if (error instanceof AxiosError) {\n const status = error.response?.status ?? 0\n const payload = error.response?.data\n return new TtfError(\n messageFrom(payload, error.message || fallback),\n status,\n codeFrom(payload),\n payload\n )\n }\n if (error instanceof Error) return new TtfError(error.message || fallback, 0)\n return new TtfError(fallback, 0)\n}\n","/**\n * Cookie access for the opt-in `cookieAuth` transport path (forwarding the\n * session cookies as headers). In the browser this is `document.cookie`.\n * Outside the browser (React Native) the same names are persisted through the\n * configured storage adapter instead — the backend accepts the session ticket\n * as a header, so a \"cookie\" only needs to survive relaunches, not be a real\n * browser cookie. This is what lets native ride the legacy cookie-session\n * login (same session as the reserved cart) with the ticket in MMKV.\n */\nimport { getConfig, isConfigured } from './config'\n\nconst hasDocument = (): boolean =>\n typeof document !== 'undefined' && typeof document.cookie === 'string'\n\nconst escapeName = (name: string): string =>\n name.replace(/([.$?*|{}()[\\]\\\\/+^])/g, '\\\\$1')\n\n/** Storage key for the non-browser fallback. */\nconst storageKey = (name: string): string => `tf_cookie_${name}`\n\nconst storageRead = (name: string): string | null => {\n if (!isConfigured()) return null\n return getConfig().storage.getItem(storageKey(name)) ?? null\n}\n\nconst storageWrite = (name: string, value: string): void => {\n if (!isConfigured()) return\n getConfig().storage.setItem(storageKey(name), value)\n}\n\nconst storageDelete = (name: string): void => {\n if (!isConfigured()) return\n getConfig().storage.removeItem(storageKey(name))\n}\n\n/** Read one cookie by name, or null when absent. */\nexport const readCookie = (name: string): string | null => {\n if (!hasDocument()) return storageRead(name)\n const match = document.cookie.match(new RegExp(`(?:^|; )${escapeName(name)}=([^;]*)`))\n return match ? decodeURIComponent(match[1]) : null\n}\n\n/** Write a session-scoped cookie (path=/), or persist via storage off-browser. */\nexport const writeCookie = (name: string, value: string): void => {\n if (!hasDocument()) {\n storageWrite(name, value)\n return\n }\n document.cookie = `${name}=${value}; path=/`\n}\n\n/**\n * Expire a browser cookie for both host-only and domain-scoped variants.\n * White-labels can receive X-TF-ECOMMERCE from either their own host or a\n * parent domain, so deleting only one form can make logout appear to fail.\n * Off-browser there is exactly one stored variant to remove.\n */\nexport const deleteCookie = (name: string): void => {\n if (!hasDocument()) {\n storageDelete(name)\n return\n }\n\n const expired = `${encodeURIComponent(name)}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0; path=/`\n // Host-only cookie.\n document.cookie = expired\n\n if (typeof window === 'undefined') return\n const hostname = window.location?.hostname ?? ''\n if (!hostname || hostname === 'localhost' || /^\\d+(?:\\.\\d+){3}$/.test(hostname)) {\n return\n }\n\n const parts = hostname.split('.')\n for (let index = 0; index < parts.length - 1; index += 1) {\n const domain = parts.slice(index).join('.')\n document.cookie = `${expired}; domain=${domain}`\n document.cookie = `${expired}; domain=.${domain}`\n }\n}\n\n/** The raw `document.cookie` string ('' outside the browser — the storage\n * fallback carries named cookies as individual headers, never a cookie jar). */\nexport const allCookies = (): string => (hasDocument() ? document.cookie : '')\n","/**\n * Token bookkeeping, one level above the raw storage adapter. The transport\n * reads these on every request; `auth.ts` writes them on login and clears them\n * on logout / 401. Keys match what the backend hands back so a future migration\n * off the legacy client stays drop-in.\n */\nimport { getConfig, isConfigured } from './config'\nimport { deleteCookie, readCookie } from './cookies'\n\nconst ACCESS_TOKEN = 'tf_access_token'\nconst REFRESH_TOKEN = 'tf_refresh_token'\nconst GUEST_TOKEN = 'tf_auth_guest_token'\nconst LEGACY_GUEST_TOKEN = 'auth_guest_token'\nconst CART_GUEST_TOKEN = 'tf_checkout_cart_guest_token'\n\ntype SessionListener = () => void\nconst listeners = new Set<SessionListener>()\n\nconst emitSessionChange = (): void => {\n for (const listener of listeners) listener()\n}\n\n/** Notify subscribers after a cookie-session login that writes no bearer token\n * (so `setTokens`' own notification never fires). Web sign-in rides the legacy\n * `/auth` cookie flow: the X-TF-ECOMMERCE ticket lands via the response\n * interceptor, and this lets `useAuthSession` observe the signed-in state. */\nexport const notifyCookieSession = (): void => emitSessionChange()\n\n/** React/platform bindings subscribe here instead of maintaining a second auth\n * flag. Tokens remain the single source of truth. */\nexport const subscribeSession = (listener: SessionListener): (() => void) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nexport const getAccessToken = (): string | null =>\n getConfig().storage.getItem(ACCESS_TOKEN) ?? null\n\nexport const getGuestToken = (): string | null =>\n getConfig().storage.getItem(GUEST_TOKEN) ??\n getConfig().storage.getItem(LEGACY_GUEST_TOKEN) ??\n null\n\nexport const setTokens = (tokens: { access?: string; refresh?: string }): void => {\n const { storage } = getConfig()\n if (tokens.access) storage.setItem(ACCESS_TOKEN, tokens.access)\n if (tokens.refresh) storage.setItem(REFRESH_TOKEN, tokens.refresh)\n if (tokens.access || tokens.refresh) emitSessionChange()\n}\n\n/** The transport captures the rotating guest token from response headers.\n * Keep the legacy key synchronized while old and new checkout clients coexist. */\nexport const setGuestToken = (token: string): void => {\n const { storage } = getConfig()\n storage.setItem(GUEST_TOKEN, token)\n storage.setItem(LEGACY_GUEST_TOKEN, token)\n}\n\n/** Pin the identity that owns the active reservation. OAuth can rotate the\n * general guest token during a mid-checkout login, but the cart must keep using\n * the token captured immediately after add-to-cart. */\nexport const pinCartGuestToken = (): void => {\n if (!isConfigured()) return\n const token = getGuestToken()\n if (token) getConfig().storage.setItem(CART_GUEST_TOKEN, token)\n}\n\nexport const getCartGuestToken = (): string | null =>\n isConfigured() ? (getConfig().storage.getItem(CART_GUEST_TOKEN) ?? null) : null\n\nexport const clearCartGuestToken = (): void => {\n if (isConfigured()) getConfig().storage.removeItem(CART_GUEST_TOKEN)\n}\n\nexport const clearSession = (): void => {\n const { storage } = getConfig()\n storage.removeItem(ACCESS_TOKEN)\n storage.removeItem(REFRESH_TOKEN)\n storage.removeItem(GUEST_TOKEN)\n storage.removeItem(LEGACY_GUEST_TOKEN)\n storage.removeItem(CART_GUEST_TOKEN)\n deleteCookie('X-TF-ECOMMERCE')\n emitSessionChange()\n}\n\n/**\n * True when a signed-in access token is present. Cookie-enabled web consumers\n * also recognize an existing legacy storefront session during migration.\n */\nexport const isAuthenticated = (): boolean =>\n Boolean(getAccessToken() || (getConfig().cookieAuth && readCookie('X-TF-ECOMMERCE')))\n","/**\n * The SDK's single HTTP transport. One axios instance, built lazily from\n * `configure()` and rebuilt only if the config reference changes.\n *\n * Matches the engine's checkout client exactly: base is `<host>/api`, the\n * JSON:API content headers, `withCredentials` for the web session cookie, and a\n * request interceptor that sends both identities during the guest → authenticated\n * transition: the bearer identifies the buyer while `Authorization-Guest`\n * preserves the cart that was reserved before login.\n *\n * Self-contained by design: imports nothing from checkout-flow / checkout-core.\n */\nimport axios, {\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n InternalAxiosRequestConfig,\n} from 'axios'\n\nimport { allCookies, readCookie, writeCookie } from './cookies'\nimport { getConfig, ResolvedTtfConfig } from './config'\nimport { toTtfError } from './errors'\nimport {\n clearSession,\n getAccessToken,\n getCartGuestToken,\n getGuestToken,\n setGuestToken,\n} from './session'\n\n/** Persist the guest session token the backend echoes on every response. Always\n * on: it is the cookieless session carrier, and bearer-auth consumers (React\n * Native) need it to keep the reserved cart across a mid-checkout login. */\nconst captureGuestToken = (res: AxiosResponse): void => {\n const guest = res.headers?.['authorization-guest']\n if (guest) setGuestToken(String(guest))\n}\n\n/** Persist the login cookie the backend hands back. Browser-only (`cookieAuth`). */\nconst captureCookieSession = (res: AxiosResponse): void => {\n const xtf = res.headers?.['x-tf-ecommerce']\n if (xtf) writeCookie('X-TF-ECOMMERCE', String(xtf))\n}\n\n/** A logged-in buyer can still own a cart created moments earlier as a guest:\n * the bearer identifies the buyer while `Authorization-Guest` preserves the\n * cart's session. Without it the backend swaps a bearer request onto a\n * synthetic empty session (init.php) and on-checkout 422s \"cart expired\". */\nexport const resolveAuthorizationHeaders = (\n accessToken: string | null,\n guestToken: string | null\n): Record<string, string> => ({\n ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),\n ...(guestToken ? { 'Authorization-Guest': guestToken } : {}),\n})\n\nlet instance: AxiosInstance | null = null\nlet builtFrom: ResolvedTtfConfig | null = null\n\nconst build = (config: ResolvedTtfConfig): AxiosInstance => {\n const http = axios.create({\n baseURL: config.apiBaseUrl,\n timeout: 30_000,\n withCredentials: true,\n headers: {\n Accept: 'application/vnd.api+json',\n 'Content-Type': 'application/vnd.api+json',\n },\n })\n\n http.interceptors.request.use((req: InternalAxiosRequestConfig) => {\n const access = getAccessToken()\n const authorization = resolveAuthorizationHeaders(\n access,\n getCartGuestToken() ?? getGuestToken()\n )\n for (const [key, value] of Object.entries(authorization)) {\n req.headers.set(key, value)\n }\n if (config.sourceOrigin) req.headers.set('X-Source-Origin', config.sourceOrigin)\n\n // Cookie-based session context, opt-in for browser white-labels.\n if (config.cookieAuth) {\n const xtf = readCookie('X-TF-ECOMMERCE')\n if (xtf) req.headers.set('X-TF-ECOMMERCE', xtf)\n const cookies = allCookies()\n if (cookies) req.headers.set('Additional-Cookies', cookies)\n }\n\n // Bring-your-own auth wins — merged last (token, cookie, or anything).\n const extra = config.auth?.()\n if (extra) {\n for (const [key, value] of Object.entries(extra)) req.headers.set(key, value)\n }\n return req\n })\n\n http.interceptors.response.use(\n (res) => {\n captureGuestToken(res)\n if (config.cookieAuth) captureCookieSession(res)\n return res\n },\n (error) => {\n if (error?.response) {\n captureGuestToken(error.response)\n if (config.cookieAuth) captureCookieSession(error.response)\n }\n if (error?.response?.status === 401) clearSession()\n return Promise.reject(error)\n }\n )\n\n return http\n}\n\n/** The active axios instance, rebuilt if `configure()` was called with a new object. */\nexport const getHttp = (): AxiosInstance => {\n const config = getConfig()\n if (!instance || builtFrom !== config) {\n instance = build(config)\n builtFrom = config\n }\n return instance\n}\n\n/** Drop the cached instance — used by tests and after `configure()` swaps. */\nexport const resetHttp = (): void => {\n instance = null\n builtFrom = null\n}\n\n// --- thin verbs: return response data, throw a normalized TtfError ----------\n\nexport const get = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {\n try {\n return (await getHttp().get<T>(url, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const post = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().post<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const put = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().put<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const patch = async <T>(\n url: string,\n body?: unknown,\n config?: AxiosRequestConfig\n): Promise<T> => {\n try {\n return (await getHttp().patch<T>(url, body, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n\nexport const del = async <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {\n try {\n return (await getHttp().delete<T>(url, config)).data\n } catch (error) {\n throw toTtfError(error)\n }\n}\n","/**\n * THE endpoint registry — every path the SDK calls, in one place, grouped by\n * domain to mirror `api/`, `dtos/`, and the `ttf` facade. No api function spells\n * a URL inline; they all read from here.\n *\n * Conventions:\n * - Paths are relative to the transport base (`<host>/api`) — see `client/http`.\n * A few legacy endpoints live off `/api` (`event/:id/time-slot-by-date`,\n * `event/:id/reservation/refresh/`); those omit the `v1/` prefix on purpose.\n * - `auth.contactEmail` is origin-rooted (NOT under `/api`) — it's joined with\n * `getOriginUrl()` at the call site.\n * - Static resources are string constants; parameterized ones are builder\n * functions that take the id/hash. Dynamic query params (pagination, filters)\n * are appended by the api function — only canonical flags that ARE the\n * endpoint (`?payment_config=1`) are baked in here.\n */\n\nimport { Id } from '../dtos/common'\n\nexport const ENDPOINTS = {\n /** OAuth login, registration, password recovery, and identity verification. */\n auth: {\n /** OAuth step 1 — exchange email+password for an authorization code. */\n authorizeRn: (clientId: Id) => `v1/oauth/authorize-rn?client_id=${clientId}`,\n /** OAuth step 2 — exchange the code for an access token. */\n accessToken: 'v1/oauth/access_token',\n /** Create an account (multipart form data). */\n registerRn: 'v1/oauth/register-rn',\n /** Cookie session — `DELETE` to sign out. */\n session: '/auth',\n /** Request a \"forgot password\" email (web). */\n restorePassword: '/auth/restore-password',\n /** Request a \"forgot password\" email (React Native variant). */\n restorePasswordRn: 'v1/oauth/restore-password-rn',\n /** Complete a password reset with the token from the email. */\n resetPassword: '/auth/reset-password',\n /** Existing-account lookup — ORIGIN-rooted + form-encoded, NOT under /api.\n * Joined with `getOriginUrl()` at the call site. */\n contactEmail: 'ajax/contact-email/',\n /** Read the signed-in user's identity-verification status (Netverify). */\n verificationInfo: 'v1/authenticate/get-verification-info',\n /** `GET` mints the hosted verification URL; `PATCH` marks it PENDING. */\n verify: 'v1/authenticate/verify',\n },\n\n /** The signed-in user's profile. */\n profile: {\n get: '/customer/profile/',\n },\n\n /** Billing-select geography. */\n geo: {\n /** All selectable countries. */\n countries: '/countries/list',\n /** States/provinces for a country (id→name map). */\n states: (countryId: Id) => `/countries/${countryId}/states/`,\n },\n\n /** Event catalog + engagement — everything keyed by an event id. */\n events: {\n /** `GET v1/event/:id` — event details (seated detection, slug, name). */\n info: (eventId: Id) => `v1/event/${eventId}`,\n /** Purchasable ticket types (+ promo/waiting-list metadata). */\n tickets: (eventId: Id) => `v1/event/${eventId}/tickets/`,\n /** Ticket types for one date of a time-slot event (legacy, off /api). */\n timeSlotByDate: (eventId: Id) => `event/${eventId}/time-slot-by-date`,\n /** Event add-ons. */\n addOns: (eventId: Id) => `v1/event/${eventId}/add-ons`,\n /** Custom-field groups (order / ticket / add-on scopes). */\n customFields: (eventId: Id) => `v1/event/${eventId}/custom_fields/`,\n /** Terms/conditions the buyer may need to accept. */\n conditions: (eventId: Id) => `v1/event/${eventId}/conditions`,\n /** Apply a promo/access code to the session. */\n promo: (eventId: Id) => `v1/event/${eventId}/promo`,\n /** Session currency preference (multi-currency events). */\n currency: (eventId: Id) => `v1/event/${eventId}/currency`,\n /** Unlock a password-protected event. */\n authenticate: (eventId: Id) => `v1/event/${eventId}/authenticate`,\n /** Tracking pixel (page view / order attribution). */\n track: (eventId: Id) => `v1/event/${eventId}/track`,\n /** Write ORDER-level custom-field values after the order exists. */\n orderDataCapture: (eventId: Id) => `v1/event/${eventId}/order-data-capture`,\n /** Write TICKET-level (per-holder) custom-field values. */\n ticketDataCapture: (eventId: Id) => `v1/event/${eventId}/ticket-data-capture`,\n /** Attribute the session to a referrer/promoter. */\n referrer: (eventId: Id) => `v1/event/${eventId}/referrer`,\n /** Join the sold-out waiting list. */\n waitingList: (eventId: Id) => `v1/event/${eventId}/add_to_waiting_list`,\n /** Submit RSVP details. */\n rsvp: (eventId: Id) => `v1/event/${eventId}/send-rsvp-info`,\n },\n\n /** Cart + pricing session. */\n cart: {\n /** Read the cart back (pins the event's payment method into the session). */\n get: 'v1/cart/',\n /** Cart + pre-order payment config (identifies the gateway pre-order). */\n withPaymentConfig: 'v1/cart?payment_config=1',\n /** Cart + display-ready server price breakdown; optional add-on query. */\n withPriceBreakdown: (addOnsQuery?: string) =>\n `v1/cart?price_breakdown=1${addOnsQuery ? `&${addOnsQuery}` : ''}`,\n /** Replace the whole cart with the current ticket selection. */\n addToCart: (eventId: Id) => `v1/event/${eventId}/add-to-cart/`,\n /** Price the cart (+ add-ons). */\n checkout: 'v1/checkout',\n /** Checkout gates for the current session (names_required, field gates). */\n checkoutConfigs: 'v1/checkout-configs',\n /** Payment-plan charge by explicit payment method (saved-card shortcut). */\n paymentPlan: (orderHash: string) => `cart/payment-plan/${orderHash}`,\n },\n\n /** Order lifecycle — create, review, finalize. */\n order: {\n /** Create the order from buyer + holders + add-ons (the on-checkout body). */\n create: 'v1/on-checkout/',\n /** Post-order review — gateway identity + Stripe/plan secrets + totals. */\n review: (orderHash: string) => `v1/order/${orderHash}/review`,\n /** Finalize a paid/pending order (emails receipt/voucher, defers webhook). */\n success: (orderHash: string) => `v1/order/${orderHash}/success/`,\n /** Complete a free (zero-total) registration. */\n completeFreeRegistration: (orderHash: string) =>\n `v1/order/${orderHash}/complete_free_registration`,\n /** Guard: does the signed-in user own this order hash. */\n verifyCustomer: (orderHash: string) => `v1/order/${orderHash}/verify-customer-order`,\n /** ID-verification round trip (`?url=1` mints the provider session URL). */\n idVerification: (orderHash: string, mintUrl?: boolean) =>\n `v1/order/${orderHash}/id-verification${mintUrl ? '?url=1' : ''}`,\n /** Confirmation-page payload for a completed order. */\n confirmation: (orderHash: string) => `v1/order/${orderHash}/payment/complete`,\n },\n\n /** Payment rails — the per-gateway wire after the order exists. */\n payment: {\n /** Xendit charges (e-wallets AND cards) — form-encoded, not JSON:API. */\n submitPayment: (orderHash: string) => `payments/submit-payment/${orderHash}`,\n /** OXXO: move the order to the pending-voucher state before the confirm. */\n prepareOxxo: (orderHash: string) => `order/${orderHash}/prepare-for-oxxo`,\n /** Per-payment-method-type fee re-price (re-fetch the review after). */\n methodType: (orderHash: string) => `v1/order/${orderHash}/payment-method-type`,\n /** MSI installment offers (between PM creation and the confirm). */\n installmentOffers: (orderHash: string) => `stripe/${orderHash}/installment-offers`,\n /** MSI confirm (server-side; follow with handleNextAction only). */\n confirmInstallments: (orderHash: string) =>\n `stripe/${orderHash}/confirm-installments`,\n /** PayPal Standard step 1 — switch the placed order's method. */\n changeMethod: 'v1/change-payment-method',\n /** PayPal Standard step 2 — the {action_url, fields} to top-level POST. */\n paypalForm: (orderHash: string) => `v1/order/${orderHash}/paypal-form`,\n /** Server-side confirm for redirect-based Stripe methods. */\n confirmRedirect: (orderHash: string) =>\n `v1/order/${orderHash}/stripe/confirm-redirect`,\n /** Schedule a payment plan against a new card's PaymentMethod. */\n paymentPlanCreate: (orderHash: string) => `v1/order/${orderHash}/payment_plan/create`,\n },\n\n /** Account — the buyer's own orders and tickets. */\n account: {\n /** Order history (server-paginated; caller appends page/limit/filter query). */\n orders: 'v1/account/orders/',\n /** One order's full detail. */\n order: (orderId: Id) => `v1/account/order/${orderId}`,\n /** The buyer's tickets/wallet (caller appends the query). */\n tickets: 'v1/account/tickets/',\n /** Twilio-backed phone validation. */\n validatePhone: (phone: string) =>\n `/v1/account/validate_phone?phone=${encodeURIComponent(phone)}`,\n },\n\n /** Ticket resale. */\n resale: {\n sell: (ticketId: Id) => `v1/ticket/${ticketId}/sell`,\n process: (ticketId: Id) => `v1/ticket/${ticketId}/process`,\n decline: (ticketId: Id) => `v1/ticket/${ticketId}/decline`,\n },\n\n /** Pre-registration (\"register interest, then share\"). */\n preRegistration: {\n /** Confirm pre-registration for an event. */\n confirm: (eventId: Id) => `v1/event/${eventId}/pre-registration/confirm`,\n /** Influencers/promoters available to share to. */\n influencers: (eventId: Id) => `v1/event/${eventId}/pre-registration/influencers`,\n /** The post-confirm share page (options + current standing). */\n confirmationPage: (hash: string) => `/v1/pre-registration/${hash}/confirmation-page`,\n /** Record a share action (a referral phase step). */\n submitAction: (hash: string) => `/v1/pre-registration/${hash}/submit-action`,\n },\n\n /** Guest ticket delegation (claim a ticket via an access link). */\n delegation: {\n /** Whether the recipient already has an account. */\n customerExists: (accessHash: string) =>\n `/v1/delegation-access/${accessHash}/customer-exists`,\n /** The claim page (event + ticket context). */\n consumerPageInfo: (accessHash: string) =>\n `v1/delegation-access/${accessHash}/consumer-page-info`,\n /** Issue (claim) the delegated ticket. */\n issueTicket: (accessHash: string) =>\n `v1/delegation-access/${accessHash}/issue-ticket`,\n },\n\n /** Seated events — the seat picker's wire. */\n seatmap: {\n /** The venue seat map. */\n data: (eventId: Id) => `v1/event/${eventId}/seat-map-data`,\n /** Live seat statuses (poll during selection). */\n statuses: (eventId: Id) => `v1/event/${eventId}/seats/status`,\n /** Reserve a seat selection. */\n reserve: (eventId: Id) => `v1/event/${eventId}/seats/reserve`,\n /** Release a held reservation. */\n deleteReserved: (eventId: Id) => `v1/event/${eventId}/seats/delete-reserved`,\n /** Extend a reservation's TTL (legacy, off /api). */\n refreshReservation: (eventId: Id) => `event/${eventId}/reservation/refresh/`,\n },\n} as const\n\n/** The `ENDPOINTS` shape, for callers that want to type against it. */\nexport type Endpoints = typeof ENDPOINTS\n","/**\n * Gateway-level constant sets: which Stripe payment-method types re-price the\n * order, and the Xendit processor rules. Pure data — the logic that reads them\n * lives in `logic/`.\n */\n\n/** Non-single-charge Stripe payment modes: every type here re-prices the order\n * before the client confirm. Card and wallet payments stay single_charge and\n * skip the call. */\nexport const FEE_MODE_PAYMENT_METHOD_TYPES: ReadonlySet<string> = new Set([\n 'afterpay_clearpay',\n 'zip',\n 'affirm',\n 'klarna',\n 'bancontact',\n 'paypal',\n 'ideal',\n 'cashapp',\n 'oxxo',\n 'crypto',\n 'mb_way',\n])\n\n/** Xendit wallet keys that need one extra buyer-typed field before charging. */\nexport const XENDIT_EWALLET_EXTRA_FIELD: Readonly<Record<string, string>> = {\n jenius_pay: 'cashtag',\n ovo: 'phoneNumber',\n}\n\n/** Xendit selector rows that are NOT one-tap e-wallet charges (cards tokenize\n * client-side, bank transfers issue virtual accounts) — filter these out when\n * offering the wallet buttons. */\nexport const XENDIT_NON_EWALLET_PROCESSORS: ReadonlySet<string> = new Set([\n 'credit_card',\n 'bank_transfer',\n 'virtual_account',\n])\n","/**\n * Redirect-based Stripe payment methods (Klarna/Afterpay/Affirm/iDEAL-class)\n * the WebView/popup round trip supports, keyed by the server's\n * payment_method_types spelling.\n */\nexport const SUPPORTED_REDIRECT_METHODS: ReadonlySet<string> = new Set([\n 'klarna',\n 'afterpay_clearpay',\n 'affirm',\n 'ideal',\n 'bancontact',\n 'eps',\n 'giropay',\n 'p24',\n 'alipay',\n 'grabpay',\n 'cashapp',\n 'paypal',\n])\n\n/** Filters a server `paymentMethodTypes` list to the redirect methods the flow\n * supports (order preserved, unknown types dropped). */\nexport const listRedirectMethods = (paymentMethodTypes?: string[] | null): string[] =>\n (paymentMethodTypes || []).filter(\n (type) => typeof type === 'string' && SUPPORTED_REDIRECT_METHODS.has(type)\n )\n","/**\n * Gateway identity — which processor an event/order pays through, read the same\n * way the hosted embed keys on it. Post-order (`detectGateway`, off the review's\n * payment_method) and pre-order (`identifyPreOrderGateway` + the Xendit/PayPal\n * config, off the cart payment block).\n */\nimport type {\n Gateway,\n PayPalTabConfig,\n PreOrderGateway,\n PreOrderPaymentConfig,\n XenditPreOrderConfig,\n XenditProcessor,\n} from '../dtos'\n\n/** Post-order gateway from the review's payment_method block. */\nexport const detectGateway = (\n paymentMethod: Record<string, unknown> | null | undefined\n): Gateway => {\n const pm = paymentMethod || {}\n if (pm.stripe_publishable_key || pm.stripe_client_secret) return 'stripe'\n const name = String(pm.name || '').toLowerCase()\n if (pm.razorpay_key_id || pm.key_id || name.indexOf('razorpay') !== -1) {\n return 'razorpay'\n }\n if (pm.xendit_publishable_key || name.indexOf('xendit') !== -1) return 'xendit'\n return 'unsupported'\n}\n\nconst paymentBlock = (\n cartAttributes: Record<string, unknown> | null | undefined\n): Record<string, unknown> | null => {\n const payment = cartAttributes && (cartAttributes.payment as Record<string, unknown>)\n return payment && typeof payment === 'object' ? payment : null\n}\n\n/** Pre-order gateway from the cart payment-config block. Null when unrecognised. */\nexport const identifyPreOrderGateway = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PreOrderGateway | null => {\n const payment = paymentBlock(cartAttributes)\n const gateway = payment && payment.gateway\n if (\n gateway === 'stripe_payment_intents' ||\n gateway === 'xendit' ||\n gateway === 'razorpay'\n ) {\n return gateway\n }\n return null\n}\n\n/** Xendit pre-order config (publishable key, processors, UI). Null when the\n * event isn't Xendit or the key is missing. */\nexport const xenditPreOrderConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): XenditPreOrderConfig | null => {\n const payment = paymentBlock(cartAttributes)\n if (!payment || payment.gateway !== 'xendit') return null\n const method = payment.payment_method as Record<string, unknown> | undefined\n const publishableKey = method && method.xendit_publishable_key\n if (typeof publishableKey !== 'string' || !publishableKey) return null\n return {\n publishableKey,\n onBehalfOf:\n typeof method?.xendit_on_behalf_of === 'string' && method.xendit_on_behalf_of\n ? method.xendit_on_behalf_of\n : null,\n processors: Array.isArray(payment.payment_processors)\n ? (payment.payment_processors as XenditProcessor[])\n : [],\n failureReasons:\n payment.failure_reasons && typeof payment.failure_reasons === 'object'\n ? (payment.failure_reasons as Record<string, string>)\n : {},\n ui:\n payment.ui && typeof payment.ui === 'object'\n ? (payment.ui as Record<string, string>)\n : {},\n }\n}\n\n/** PayPal Standard tab config off the cart payment block. Null when absent. */\nexport const paypalTabConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PayPalTabConfig | null => {\n const payment = paymentBlock(cartAttributes)\n const paypal = payment && (payment.paypal as PayPalTabConfig | null)\n if (!paypal || typeof paypal !== 'object') return null\n if (!paypal.payment_method_id || !paypal.payment_method_hash) return null\n return paypal\n}\n\n/** Pre-order deferred Stripe Elements config (single-page card mount). Null in\n * every fallback case (no config, non-Stripe, free cart). */\nexport const resolvePaymentConfig = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PreOrderPaymentConfig | null => {\n const payment = cartAttributes && (cartAttributes.payment as PreOrderPaymentConfig)\n if (!payment || typeof payment !== 'object') return null\n if (!payment.elements_config || !payment.basic_config || !payment.basic_config.apiKey) {\n return null\n }\n return payment\n}\n","/**\n * Pricing logic — resolve the display-ready server breakdown, build the\n * display-only add-on query, and map `stripe_wallets` to the Payment Element\n * wallets option (payment-plan mode forces both wallets off — they can't\n * authorize future installments).\n */\nimport type { PriceBreakdown, StripeWallets, WalletsOption } from '../dtos'\n\n/** Query-string form of the display-only add-on map: `add_ons[<id>]=<qty>`.\n * The server caps at 50 entries / qty 100 and drops anything not in the cart. */\nexport const priceBreakdownAddOnsQuery = (\n addOns: Record<string | number, number> | null | undefined\n): string =>\n Object.entries(addOns || {})\n .filter(([id, qty]) => Number(id) > 0 && Number(qty) > 0)\n .map(([id, qty]) => `add_ons[${Number(id)}]=${Number(qty)}`)\n .join('&')\n\n/** Pull the `price_breakdown` block off cart attributes. Null when the backend\n * doesn't serve it (older backends) — callers keep their own rendering. */\nexport const resolvePriceBreakdown = (\n cartAttributes: Record<string, unknown> | null | undefined\n): PriceBreakdown | null => {\n const breakdown =\n cartAttributes && (cartAttributes.price_breakdown as PriceBreakdown | null)\n if (!breakdown || typeof breakdown !== 'object') return null\n if (typeof breakdown.total !== 'string' || !Array.isArray(breakdown.tickets)) {\n return null\n }\n return {\n ...breakdown,\n add_ons: Array.isArray(breakdown.add_ons) ? breakdown.add_ons : [],\n }\n}\n\nexport const walletsOption = (\n stripeWallets: StripeWallets | null | undefined,\n paymentPlanMode = false\n): WalletsOption => {\n if (paymentPlanMode) {\n return { applePay: 'never', googlePay: 'never' }\n }\n const w = stripeWallets || {}\n return {\n applePay: w.applePay === false || w.applePay === 'never' ? 'never' : 'auto',\n googlePay: w.googlePay === false || w.googlePay === 'never' ? 'never' : 'auto',\n }\n}\n","/**\n * Checkout logic — compose the on-checkout body (in-body per-ticket capture,\n * order data_capture, buyer fields), evaluate buyer-field gates, find missing\n * required add-ons, and detect seated events.\n *\n * `buildOnCheckoutBody` matters: on_checkout is the SAME engine the hosted\n * checkout runs, and REQUIRED custom fields are validated AT PLACEMENT — events\n * with required fields can only be placed when the capture rides this body.\n */\nimport type {\n BuyerFieldVisibility,\n CheckoutBilling,\n CheckoutBreakdown,\n CheckoutHolder,\n CustomFieldValues,\n EventAddon,\n EventCustomField,\n EventCustomFieldGroup,\n FieldGates,\n OnCheckoutAttributes,\n OnCheckoutInput,\n RequiredAddOnLike,\n TicketSelection,\n TicketType,\n} from '../dtos'\n\nconst hasKeys = (value?: Record<string, unknown>) =>\n !!value && Object.keys(value).length > 0\n\n/** True when a custom-field answer has been provided (array = at least one). */\nexport const hasValue = (value: string | string[] | undefined): boolean =>\n Array.isArray(value)\n ? value.length > 0\n : Boolean(value !== undefined && String(value).trim())\n\n/** The checkout's single email rule — UIs must not re-derive their own. */\nexport const isEmail = (value: string | undefined): boolean =>\n /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(value?.trim() ?? '')\n\n/** The checkout's single phone rule: 7–15 digits, punctuation ignored. */\nexport const isPhone = (value: string | undefined): boolean => {\n const digits = value?.replace(/\\D/g, '') ?? ''\n return digits.length >= 7 && digits.length <= 15\n}\n\nconst ageOn = (billing: CheckoutBilling, now: Date): number | null => {\n const { dobDay, dobMonth, dobYear } = billing\n if (!dobDay || !dobMonth || !dobYear) return null\n let age = now.getUTCFullYear() - dobYear\n const birthdayPassed =\n now.getUTCMonth() + 1 > dobMonth ||\n (now.getUTCMonth() + 1 === dobMonth && now.getUTCDate() >= dobDay)\n if (!birthdayPassed) age -= 1\n return age\n}\n\nconst ticketSlots = (\n breakdown: CheckoutBreakdown | undefined,\n selections: TicketSelection[]\n): { ticketTypeId?: string }[] => {\n const slots: { ticketTypeId?: string }[] = []\n if (breakdown?.tickets.length) {\n for (const line of breakdown.tickets)\n for (let i = 0; i < line.quantity; i++)\n slots.push({ ticketTypeId: line.ticketTypeId })\n return slots\n }\n for (const selection of selections)\n for (let i = 0; i < selection.quantity; i++) slots.push({})\n return slots\n}\n\n/**\n * Does a ticket-scoped custom field apply to this ticket type? A field with no\n * `ticketTypeIds` applies to every ticket. This is the single owner of the rule\n * — the UIs previously each carried their own copy.\n */\nexport const fieldAppliesToTicketType = (\n field: Pick<EventCustomField, 'ticketTypeIds'>,\n ticketTypeId?: string | number\n): boolean =>\n !ticketTypeId ||\n !field.ticketTypeIds ||\n field.ticketTypeIds.map(String).includes(String(ticketTypeId))\n\n/** The ticket-scoped fields that apply to a given ticket type. */\nexport const ticketFieldsFor = <T extends Pick<EventCustomField, 'ticketTypeIds'>>(\n fields: T[],\n ticketTypeId?: string | number\n): T[] => fields.filter((field) => fieldAppliesToTicketType(field, ticketTypeId))\n\n/**\n * Are every required field in `fields` answered? Mirrors the engine's own\n * preflight, including its rule that `image` fields are server-authoritative\n * and never block the client.\n */\nexport const customFieldsComplete = (\n fields: EventCustomField[],\n values: CustomFieldValues\n): boolean =>\n fields\n .filter((field) => field.required && field.type !== 'image')\n .every((field) => hasValue(values[field.name]))\n\nconst requiredFields = (\n groups: EventCustomFieldGroup[],\n scope: 'order' | 'ticket'\n): EventCustomField[] =>\n groups\n .filter((group) => group.scope === scope)\n .flatMap((group) => group.fields)\n // Image upload is not supported by this checkout yet. The server remains\n // authoritative for those fields, matching the engine preflight.\n .filter((field) => field.required && field.type !== 'image')\n\nexport interface CheckoutDetailsState {\n billing?: CheckoutBilling\n holders: CheckoutHolder[]\n selections: TicketSelection[]\n breakdown?: CheckoutBreakdown\n holderNamesRequired: boolean\n fieldGates: BuyerFieldVisibility\n customFields: EventCustomFieldGroup[]\n}\n\nexport interface CheckoutDetailsValidationOptions {\n /** Embedded guest checkout asks the buyer to type their email twice. */\n requireEmailConfirmation?: boolean\n /** Always collect one named holder per selected ticket. The hosted event\n * checkout normally follows the backend holder-name/custom-field gates;\n * tf-sports' embedded flow opts into this stricter policy. */\n collectTicketHolders?: boolean\n /** Storefront parity: collect email and phone for every ticket holder. */\n requireHolderContact?: boolean\n /** Injectable clock keeps minimum-age checks deterministic in tests. */\n now?: Date\n}\n\n/**\n * One source of truth for every buyer/holder field that must be completed\n * before payment. UI sections use the returned labels for gating and the\n * framework-agnostic engine calls the same function during preflight.\n */\nexport const missingCheckoutDetails = (\n state: CheckoutDetailsState,\n options: CheckoutDetailsValidationOptions = {}\n): string[] => {\n const missing: string[] = []\n const billing = state.billing\n if (!billing) return ['Billing details']\n\n if (!billing.firstName.trim()) missing.push('First name')\n if (!billing.lastName.trim()) missing.push('Last name')\n if (!isEmail(billing.email)) missing.push('Valid email address')\n if (\n options.requireEmailConfirmation &&\n billing.confirmEmail?.trim().toLowerCase() !== billing.email.trim().toLowerCase()\n ) {\n missing.push('Matching email confirmation')\n }\n\n const gates = state.fieldGates\n if (gates.nationalityRequired && !billing.nationality?.trim()) {\n missing.push('Nationality')\n }\n if (gates.genderRequired && !billing.gender?.trim()) missing.push('Gender')\n if (gates.requireInstagram && !billing.instagramHandle?.trim()) {\n missing.push('Instagram handle')\n }\n if (gates.phoneRequired && !isPhone(billing.phone)) missing.push('Valid phone number')\n if (gates.dobRequired) {\n const age = ageOn(billing, options.now ?? new Date())\n if (age === null) missing.push('Date of birth')\n else if (gates.minimumAge !== undefined && age < gates.minimumAge) {\n missing.push(`Age ${gates.minimumAge} or older`)\n }\n }\n if (gates.showAddress) {\n if (!billing.streetAddress?.trim()) missing.push('Street address')\n if (!billing.city?.trim()) missing.push('City')\n if (!billing.zip?.trim()) missing.push('ZIP / postcode')\n if (!billing.countryId) missing.push('Country')\n if (billing.stateRequired && !billing.stateId) missing.push('State / county')\n }\n\n for (const field of requiredFields(state.customFields, 'order')) {\n if (!hasValue(billing.dataCapture?.[field.name])) {\n missing.push(field.label || field.name)\n }\n }\n\n const slots = ticketSlots(state.breakdown, state.selections)\n const ticketFields = requiredFields(state.customFields, 'ticket')\n const holderNamesRequired =\n state.holderNamesRequired || options.collectTicketHolders === true\n const needsHolders = holderNamesRequired || ticketFields.length > 0\n const holderContactRequired = options.requireHolderContact && needsHolders\n if (needsHolders) {\n slots.forEach((slot, index) => {\n const holder = state.holders[index]\n const ticketNumber = index + 1\n if (holderNamesRequired) {\n if (!holder?.firstName.trim()) {\n missing.push(`Ticket ${ticketNumber} holder first name`)\n }\n if (!holder?.lastName.trim()) {\n missing.push(`Ticket ${ticketNumber} holder last name`)\n }\n }\n if (holderContactRequired) {\n if (!isEmail(holder?.email)) {\n missing.push(`Ticket ${ticketNumber} holder email`)\n }\n if (!isPhone(holder?.phone)) {\n missing.push(`Ticket ${ticketNumber} holder phone`)\n }\n }\n for (const field of ticketFields) {\n const ticketTypeId = holder?.ticketTypeId ?? slot.ticketTypeId\n if (\n field.ticketTypeIds &&\n ticketTypeId &&\n !field.ticketTypeIds.map(String).includes(String(ticketTypeId))\n ) {\n continue\n }\n if (!hasValue(holder?.ticketDataCapture?.[field.name])) {\n missing.push(`${field.label || field.name} (ticket ${ticketNumber})`)\n }\n }\n })\n }\n\n return missing\n}\n\n/** Merge the parity fields into an existing attributes `base` object. */\nexport const buildOnCheckoutBody = (\n input: OnCheckoutInput,\n base: Record<string, unknown> = {}\n): OnCheckoutAttributes & Record<string, unknown> => {\n const attributes: OnCheckoutAttributes & Record<string, unknown> = { ...base }\n\n const buyer = input.buyerFields || {}\n if (buyer.nationality !== undefined && buyer.nationality !== '') {\n attributes.nationality = buyer.nationality\n }\n if (buyer.gender) {\n attributes.gender = buyer.gender\n }\n if (buyer.instagramHandle) {\n attributes.instagram_handle = buyer.instagramHandle\n }\n\n if (hasKeys(input.dataCapture)) {\n attributes.data_capture = { ...input.dataCapture }\n }\n\n if (input.ticketHolders && input.ticketHolders.length) {\n const holders: Array<Record<string, unknown>> = []\n const ticketDataCapture: Array<Record<string, unknown>> = []\n let hasTicketCapture = false\n\n input.ticketHolders.forEach((holder) => {\n const row: Record<string, unknown> = {\n first_name: holder.firstName || '',\n last_name: holder.lastName || '',\n }\n if (holder.email !== undefined) row.email = holder.email\n if (holder.phone !== undefined) row.phone = holder.phone\n if (holder.ticketTypeId !== undefined) {\n row.ticket_type_id = holder.ticketTypeId\n }\n const capture = holder.ticketDataCapture || {}\n if (hasKeys(capture)) {\n row.ticket_data_capture = { ...capture }\n hasTicketCapture = true\n }\n holders.push(row)\n ticketDataCapture.push(hasKeys(capture) ? { ...capture } : {})\n })\n\n attributes.ticket_holders = holders\n\n if (hasTicketCapture) {\n attributes.ticket_data_capture = ticketDataCapture\n }\n }\n\n if (hasKeys(input.addOns)) {\n attributes.add_ons = { ...(input.addOns as Record<string, number>) }\n }\n\n if (hasKeys(input.addOnDataCapture)) {\n attributes.add_on_data_capture = { ...input.addOnDataCapture }\n }\n\n return attributes\n}\n\n/** Evaluate the buyer-field gates off `GET v1/checkout-configs` (next_page_info). */\nexport const evaluateFieldGates = (\n gates: FieldGates | null | undefined\n): BuyerFieldVisibility => {\n const g = gates || {}\n const showNationality = !!g.show_nationality_field\n const showGender = !!g.show_gender_field\n const minAge = g.minimum_age == null ? undefined : Number(g.minimum_age)\n return {\n showNationality,\n nationalityRequired: showNationality && !!g.nationality_field_required,\n showGender,\n genderRequired: showGender && !!g.gender_field_required,\n requireInstagram: !!g.require_instagram,\n showPhone: !g.hide_phone_field,\n phoneRequired: !!g.phone_required,\n showDob: !!g.age_required,\n dobRequired: !!g.age_required,\n minimumAge: Number.isFinite(minAge) ? minAge : undefined,\n showAddress: !g.free_ticket,\n }\n}\n\n/**\n * The required add-ons the selection is still missing. Empty means the\n * requirement is satisfied. A sold-out required add-on (stock exactly 0) is\n * exempt — it never blocks placement (the hosted rule).\n */\nexport const missingRequiredAddOns = <T extends RequiredAddOnLike>(\n addOns: T[] | null | undefined,\n selectedQuantities: Record<string | number, number> | null | undefined\n): T[] =>\n (addOns || []).filter((addOn) => {\n if (!addOn.required || addOn.active === false) return false\n if (addOn.stock === 0) return false\n return (Number(selectedQuantities?.[addOn.id]) || 0) < 1\n })\n\n/** The hosted cap when nothing else bounds an add-on (embed-checkout-app.js). */\nexport const ADD_ON_DEFAULT_MAX_QUANTITY = 10\n\n/**\n * The selectable quantity cap for ONE add-on — the minimum of every bound that\n * applies, mirroring the hosted `order_add_on` partial exactly:\n *\n * - `flagLimitToTicketQuantity` → the number of tickets in the cart\n * - `limitPerTicket` → `limitPerTicket × ticketQuantity`\n * - `maxQuantity` → itself (already min'd with available stock\n * server-side on public reads)\n * - nothing set → the hosted default of 10\n * - `isCheckbox` → a yes/no choice, so at most 1\n *\n * This is NOT cosmetic: the server hard-rejects quantities above these\n * (`add_on_max_quantity`), so an over-generous picker builds an order that\n * fails at placement. `stock` is deliberately not a candidate — on public\n * reads it is only a sold-out signal (0 or null), never a count.\n */\nexport const addOnMaxQuantity = (\n addOn: Pick<\n EventAddon,\n 'flagLimitToTicketQuantity' | 'limitPerTicket' | 'maxQuantity' | 'isCheckbox'\n >,\n ticketQuantity: number\n): number => {\n const candidates: number[] = []\n if (addOn.flagLimitToTicketQuantity) candidates.push(ticketQuantity)\n if (addOn.limitPerTicket && addOn.limitPerTicket > 0) {\n candidates.push(Math.floor(addOn.limitPerTicket) * ticketQuantity)\n }\n if (addOn.maxQuantity && addOn.maxQuantity > 0) {\n candidates.push(Math.floor(addOn.maxQuantity))\n }\n const max = candidates.length\n ? Math.max(0, Math.min(...candidates))\n : ADD_ON_DEFAULT_MAX_QUANTITY\n return addOn.isCheckbox ? Math.min(max, 1) : max\n}\n\n/**\n * The selectable quantity bounds for a ticket type's dropdown: `{ min, max,\n * step }`. Tables are the subtlety — their quantity is a GUEST count (bounded by\n * `minGuests`/`maxGuests`), not a count of tickets, so a \"full table of 8\" must\n * offer 8…maxGuests and never a smaller number; the generic `min/maxQuantity`\n * stay 1/10 on the wire and would wrongly let the buyer pick fewer. `step` is the\n * `multiplier` (the cart sells in blocks of N). Mirrors the old checkout's\n * `getTicketSelectOptions(maxCount, minCount, multiplier)` with\n * `maxCount = isTable ? maxGuests : maxQuantity`.\n */\nexport const ticketQuantityRange = (\n ticket: Pick<\n TicketType,\n 'isTable' | 'minQuantity' | 'maxQuantity' | 'minGuests' | 'maxGuests' | 'multiplier'\n >\n): { min: number; max: number; step: number } => ({\n min: ticket.isTable ? (ticket.minGuests ?? ticket.minQuantity) : ticket.minQuantity,\n max: ticket.isTable ? (ticket.maxGuests ?? ticket.maxQuantity) : ticket.maxQuantity,\n step: ticket.multiplier || 1,\n})\n\n/**\n * Reserved-seating detection. A seated event sells through a seat-map picker, so\n * a surface without one hands the buyer off to the event page. Accepts event\n * details, the cart/payment payload, or raw event attributes.\n */\nexport const isSeatedEvent = (event: object | null | undefined): boolean => {\n const e = (event || {}) as Record<string, unknown>\n return !!(e.seatMapAllowed || e.flagSeatMapAllowed || e.seat_map_allowed === 'yes')\n}\n","/**\n * Payment logic — the pure request-builders and response-interpreters each rail\n * needs: redirect confirm, OXXO voucher, PayPal Standard, saved-card plan, fee\n * re-price, MSI installments, and Xendit e-wallets. The `payment` api calls\n * these; they touch no transport.\n */\nimport { FEE_MODE_PAYMENT_METHOD_TYPES } from '../constants'\nimport type {\n ChangePaymentMethodInput,\n InstallmentOffer,\n InstallmentOffers,\n OxxoVoucher,\n PaymentMethodTypeInput,\n PaymentMethodTypeRequest,\n PayPalForm,\n RedirectConfirmResponse,\n RedirectOutcome,\n SavedPlanCard,\n XenditChargeOutcome,\n XenditEWalletChargeInput,\n} from '../dtos'\n\n// --- redirect methods ------------------------------------------------------\n\nexport const interpretRedirectConfirm = (\n response: RedirectConfirmResponse\n): RedirectOutcome => {\n if (response.requires_action && response.redirect_url) {\n return { kind: 'redirect', url: response.redirect_url }\n }\n if (response.requires_action && response.client_secret) {\n return {\n kind: 'inline_action',\n clientSecret: response.client_secret,\n nextActionType: response.next_action_type || '',\n }\n }\n if (response.requires_action) {\n return { kind: 'unresolved_action', status: response.status }\n }\n return { kind: 'settled', status: response.status }\n}\n\n// --- OXXO ------------------------------------------------------------------\n\n/** Read the voucher off a confirmed PaymentIntent's next action — tolerant of\n * both the web (oxxo_display_details) and RN (voucherURL) shapes. */\nexport const oxxoVoucherFromNextAction = (\n nextAction: Record<string, unknown> | null | undefined\n): OxxoVoucher | null => {\n if (!nextAction || typeof nextAction !== 'object') return null\n\n const details = nextAction.oxxo_display_details as Record<string, unknown> | undefined\n if (details && typeof details.hosted_voucher_url === 'string') {\n return {\n voucherUrl: details.hosted_voucher_url,\n voucherNumber: typeof details.number === 'string' ? details.number : null,\n expiresAt: typeof details.expires_after === 'number' ? details.expires_after : null,\n }\n }\n\n if (typeof nextAction.voucherURL === 'string' && nextAction.voucherURL) {\n return {\n voucherUrl: nextAction.voucherURL,\n voucherNumber:\n typeof nextAction.voucherNumber === 'string' ? nextAction.voucherNumber : null,\n expiresAt: typeof nextAction.expiration === 'number' ? nextAction.expiration : null,\n }\n }\n\n return null\n}\n\n// --- PayPal Standard + saved-card plan -------------------------------------\n\nexport const buildChangePaymentMethodAttributes = (\n input: ChangePaymentMethodInput\n): Record<string, unknown> => ({\n payment_method_id: input.paymentMethodId,\n payment_method_hash: input.paymentMethodHash,\n order_id: Number(input.orderId),\n order_hash: input.orderHash,\n redirect: false,\n})\n\nexport const resolvePayPalForm = (\n attributes: Record<string, unknown> | null | undefined\n): PayPalForm | null => {\n const actionUrl = attributes && attributes.action_url\n const fields = attributes && attributes.fields\n if (typeof actionUrl !== 'string' || !actionUrl) return null\n if (!fields || typeof fields !== 'object') return null\n return { action_url: actionUrl, fields: fields as Record<string, string> }\n}\n\n/** The saved-card shortcut off the review's payment_method — null unless the\n * plan configuration carries a reusable card. */\nexport const savedPlanCard = (\n paymentMethod: Record<string, unknown> | null | undefined\n): SavedPlanCard | null => {\n const plan = paymentMethod?.stripe_payment_plan_configuration as\n | Record<string, unknown>\n | undefined\n const savedCard = plan?.saved_card as Record<string, unknown> | undefined\n const paymentMethodId = savedCard?.stripe_payment_method_id\n if (typeof paymentMethodId !== 'string' || !paymentMethodId) return null\n return {\n last4: typeof savedCard?.last_4_digits === 'string' ? savedCard.last_4_digits : '',\n paymentMethodId,\n }\n}\n\n// --- fee re-price ----------------------------------------------------------\n\nexport const requiresFeeReprice = (type: string | null | undefined): boolean =>\n !!type && FEE_MODE_PAYMENT_METHOD_TYPES.has(type)\n\nexport const buildPaymentMethodTypeAttributes = (\n input: PaymentMethodTypeInput\n): PaymentMethodTypeRequest => ({\n payment_method_type: input.paymentMethodType,\n order_id: Number(input.orderId),\n order_hash: input.orderHash,\n stripe_intent_id: input.stripeIntentId,\n})\n\n/** A PaymentIntent client secret is `pi_<id>_secret_<nonce>` — the review\n * carries the secret, the re-price endpoint wants the id. Null for setup-intent\n * secrets (seti_…) and anything else. */\nexport const paymentIntentIdFromClientSecret = (\n clientSecret: string | null | undefined\n): string | null => {\n const match = /^(pi_[A-Za-z0-9]+)_secret_/.exec(clientSecret || '')\n return match ? match[1] : null\n}\n\n// --- MSI installments ------------------------------------------------------\n\nexport const buildInstallmentOffersFields = (input: {\n paymentIntentId: string\n paymentMethodId: string\n}): Record<string, string> => ({\n payment_intent: input.paymentIntentId,\n payment_method: input.paymentMethodId,\n})\n\nexport const resolveInstallmentOffers = (\n raw: Record<string, unknown> | null | undefined\n): InstallmentOffers => ({\n installments: Array.isArray(raw?.installments)\n ? (raw?.installments as InstallmentOffer[])\n : [],\n installmentsSupported: !!raw?.installments_supported,\n original:\n raw?.original && typeof raw.original === 'object'\n ? (raw.original as InstallmentOffers['original'])\n : {},\n})\n\nexport const buildConfirmInstallmentsFields = (input: {\n paymentIntentId: string\n offer: InstallmentOffer\n}): Record<string, string> => ({\n payment_intent: input.paymentIntentId,\n 'installments[count]': String(input.offer.count),\n 'installments[interval]': input.offer.interval,\n 'installments[type]': input.offer.type,\n})\n\nexport const confirmInstallmentsHasNextAction = (\n raw: Record<string, unknown> | null | undefined\n): boolean => !!raw?.has_next_action\n\n// --- Xendit e-wallets ------------------------------------------------------\n\n/** The flat form-field map (PHP bracket notation) the charge endpoint reads —\n * send it form-encoded, never as JSON. */\nexport const buildXenditEWalletChargeFields = (\n input: XenditEWalletChargeInput\n): Record<string, string> => {\n const fields: Record<string, string> = {\n order: String(input.orderId),\n orderHash: input.orderHash,\n 'paymentData[paymentType]': input.paymentType,\n }\n if (input.cashtag) fields['paymentData[data][cashtag]'] = input.cashtag\n if (input.phoneNumber) fields['paymentData[data][phoneNumber]'] = input.phoneNumber\n return fields\n}\n\nexport const interpretXenditChargeResponse = (\n raw: Record<string, unknown> | null | undefined\n): XenditChargeOutcome => {\n const redirectUrl = raw && raw.redirectUrl\n if (typeof redirectUrl === 'string' && redirectUrl) {\n return {\n kind: 'redirect',\n url: redirectUrl,\n notice: typeof raw?.popupMessage === 'string' ? raw.popupMessage : null,\n }\n }\n const reason =\n (typeof raw?.message === 'string' && raw.message) ||\n (typeof raw?.failure_reason === 'string' && raw.failure_reason) ||\n 'The payment could not be started. Please try again or pick a different payment method.'\n return { kind: 'failed', reason }\n}\n","/**\n * Payment-plan terms — the buyer-facing disclosure block.\n *\n * A faithful port of the hosted checkout's `renderPaymentPlanSelector`\n * (embed-checkout-app.js), which composes these paragraphs from the same\n * `payment_plan_configuration` the backend already sends us. Everything here is\n * pure string composition over the preview DTO, so web and native render the\n * identical wording and one set of tests covers both.\n *\n * This is not cosmetic copy. The admin-fee line states a real per-installment\n * charge, and the non-refundable line states what the buyer forfeits if they\n * default. A plan UI that omits them is understating the cost of the purchase.\n *\n * Wording is the hosted DEFAULT for each i18n key. Consumers that already\n * localize can map over the returned parts by `id`.\n */\nimport type { CheckoutPaymentPlanPreview } from '../dtos'\n\n/** The default word for a plan when the brand hasn't renamed it. */\nexport const DEFAULT_PLAN_TERMINOLOGY = 'Payment Plan'\n\n/** The brand's word for the plan — \"Payment Plan\", \"Layaway\", … */\nexport const planTerminology = (plan?: CheckoutPaymentPlanPreview | null): string =>\n plan?.terminology?.trim() || DEFAULT_PLAN_TERMINOLOGY\n\n/** `currency_symbol` + 2dp, matching the hosted `money()` helper exactly. */\nexport const formatPlanMoney = (\n plan: CheckoutPaymentPlanPreview | null | undefined,\n value: number | null | undefined\n): string => {\n const symbol = plan?.currencySymbol ?? ''\n const num = Number(value)\n return `${symbol}${Number.isFinite(num) ? num.toFixed(2) : String(value ?? '')}`\n}\n\n/** \"Click to pay in 3 payments with a Payment Plan\" — the opt-in label. */\nexport const planCheckboxLabel = (plan: CheckoutPaymentPlanPreview): string =>\n `Click to pay in ${plan.totalInstallments ?? 0} payments with a ${planTerminology(plan)}`\n\n/** The plan's submit CTA — \"Confirm Payment Plan\". */\nexport const planConfirmLabel = (plan?: CheckoutPaymentPlanPreview | null): string =>\n `Confirm ${planTerminology(plan)}`\n\n/** \"CN Brand TTF Payment Plan Terms\" — the terms heading. */\nexport const planTermsTitle = (plan: CheckoutPaymentPlanPreview): string =>\n `${plan.manufacturerName ?? ''} ${planTerminology(plan)} Terms`.trim()\n\n/** One paragraph of the terms block. `id` is stable for localization/testing. */\nexport interface PlanTermsParagraph {\n id: 'schedule' | 'adminFee' | 'nonRefundable' | 'custom' | 'note'\n text: string\n}\n\n/**\n * The schedule sentence — five variants, selected exactly as the hosted block\n * does: down-payment (event-anchored final / two-payment / many), the plain\n * two-payment case, then the general auto-equal / staged wording.\n */\nconst scheduleParagraph = (plan: CheckoutPaymentPlanPreview): string => {\n const terminology = planTerminology(plan)\n const installments = Math.trunc(Number(plan.totalInstallments ?? 0)) || 0\n const periodicity = plan.interval == null ? '' : String(plan.interval)\n const installmentPrice = formatPlanMoney(plan, plan.pricePerInstallment)\n const confirm = `By clicking on the \"Confirm ${terminology}\" button`\n\n if (plan.downPaymentEnabled && plan.downPaymentAmount != null) {\n const amount = formatPlanMoney(plan, plan.downPaymentAmount)\n const remaining = Math.max(installments - 1, 1)\n if (remaining === 1 && plan.isEventAnchored && plan.finalChargeDate) {\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by a final payment of ${installmentPrice} on ${plan.finalChargeDate}.`\n }\n if (remaining === 1) {\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by a final payment of ${installmentPrice} in ${periodicity} days.`\n }\n return `${confirm}, you are starting your ${terminology} with a down payment of ${amount} today, followed by ${remaining} further payments of ${installmentPrice}, drawn from your account every ${periodicity} days.`\n }\n\n if (installments === 2) {\n return `${confirm}, you are starting your ${terminology} of 2 payments of ${installmentPrice}, with the first payment taken today and the final payment in ${periodicity} days.`\n }\n\n return `${confirm}, you are starting your ${terminology} of ${installments} payments of ${installmentPrice}, which will be drawn from your account every ${periodicity} days, with the first payment taken today.`\n}\n\n/**\n * The full terms block, in render order. Empty when there is nothing to state\n * (no installment shape), so callers can render unconditionally.\n */\nexport const paymentPlanTerms = (\n plan: CheckoutPaymentPlanPreview | null | undefined\n): PlanTermsParagraph[] => {\n if (!plan || (plan.totalInstallments == null && plan.pricePerInstallment == null)) {\n return []\n }\n\n const parts: PlanTermsParagraph[] = [{ id: 'schedule', text: scheduleParagraph(plan) }]\n\n const hasAdminFee = Boolean(plan.hasAdminFee && plan.adminFee)\n if (hasAdminFee) {\n parts.push({\n id: 'adminFee',\n text: `This includes a non-refundable admin fee of ${formatPlanMoney(plan, plan.adminFee)} per payment.`,\n })\n }\n\n // The hosted flow folds the admin fee into the cancellation sentence unless\n // the event opts out — hence a clause rather than its own paragraph.\n const additionalClause =\n hasAdminFee && !plan.hideNonRefundableAdminFeeText\n ? ` and an admin fee of ${formatPlanMoney(plan, plan.adminFee)} for each installment paid,`\n : ''\n const forfeited = formatPlanMoney(plan, plan.totalNonRefundableAmount)\n const cancelled =\n 'If you do not complete your payments, your order will be cancelled. At that point,'\n const refunded = 'Any remaining amount you have paid will be refunded.'\n\n if (plan.nonRefundableType === 'fixed' && plan.totalNonRefundableAmount) {\n parts.push({\n id: 'nonRefundable',\n text: `${cancelled} a set amount of ${forfeited}${additionalClause} will not be refunded. ${refunded}`,\n })\n } else if (plan.nonRefundableType === 'percent' && plan.nonRefundableAmount) {\n parts.push({\n id: 'nonRefundable',\n text: `${cancelled} ${plan.nonRefundableAmount}% of your order total (${forfeited})${additionalClause} will not be refunded. ${refunded}`,\n })\n }\n\n if (plan.customMessage) {\n parts.push({ id: 'custom', text: String(plan.customMessage) })\n }\n\n parts.push({\n id: 'note',\n text: 'NOTE: If today’s payment fails, your plan will not activate. Your tickets will not be issued until you complete your final payment.',\n })\n\n return parts\n}\n","/**\n * Account/session logic — interpret the existing-account lookup and drive the\n * multi-currency preference sync.\n */\nimport type {\n ContactEmailResponse,\n CurrencyState,\n CurrencySync,\n CurrencySyncOptions,\n CurrencyTransport,\n ExistingAccount,\n} from '../dtos'\n\n/** Normalize the `/ajax/contact-email` response to a boolean existence flag. */\nexport const interpretContactEmail = (\n raw: Partial<ContactEmailResponse> | null | undefined\n): ExistingAccount => {\n const exists = !!raw && !raw.error && Number(raw.exists) === 1\n return {\n exists,\n verified: exists && typeof raw?.verified === 'boolean' ? raw.verified : null,\n }\n}\n\n/** True when the event offers more than one currency (render a switcher only\n * then — currency selection exists solely for multi-currency events). */\nexport const isMultiCurrency = (state: CurrencyState | null | undefined): boolean =>\n !!state && Array.isArray(state.available) && state.available.length > 1\n\n/**\n * Run a currency sync through the injected transport. A bare sync (no code)\n * geo-seeds and reports state; a code switches it (requiresCatalogRefresh — a\n * currency change is a full reprice, so refetch the catalog and reset selection).\n */\nexport const syncCurrency = async (\n transport: CurrencyTransport,\n eventId: string | number,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencySync> => {\n const state = await transport(eventId, code, options)\n return {\n state,\n requiresCatalogRefresh: !!code,\n }\n}\n","/**\n * Authentication rules shared by web and React Native. This module is pure:\n * no React, browser APIs, FormData, or transport. Platform UI owns only field\n * rendering while the API layer owns the final multipart encoding.\n */\nimport type {\n AuthFieldErrors,\n AuthLoginInput,\n AuthRegistrationInput,\n AuthValidationResult,\n} from '../dtos'\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst SPECIAL_CHARACTER = /[^A-Za-z0-9]/\n\nconst result = (errors: AuthFieldErrors): AuthValidationResult => ({\n valid: Object.keys(errors).length === 0,\n errors,\n})\n\nexport const normalizeAuthEmail = (email: string): string => email.trim().toLowerCase()\n\nexport const validateLoginInput = (input: AuthLoginInput): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const email = normalizeAuthEmail(input.email)\n if (!email) errors.email = 'Email is required.'\n else if (!EMAIL.test(email)) errors.email = 'Enter a valid email address.'\n if (!input.password) errors.password = 'Password is required.'\n return result(errors)\n}\n\nexport const validatePasswordResetEmail = (email: string): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const normalized = normalizeAuthEmail(email)\n if (!normalized) errors.email = 'Email is required.'\n else if (!EMAIL.test(normalized)) errors.email = 'Enter a valid email address.'\n return result(errors)\n}\n\nexport const validateRegistrationInput = (\n input: AuthRegistrationInput,\n options: { requireAddress?: boolean; requireState?: boolean } = {}\n): AuthValidationResult => {\n const errors: AuthFieldErrors = {}\n const email = normalizeAuthEmail(input.email)\n\n if (!input.firstName.trim()) errors.firstName = 'First name is required.'\n if (!input.lastName.trim()) errors.lastName = 'Last name is required.'\n if (!email) errors.email = 'Email is required.'\n else if (!EMAIL.test(email)) errors.email = 'Enter a valid email address.'\n\n if (!input.password) errors.password = 'Password is required.'\n else if (input.password.length < 8)\n errors.password = 'Password must be at least 8 characters.'\n else if (!SPECIAL_CHARACTER.test(input.password))\n errors.password = 'Password must include a special character.'\n\n if (!input.passwordConfirmation) errors.passwordConfirmation = 'Confirm your password.'\n else if (input.passwordConfirmation !== input.password)\n errors.passwordConfirmation = 'Passwords do not match.'\n\n if (options.requireAddress) {\n if (!input.streetAddress?.trim()) errors.streetAddress = 'Street address is required.'\n if (!input.city?.trim()) errors.city = 'City is required.'\n if (!input.zip?.trim()) errors.zip = 'ZIP / postcode is required.'\n if (!input.countryId) errors.countryId = 'Country is required.'\n }\n if (options.requireState && !input.stateId)\n errors.stateId = 'State / region is required.'\n\n return result(errors)\n}\n\n/** Map the platform-neutral shape to the backend's registration contract. */\nexport const buildRegistrationFields = (\n input: AuthRegistrationInput\n): Record<string, string> => {\n const fields: Record<string, string> = {\n first_name: input.firstName.trim(),\n last_name: input.lastName.trim(),\n email: normalizeAuthEmail(input.email),\n password: input.password,\n password_confirmation: input.passwordConfirmation,\n }\n\n const optional: Array<[string, string | undefined]> = [\n ['phone', input.phone?.trim()],\n ['street_address', input.streetAddress?.trim()],\n ['city', input.city?.trim()],\n ['zip', input.zip?.trim()],\n ['country', input.countryId],\n ['state', input.stateId],\n ]\n for (const [key, value] of optional) {\n if (value) fields[key] = value\n }\n return { ...fields, ...input.registrationFields }\n}\n","/**\n * ID-verification poller — a NEED_ID_VERIFICATION order signals\n * `needIdVerification`; the buyer completes the provider check in a new\n * tab/window while this polls `GET v1/order/:hash/id-verification` until\n * verified. Pure state machine — fetch and clock are injected, so it runs\n * identically in React, React Native, and tests (5s ticks, capped).\n */\nimport type {\n IdVerificationCallbacks,\n IdVerificationPoller,\n IdVerificationStatus,\n} from '../dtos'\n\nexport const ID_VERIFICATION_POLL_MS = 5000\nexport const ID_VERIFICATION_MAX_TICKS = 60\nexport const ID_VERIFICATION_MAX_CONSECUTIVE_FAILURES = 3\n\nexport const createIdVerificationPoller = (\n callbacks: IdVerificationCallbacks\n): IdVerificationPoller => {\n const schedule =\n callbacks.schedule || ((fn: () => void, ms: number) => setTimeout(fn, ms))\n let ticks = 0\n let consecutiveFailures = 0\n let stopped = false\n // Injected schedulers can't be portably cancelled, so a generation token\n // invalidates ticks scheduled by a previous start()/stop() cycle.\n let generation = 0\n\n const scheduleNextOrTimeout = (\n runGeneration: number,\n status?: IdVerificationStatus\n ) => {\n ticks += 1\n if (ticks >= ID_VERIFICATION_MAX_TICKS) {\n callbacks.onPhase('timeout', status)\n return\n }\n schedule(() => tick(runGeneration), ID_VERIFICATION_POLL_MS)\n }\n\n const tick = (runGeneration: number) => {\n if (stopped || runGeneration !== generation) return\n callbacks\n .fetchStatus()\n .then((status) => {\n if (stopped || runGeneration !== generation) return\n consecutiveFailures = 0\n if (status.verified || !status.required) {\n callbacks.onPhase('verified', status)\n return\n }\n scheduleNextOrTimeout(runGeneration, status)\n })\n .catch(() => {\n if (stopped || runGeneration !== generation) return\n // Transient failures keep polling — the buyer may be mid-check — but a\n // persistently failing endpoint surfaces as an error instead of five\n // silent minutes.\n consecutiveFailures += 1\n if (consecutiveFailures >= ID_VERIFICATION_MAX_CONSECUTIVE_FAILURES) {\n callbacks.onPhase('error')\n return\n }\n scheduleNextOrTimeout(runGeneration)\n })\n }\n\n return {\n start: () => {\n stopped = false\n ticks = 0\n consecutiveFailures = 0\n generation += 1\n // Capture before onPhase — a synchronously re-entrant start() inside the\n // callback must make THIS run stale, not adopt its token.\n const runGeneration = generation\n callbacks.onPhase('polling')\n tick(runGeneration)\n },\n stop: () => {\n stopped = true\n generation += 1\n },\n }\n}\n","/**\n * The checkout store — a tiny framework-agnostic observable over the\n * `CheckoutSnapshot`. The engine writes to it; `useCheckout()` (or a plain\n * `subscribe()` in a non-React app) reads from it. No React, no globals: the\n * same store instance drives web, React Native, Node, and tests.\n *\n * State updates are immutable (a new snapshot object each change) so\n * `useSyncExternalStore` and shallow-equality consumers re-render correctly.\n *\n * `progress` is separate on purpose: it holds the retry-safety bookkeeping\n * (which order exists, whether it's been charged) that must NEVER be part of\n * the reactive snapshot — it's how retries avoid creating a second order or\n * charging twice.\n */\nimport type { CheckoutSnapshot } from '../dtos'\n\nexport type CheckoutListener = (snapshot: CheckoutSnapshot) => void\n\n/** Retry-safety bookkeeping — mutated directly by the engine, never rendered. */\nexport interface OrderProgress {\n /** The created order's hash — a retry reuses it instead of minting a second. */\n orderHash?: string\n /** True once the charge landed — a retry then only replays finalization. */\n paymentConfirmed?: boolean\n}\n\nexport interface CheckoutStore {\n /** The current snapshot (stable reference until the next change). */\n getState: () => CheckoutSnapshot\n /** Merge a partial snapshot (or a function of the current one) and notify. */\n setState: (\n patch:\n | Partial<CheckoutSnapshot>\n | ((prev: CheckoutSnapshot) => Partial<CheckoutSnapshot>)\n ) => void\n /** Subscribe to changes; returns an unsubscribe function. */\n subscribe: (listener: CheckoutListener) => () => void\n /** Reset to the initial idle snapshot (and clear progress) and notify. */\n reset: () => void\n /** Retry-safety state (order hash + charged flag). Not reactive. */\n progress: OrderProgress\n /** Drop any half-created order — the cart contents changed, so a previously\n * created order is stale and must not be reused. */\n invalidateOrderProgress: () => void\n /** Move to the terminal 'expired' state and clear progress. */\n expireCart: () => void\n}\n\n/** The empty checkout — what every store starts at and `reset()` returns to. */\nexport const initialSnapshot = (): CheckoutSnapshot => ({\n status: 'idle',\n selections: [],\n ticketTypeIds: [],\n customFields: [],\n holderNamesRequired: false,\n fieldGates: {\n showNationality: false,\n nationalityRequired: false,\n showGender: false,\n genderRequired: false,\n requireInstagram: false,\n showPhone: false,\n phoneRequired: false,\n showDob: false,\n dobRequired: false,\n showAddress: false,\n },\n addOns: {},\n holders: [],\n consent: { ttfOptIn: false, brandOptIn: false },\n})\n\nexport const createCheckoutStore = (\n initial: CheckoutSnapshot = initialSnapshot()\n): CheckoutStore => {\n let state = initial\n const listeners = new Set<CheckoutListener>()\n // .forEach (not for-of) so the SDK stays iterable under an es5 consumer target.\n const emit = () => {\n listeners.forEach((listener) => listener(state))\n }\n\n const store: CheckoutStore = {\n progress: {},\n getState: () => state,\n setState: (patch) => {\n const next = typeof patch === 'function' ? patch(state) : patch\n state = { ...state, ...next }\n emit()\n },\n subscribe: (listener) => {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n reset: () => {\n state = initialSnapshot()\n store.progress = {}\n emit()\n },\n invalidateOrderProgress: () => {\n store.progress = {}\n },\n expireCart: () => {\n store.progress = {}\n state = { ...state, status: 'expired' }\n emit()\n },\n }\n return store\n}\n","/**\n * The payment-confirmation port — the hexagonal seam that keeps the engine\n * framework- AND payment-SDK-agnostic. The orchestration is pure TS EXCEPT for\n * the calls that talk to a Stripe SDK (init, read intent status, confirm card /\n * wallet). Those live behind this interface: React Native binds it with\n * @stripe/stripe-react-native, web with stripe-js, tests with a fake.\n *\n * Status vocabulary: confirmers return Stripe PaymentIntent statuses in the RN\n * SDK's PascalCase form ('Succeeded' | 'RequiresCapture' | 'Processing' | …).\n * Adapters over SDKs with other spellings (stripe-js is lowercase) normalize.\n */\nimport type { CheckoutBilling, InstallmentOffer, PayPalForm } from '../dtos'\n\nexport interface PaymentConfirmer {\n /** Initialize the underlying SDK for the given keys. */\n init(options: {\n publishableKey: string\n /** Stripe connected-account id (already cleaned — never ''). */\n accountId?: string\n /** Apple Pay merchant id, when the platform supports it. */\n merchantIdentifier?: string\n /** App deep-link scheme (React Native) — redirect methods return through it. */\n urlScheme?: string\n }): Promise<void>\n\n /** Status of the PaymentIntent behind `clientSecret`, or undefined when it\n * can't be retrieved. Used to skip re-charging on retries. */\n getIntentStatus(clientSecret: string): Promise<string | undefined>\n\n /** Confirm a card payment. Returns the resulting intent status or throws. */\n confirmCard(clientSecret: string, billing: CheckoutBilling): Promise<string | undefined>\n\n /** Present the platform-pay sheet (Apple Pay on iOS). Returns the resulting\n * intent status or throws — a user-cancelled sheet is an error. */\n confirmApplePay(\n clientSecret: string,\n total: string,\n currencyCode: string,\n merchant: { merchantCountryCode?: string; merchantName?: string }\n ): Promise<string | undefined>\n\n /** Present the Google Pay sheet (Android). Optional — only platforms with a\n * native Google Pay SDK bind it; unbound, the engine throws UNSUPPORTED_GATEWAY. */\n confirmGooglePay?(\n clientSecret: string,\n total: string,\n currencyCode: string,\n merchant: {\n merchantCountryCode?: string\n merchantName?: string\n /** Use Google Pay's TEST environment (no real charge). */\n testEnv?: boolean\n }\n ): Promise<string | undefined>\n}\n\n/**\n * A payment is confirmed enough to finalize in any of these states: Succeeded\n * (auto-capture), RequiresCapture (manual-capture authorizes now, captures\n * later — NOT a failure), or Processing (settling asynchronously).\n */\nexport const CONFIRMED_INTENT_STATUSES: string[] = [\n 'Succeeded',\n 'RequiresCapture',\n 'Processing',\n]\n\n/**\n * A Stripe connected-account id, or undefined when there is none. The backend\n * returns '' for platform-account events; passing '' sets an empty\n * `Stripe-Account` header, which Stripe rejects — coerce empties to undefined.\n */\nexport const cleanAccountId = (id?: string | null): string | undefined =>\n id && id.trim() ? id : undefined\n\n/**\n * Optional confirmer capabilities the alternative rails need. A platform that\n * doesn't implement one simply can't run that rail — the engine throws a typed\n * UNSUPPORTED_GATEWAY error instead of failing mid-payment.\n */\nexport interface PaymentConfirmerExtras {\n /** Create a card PaymentMethod (MSI offer lookup runs between creation and\n * the confirm). Returns the PaymentMethod id. */\n createCardPaymentMethod?(billing: CheckoutBilling): Promise<string>\n /** Create a redirect-method PaymentMethod (Klarna/Afterpay/iDEAL-class).\n * Returns the id, or null when the platform can't express the type. */\n createRedirectPaymentMethod?(\n methodType: string,\n billing: CheckoutBilling\n ): Promise<string | null>\n /** Run the pending next action of a SERVER-confirmed intent (MSI). Throws on\n * failure; never confirms a second time. */\n handleNextAction?(clientSecret: string): Promise<void>\n /** Confirm an OXXO voucher intent. Returns the raw nextAction payload (engine\n * extracts the voucher) plus any error — Stripe can report an error while\n * still issuing the voucher. */\n confirmOxxo?(\n clientSecret: string,\n billing: CheckoutBilling\n ): Promise<{ error?: string; nextAction?: unknown }>\n /** Payment plan (new card): confirm the review's SetupIntent to SAVE the card\n * — NOTHING is charged; the plan schedules server-side. Returns the saved\n * PaymentMethod id, or throws. */\n confirmPaymentPlanSetup?(\n clientSecret: string,\n billing: CheckoutBilling\n ): Promise<string>\n /** Payment plan (saved-card shortcut): confirm an on-session card payment\n * against an EXISTING PaymentMethod — the 3DS step runs only when the plan\n * charge comes back requires_action. Throws on failure. */\n confirmSavedCardPayment?(clientSecret: string, paymentMethodId: string): Promise<void>\n}\n\n/** What a provider page run should load: a URL, or an inline HTML document\n * (PayPal's auto-submitting top-level form). */\nexport interface ProviderPageRequest {\n uri?: string\n html?: string\n /** Base URL for an inline document (relative return-leg resolution). */\n baseUrl?: string\n /** Navigating to a URL with this prefix ends the run as 'success'. */\n returnUrlPrefix: string\n}\n\nexport interface ProviderPageOutcome {\n event: 'success' | 'dismiss' | 'failed'\n /** The intercepted return URL (carries e.g. `redirect_status`). */\n returnUrl?: string\n /** Payload posted by data-driven sheets (Razorpay's `razorpay_payment_id`,\n * Xendit card tokenization's `token`) — the platform's plumbing delivers it. */\n data?: Record<string, unknown>\n description?: string\n}\n\n/**\n * The full port set the pay rails run on. `confirmer` is required (card/Apple\n * Pay); the rest are optional platform capabilities:\n * - providerPage: run a provider's page and resolve on the return leg (a\n * WebView sheet on RN, a redirect/popup on web).\n * - openUrl: open an external URL (OXXO voucher, ID-verification).\n * - onInstallmentOffers: offer MSI plans; resolve the chosen one, or null to\n * decline and fall through to a normal single charge.\n * - tokenizeXenditCard: tokenize a Xendit card inline (web); when absent the\n * engine runs the Xendit card document through `providerPage`.\n */\nexport interface CheckoutPorts extends PaymentConfirmerExtras {\n confirmer: PaymentConfirmer\n providerPage?: (request: ProviderPageRequest) => Promise<ProviderPageOutcome>\n openUrl?: (url: string) => void | Promise<void>\n onInstallmentOffers?: (offers: InstallmentOffer[]) => Promise<InstallmentOffer | null>\n tokenizeXenditCard?: (params: {\n publishableKey: string\n amount: string | number\n billing: CheckoutBilling\n onBehalfOf?: string | null\n }) => Promise<Record<string, unknown>>\n}\n\n/** A typed \"this platform can't run this rail\" error — consumers branch on\n * `code` to hand off to the event page. */\nexport const unsupportedGatewayError = (message?: string): Error & { code: string } => {\n const err = new Error(\n message ??\n \"This payment method isn't available in the app. Please finish buying on the event page.\"\n ) as Error & { code: string }\n err.code = 'UNSUPPORTED_GATEWAY'\n return err\n}\n\nconst escapeHtmlAttribute = (value: string) =>\n value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n\n/**\n * PayPal Standard runs as a TOP-LEVEL form POST (PayPal refuses framing) — an\n * auto-submitting form document is all the provider page needs to load.\n */\nexport const buildAutoSubmitFormHtml = (form: PayPalForm): string => {\n const inputs = Object.entries(form.fields)\n .map(\n ([name, value]) =>\n `<input type=\"hidden\" name=\"${escapeHtmlAttribute(name)}\" value=\"${escapeHtmlAttribute(String(value ?? ''))}\" />`\n )\n .join('\\n ')\n\n return `<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n </head>\n <body>\n <form id=\"gateway-form\" method=\"POST\" action=\"${escapeHtmlAttribute(form.action_url)}\">\n ${inputs}\n </form>\n <script>\n document.getElementById('gateway-form').submit();\n </script>\n </body>\n</html>`\n}\n","/**\n * Gateway sheet documents (Razorpay web checkout, Xendit card tokenization) —\n * pure HTML string builders the `providerPage` port loads (a WebView on RN, a\n * popup on web). No runtime deps: these just build a document; the raw card\n * details never leave the page — only the resulting token/payment id is posted\n * back through the provider-page outcome.\n */\nexport interface RazorpayCheckoutHtmlOptions {\n keyId: string\n /** Charge amount in minor units (paise) — the server's pay_now × 100. */\n amountMinor: number\n description?: string\n buyerName?: string\n buyerEmail?: string\n orderHash: string\n}\n\n/**\n * Razorpay hosted checkout inside a WebView. Reports back via\n * `window.ReactNativeWebView.postMessage` with `{event:'success',\n * razorpay_payment_id}` / `{event:'dismiss'}` / `{event:'failed', description}`.\n * `notes.order_hash` ties the charge to the order server-side.\n */\nexport const buildRazorpayCheckoutHtml = (\n options: RazorpayCheckoutHtmlOptions\n): string => {\n const rzpOptions = JSON.stringify({\n key: options.keyId,\n amount: Math.round(options.amountMinor),\n name: 'Ticket Fairy',\n description: options.description || '',\n prefill: {\n name: options.buyerName || '',\n email: options.buyerEmail || '',\n },\n notes: {\n order_hash: options.orderHash,\n },\n })\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<script src=\"https://checkout.razorpay.com/v1/checkout.js\"></script>\n</head>\n<body style=\"margin:0;background:#ffffff\">\n<script>\n function report(payload) {\n if (window.ReactNativeWebView) {\n window.ReactNativeWebView.postMessage(JSON.stringify(payload));\n }\n }\n try {\n var options = ${rzpOptions};\n options.handler = function (response) {\n report({\n event: 'success',\n razorpay_payment_id: response && response.razorpay_payment_id,\n });\n };\n options.modal = {\n ondismiss: function () {\n report({ event: 'dismiss' });\n },\n };\n var rzp = new Razorpay(options);\n rzp.on('payment.failed', function (resp) {\n report({\n event: 'failed',\n description: resp && resp.error && resp.error.description,\n });\n });\n rzp.open();\n } catch (e) {\n report({ event: 'failed', description: e && e.message });\n }\n</script>\n</body>\n</html>`\n}\n\nexport interface XenditCheckoutHtmlOptions {\n publishableKey: string\n /** Tokenization amount — the server-returned pay-now figure verbatim. The\n * CHARGE amount stays server-side in submit-payment. */\n amount: number | string\n buyerFirstName?: string\n buyerLastName?: string\n buyerEmail?: string\n buyerPhone?: string\n onBehalfOf?: string | null\n}\n\n/**\n * Xendit card tokenization inside a WebView: card entry, `Xendit.card.createToken`\n * with 3DS (the challenge iframe re-invokes the handler when it resolves),\n * reporting `{event:'success', token}` / `{event:'failed', description}`.\n */\nexport const buildXenditCheckoutHtml = (options: XenditCheckoutHtmlOptions): string => {\n const opts = JSON.stringify({\n publishableKey: options.publishableKey,\n amount: options.amount,\n firstName: options.buyerFirstName || '',\n lastName: options.buyerLastName || '',\n email: options.buyerEmail || '',\n phone: options.buyerPhone || '',\n onBehalfOf: options.onBehalfOf || null,\n })\n\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<script src=\"https://js.xendit.co/v1/xendit.min.js\"></script>\n<style>\n body { margin: 0; background: #ffffff; font-family: -apple-system, Roboto, sans-serif; }\n .wrap { padding: 16px; }\n label { display: block; font-size: 14px; margin-bottom: 12px; color: #333; }\n input { display: block; width: 100%; box-sizing: border-box; margin-top: 4px;\n padding: 12px 10px; font-size: 16px; border: 1px solid #e0e0e0; border-radius: 8px; }\n .row { display: flex; gap: 12px; }\n .row label { flex: 1; }\n .note { font-size: 13px; color: #666; margin-bottom: 12px; display: none; }\n .err { font-size: 13px; color: #c0392b; margin-bottom: 12px; min-height: 16px; }\n button { width: 100%; padding: 14px; font-size: 16px; border: 0; border-radius: 8px;\n background: #111111; color: #ffffff; }\n button:disabled { opacity: 0.5; }\n #threeds { display: none; position: fixed; inset: 0; background: #ffffff; }\n #threeds iframe { width: 100%; height: 100%; border: 0; }\n</style>\n</head>\n<body>\n<div class=\"wrap\">\n <label>Card number\n <input id=\"num\" inputmode=\"numeric\" autocomplete=\"cc-number\">\n </label>\n <div class=\"row\">\n <label>Expiry (MM/YY)\n <input id=\"exp\" inputmode=\"numeric\" autocomplete=\"cc-exp\" placeholder=\"MM/YY\">\n </label>\n <label>Security code\n <input id=\"cvn\" type=\"password\" inputmode=\"numeric\" autocomplete=\"cc-csc\">\n </label>\n </div>\n <div class=\"note\" id=\"note\">Your bank may ask you to confirm it’s really you.</div>\n <div class=\"err\" id=\"err\"></div>\n <button id=\"pay\">Submit Payment</button>\n</div>\n<div id=\"threeds\"><iframe id=\"threedsFrame\"></iframe></div>\n<script>\n var OPTS = ${opts};\n var payBtn = document.getElementById('pay');\n var errBox = document.getElementById('err');\n var note = document.getElementById('note');\n var threeds = document.getElementById('threeds');\n var threedsFrame = document.getElementById('threedsFrame');\n var submitting = false;\n\n function report(payload) {\n if (window.ReactNativeWebView) {\n window.ReactNativeWebView.postMessage(JSON.stringify(payload));\n }\n }\n function reset(message) {\n submitting = false;\n payBtn.disabled = false;\n note.style.display = 'none';\n threeds.style.display = 'none';\n threedsFrame.src = 'about:blank';\n errBox.textContent = message || '';\n }\n\n function handler(err, token) {\n if (err) {\n reset(err.message || 'Your payment was not accepted. Please try again or use a different card.');\n return;\n }\n if (token.status === 'VERIFIED') {\n threeds.style.display = 'none';\n report({ event: 'success', token: token });\n } else if (token.status === 'IN_REVIEW' && token.payer_authentication_url) {\n note.style.display = 'block';\n threedsFrame.src = token.payer_authentication_url;\n threeds.style.display = 'block';\n } else {\n var reason = token && token.failure_reason ? ' (' + token.failure_reason + ')' : '';\n reset('Your payment was not accepted' + reason + '. Please try again or use a different card.');\n }\n }\n\n payBtn.addEventListener('click', function () {\n if (submitting) return;\n errBox.textContent = '';\n var number = (document.getElementById('num').value || '').replace(/\\\\s+/g, '');\n var expParts = (document.getElementById('exp').value || '').split('/');\n var expMonth = (expParts[0] || '').trim();\n var expYear = (expParts[1] || '').trim();\n if (expYear.length === 2) expYear = '20' + expYear;\n var cvn = (document.getElementById('cvn').value || '').trim();\n if (!number || !expMonth || !expYear || !cvn) {\n errBox.textContent = 'Please fill in your card details.';\n return;\n }\n if (!window.Xendit) {\n report({ event: 'failed', description: 'The payment service could not be loaded.' });\n return;\n }\n submitting = true;\n payBtn.disabled = true;\n try {\n window.Xendit.setPublishableKey(OPTS.publishableKey);\n var data = {\n amount: OPTS.amount,\n card_number: number,\n card_exp_month: expMonth,\n card_exp_year: expYear,\n card_cvn: cvn,\n is_multiple_use: false,\n should_authenticate: true,\n };\n // card_holder_* fields are ALL-OR-NOTHING peers in Xendit's validation —\n // send the group only when complete.\n if (OPTS.firstName && OPTS.lastName && OPTS.email && OPTS.phone) {\n data.card_holder_first_name = OPTS.firstName;\n data.card_holder_last_name = OPTS.lastName;\n data.card_holder_email = OPTS.email;\n data.card_holder_phone_number = OPTS.phone;\n }\n if (OPTS.onBehalfOf) data.on_behalf_of = OPTS.onBehalfOf;\n window.Xendit.card.createToken(data, handler);\n } catch (e) {\n reset((e && e.message) || 'Something went wrong. Please try again.');\n }\n });\n</script>\n</body>\n</html>`\n}\n","/**\n * Engine error helpers. Failures already arrive as `TtfError` (the transport\n * normalizes them), so these just read it: a friendly message, and whether the\n * failure is the backend rejecting an expired cart/checkout session.\n */\nimport { toTtfError } from '../client'\n\n/** The friendliest message for a failed call (the backend's own, else generic). */\nexport const errorMessage = (error: unknown): string => toTtfError(error).message\n\n/**\n * \"expired\" in the languages the backend's per-locale cart-expiry message can\n * use. Message-sniffing is a fallback — the 422 body carries no structured code.\n */\nconst EXPIRED_WORDS =\n /expir|caduc|scadut|abgelaufen|verlopen|udløbet|löpt ut|utløpt|vypršel|wygasł|истек|expirou|kedaluwarsa|hết hạn|期限切れ|已过期|已過期|만료/i\n\n/**\n * True when a failed request is the backend rejecting an expired cart/checkout\n * session (422 + an \"…expired\" message). Lets the flow show a \"restart\"\n * recovery instead of a raw error; ordinary 422 validation errors stay generic.\n */\nexport const isCartExpiredError = (error: unknown): boolean => {\n const e = toTtfError(error)\n if (e.status !== 422) return false\n return EXPIRED_WORDS.test(e.message)\n}\n","/**\n * The raw api surface — one function per endpoint, each \"just does the call\"\n * and returns typed data (or throws `TtfError`). The `ttf` facade in\n * `services.ts` is a thin, domain-grouped convenience over exactly these.\n * Power users can import them directly.\n */\nexport * from './auth'\nexport * from './profile'\nexport * from './geo'\nexport * from './engagement'\nexport * from './orders'\nexport * from './resale'\nexport * from './confirmation'\nexport * from './preRegistration'\nexport * from './delegation'\nexport * from './seatmap'\n// Checkout flow — catalog, cart/pricing, order, payment rails\nexport * from './events'\nexport * from './cart'\nexport * from './order'\nexport * from './payment'\n","/**\n * Profile reads. The signed-in user's record, straight off `/customer/profile/`.\n * (Login lives in `auth.ts`; this is imported there to resolve the profile after\n * the token lands.)\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfEnvelope, TfProfile } from '../types'\n\n/** Fetch the signed-in user's profile. Throws `TtfError` if unauthenticated. */\nexport const getProfile = async (): Promise<TfProfile> => {\n const res = await get<TfEnvelope<TfProfile>>(ENDPOINTS.profile.get, {\n withCredentials: true,\n })\n return res.data\n}\n","/**\n * Auth — the whole surface, not just login. This is the domain shared was\n * missing most: register, password reset/restore, logout, email-exists.\n *\n * Login is the platform's two-step OAuth chain (authorize-rn → access_token);\n * on success we persist the tokens via the session module and every later call\n * rides the bearer automatically.\n */\nimport { getConfig, getOriginUrl } from '../client/config'\nimport { TtfError } from '../client/errors'\nimport { del, get, patch, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { clearSession, notifyCookieSession, setTokens } from '../client/session'\nimport type { AuthRegistrationInput } from '../dtos'\nimport { buildRegistrationFields } from '../logic/auth'\nimport { TfEnvelope, TfProfile } from '../types'\nimport { getProfile } from './profile'\n\nconst toFormData = (fields: Record<string, string | Blob>): FormData => {\n const form = new FormData()\n for (const [key, value] of Object.entries(fields)) form.append(key, value)\n return form\n}\n\n/**\n * Sign in with email + password. Runs the OAuth chain, stores the tokens, and\n * resolves to the freshly-loaded profile. Throws `TtfError` on bad credentials.\n */\nexport const login = async (email: string, password: string): Promise<TfProfile> => {\n const { clientId, clientSecret, cookieAuth } = getConfig()\n\n // Web checkouts share TicketFairy's session cookie (`cookieAuth`). Sign in the\n // way the legacy checkout did — POST /auth (backend `customerLogin`) — so the\n // server issues the X-TF-ECOMMERCE session ticket and the buyer stays on the\n // SAME session that already holds their reserved cart. The OAuth bearer chain\n // below issues no such ticket and rides a separate identity, so a guest who\n // logs in mid-checkout loses the reserved cart and the next on-checkout 422s\n // with \"cart expired\". Bearerless by design (no `setTokens`), exactly like the\n // old flow — the response interceptor captures the ticket the backend returns.\n if (cookieAuth) {\n await post(`${ENDPOINTS.auth.session}?clientId=${clientId}`, { email, password })\n const profile = await getProfile()\n notifyCookieSession()\n return profile\n }\n\n if (!clientId || !clientSecret) {\n throw new TtfError('login: clientId/clientSecret are not configured.', 0)\n }\n\n const authorize = await post<{ data?: { code?: string } }>(\n ENDPOINTS.auth.authorizeRn(clientId),\n toFormData({ email, password }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n const code = authorize.data?.code\n if (!code) throw new TtfError('login: authorization code not received.', 0)\n\n const token = await post<{ access_token?: string; refresh_token?: string }>(\n ENDPOINTS.auth.accessToken,\n toFormData({\n code,\n scope: 'profile',\n grant_type: 'authorization_code',\n client_id: clientId,\n client_secret: clientSecret,\n }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n if (!token.access_token) throw new TtfError('login: no access token received.', 0)\n\n setTokens({ access: token.access_token, refresh: token.refresh_token })\n return getProfile()\n}\n\n/**\n * Create an account. Pass the registration fields as a flat record — the\n * backend endpoint (`v1/oauth/register-rn`) takes multipart form data, so field\n * names are forwarded verbatim (`email`, `password`, `first_name`, …).\n */\nexport const register = async (\n fields: Record<string, string | Blob>\n): Promise<TfProfile> => {\n const { clientId, clientSecret } = getConfig()\n const requestFields = {\n ...fields,\n client_id: fields.client_id ?? clientId,\n client_secret: fields.client_secret ?? clientSecret,\n }\n if (!requestFields.client_id || !requestFields.client_secret) {\n throw new TtfError('register: clientId/clientSecret are not configured.', 0)\n }\n const res = await post<\n | TfEnvelope<TfProfile>\n | {\n data?: {\n attributes?: {\n access_token?: string\n refresh_token?: string\n user_profile?: Record<string, unknown>\n }\n }\n }\n >(ENDPOINTS.auth.registerRn, toFormData(requestFields), {\n headers: { 'Content-Type': 'multipart/form-data' },\n })\n const data = res.data\n const attributes =\n data && typeof data === 'object' && 'attributes' in data ? data.attributes : undefined\n if (attributes?.access_token) {\n setTokens({\n access: attributes.access_token,\n refresh: attributes.refresh_token,\n })\n try {\n return await getProfile()\n } catch {\n // Some staging responses expose a reduced profile while the full profile\n // endpoint catches up. Fall through to it instead of failing a completed\n // registration.\n }\n }\n\n const candidate = (attributes?.user_profile ?? data) as Record<string, unknown>\n const firstName = String(candidate?.firstName ?? candidate?.first_name ?? '')\n const lastName = String(candidate?.lastName ?? candidate?.last_name ?? '')\n const email = String(candidate?.email ?? '')\n return {\n id: String(candidate?.id ?? ''),\n firstName,\n lastName,\n email,\n phone: candidate?.phone ? String(candidate.phone) : undefined,\n streetAddress: candidate?.streetAddress\n ? String(candidate.streetAddress)\n : candidate?.street_address\n ? String(candidate.street_address)\n : undefined,\n zipCode: candidate?.zipCode\n ? String(candidate.zipCode)\n : candidate?.zip\n ? String(candidate.zip)\n : undefined,\n countryId: String(candidate?.countryId ?? candidate?.country_id ?? ''),\n company: null,\n stateId: candidate?.stateId\n ? String(candidate.stateId)\n : candidate?.state_id\n ? String(candidate.state_id)\n : undefined,\n city: candidate?.city ? String(candidate.city) : undefined,\n username: String(candidate?.username ?? email),\n screenName: null,\n bio: null,\n shortBio: null,\n region: null,\n image: null,\n recommendedEvents: [],\n rnRoles: [],\n hasDashboardAccess: false,\n ticketHolders: [],\n linkedCryptoWallets: [],\n }\n}\n\n/** Typed registration used by platform auth flows. */\nexport const registerAccount = (input: AuthRegistrationInput): Promise<TfProfile> =>\n register(buildRegistrationFields(input))\n\n/** Kick off the \"forgot password\" email for an address. */\nexport const restorePassword = async (email: string): Promise<void> => {\n await post(ENDPOINTS.auth.restorePassword, { email })\n}\n\n/** Complete a password reset with the token from the email. */\nexport const resetPassword = async (input: {\n token: string\n password: string\n passwordConfirmation?: string\n}): Promise<void> => {\n await post(ENDPOINTS.auth.resetPassword, {\n token: input.token,\n password: input.password,\n password_confirmation: input.passwordConfirmation ?? input.password,\n })\n}\n\n/** React Native \"forgot password\" variant (`v1/oauth/restore-password-rn`). */\nexport const restorePasswordRn = async (email: string): Promise<void> => {\n await post(ENDPOINTS.auth.restorePasswordRn, { email })\n}\n\n// --- Account identity verification (Netverify/Jumio, `v1/authenticate/*`) ----\n\n/** Mint (or read) the hosted identity-verification URL for the signed-in user. */\nexport const mintVerificationUrl = async (): Promise<unknown> =>\n get(ENDPOINTS.auth.verify)\n\n/** Read the signed-in user's current identity-verification status. */\nexport const getVerificationInfo = async (): Promise<unknown> =>\n get(ENDPOINTS.auth.verificationInfo)\n\n/** Mark identity verification as PENDING after the buyer starts the provider flow. */\nexport const updateVerificationStatus = async (): Promise<unknown> =>\n patch(ENDPOINTS.auth.verify, {\n data: { attributes: { verification: { verificationStatus: 'PENDING' } } },\n })\n\n/** Sign out: tell the backend, then drop local tokens regardless of the result. */\nexport const logout = async (): Promise<void> => {\n try {\n await del(ENDPOINTS.auth.session)\n } finally {\n clearSession()\n }\n}\n\n/**\n * Whether an email already has an account. Normalizes the legacy\n * `/ajax/contact-email` response (`exists: 0|1`) to a boolean; never throws —\n * returns `{ exists: false }` on failure so callers can treat it as advisory.\n */\nexport const checkEmailExists = async (\n email: string\n): Promise<{ exists: boolean; error?: string }> => {\n try {\n const res = await post<{ exists?: number; error?: number; message?: string }>(\n `${getOriginUrl()}/${ENDPOINTS.auth.contactEmail}`,\n toFormData({ email, is_checkout_flow: 'true' }),\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n return {\n exists: res.exists === 1,\n error: res.error === 1 ? res.message : undefined,\n }\n } catch {\n return { exists: false, error: 'Failed to check email' }\n }\n}\n","/**\n * Geo lookups for billing selects: the country list and a country's states.\n * The states endpoint answers with an id→name map; we normalize it to an array\n * so consumers get one consistent `{ id, name }` shape.\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfCountry, TfState } from '../types'\n\n/** All selectable countries (billing `countryId` values). */\nexport const getCountries = async (): Promise<TfCountry[]> => {\n const res = await get<{ data: TfCountry[] }>(ENDPOINTS.geo.countries)\n return res.data ?? []\n}\n\n/** States/provinces for a country, normalized from the backend's id→name map. */\nexport const getStates = async (countryId: string | number): Promise<TfState[]> => {\n const res = await get<{ data: Record<string, string> }>(ENDPOINTS.geo.states(countryId))\n return Object.entries(res.data ?? {}).map(([id, name]) => ({ id, name }))\n}\n","/**\n * Pre-purchase engagement: referral attribution, sold-out waiting lists, RSVP\n * capture, and phone validation. None of these existed in shared before — they\n * lived only in the platform packages' own api layers.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport type { WaitingListEntry } from '../dtos'\n\nexport type { WaitingListEntry }\n\n/**\n * Attribute the buyer's session to a referrer/promoter (the numeric customer id\n * from a share/tracking link). The server credits it when the order completes;\n * pass `null` to clear. The endpoint always answers success, so ids can't be\n * probed.\n */\nexport const attributeReferrer = async (\n eventId: string,\n referrer: string | number | null\n): Promise<void> => {\n await post(ENDPOINTS.events.referrer(eventId), { referrer: referrer ?? '' })\n}\n\n/** Join the waiting list for a sold-out event (or one sold-out ticket type). */\nexport const joinWaitingList = async (\n eventId: string,\n entry: WaitingListEntry\n): Promise<void> => {\n await post(ENDPOINTS.events.waitingList(eventId), {\n data: { attributes: entry },\n })\n}\n\n/** Submit RSVP details for an RSVP-style event. */\nexport const sendRsvp = async (\n eventId: string,\n data: Record<string, unknown>\n): Promise<unknown> => post(ENDPOINTS.events.rsvp(eventId), data)\n\n/** Validate a phone number (Twilio-backed) before letting the buyer proceed. */\nexport const validatePhone = async (\n phone: string\n): Promise<{ valid: boolean; [key: string]: unknown }> => {\n const res = await get<{ valid?: boolean; [key: string]: unknown }>(\n ENDPOINTS.account.validatePhone(phone)\n )\n return { valid: Boolean(res?.valid), ...res }\n}\n","/**\n * Account orders — the buyer's purchase history and a single order's detail.\n * Backed by `v1/account/orders` (paginated, filterable by event/brand) and\n * `v1/account/order/:id`. New to shared; previously platform-only.\n */\nimport { get, put } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { TfEnvelope, TfListEnvelope } from '../types'\n\n/** A row in the order history. Fields the platform is known to return are typed;\n * the index signature keeps forward-compatible extras accessible. */\nexport interface TfOrderSummary {\n id?: string | number\n hash?: string\n status?: string\n total?: string | number\n currency?: string\n eventName?: string\n createdAt?: string\n [key: string]: unknown\n}\n\n/** A single order's full detail (tickets, buyer, totals). */\nexport interface TfOrderDetails extends TfOrderSummary {\n tickets?: unknown[]\n}\n\nexport interface OrdersQuery {\n page?: number\n limit?: number\n /** Restrict to one event by slug. */\n eventSlug?: string\n /** Restrict to a brand (and its subbrands). */\n brandSlug?: string\n}\n\n/** List the signed-in user's orders, newest first (server-paginated). */\nexport const getOrders = async (\n query: OrdersQuery = {}\n): Promise<TfListEnvelope<TfOrderSummary>> => {\n const { page = 1, limit = 10, eventSlug = '', brandSlug } = query\n const params = new URLSearchParams({\n page: String(page),\n limit: String(limit),\n 'filter[event]': eventSlug,\n })\n if (brandSlug) {\n params.set('filter[brand]', brandSlug)\n params.set('filter[subbrands]', 'true')\n }\n return get<TfListEnvelope<TfOrderSummary>>(\n `${ENDPOINTS.account.orders}?${params.toString()}`\n )\n}\n\n/** The authenticated account endpoint accepts the numeric order id. Public\n * order hashes belong to the confirmation endpoint and must be resolved first. */\nexport const getOrder = async (orderId: string): Promise<TfEnvelope<TfOrderDetails>> => {\n if (!/^\\d+$/.test(String(orderId))) {\n throw new TypeError(\n 'Account order details require a numeric order id; resolve public order hashes first.'\n )\n }\n return get<TfEnvelope<TfOrderDetails>>(ENDPOINTS.account.order(orderId))\n}\n\n/** The signed-in user's tickets (wallet), server-paginated + filterable. */\nexport const getMyTickets = async (\n query: OrdersQuery & { from?: string } = {}\n): Promise<TfListEnvelope<Record<string, unknown>>> => {\n const { page = 1, limit = 10, eventSlug = '', brandSlug, from } = query\n const params = new URLSearchParams({\n page: String(page),\n limit: String(limit),\n 'filter[event]': eventSlug,\n })\n if (brandSlug) {\n params.set('filter[brand]', brandSlug)\n params.set('filter[subbrands]', 'true')\n }\n if (from) params.set('from', from)\n return get<TfListEnvelope<Record<string, unknown>>>(\n `${ENDPOINTS.account.tickets}?${params.toString()}`\n )\n}\n\n/** Update the order-level data-capture answers shown on the order detail page. */\nexport const updateOrderCustomFields = async (\n eventId: string,\n orderId: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(`v1/event/${eventId}/order-data-capture`, {\n data: {\n attributes: {\n order_id: orderId,\n data_capture: values,\n },\n },\n })\n\n/** Update data-capture answers for one issued ticket. */\nexport const updateTicketHolderCustomFields = async (\n eventId: string,\n ticketHash: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(`v1/event/${eventId}/ticket-data-capture`, {\n data: {\n attributes: {\n ticket_hash: ticketHash,\n ticket_data_capture: {\n [ticketHash]: values,\n },\n },\n },\n })\n","/**\n * Ticket resale — list a ticket for resale, process a pending resale, or\n * decline one. Backed by `v1/ticket/:id/{sell,process,decline}`. New to shared;\n * previously only in the web package's `resale.ts`.\n */\nimport { del, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Put a ticket up for resale. `payload` carries price/recipient per the event's\n * resale rules; forwarded verbatim. */\nexport const sellTicket = async (\n ticketId: string,\n payload: Record<string, unknown> = {}\n): Promise<unknown> => post(ENDPOINTS.resale.sell(ticketId), payload)\n\n/** Remove a ticket that is currently listed for resale. */\nexport const removeTicketFromResale = async (ticketId: string): Promise<unknown> =>\n del(ENDPOINTS.resale.sell(ticketId))\n\n/** Process (accept/complete) a pending resale for a ticket. */\nexport const processResale = async (\n ticketId: string,\n payload: Record<string, unknown> = {}\n): Promise<unknown> => post(ENDPOINTS.resale.process(ticketId), payload)\n\n/** Decline a pending resale for a ticket. */\nexport const declineResale = async (ticketId: string): Promise<unknown> =>\n post(ENDPOINTS.resale.decline(ticketId))\n","/**\n * Post-purchase confirmation — the \"your order is complete\" page data, keyed by\n * order hash. Backed by `v1/order/:hash/payment/complete`. New to shared.\n */\nimport { get } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Fetch the confirmation-page payload for a completed order. */\nexport const getConfirmation = async (\n orderHash: string\n): Promise<Record<string, unknown>> =>\n get<Record<string, unknown>>(ENDPOINTS.order.confirmation(orderHash))\n","/**\n * Pre-registration — the \"register your interest, then share to climb the list\"\n * flow. Confirm interest for an event, then read the post-confirm share page and\n * submit share actions (referral phases). Backed by `pre-registration/*`\n * endpoints. New to shared.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Decode the backend's lightweight pre-registration share-action token. */\nexport const decodeShareActionToken = (value: string, method?: string): string => {\n if (method === 'reverse_string') return value.split('').reverse().join('')\n if (method === 'symmetric_shuffle_string') {\n const split = Math.floor(value.length / 2)\n return value.substring(split) + value.substring(0, split)\n }\n if (method === 'shuffle_every_two_symbols_in_string') {\n let shuffled = ''\n for (let index = 0; index < value.length; index += 2) {\n shuffled += `${value[index + 1] ?? ''}${value[index] ?? ''}`\n }\n return shuffled\n }\n return value\n}\n\n/** Confirm pre-registration for an event. `attributes` carries the buyer's\n * answers; forwarded under the JSON:API `{ data: { attributes } }` envelope. */\nexport const confirmPreRegistration = async (\n eventId: string,\n attributes: Record<string, unknown>\n): Promise<unknown> =>\n post(ENDPOINTS.preRegistration.confirm(eventId), { data: { attributes } })\n\n/** Influencers/promoters available to share to for an event's pre-reg phase. */\nexport const getInfluencers = async (eventId: string): Promise<unknown> =>\n get(ENDPOINTS.preRegistration.influencers(eventId))\n\n/** The post-confirmation share page (options + the buyer's current standing). */\nexport const getConfirmationPage = async (hash: string): Promise<unknown> =>\n get(ENDPOINTS.preRegistration.confirmationPage(hash))\n\n/** Record a share action (a referral phase step) against a pre-reg hash. */\nexport const submitShareAction = async (\n hash: string,\n input: {\n eventActionId: number | string\n accessToken?: string\n shareActionToken?: string\n tokenShuffleMethod?: string\n phase?: string\n }\n): Promise<unknown> =>\n post(ENDPOINTS.preRegistration.submitAction(hash), {\n data: {\n attributes: {\n phase: input.phase ?? 'pre-registration',\n eventActionId: Number(input.eventActionId),\n accessToken:\n input.accessToken ??\n decodeShareActionToken(input.shareActionToken ?? '', input.tokenShuffleMethod),\n },\n },\n })\n","/**\n * Guest ticket delegation — the flow where someone is handed a ticket via an\n * access link and claims it without a full account. Check whether they already\n * have an account, read the claim page, and issue the ticket. Backed by\n * `v1/delegation-access/:hash/*`. New to shared.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** Whether the delegated recipient already has an account. */\nexport const checkCustomerExists = async (\n accessHash: string\n): Promise<Record<string, unknown>> =>\n get(ENDPOINTS.delegation.customerExists(accessHash))\n\n/** The claim page for a delegation access link (event + ticket context). */\nexport const getConsumerPageInfo = async (accessHash: string): Promise<unknown> =>\n get(ENDPOINTS.delegation.consumerPageInfo(accessHash))\n\n/** Issue (claim) the delegated ticket. `data` carries the recipient details;\n * forwarded under the JSON:API `{ data: { attributes } }` envelope. */\nexport const issueTicket = async (\n accessHash: string,\n data: Record<string, unknown>\n): Promise<unknown> =>\n post(ENDPOINTS.delegation.issueTicket(accessHash), {\n data: { attributes: data },\n })\n","/**\n * Seated events — the wire behind the seat picker. Fetch the venue map, poll\n * live seat statuses, and reserve a selection. The seats.io / tf-seat-map-view\n * widget itself is platform UI; these are just its API calls, so they belong in\n * shared. Backed by `v1/event/:id/{seat-map-data,seats/status,seats/reserve}`.\n * New to shared.\n */\nimport { del, get, patch, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\n\n/** The venue seat map for an event (optionally scoped via `params`). */\nexport const getSeatMapData = async (\n eventId: string,\n params?: Record<string, unknown>\n): Promise<unknown> => {\n const url = ENDPOINTS.seatmap.data(eventId)\n console.log('[SeatMap API] getSeatMapData called', { eventId, params, url })\n try {\n const resp = await get(url, { params })\n console.log('[SeatMap API] getSeatMapData response', JSON.stringify(resp, null, 2))\n return resp\n } catch (err) {\n console.error('[SeatMap API] getSeatMapData FAILED', err)\n throw err\n }\n}\n\n/** Live availability/status for the event's seats (poll during selection). */\nexport const getSeatStatuses = async (eventId: string): Promise<unknown> =>\n get(ENDPOINTS.seatmap.statuses(eventId))\n\n/** Reserve a seat selection, e.g. `{ tierId, seatId, ttl: 10 }` — forwarded\n * under the backend's `{ data: … }` envelope. */\nexport const reserveSeats = async (\n eventId: string,\n reservation: Record<string, unknown>\n): Promise<unknown> => post(ENDPOINTS.seatmap.reserve(eventId), { data: reservation })\n\n/** Release a held reservation (DELETE with a body). */\nexport const removeReservedSeats = async (\n eventId: string,\n tierId: string,\n seatIds: string[]\n): Promise<unknown> =>\n // axios DELETE body rides `config.data`; the web sends { tierId, seatIds } bare.\n del(ENDPOINTS.seatmap.deleteReserved(eventId), {\n data: { tierId, seatIds },\n })\n\n/** Extend a seat reservation's TTL for an in-flight order. */\nexport const refreshReservation = async (\n eventId: string,\n orderId: string\n): Promise<unknown> =>\n patch(ENDPOINTS.seatmap.refreshReservation(eventId), { order_id: orderId })\n","/**\n * Catalog — the read side of an event: tickets, seating/info, terms, time-slot\n * sessions, custom fields, add-ons, promo codes, and multi-currency. Ported\n * faithfully from the engine's api layer; this layer OWNS the wire contract\n * (JSON:API `{ data: { attributes } }` envelopes, cents-vs-units, map-vs-array)\n * so nothing above it sees those details.\n */\nimport { get, post, put } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport { isSeatedEvent as coreIsSeatedEvent } from '../logic'\nimport type {\n CurrencyState,\n CurrencySyncOptions,\n EventAddon,\n EventCondition,\n EventCustomField,\n EventCustomFieldGroup,\n TicketType,\n} from '../dtos'\n\nconst mapTicket = (t: any): TicketType => ({\n id: String(t.id),\n name: t.displayName ?? '',\n groupName: t.groupName ?? t.group_name ?? null,\n optionName: t.optionName ?? '',\n price: Number(t.price ?? 0),\n // `basePrice` is the with-fees amount; fall back to price when the wire omits it.\n priceWithFees: Number(t.basePrice ?? t.price ?? 0),\n priceSymbol: t.priceSymbol ?? '',\n currency: t.priceCurrency ?? '',\n feeIncluded: Boolean(t.feeIncluded),\n // `depositPercent` arrives as a string (\"50.00\") or null.\n depositPercent: t.depositPercent != null ? Number(t.depositPercent) : null,\n soldOut: Boolean(t.soldOut),\n salesStarted: Boolean(t.salesStarted),\n salesEnded: Boolean(t.salesEnded),\n minQuantity: Number(t.minQuantity ?? 1),\n maxQuantity: Number(t.maxQuantity ?? 10),\n multiplier: Number(t.multiplier ?? 1) || 1,\n isTable: Boolean(t.isTable),\n // Tables constrain the selectable quantity by guests, not the generic\n // min/max (which stay 1/10 on the wire). Undefined for non-tables.\n minGuests: t.minGuests != null ? Number(t.minGuests) : undefined,\n maxGuests: t.maxGuests != null ? Number(t.maxGuests) : undefined,\n allowDirectPurchase: Boolean(t.allowDirectPurchase),\n waitingListEnabled: Boolean(t.waitingListEnabled),\n waitingListMaxQuantity:\n t.waitingListMaxQuantity != null ? Number(t.waitingListMaxQuantity) : undefined,\n descriptionRich: t.descriptionRich ?? null,\n})\n\n/** Purchasable ticket types for an event. */\nexport const getEventTickets = async (eventId: string): Promise<TicketType[]> => {\n const body = await get<any>(ENDPOINTS.events.tickets(eventId))\n const ticketsObj = body?.data?.attributes?.tickets ?? {}\n return Object.values(ticketsObj).map(mapTicket)\n}\n\nexport interface EventSeatingInfo {\n /** The event uses reserved seating — the buyer picks on a seat map instead of\n * choosing quantities. Render seat-map ticket types read-only and route to\n * \"Select seats\". */\n isSeatedEvent: boolean\n /** The seat map is a TABLE map (its CTA reads \"Select on map\" vs \"Select\n * seats\"). Only meaningful when `isSeatedEvent`. */\n tableMapEnabled: boolean\n /** The event sells per date/time session — pick a date, then time-slot tickets.\n * (Attribute names inferred defensively; pass dates via a prop if your page\n * data already has them.) */\n isTimeSlotEvent: boolean\n /** Selectable session dates (ISO `yyyy-mm-dd`) for a time-slot event. */\n availableDates: string[]\n /** The event lets a buyer combine MORE THAN ONE ticket type in a single order.\n * When false (the default), selecting a new type replaces the previous one —\n * the ticket screen enforces one type at a time. Tables and regular tickets\n * are mutually exclusive regardless. */\n allowMultipleTicketTypePurchases: boolean\n slug: string | null\n name: string | null\n /** ISO country code used to seed billing/phone inputs like the storefront. */\n countryCode: string | null\n}\n\n/**\n * `GET v1/event/:id` — returns what the seated-event handoff needs:\n * `isSeatedEvent` (core's helper over the event attributes), plus slug/name for\n * the event-page link. `pk` is the optional preview key for unpublished events.\n */\nexport const getEventInfo = async (\n eventId: string,\n pk?: string\n): Promise<EventSeatingInfo> => {\n const body = await get<any>(ENDPOINTS.events.info(eventId), {\n params: pk ? { pk } : undefined,\n })\n const attributes = body?.data?.attributes ?? {}\n const a = attributes as Record<string, any>\n const slotSettings = a.timeslotSettings ?? a.timeslot_settings ?? {}\n const dates =\n slotSettings.availableDates ?? slotSettings.available_dates ?? a.available_dates ?? []\n const rawCountry = a.country\n const countryCode =\n (typeof rawCountry === 'string' ? rawCountry : rawCountry?.code) ??\n a.countryCode ??\n a.country_code ??\n null\n return {\n isSeatedEvent: coreIsSeatedEvent(attributes),\n tableMapEnabled: Boolean(a.tableMapEnabled ?? a.table_map_enabled),\n isTimeSlotEvent: Boolean(\n a.isTimeSlotEvent ?? a.is_time_slot_event ?? a.time_slot_event ?? a.is_timeslot\n ),\n availableDates: Array.isArray(dates) ? dates.map(String) : [],\n allowMultipleTicketTypePurchases: Boolean(\n a.allowMultipleTicketTypePurchases ?? a.allow_multiple_ticket_type_purchases\n ),\n slug: attributes.slug ?? null,\n name: attributes.name ?? null,\n countryCode: countryCode ? String(countryCode).toUpperCase() : null,\n }\n}\n\n/**\n * Event terms/conditions (client-side gate — nothing is submitted, the server\n * already knows them). LIVE contract: `attributes` is an ARRAY OF STRINGS, each\n * a MANDATORY acknowledgement; null when none. The object form\n * `{ conditions: [{id,name,content,is_required}] }` is tolerated defensively.\n */\nexport const getEventConditions = async (eventId: string): Promise<EventCondition[]> => {\n const body = await get<any>(ENDPOINTS.events.conditions(eventId))\n const attrs = body?.data?.attributes\n const items: any[] = Array.isArray(attrs)\n ? attrs\n : Array.isArray(attrs?.conditions)\n ? attrs.conditions\n : []\n return items\n .map((c, i): EventCondition => {\n if (typeof c === 'string') {\n return { id: String(i + 1), name: '', content: c, isRequired: true }\n }\n return {\n id: String(c?.id ?? i + 1),\n name: String(c?.name ?? ''),\n content: String(c?.content ?? ''),\n isRequired: c?.is_required === true,\n }\n })\n .filter((c) => c.content || c.name)\n}\n\n/**\n * Ticket types for one DATE of a time-slot (session/calendar) event. Each\n * returned `id` (matrix_record_id) is specific to the chosen date/session — how\n * the server knows the date; no date field exists in the add-to-cart body.\n * @param date \"YYYY-MM-DD\"\n * @param options.groupIds restrict to specific slot groups; omit for all.\n */\nexport const getEventTimeSlotTickets = async (\n eventId: string,\n date: string,\n options?: { groupIds?: number[] }\n): Promise<TicketType[]> => {\n const body = await get<any>(ENDPOINTS.events.timeSlotByDate(eventId), {\n params: {\n date,\n remove_past_slots: true,\n ...(options?.groupIds?.length ? { groupIds: options.groupIds } : {}),\n },\n })\n const grouped = body?.data?.attributes?.time_grouped_slot_ticket_types ?? {}\n const out: TicketType[] = []\n for (const [slotDate, hours] of Object.entries<any>(grouped ?? {})) {\n for (const hourKey of Object.keys(hours ?? {}).sort()) {\n const times = hours[hourKey] ?? {}\n for (const timeKey of Object.keys(times).sort()) {\n for (const s of Object.values<any>(times[timeKey] ?? {})) {\n if (!s?.matrix_record_id) continue\n const stock = Number(s.in_stock ?? s.real_stock ?? 0)\n out.push({\n id: String(s.matrix_record_id),\n name: s.display_name || s.option_value || 'Ticket',\n groupName: s.group_name ?? s.groupName ?? null,\n optionName: String(s.option_key ?? ''),\n price: Number(s.base_price ?? 0),\n priceWithFees: Number(s.price_with_fees ?? s.base_price ?? 0),\n priceSymbol: s.price_symbol ?? s.priceSymbol ?? '',\n currency: '',\n feeIncluded: false,\n depositPercent: s.deposit_percent != null ? Number(s.deposit_percent) : null,\n soldOut: Boolean(s.sold_out) || stock <= 0,\n salesStarted: s.sales_started != null ? Boolean(s.sales_started) : true,\n salesEnded: Boolean(s.sales_ended),\n minQuantity: Number(s.min_quantity ?? 1) || 1,\n maxQuantity: Number(s.max_quantity ?? 10) || 10,\n multiplier: Number(s.multiplier ?? 1) || 1,\n isTable: Boolean(s.is_table),\n allowDirectPurchase: true,\n descriptionRich: s.description ?? null,\n timeSlot: { date: slotDate, time: timeKey },\n })\n }\n }\n }\n }\n return out\n}\n\n/** checkbox → '1'/null; select_multi → string[]; else → string. Matches the\n * server's `!trim(value)` required check. */\nconst normalizeDefaultValue = (type: string, raw: unknown): string | string[] | null => {\n if (type === 'checkbox') {\n if (raw === true || raw === 1 || raw === '1') return '1'\n return null\n }\n if (raw == null || raw === '') return null\n if (type === 'select_multi') {\n if (Array.isArray(raw)) return raw.map(String)\n return [String(raw)]\n }\n if (Array.isArray(raw)) return String(raw[0] ?? '')\n return String(raw)\n}\n\n/** The event's custom-field groups (order / ticket / add-on scopes). [] when\n * the event has none. */\nexport const getEventCustomFields = async (\n eventId: string\n): Promise<EventCustomFieldGroup[]> => {\n const body = await get<any>(ENDPOINTS.events.customFields(eventId))\n const items: any[] = body?.data?.attributes ?? []\n if (!Array.isArray(items)) return []\n const groups: any[] = items.flatMap((item) => {\n if (!item || typeof item !== 'object') return []\n if (item.type && Array.isArray(item.fields)) return [item]\n return Object.values<any>(item)\n .map((v) => (v && typeof v === 'object' ? v.group : undefined))\n .filter((g) => g && typeof g === 'object')\n })\n return groups\n .filter((g) => g?.type === 'order' || g?.type === 'ticket' || g?.type === 'add-on')\n .map(\n (g): EventCustomFieldGroup => ({\n id: String(g.id ?? ''),\n label: g.label ?? null,\n scope: g.type,\n fields: (Array.isArray(g.fields) ? g.fields : []).map(\n (f: any): EventCustomField => ({\n id: String(f.id ?? ''),\n name: String(f.name ?? f.id ?? ''),\n label: String(f.label || f.name || ''),\n type: f.type,\n required: f.required === true,\n description: f.description ?? null,\n defaultValue: normalizeDefaultValue(f.type, f.defaultValue),\n options: (Array.isArray(f.options) ? f.options : []).map((o: any) => ({\n id: String(o.id ?? o.value ?? ''),\n name: String(o.name ?? o.value ?? ''),\n value: String(o.value ?? o.name ?? ''),\n })),\n ticketTypeIds: Array.isArray(f.settings?.ticketTypes)\n ? f.settings.ticketTypes.map(String)\n : null,\n })\n ),\n })\n )\n}\n\n/** Labels of REQUIRED order/ticket custom fields. Fails OPEN ([]) on error. */\nexport const getRequiredCustomFieldLabels = async (\n eventId: string\n): Promise<string[]> => {\n try {\n const groups = await getEventCustomFields(eventId)\n return groups\n .filter((g) => g.scope === 'order' || g.scope === 'ticket')\n .flatMap((g) => g.fields)\n .filter((f) => f.required)\n .map((f) => f.label || f.name)\n } catch {\n return []\n }\n}\n\n/** Event add-ons (active only), prices converted from wire cents to units. */\nexport const getEventAddons = async (eventId: string): Promise<EventAddon[]> => {\n const body = await get<any>(ENDPOINTS.events.addOns(eventId))\n const items: any[] = body?.data?.attributes?.add_ons ?? []\n return items\n .map((item) => {\n const a = item.attributes ?? {}\n return {\n id: String(a.id ?? item.id),\n name: a.name ?? '',\n description: a.description ?? null,\n price: Number(a.price ?? 0) / 100,\n currency: a.currency ?? '',\n feeIncluded: Boolean(a.feeIncluded),\n imageUrl: a.imageUrl ?? a.image ?? null,\n // NEVER coerce null to 0. The wire uses null for \"untracked\" (an\n // unlimited add-on) and an explicit 0 for \"sold out\"; every consumer\n // below treats `stock === 0` as the sold-out sentinel. Collapsing the\n // two made unlimited add-ons look sold out, which hid the whole\n // section (`addons.every(a => a.stock === 0)`) and silently exempted\n // required add-ons from the pre-flight gate.\n stock: a.stock == null ? null : Number(a.stock),\n maxQuantity: a.maxQuantity == null ? null : Number(a.maxQuantity),\n // The quantity-cap inputs. Dropping these let the UI offer quantities\n // the server hard-rejects (add_on_max_quantity) — see addOnMaxQuantity.\n flagLimitToTicketQuantity: Boolean(a.flagLimitToTicketQuantity),\n limitPerTicket: a.limitPerTicket == null ? null : Number(a.limitPerTicket),\n isCheckbox: Boolean(a.isCheckbox),\n level: a.level ?? null,\n groupName: a.groupName ?? null,\n required: Boolean(a.required),\n prerequisiteTicketTypeIds: Array.isArray(a.prerequisiteTicketTypeIds)\n ? a.prerequisiteTicketTypeIds.map(String)\n : null,\n active: a.active !== false,\n }\n })\n .filter((a) => a.active)\n .map(({ active: _active, ...addon }) => addon)\n}\n\n/**\n * The web checkout's add-on visibility rule: an add-on applies iff it has no\n * prerequisite ticket types, or they intersect the cart's DECRYPTED ids. With\n * no ids yet (cart not primed), returns the list unchanged. Pure — no request.\n */\nexport const filterAddonsForTickets = (\n addons: EventAddon[],\n ticketTypeIds: string[]\n): EventAddon[] => {\n if (!ticketTypeIds.length) return addons\n const selected = new Set(ticketTypeIds.map(String))\n return addons.filter((a) => {\n const prereq = a.prerequisiteTicketTypeIds\n if (!prereq || prereq.length === 0) return true\n return prereq.some((id) => selected.has(String(id)))\n })\n}\n\nexport interface TicketCatalogPromoMeta {\n isPromotionsEnabled: boolean\n isAccessCodeEnabled: boolean\n promoCodeValid?: boolean\n promoCodeMessage?: string\n}\n\n/** Tickets plus the catalog-level promo/access metadata the same response\n * carries — the read-back half of the promo-code loop. */\nexport const getEventTicketsWithMeta = async (\n eventId: string\n): Promise<{\n tickets: TicketType[]\n promo: TicketCatalogPromoMeta\n showWaitingList: boolean\n}> => {\n const body = await get<any>(ENDPOINTS.events.tickets(eventId))\n const attrs = body?.data?.attributes ?? {}\n const ticketsObj = attrs.tickets ?? {}\n return {\n tickets: Object.values(ticketsObj).map(mapTicket),\n promo: {\n isPromotionsEnabled: attrs.isPromotionsEnabled === true,\n isAccessCodeEnabled: attrs.is_access_code === true,\n promoCodeValid:\n typeof attrs.ValidPromoCode === 'boolean' ? attrs.ValidPromoCode : undefined,\n promoCodeMessage: attrs.PromoCodeValidationMessage ?? undefined,\n },\n showWaitingList: attrs.showWaitingList === true,\n }\n}\n\n/**\n * Applies a promo/access code to the session (empty string removes it). The\n * endpoint ALWAYS answers success (anti-brute-force) — read the outcome from a\n * fresh `getEventTicketsWithMeta` (`promo.promoCodeValid`).\n */\nexport const submitPromoCode = async (eventId: string, promo: string): Promise<void> => {\n await post(ENDPOINTS.events.promo(eventId), { promo: promo.trim() })\n}\n\n/**\n * Session currency preference (multi-currency events). A bare call geo-seeds and\n * reports the resolved state; passing a code switches it (every later read\n * reprices — restart ticket selection after a switch). `{ seed: true }` replays\n * a carried-over currency without overwriting the buyer's own choice.\n */\nexport const setEventCurrency = async (\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencyState> => {\n const body = await post<any>(ENDPOINTS.events.currency(eventId), {\n data: {\n attributes: code\n ? options?.seed\n ? { currency: code, seed: true }\n : { currency: code }\n : {},\n },\n })\n return body?.data?.attributes as CurrencyState\n}\n\n/** Unlock a password-protected event. Throws `TtfError` on the wrong password. */\nexport const authenticateEvent = async (\n eventId: string,\n password: string\n): Promise<unknown> =>\n post(ENDPOINTS.events.authenticate(eventId), {\n attributes: { data: { password } },\n })\n\n/** Fire the event's tracking pixel (page view / order attribution). */\nexport const trackEvent = async (\n eventId: string,\n options: { pageUrl?: string; page?: string; orderHash?: string }\n): Promise<unknown> =>\n get(ENDPOINTS.events.track(eventId), {\n params: {\n page_url: options.pageUrl,\n page: options.page,\n order_hash: options.orderHash,\n },\n })\n\n/** Write ORDER-level custom-field values after the order exists. */\nexport const updateOrderDataCapture = async (\n eventId: string,\n orderId: string,\n dataCapture: Record<string, unknown>\n): Promise<unknown> =>\n put(ENDPOINTS.events.orderDataCapture(eventId), {\n data: { attributes: { order_id: orderId, data_capture: dataCapture } },\n })\n\n/** Write TICKET-level (per-holder) custom-field values for one ticket hash. */\nexport const updateTicketDataCapture = async (\n eventId: string,\n ticketHash: string,\n values: Record<string, unknown>\n): Promise<unknown> =>\n put(ENDPOINTS.events.ticketDataCapture(eventId), {\n data: {\n attributes: {\n ticket_hash: ticketHash,\n ticket_data_capture: { [ticketHash]: values },\n },\n },\n })\n","/**\n * Cart + checkout session — build the server cart, read it back (pins the\n * event's payment method into the session), price it with add-ons, and read the\n * pre-order payment config. Ported faithfully from the engine's api layer.\n */\nimport { ENV_HOSTS, getOriginUrl } from '../client/config'\nimport { get, post } from '../client/http'\nimport {\n ENDPOINTS,\n listRedirectMethods,\n XENDIT_NON_EWALLET_PROCESSORS,\n} from '../constants'\nimport {\n evaluateFieldGates,\n identifyPreOrderGateway,\n interpretContactEmail,\n paypalTabConfig,\n priceBreakdownAddOnsQuery,\n resolvePriceBreakdown,\n walletsOption,\n xenditPreOrderConfig,\n} from '../logic'\nimport type {\n AddonSelection,\n BuyerFieldVisibility,\n CheckoutBreakdown,\n CheckoutPaymentPlan,\n CheckoutPaymentPlanPreview,\n CheckoutWalletAvailability,\n ExistingAccount,\n PreOrderGateway,\n PriceBreakdown,\n SeatLine,\n StripeConfig,\n StripeWallets,\n TicketSelection,\n XenditProcessor,\n} from '../dtos'\n\n/**\n * Adds ALL selected ticket types to the server cart in ONE call. The endpoint\n * REPLACES the entire cart every call, so per-type calls would keep only the\n * last. The `{ data: { attributes } }` envelope is mandatory (the backend\n * copies data.attributes into $_POST and 422s without it).\n */\nexport const addTicketsToCart = async (\n eventId: string,\n selections: TicketSelection[]\n): Promise<{ holderNamesRequired: boolean }> => {\n const first = selections[0]\n if (!first) throw new Error('addTicketsToCart: no tickets selected.')\n const body = await post<any>(ENDPOINTS.cart.addToCart(eventId), {\n data: {\n attributes: {\n alternative_view_id: null,\n product_cart_quantity: first.quantity,\n product_options: { [first.optionName]: first.id },\n product_id: Number(eventId),\n ticket_types: Object.fromEntries(\n selections.map((t) => [\n t.id,\n {\n product_options: { [t.optionName]: t.id, ticket_price: t.price },\n quantity: t.quantity,\n },\n ])\n ),\n },\n },\n })\n return { holderNamesRequired: Boolean(body?.data?.attributes?.names_required) }\n}\n\n/**\n * Adds RESERVED SEATS to the server cart — the seat-map analogue of\n * `addTicketsToCart`, a faithful port of the legacy `getAddToCartRequestData`\n * (`seatMapContainer/utils.ts`). Kept separate because a seated order's body\n * differs from a plain-ticket one in two ways `addTicketsToCart` can't express:\n *\n * - `product_cart_quantity` is the TOTAL number of reserved seats (not the\n * first line's quantity), and\n * - when ANY line carries a guest count (tables / group tickets) the\n * `ticket_types` map is keyed by INDEX with `quantity = guests` (one line per\n * seat); otherwise it's keyed by ticket-type id with quantities aggregated.\n *\n * Seat ids never appear in the body — the server binds cart lines to seats\n * through the live reservation (held by `ttf.seatmap.reserve`).\n */\nexport const addSeatsToCart = async (\n eventId: string,\n lines: SeatLine[]\n): Promise<{ holderNamesRequired: boolean }> => {\n if (!lines.length) throw new Error('addSeatsToCart: no seats selected.')\n const hasGuests = lines.some((l) => l.guests != null)\n const product_options: Record<string, string> = {}\n const ticket_types: Record<string, unknown> = {}\n lines.forEach((l, index) => {\n // Last-write-wins over the shared option key — matches legacy utils.ts.\n product_options[l.optionName] = l.ticketTypeId\n const key = hasGuests ? index : l.ticketTypeId\n const prevQty = hasGuests\n ? 0\n : ((ticket_types[l.ticketTypeId] as { quantity?: number } | undefined)?.quantity ??\n 0)\n const quantity = hasGuests ? (l.guests as number) : prevQty + 1\n ticket_types[key] = {\n quantity,\n product_options: { [l.optionName]: l.ticketTypeId, ticket_price: l.price },\n }\n })\n const body = await post<any>(ENDPOINTS.cart.addToCart(eventId), {\n data: {\n attributes: {\n alternative_view_id: null,\n product_cart_quantity: lines.length,\n product_options,\n product_id: Number(eventId),\n ticket_types,\n },\n },\n })\n return { holderNamesRequired: Boolean(body?.data?.attributes?.names_required) }\n}\n\n/**\n * Reads the cart back. MANDATORY between add-to-cart and updateCheckout: this\n * call writes the event's payment method into the PHP session, which\n * POST v1/checkout reads. Returns reservation seconds remaining plus the raw\n * pre-order gateway string (preserved verbatim so an unknown/future gateway\n * stays fail-closed at the engine's Stripe-only guard).\n */\nexport const getCart = async (): Promise<{\n expiresInSeconds: number\n preOrderGateway: string | null\n}> => {\n const body = await get<any>(ENDPOINTS.cart.get, { params: { payment_config: 1 } })\n const attrs = body?.data?.attributes\n const raw = Number(attrs?.expiresAt)\n const gateway = attrs?.payment?.gateway\n return {\n expiresInSeconds: Number.isFinite(raw) && raw > 0 ? raw : 420,\n preOrderGateway: typeof gateway === 'string' && gateway ? gateway : null,\n }\n}\n\n/**\n * Checkout gates for the CURRENT cart session (`GET v1/checkout-configs`).\n * Session-scoped: call only after the cart exists. The reliable source for the\n * collect_names gate (staging's add-to-cart returns empty attributes).\n */\nexport const getCheckoutConfigs = async (): Promise<{\n holderNamesRequired: boolean\n fieldGates: BuyerFieldVisibility\n}> => {\n const body = await get<any>(ENDPOINTS.cart.checkoutConfigs)\n const attrs = body?.data?.attributes ?? {}\n return {\n holderNamesRequired: Boolean(attrs.names_required),\n fieldGates: evaluateFieldGates(attrs),\n }\n}\n\nexport interface CheckoutPricing {\n /** DECRYPTED ticket type ids (the tickets endpoint only has encrypted ones). */\n ticketTypeIds: string[]\n breakdown?: CheckoutBreakdown\n stripe?: StripeConfig\n paymentPlan?: CheckoutPaymentPlan\n redirectPaymentMethods?: string[]\n walletAvailability?: CheckoutWalletAvailability\n /** Server deferred-mode Stripe Elements config (mode/amount/currency) — mounts\n * the wallet-capable Payment Element exactly as the old checkout did. */\n stripeElementsConfig?: Record<string, unknown>\n}\n\n/** Parses `payment_plan_configuration` into the camelCase installment preview\n * (display-only). Undefined when absent or without an installment shape. */\nconst parsePlanPreview = (\n config: Record<string, any> | null | undefined\n): CheckoutPaymentPlanPreview | undefined => {\n if (!config || typeof config !== 'object') return undefined\n const num = (v: unknown): number | undefined =>\n v == null || v === '' || Number.isNaN(Number(v)) ? undefined : Number(v)\n const bool = (v: unknown): boolean | undefined =>\n typeof v === 'boolean' ? v : undefined\n const preview: CheckoutPaymentPlanPreview = {\n interval: num(config.interval),\n totalInstallments: num(config.total_installments),\n pricePerInstallment: num(config.price_per_installment),\n total: num(config.total),\n downPaymentEnabled:\n typeof config.down_payment_enabled === 'boolean'\n ? config.down_payment_enabled\n : undefined,\n downPaymentAmount:\n config.down_payment_amount == null ? null : num(config.down_payment_amount),\n currency: typeof config.currency === 'string' ? config.currency : undefined,\n currencySymbol:\n typeof config.currency_symbol === 'string' ? config.currency_symbol : undefined,\n customMessage: config.custom_message == null ? null : String(config.custom_message),\n terminology: typeof config.terminology === 'string' ? config.terminology : undefined,\n manufacturerName:\n typeof config.manufacturer_name === 'string' ? config.manufacturer_name : undefined,\n\n // The disclosure fields. The backend has always sent these; dropping them\n // here is what made our plan terms a three-line summary while the hosted\n // checkout states the admin fee and what the buyer forfeits on default.\n isAutoEqual: bool(config.is_auto_equal),\n hasAdminFee: bool(config.has_admin_fee),\n adminFee: config.admin_fee == null ? null : (num(config.admin_fee) ?? null),\n nonRefundableType:\n config.non_refundable_type === 'fixed' || config.non_refundable_type === 'percent'\n ? config.non_refundable_type\n : null,\n nonRefundableAmount:\n config.non_refundable_amount == null\n ? null\n : (num(config.non_refundable_amount) ?? null),\n totalNonRefundableAmount:\n config.total_non_refundable_amount == null\n ? null\n : (num(config.total_non_refundable_amount) ?? null),\n hideNonRefundableAdminFeeText: bool(config.hide_non_refundable_admin_fee_text),\n isEventAnchored: bool(config.is_event_anchored),\n finalChargeDate:\n config.final_charge_date == null ? null : String(config.final_charge_date),\n\n downPaymentMode:\n config.down_payment_mode == null ? null : String(config.down_payment_mode),\n downPaymentScope:\n config.down_payment_scope == null ? null : String(config.down_payment_scope),\n downPaymentPercent:\n config.down_payment_percent == null\n ? null\n : (num(config.down_payment_percent) ?? null),\n downPaymentPerTicketAmount:\n config.down_payment_per_ticket_amount == null\n ? null\n : (num(config.down_payment_per_ticket_amount) ?? null),\n downPaymentTicketCount:\n config.down_payment_ticket_count == null\n ? null\n : (num(config.down_payment_ticket_count) ?? null),\n }\n return preview.totalInstallments != null || preview.pricePerInstallment != null\n ? preview\n : undefined\n}\n\n/**\n * Prices the cart (+ chosen add-ons); returns the decrypted ticket type ids and\n * the Stripe config. Re-run whenever the add-on selection changes.\n *\n * paymentOption MUST be 'single_charge' — any other value makes the backend\n * reprice with a method-specific fee structure and silently drop booking fees\n * (undercharge vs. the price shown on the event page).\n */\nexport const updateCheckout = async (\n eventId: string,\n addOns: AddonSelection,\n options: { isFromResale?: boolean } = {}\n): Promise<CheckoutPricing> => {\n const body = await post<any>(ENDPOINTS.cart.checkout, {\n data: {\n attributes: {\n event_id: eventId,\n add_ons: addOns,\n is_from_resale: options.isFromResale ?? false,\n payment_information: {\n paymentSolution: 'stripe',\n paymentOption: 'single_charge',\n },\n },\n },\n })\n const attrs = body?.data?.attributes\n const cb = attrs?.cart_price_breakdown\n const api = attrs?.additional_payment_information\n const basic = api?.basic_config\n const planConfig = api?.payment_plan_configuration\n const planSavedLast4 = planConfig?.saved_card?.last_4_digits\n const redirectPaymentMethods = listRedirectMethods(\n api?.elements_config?.paymentMethodTypes\n )\n const wallets = walletsOption(api?.stripe_wallets as StripeWallets | undefined)\n\n return {\n ticketTypeIds: (cb?.tickets_price_breakdown ?? []).map((i: any) =>\n String(i.ticket_type_id)\n ),\n breakdown: cb\n ? {\n total: Number(cb.total ?? 0),\n totalAddOns: Number(cb.total_add_ons ?? 0),\n currencyCode: cb.currency?.currency ?? '',\n currencySymbol: cb.currency?.symbol ?? '',\n tickets: (cb.tickets_price_breakdown ?? []).map((t: any) => ({\n name: t.ticket_type_name,\n ticketTypeId: t.ticket_type_id != null ? String(t.ticket_type_id) : '',\n quantity: Number(t.quantity ?? 0),\n unit: String(t.price_per_ticket ?? ''),\n total: Number(t.total_price ?? 0),\n })),\n }\n : undefined,\n stripe: basic?.apiKey\n ? { publishableKey: basic.apiKey, accountId: basic.accountId || null }\n : undefined,\n paymentPlan:\n api?.payment_plan_available === true\n ? {\n available: true,\n savedCardLast4:\n typeof planSavedLast4 === 'string' ? planSavedLast4 : undefined,\n configuration: parsePlanPreview(planConfig),\n }\n : undefined,\n redirectPaymentMethods,\n walletAvailability: {\n applePay: wallets.applePay === 'auto',\n googlePay: wallets.googlePay === 'auto',\n },\n // The whole deferred block (mode/amount/currency/paymentMethodTypes). The\n // Payment Element mounts against this — server-computed amounts sidestep\n // zero-decimal-currency math. Undefined when the event isn't Stripe-deferred.\n stripeElementsConfig:\n api?.elements_config && typeof api.elements_config === 'object'\n ? (api.elements_config as Record<string, unknown>)\n : undefined,\n }\n}\n\n/**\n * Server-priced order summary (display-ready, server-formatted strings — render\n * verbatim, never recompute). Null when the backend doesn't serve the block.\n */\nexport const getPriceBreakdown = async (\n addOns?: AddonSelection\n): Promise<PriceBreakdown | null> => {\n const body = await get<any>(\n ENDPOINTS.cart.withPriceBreakdown(priceBreakdownAddOnsQuery(addOns))\n )\n return resolvePriceBreakdown(body?.data?.attributes)\n}\n\n/** Raw pre-order payment-config attributes (GET v1/cart?payment_config=1) — feed\n * to core's paypalTabConfig / xenditPreOrderConfig / walletsOption. */\nexport const getPaymentConfigAttributes = async (): Promise<Record<string, unknown>> => {\n const body = await get<any>(ENDPOINTS.cart.withPaymentConfig)\n return (body?.data?.attributes ?? {}) as Record<string, unknown>\n}\n\nexport interface PreOrderPaymentMethods {\n gateway: PreOrderGateway | null\n xenditEWallets: XenditProcessor[]\n xenditCard: boolean\n paypal: boolean\n}\n\n/** Resolves a (possibly relative) processor icon path against the host origin. */\nconst absolutizeIcon = (origin: string, icon?: string): string | undefined => {\n if (!icon) return undefined\n if (/^(https?:)?\\/\\//i.test(icon) || icon.startsWith('data:')) return icon\n if (!origin) return icon\n return `${origin}/${icon.replace(/^\\//, '')}`\n}\n\n/**\n * What this event's checkout can pay with BEFORE the order exists — read from\n * the pre-order payment config exactly as the hosted selector does.\n */\nexport const getPreOrderPaymentMethods = async (): Promise<PreOrderPaymentMethods> => {\n const attrs = await getPaymentConfigAttributes()\n const xendit = xenditPreOrderConfig(attrs)\n // The backend returns each processor icon as a RELATIVE path (e.g.\n // `/resources/images/payment/xendit/dana.png`). These are TicketFairy-global\n // brand marks served PUBLICLY from the production site — that's how the old\n // checkout loaded them (its relative paths resolved against the public host).\n // Resolve them the same way, against the public origin, so an <img> loads\n // them token-free even when the API is pointed at the access-gated staging\n // host (test.ticketfairy.com/resources 302s to a CF login, and an <img>\n // can't carry the CF-Access token). Absolute icon URLs are left untouched.\n const iconOrigin = ENV_HOSTS.PROD\n return {\n gateway: identifyPreOrderGateway(attrs),\n xenditEWallets: xendit\n ? xendit.processors\n .filter((row) => !XENDIT_NON_EWALLET_PROCESSORS.has(row.key))\n .map((row) => ({ ...row, icon: absolutizeIcon(iconOrigin, row.icon) }))\n : [],\n xenditCard: Boolean(xendit),\n paypal: Boolean(paypalTabConfig(attrs)),\n }\n}\n\n/**\n * Existing-account detection (the hosted `init_email_check`): reports whether a\n * live account owns the email so returning buyers get a sign-in prompt. Never a\n * gate — debounce it, keep typing unblocked. Origin-rooted and form-encoded.\n */\nexport const checkBuyerEmail = async (email: string): Promise<ExistingAccount> => {\n const res = await post<any>(\n `${getOriginUrl()}/${ENDPOINTS.auth.contactEmail}`,\n `email=${encodeURIComponent(email)}&is_checkout_flow=1`,\n { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }\n )\n return interpretContactEmail(res)\n}\n","/**\n * Order — create the order from the buyer/holders/add-ons, read the review\n * (gateway identity + Stripe/plan secrets), finalize (free registration or\n * success), and read ID-verification status. Ported faithfully from the\n * engine's api layer; the on-checkout body is composed by core's\n * `buildOnCheckoutBody` (the contract-pinned builder checkout-v2 also uses).\n */\nimport { post, get } from '../client/http'\nimport { TtfError } from '../client/errors'\nimport { ENDPOINTS } from '../constants'\nimport {\n buildOnCheckoutBody,\n detectGateway,\n paymentIntentIdFromClientSecret,\n savedPlanCard,\n} from '../logic'\nimport type {\n AddonSelection,\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n CustomFieldValues,\n IdVerificationStatus,\n SavedPlanCard,\n} from '../dtos'\nimport type { TfProfile } from '../types'\n\nexport interface CreatedOrder {\n hash: string\n total: string\n payNow: string\n status: string\n /** Duplicate-charge guard: true when the server answered with an\n * ALREADY-COMPLETED paid order (payment landed out-of-band). Go straight to\n * confirmation — never charge again. */\n alreadyPaid: boolean\n}\n\nexport const createOrder = async (input: {\n billing: CheckoutBilling\n holders: CheckoutHolder[]\n addOns: AddonSelection\n consent: CheckoutConsent\n /** Add-on custom-field values keyed by add-on id → add_on_data_capture. */\n addOnDataCapture?: Record<string, CustomFieldValues>\n}): Promise<CreatedOrder> => {\n const { billing, holders, addOns, consent, addOnDataCapture } = input\n\n const attributes = buildOnCheckoutBody(\n {\n buyerFields: {\n nationality: billing.nationality,\n gender: billing.gender,\n instagramHandle: billing.instagramHandle,\n },\n dataCapture: billing.dataCapture,\n ticketHolders: holders.map((h) => ({\n firstName: h.firstName,\n lastName: h.lastName,\n email: h.email,\n phone: h.phone ?? '',\n ticketTypeId: h.ticketTypeId,\n ticketDataCapture: h.ticketDataCapture,\n })),\n addOns,\n ...(addOnDataCapture\n ? {\n addOnDataCapture: Object.fromEntries(\n Object.entries(addOnDataCapture).filter(\n ([id, values]) =>\n Number(addOns[id]) > 0 && values && Object.keys(values).length > 0\n )\n ),\n }\n : {}),\n },\n {\n email: billing.email,\n confirm_email: billing.email,\n first_name: billing.firstName,\n last_name: billing.lastName,\n password: '',\n phone: billing.phone ?? '',\n ttf_opt_in: consent.ttfOptIn,\n brand_opt_in: consent.brandOptIn,\n ...(billing.streetAddress ? { street_address: billing.streetAddress } : {}),\n ...(billing.city ? { city: billing.city } : {}),\n ...(billing.zip ? { zip: billing.zip } : {}),\n ...(billing.countryId ? { country: Number(billing.countryId) } : {}),\n ...(billing.stateId ? { state: Number(billing.stateId) } : {}),\n ...(billing.dobDay && billing.dobMonth && billing.dobYear\n ? {\n dob_day: billing.dobDay,\n dob_month: billing.dobMonth,\n dob_year: billing.dobYear,\n }\n : {}),\n }\n )\n\n const body = await post<any>(ENDPOINTS.order.create, { data: { attributes } })\n const a = body?.data?.attributes\n if (!a?.hash) throw new TtfError('Order was not created (no hash in response).', 0)\n return {\n hash: String(a.hash),\n total: String(a.total ?? ''),\n payNow: String(a.pay_now ?? ''),\n status: String(a.status ?? ''),\n alreadyPaid: String(a.status ?? '') === 'paid',\n }\n}\n\nexport interface OrderReview {\n total: string\n clientSecret: string | null\n publishableKey: string | null\n connectedAccount: string | null\n expiresInSeconds?: number\n paymentAlreadyProcessed: boolean\n gateway: ReturnType<typeof detectGateway>\n orderId?: string\n currency?: string\n stripeIntentId?: string\n payNow?: string\n razorpayKeyId?: string\n xenditPublishableKey?: string\n xenditOnBehalfOf?: string | null\n paymentPlanSetupSecret?: string\n paymentPlanSavedCard: SavedPlanCard | null\n}\n\nexport const getOrderReview = async (orderHash: string): Promise<OrderReview> => {\n const body = await get<any>(ENDPOINTS.order.review(orderHash))\n const a = body?.data?.attributes\n const method = a?.payment_method ?? {}\n const rawExpiry = Number(a?.expires_at)\n return {\n total: String(a?.order_details?.total ?? ''),\n paymentAlreadyProcessed: Boolean(method.payment_already_processed),\n clientSecret: method.stripe_client_secret ?? null,\n publishableKey: method.stripe_publishable_key ?? null,\n connectedAccount: method.stripe_connected_account || null,\n expiresInSeconds: Number.isFinite(rawExpiry) && rawExpiry > 0 ? rawExpiry : undefined,\n gateway: detectGateway(method),\n orderId: a?.order_details?.id != null ? String(a.order_details.id) : undefined,\n currency: a?.order_details?.currency ?? undefined,\n stripeIntentId:\n (typeof method.stripe_intent_id === 'string' && method.stripe_intent_id) ||\n paymentIntentIdFromClientSecret(method.stripe_client_secret) ||\n undefined,\n payNow:\n a?.order_details?.pay_now != null ? String(a.order_details.pay_now) : undefined,\n razorpayKeyId: method.razorpay_key_id || method.key_id || method.api_key || undefined,\n xenditPublishableKey:\n method.xendit_publishable_key ||\n method.publishable_key ||\n method.api_key ||\n undefined,\n xenditOnBehalfOf: (method.xendit_on_behalf_of as string | undefined) ?? null,\n paymentPlanSetupSecret:\n (typeof method.stripe_payment_plan_configuration?.stripe_setup_intent_secret ===\n 'string' &&\n method.stripe_payment_plan_configuration.stripe_setup_intent_secret) ||\n undefined,\n paymentPlanSavedCard: savedPlanCard(method as Record<string, unknown>),\n }\n}\n\n/**\n * Maps a signed-in user's profile into a `CheckoutBilling` to prefill the\n * billing form. Merge over your own edits:\n * `setBilling({ ...mapProfileToBilling(profile), ...edits })`.\n */\nexport const mapProfileToBilling = (profile: TfProfile): CheckoutBilling => {\n const str = (v: string | number | null | undefined): string | undefined =>\n v == null || v === '' ? undefined : String(v)\n // 0 / '0' / '-1' are \"no selection\" sentinels for country/state ids.\n const idStr = (v: string | number | null | undefined): string | undefined => {\n const s = str(v)\n return s === undefined || s === '0' || s === '-1' ? undefined : s\n }\n // Split the ISO date by hand rather than via `new Date(...)`: that parses\n // `1990-05-01` as UTC midnight, so a buyer west of Greenwich reads their\n // birthday back a day early. `0000-00-00` is a legacy empty-date sentinel,\n // which the year test rejects along with anything else malformed.\n const dobParts = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(profile.dateOfBirth ?? '')\n const dob =\n dobParts && Number(dobParts[1]) > 1900\n ? {\n dobYear: Number(dobParts[1]),\n dobMonth: Number(dobParts[2]),\n dobDay: Number(dobParts[3]),\n }\n : {}\n return {\n firstName: profile.firstName ?? '',\n lastName: profile.lastName ?? '',\n email: profile.email ?? '',\n phone: str(profile.phone),\n streetAddress: str(profile.streetAddress),\n city: str(profile.city),\n zip: str(profile.zipCode),\n countryId: idStr(profile.countryId),\n stateId: idStr(profile.stateId),\n ...dob,\n }\n}\n\nexport const completeFreeRegistration = async (orderHash: string): Promise<void> => {\n await post(ENDPOINTS.order.completeFreeRegistration(orderHash))\n}\n\nexport const confirmOrderSuccess = async (\n orderHash: string,\n options?: {\n /** Razorpay settle token (`razorpay_payment_id`) — the server fetches +\n * captures the charge with it. */\n token?: string\n }\n): Promise<{ needIdVerification: boolean }> => {\n const body = await post<any>(\n ENDPOINTS.order.success(orderHash),\n options?.token ? { token: options.token } : undefined\n )\n return {\n needIdVerification: Boolean(\n body?.data?.attributes?.needIdVerification ?? body?.data?.needIdVerification\n ),\n }\n}\n\n/**\n * ID-verification status for a NEED_ID_VERIFICATION order. Pass `mintUrl: true`\n * on the call that OPENS the provider session (the server mints\n * `verification_url` on that call only); poll the plain form afterwards.\n */\nexport const getIdVerificationStatus = async (\n orderHash: string,\n mintUrl?: boolean\n): Promise<IdVerificationStatus> => {\n const body = await get<any>(ENDPOINTS.order.idVerification(orderHash, mintUrl))\n return (body?.data?.attributes ?? {}) as IdVerificationStatus\n}\n\n/** Whether the signed-in user owns this order (guards the confirmation page\n * against someone opening another buyer's order hash). */\nexport const verifyCustomerOrder = async (orderHash: string): Promise<unknown> =>\n get(ENDPOINTS.order.verifyCustomer(orderHash))\n","/**\n * Payment-rail transports — the per-gateway wire calls the engine dispatches to\n * after the order exists: fee re-price, redirect confirm, OXXO prepare, Xendit\n * e-wallet/card charge, MSI installments, payment plans, and PayPal Standard.\n * Ported faithfully from the engine's api layer; request/response shaping stays\n * in core's interpreters.\n */\nimport { get, post } from '../client/http'\nimport { ENDPOINTS } from '../constants'\nimport {\n buildPaymentMethodTypeAttributes,\n interpretRedirectConfirm,\n resolvePayPalForm,\n} from '../logic'\nimport type {\n PaymentMethodTypeInput,\n PayPalForm,\n RedirectConfirmRequest,\n RedirectOutcome,\n} from '../dtos'\n\nconst postFormEncoded = (\n uri: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n post<Record<string, unknown>>(\n uri,\n Object.entries(fields)\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join('&'),\n { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }\n ).then((data) => data ?? {})\n\nconst appendFormObject = (\n form: FormData,\n prefix: string,\n obj: Record<string, unknown>\n) => {\n Object.keys(obj).forEach((key) => {\n const value = obj[key]\n if (value === null || value === undefined) return\n if (typeof value === 'object') {\n appendFormObject(form, `${prefix}[${key}]`, value as Record<string, unknown>)\n } else {\n form.append(`${prefix}[${key}]`, String(value))\n }\n })\n}\n\n/**\n * Per-payment-method-type fee re-price (Klarna/Afterpay-class types carry their\n * own fee structures). Run BEFORE confirming a fee-mode type, then re-fetch the\n * review — charging the pre-reprice amount would undercharge.\n */\nexport const changePaymentMethodType = async (\n orderHash: string,\n input: PaymentMethodTypeInput\n): Promise<void> => {\n await post(ENDPOINTS.payment.methodType(orderHash), {\n data: { attributes: buildPaymentMethodTypeAttributes(input) },\n })\n}\n\n/** Server-side confirm for redirect-based Stripe methods — returns the provider\n * hand-off (or 'settled' when no redirect is needed). */\nexport const confirmRedirect = async (\n orderHash: string,\n request: RedirectConfirmRequest\n): Promise<RedirectOutcome> => {\n const body = await post<any>(ENDPOINTS.payment.confirmRedirect(orderHash), request)\n return interpretRedirectConfirm(body?.data?.attributes)\n}\n\n/** OXXO: move the order (and its goods) to the pending-voucher state BEFORE the\n * client confirm. Empty body; needs the registered session. */\nexport const prepareForOxxo = async (orderHash: string): Promise<void> => {\n await post(ENDPOINTS.payment.prepareOxxo(orderHash))\n}\n\n/** Xendit e-wallet charge — multipart fields from core's\n * `buildXenditEWalletChargeFields`; interpret with `interpretXenditChargeResponse`. */\nexport const submitXenditEWalletCharge = async (\n fields: Record<string, string>\n): Promise<Record<string, unknown>> => {\n const form = new FormData()\n Object.entries(fields).forEach(([key, value]) => form.append(key, value))\n const data = await post<Record<string, unknown>>(\n ENDPOINTS.payment.submitPayment(encodeURIComponent(fields.orderHash)),\n form,\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n return data ?? {}\n}\n\n/** MSI offers — between payment-method creation and the confirm; the server\n * gates to MXN carts. Fields from `buildInstallmentOffersFields`. */\nexport const getInstallmentOffers = (\n orderHash: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n postFormEncoded(ENDPOINTS.payment.installmentOffers(orderHash), fields)\n\n/** MSI confirm: the intent confirms SERVER-SIDE — when has_next_action comes\n * back, run only handleNextAction, never a second confirmPayment. */\nexport const confirmInstallments = (\n orderHash: string,\n fields: Record<string, string>\n): Promise<Record<string, unknown>> =>\n postFormEncoded(ENDPOINTS.payment.confirmInstallments(orderHash), fields)\n\n/**\n * Payment plan (installments) with a NEW card: the card is saved via the\n * review's SetupIntent (confirmed on the confirmer, nothing charged), then this\n * schedules the plan server-side against the resulting PaymentMethod.\n */\nexport const createPaymentPlan = async (\n orderHash: string,\n stripePaymentMethodId: string\n): Promise<{ needIdVerification: boolean }> => {\n const body = await post<any>(ENDPOINTS.payment.paymentPlanCreate(orderHash), {\n stripe_payment_method_id: stripePaymentMethodId,\n })\n return {\n needIdVerification: Boolean(\n body?.data?.attributes?.needIdVerification ?? body?.data?.needIdVerification\n ),\n }\n}\n\n/**\n * Payment-plan saved-card shortcut: charge the plan directly to the reusable\n * card the review carries, skipping the SetupIntent round trip. The server may\n * answer `requires_action` with a client secret — run 3DS, then settle.\n */\nexport const chargeSavedCardPlan = async (\n orderHash: string,\n paymentMethodId: string\n): Promise<{ requiresAction: boolean; clientSecret?: string }> => {\n const data = await postFormEncoded(ENDPOINTS.cart.paymentPlan(orderHash), {\n paymentMethodId,\n })\n const inner = ((data.data as Record<string, unknown> | undefined) ?? data) || {}\n return {\n requiresAction: Boolean(inner.requires_action),\n clientSecret:\n typeof inner.client_secret === 'string' ? inner.client_secret : undefined,\n }\n}\n\n/** PayPal Standard step 1: switch the placed order's payment method (attributes\n * from core's `buildChangePaymentMethodAttributes`). */\nexport const changePaymentMethod = async (\n attributes: Record<string, unknown>\n): Promise<void> => {\n await post(ENDPOINTS.payment.changeMethod, {\n data: { attributes },\n })\n}\n\n/** PayPal Standard step 2: the `{action_url, fields}` document the provider page\n * auto-submits (PayPal refuses framing — top-level POST only). */\nexport const getPayPalForm = async (orderHash: string): Promise<PayPalForm | null> => {\n const body = await get<any>(ENDPOINTS.payment.paypalForm(orderHash))\n return resolvePayPalForm(body?.data?.attributes ?? null)\n}\n\n/**\n * Xendit CARD charge: the sheet tokenized the card (with 3DS) client-side; the\n * token is charged server-side (the amount is resolved from the order, the\n * token only proves the card). Success responses may still carry error:true;\n * that throws here.\n */\nexport const submitXenditCardCharge = async (\n orderId: string,\n orderHash: string,\n token: Record<string, unknown>\n): Promise<Record<string, unknown>> => {\n const form = new FormData()\n form.append('order', String(orderId))\n form.append('orderHash', orderHash)\n form.append('paymentData[paymentType]', 'credit_card')\n appendFormObject(form, 'paymentData[data]', token)\n\n const result = await post<Record<string, unknown>>(\n ENDPOINTS.payment.submitPayment(encodeURIComponent(orderHash)),\n form,\n { headers: { 'Content-Type': 'multipart/form-data' } }\n )\n const data = result ?? {}\n if (data.error === true) {\n throw new Error(\n String(\n data.message ||\n data.failure_reason ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n )\n }\n return data\n}\n","/**\n * The checkout sequence — framework-free and payment-SDK-free (card/wallet\n * confirmation goes through the injected PaymentConfirmer port). Encodes the\n * traps the server contract hides:\n * - add-to-cart replaces the whole cart → ONE call with every ticket type\n * - GET /cart must run before POST /checkout (primes the session)\n * - decrypted ticket_type_ids only exist in the pricing response\n * - free strictly means order total === 0\n * - retries must never create a second order or charge twice\n */\nimport {\n addSeatsToCart,\n addTicketsToCart,\n changePaymentMethod,\n changePaymentMethodType,\n chargeSavedCardPlan,\n checkBuyerEmail as checkBuyerEmailApi,\n completeFreeRegistration,\n confirmInstallments,\n confirmOrderSuccess,\n confirmRedirect,\n createOrder,\n createPaymentPlan,\n getCart,\n getCheckoutConfigs,\n getEventAddons,\n getEventConditions,\n getEventCustomFields,\n getIdVerificationStatus,\n getInstallmentOffers,\n getOrderReview,\n getPaymentConfigAttributes,\n getPayPalForm,\n getPriceBreakdown,\n prepareForOxxo,\n setEventCurrency,\n submitXenditCardCharge,\n submitXenditEWalletCharge,\n updateCheckout,\n} from '../api'\nimport { getOriginUrl } from '../client'\nimport { clearCartGuestToken, pinCartGuestToken } from '../client/session'\nimport { XENDIT_EWALLET_EXTRA_FIELD } from '../constants'\nimport type {\n AddonSelection,\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n CheckoutOptions,\n CheckoutSnapshot,\n CurrencySync,\n CurrencySyncOptions,\n CustomFieldValues,\n EventAddon,\n EventCondition,\n EventCustomFieldGroup,\n IdVerificationCallbacks,\n IdVerificationPoller,\n IdVerificationStatus,\n InstallmentOffer,\n PlaceOrderResult,\n PreOrderGateway,\n RequiredAddOnLike,\n SeatLine,\n TicketSelection,\n} from '../dtos'\nimport {\n buildChangePaymentMethodAttributes,\n buildConfirmInstallmentsFields,\n buildInstallmentOffersFields,\n buildXenditEWalletChargeFields,\n confirmInstallmentsHasNextAction,\n createIdVerificationPoller,\n evaluateFieldGates,\n interpretXenditChargeResponse,\n missingCheckoutDetails,\n missingRequiredAddOns,\n oxxoVoucherFromNextAction,\n paypalTabConfig,\n requiresFeeReprice,\n resolveInstallmentOffers,\n} from '../logic'\nimport {\n buildAutoSubmitFormHtml,\n cleanAccountId,\n CONFIRMED_INTENT_STATUSES,\n unsupportedGatewayError,\n type CheckoutPorts,\n} from './confirmer'\nimport { errorMessage, isCartExpiredError } from './errors'\nimport { buildRazorpayCheckoutHtml, buildXenditCheckoutHtml } from './sheets'\nimport { createCheckoutStore, type CheckoutStore } from './store'\n\n/** How the shopper pays. Apple/Google Pay show the native wallet sheet; card\n * confirms the card field the consumer rendered. */\nexport type PaymentMethod = 'card' | 'applePay' | 'googlePay'\n\n/** A full payment request — the alternative rails carry parameters. The plain\n * `PaymentMethod` strings remain valid ('card' ≡ `{ method: 'card' }`). */\nexport type PaymentRequest =\n | { method: 'card' }\n /** Pay with the ORDER'S OWN gateway (the prebuilt \"just pay\" button):\n * razorpay → the Razorpay sheet, xendit → the Xendit card rail,\n * stripe/unknown → the card path (incl. MSI). */\n | { method: 'auto'; description?: string }\n | { method: 'applePay' }\n | { method: 'googlePay' }\n /** Redirect-based Stripe methods (Klarna/Afterpay/Affirm/iDEAL-class). Needs\n * ports.providerPage + ports.createRedirectPaymentMethod. */\n | { method: 'redirect'; methodType: string }\n /** OXXO cash voucher (Mexico). Needs ports.confirmOxxo; result is\n * `pending: true` + `pendingVoucherUrl`. */\n | { method: 'oxxo' }\n /** Xendit e-wallet (walletKey from the pre-order processors, e.g. 'dana';\n * Jenius Pay wants extra.cashtag, OVO extra.phoneNumber). Needs providerPage. */\n | {\n method: 'xenditEWallet'\n walletKey: string\n extra?: { cashtag?: string; phoneNumber?: string }\n }\n /** PayPal Standard (top-level form; settles via IPN — may return pending). */\n | { method: 'paypal' }\n /** Razorpay web checkout (posts razorpay_payment_id → settle token on /success). */\n | { method: 'razorpay'; description?: string }\n /** Xendit CARD: the sheet tokenizes (3DS) and posts `token`; charge server-side. */\n | { method: 'xenditCard' }\n /** Payment plan (installments, Stripe): the card is SAVED via the review's\n * SetupIntent (nothing charged now), the plan schedules server-side; a\n * reusable saved card is charged directly (opt out with useSavedCard:false). */\n | { method: 'paymentPlan'; useSavedCard?: boolean }\n\nconst normalizeRequest = (method?: PaymentMethod | PaymentRequest): PaymentRequest =>\n typeof method === 'string' ? { method } : (method ?? { method: 'card' })\n\n/** The platform capabilities + wallet/redirect options the rails run on. */\nexport interface EngineContext {\n ports: CheckoutPorts\n options: CheckoutOptions\n}\n\n// ---------------------------------------------------------------------------\n// Pre-flight helpers (pure)\n// ---------------------------------------------------------------------------\n\nconst hasValue = (v: string | string[] | undefined): boolean =>\n Array.isArray(v) ? v.length > 0 : Boolean(v && String(v).trim())\n\nconst missingRequiredAddOnCaptures = (\n groups: EventCustomFieldGroup[],\n addOns: AddonSelection,\n addOnDataCapture: Record<string, CustomFieldValues> | undefined\n): string[] => {\n const missing: string[] = []\n for (const g of groups.filter((g) => g.scope === 'add-on')) {\n if (!(Number(addOns[g.id]) > 0)) continue\n const values = addOnDataCapture?.[g.id]\n for (const f of g.fields.filter((f) => f.required && f.type !== 'image')) {\n if (!hasValue(values?.[f.name])) {\n missing.push(`${f.label || f.name}${g.label ? ` (${g.label})` : ''}`)\n }\n }\n }\n return missing\n}\n\nconst unacceptedRequiredConditions = (\n conditions: EventCondition[] | undefined,\n accepted: Record<string, boolean> | undefined\n): EventCondition[] =>\n (conditions ?? []).filter((c) => c.isRequired && accepted?.[c.id] !== true)\n\nconst assertNotBusy = (store: CheckoutStore) => {\n const { status } = store.getState()\n if (status === 'priming' || status === 'repricing' || status === 'placing') {\n throw new Error('Checkout is busy — please wait.')\n }\n}\n\n/**\n * Routes a failed call to the right terminal state: an expired-cart rejection\n * becomes 'expired' (offer a restart), anything else 'error'. Exception: once\n * the card is charged, the order MUST be finalized — even an expiry rejection\n * on the finalize call stays a recoverable 'error' (a retry replays only the\n * finalize on the same hash), never the destructive restart.\n */\nconst failCheckout = (store: CheckoutStore, e: unknown): void => {\n const expired = isCartExpiredError(e) && !store.progress.paymentConfirmed\n if (expired) clearCartGuestToken()\n store.setState({ status: expired ? 'expired' : 'error', error: errorMessage(e) })\n}\n\n// ---------------------------------------------------------------------------\n// Prime + reprice\n// ---------------------------------------------------------------------------\n\n/** Builds the server cart for a ticket selection and prices it. Idempotent per\n * selection (the server replaces the cart; the store resets for the new run). */\nexport const primeWith = (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n selections: TicketSelection[]\n): Promise<void> => {\n if (!selections.length) throw new Error('Select at least one ticket.')\n return primeCore(store, ctx, eventId, selections, () =>\n addTicketsToCart(eventId, selections)\n )\n}\n\n/** One reserved seat → one store selection, so the holder math (one holder per\n * ticket) stays correct. A guest-capable table contributes `guests` holders —\n * the server counts tickets from the `ticket_types` quantities, which for a\n * guest line equal the guest count. (If a real table-map event turns out to\n * need one holder per TABLE, drop the `?? l.guests` and use `1`.) */\nconst seatLinesToSelections = (lines: SeatLine[]): TicketSelection[] =>\n lines.map((l) => ({\n id: l.ticketTypeId,\n name: 'Seat',\n optionName: l.optionName,\n price: l.price,\n currency: '',\n quantity: l.guests ?? 1,\n }))\n\n/** Builds the server cart for RESERVED SEATS and prices it — the seat-map\n * analogue of `primeWith`. Reservations were already placed on seat click\n * (`ttf.seatmap.reserve`); this turns them into cart lines + prices the order,\n * reusing the exact same session-prime / gateway-guard / pricing pipeline. */\nexport const primeSeatsWith = (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n lines: SeatLine[]\n): Promise<void> => {\n if (!lines.length) throw new Error('Select at least one seat.')\n return primeCore(store, ctx, eventId, seatLinesToSelections(lines), () =>\n addSeatsToCart(eventId, lines)\n )\n}\n\n/**\n * Attach the engine to a cart that another supported flow already created\n * (currently resale and compatibility links). Unlike `prime`, this does not\n * add or replace ticket lines.\n */\nexport const resumeCartWith = async (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n options: { isFromResale?: boolean } = {}\n): Promise<void> => {\n assertNotBusy(store)\n store.reset()\n store.setState({ status: 'priming', eventId, selections: [] })\n\n try {\n const { expiresInSeconds, preOrderGateway } = await getCart()\n pinCartGuestToken()\n const payableGateways = ['stripe_payment_intents', 'xendit']\n if (preOrderGateway && !payableGateways.includes(preOrderGateway)) {\n throw new Error(\n \"This event's payment provider isn't supported in this checkout yet.\"\n )\n }\n\n const [pricing, customFields, configGates, priceBreakdown, addons, conditions] =\n await Promise.all([\n updateCheckout(eventId, {}, options),\n getEventCustomFields(eventId).catch((): EventCustomFieldGroup[] => []),\n getCheckoutConfigs().catch(() => ({\n holderNamesRequired: false,\n fieldGates: evaluateFieldGates(null),\n })),\n getPriceBreakdown().catch(() => null),\n getEventAddons(eventId).catch((): EventAddon[] => []),\n getEventConditions(eventId).catch((): EventCondition[] => []),\n ])\n\n store.setState({\n status: 'ready',\n gateway: (preOrderGateway ?? undefined) as PreOrderGateway | undefined,\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n stripe: pricing.stripe,\n paymentPlan: pricing.paymentPlan,\n customFields,\n requiredAddOns: addons\n .filter((addon) => addon.required)\n .map((addon) => ({\n id: addon.id,\n name: addon.name,\n required: true,\n stock: addon.stock,\n })),\n conditions,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n holderNamesRequired: configGates.holderNamesRequired,\n fieldGates: configGates.fieldGates,\n priceBreakdown,\n expiresAt: Date.now() + expiresInSeconds * 1000,\n })\n\n if (pricing.stripe) {\n await ctx.ports.confirmer\n .init({\n publishableKey: pricing.stripe.publishableKey,\n accountId: cleanAccountId(pricing.stripe.accountId),\n })\n .catch(() => undefined)\n }\n } catch (error) {\n failCheckout(store, error)\n throw error\n }\n}\n\n/** The shared prime pipeline: reset → populate the cart → session-prime +\n * gateway guard → price/custom-fields/conditions/add-ons fan-out → ready.\n * `populateCart` is the only thing that differs between tickets and seats. */\nconst primeCore = async (\n store: CheckoutStore,\n ctx: EngineContext,\n eventId: string,\n selections: TicketSelection[],\n populateCart: () => Promise<{ holderNamesRequired: boolean }>\n): Promise<void> => {\n assertNotBusy(store)\n\n // Never start a new cart on top of a CHARGED-but-unfinalized order: priming\n // resets the store, which would drop the confirmed payment and let the shopper\n // pay a second time. That order must be finalized (retry placeOrder), not replaced.\n if (store.progress.paymentConfirmed) {\n throw new Error(\n 'You already have a paid order being finalized. Please complete it before starting a new purchase.'\n )\n }\n\n store.reset()\n store.setState({ status: 'priming', eventId, selections })\n\n try {\n const { holderNamesRequired } = await populateCart()\n pinCartGuestToken()\n // Mandatory session priming — also identifies the payment gateway.\n const { expiresInSeconds, preOrderGateway } = await getCart()\n\n // Fail fast — BEFORE any order exists — on events this package can't pay.\n // Fails open when the backend doesn't identify a gateway. Xendit events are\n // payable through the e-wallet rail, so they prime.\n const PAYABLE_PRE_ORDER_GATEWAYS = ['stripe_payment_intents', 'xendit']\n if (preOrderGateway && !PAYABLE_PRE_ORDER_GATEWAYS.includes(preOrderGateway)) {\n throw new Error(\n \"This event's payment provider isn't supported in the app yet. Please complete your purchase on the event page.\"\n )\n }\n\n const [pricing, customFields, configGates, priceBreakdown, addons, conditions] =\n await Promise.all([\n updateCheckout(eventId, {}),\n getEventCustomFields(eventId).catch((): EventCustomFieldGroup[] => []),\n getCheckoutConfigs().catch(() => ({\n holderNamesRequired: false,\n fieldGates: evaluateFieldGates(null),\n })),\n getPriceBreakdown().catch(() => null),\n getEventAddons(eventId).catch((): EventAddon[] => []),\n getEventConditions(eventId).catch((): EventCondition[] => []),\n ])\n\n const requiredAddOns: RequiredAddOnLike[] = addons\n .filter((a) => a.required)\n .map((a) => ({ id: a.id, name: a.name, required: true, stock: a.stock }))\n\n store.setState({\n status: 'ready',\n // Validated payable above; the raw string narrows to the gateway union.\n gateway: (preOrderGateway ?? undefined) as PreOrderGateway | undefined,\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n stripe: pricing.stripe,\n paymentPlan: pricing.paymentPlan,\n customFields,\n requiredAddOns,\n conditions,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n holderNamesRequired: holderNamesRequired || configGates.holderNamesRequired,\n fieldGates: configGates.fieldGates,\n priceBreakdown,\n expiresAt: Date.now() + expiresInSeconds * 1000,\n })\n\n // Initialize the payment SDK as soon as the keys exist so the consumer's\n // card field is ready without any wiring on their side.\n if (pricing.stripe) {\n await ctx.ports.confirmer\n .init({\n publishableKey: pricing.stripe.publishableKey,\n accountId: cleanAccountId(pricing.stripe.accountId),\n })\n .catch(() => undefined) // re-initialized at pay time with review keys\n }\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n/** Stores the add-on selection and re-prices the cart with it. */\nexport const repriceWith = async (\n store: CheckoutStore,\n addOns: AddonSelection\n): Promise<void> => {\n const { eventId } = store.getState()\n if (!eventId) throw new Error('reprice: no active checkout.')\n assertNotBusy(store)\n\n // Changing add-ons invalidates any order created by a failed attempt.\n store.invalidateOrderProgress()\n\n store.setState({ status: 'repricing', addOns })\n try {\n const pricing = await updateCheckout(eventId, addOns)\n const priceBreakdown = await getPriceBreakdown(addOns).catch(() => null)\n store.setState({\n status: 'ready',\n ticketTypeIds: pricing.ticketTypeIds,\n breakdown: pricing.breakdown,\n priceBreakdown,\n paymentPlan: pricing.paymentPlan,\n redirectPaymentMethods: pricing.redirectPaymentMethods,\n walletAvailability: pricing.walletAvailability,\n stripeElementsConfig: pricing.stripeElementsConfig,\n ...(pricing.stripe ? { stripe: pricing.stripe } : {}),\n })\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n// ---------------------------------------------------------------------------\n// Place order (create → review → rail dispatch → finalize)\n// ---------------------------------------------------------------------------\n\nexport const placeOrderWith = async (\n store: CheckoutStore,\n ctx: EngineContext,\n method: PaymentMethod | PaymentRequest = 'card'\n): Promise<PlaceOrderResult> => {\n const { ports, options } = ctx\n const { confirmer } = ports\n let request = normalizeRequest(method)\n const snap = store.getState()\n const { billing, holders, addOns, consent, selections, stripe } = snap\n\n assertNotBusy(store)\n\n const failPreflight = (message: string): Error => {\n store.setState({ status: 'error', error: message })\n return new Error(message)\n }\n\n const missingDetails = missingCheckoutDetails(snap)\n if (missingDetails.length > 0) {\n throw failPreflight(\n `Please complete the required checkout detail${missingDetails.length > 1 ? 's' : ''}: ${missingDetails\n .slice(0, 4)\n .join(', ')}${missingDetails.length > 4 ? '…' : ''}.`\n )\n }\n if (!billing) {\n // `missingCheckoutDetails` already reports this; retain the explicit guard\n // so TypeScript and non-standard callers both see billing as required.\n throw failPreflight('Billing details are incomplete.')\n }\n // Don't attempt an order the server will reject on an elapsed reservation.\n // Exception: once payment is confirmed we MUST finalize regardless of the timer.\n if (\n !store.progress.paymentConfirmed &&\n (snap.status === 'expired' ||\n (snap.expiresAt != null && Date.now() >= snap.expiresAt))\n ) {\n store.expireCart()\n throw new Error('Your cart has expired. Please choose your tickets again.')\n }\n\n // One holder entry per ticket; pad/trim to match.\n const totalTickets = selections.reduce((sum, t) => sum + t.quantity, 0) || 1\n const paddedHolders: CheckoutHolder[] = Array.from(\n { length: totalTickets },\n (_, i) => holders[i] ?? { firstName: '', lastName: '', email: '', phone: undefined }\n )\n\n const unaccepted = unacceptedRequiredConditions(\n snap.conditions,\n snap.acceptedConditions\n )\n if (unaccepted.length > 0) {\n const names = unaccepted.map((c) => c.name).filter(Boolean)\n throw failPreflight(\n `Please accept the required condition${unaccepted.length > 1 ? 's' : ''}${\n names.length ? `: ${names.join(', ')}` : ''\n }.`\n )\n }\n\n const missingCaptures = missingRequiredAddOnCaptures(\n snap.customFields,\n addOns,\n snap.addOnDataCapture\n )\n if (missingCaptures.length > 0) {\n throw failPreflight(\n `Please fill in the required field${missingCaptures.length > 1 ? 's' : ''}: ${missingCaptures\n .slice(0, 4)\n .join(', ')}${missingCaptures.length > 4 ? '…' : ''}.`\n )\n }\n\n const missingAddOns = missingRequiredAddOns(snap.requiredAddOns, addOns)\n if (missingAddOns.length > 0) {\n const names = missingAddOns.map((a) => a.name || '').filter(Boolean)\n throw failPreflight(\n `Please add the required add-on${missingAddOns.length > 1 ? 's' : ''}: ${names.join(', ')}`\n )\n }\n\n store.setState({ status: 'placing', error: undefined })\n try {\n // 1. Create the order (skip if a previous attempt already did).\n let orderHash = store.progress.orderHash\n if (!orderHash) {\n const order = await createOrder({\n billing,\n holders: paddedHolders,\n addOns,\n consent,\n addOnDataCapture: snap.addOnDataCapture,\n })\n orderHash = order.hash\n store.progress.orderHash = orderHash\n\n // Duplicate-charge guard: the server answered with the ALREADY-COMPLETED\n // paid order for this checkout — go straight to confirmation.\n if (order.alreadyPaid) {\n const result: PlaceOrderResult = {\n orderHash,\n free: false,\n needIdVerification: false,\n alreadyPaid: true,\n }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n }\n\n // 2. Review — order lock + authoritative total + Stripe secrets.\n const review = await getOrderReview(orderHash)\n if (review.expiresInSeconds != null) {\n store.setState({ expiresAt: Date.now() + review.expiresInSeconds * 1000 })\n }\n\n // 'auto' pays with the order's own gateway.\n if (request.method === 'auto') {\n request =\n review.gateway === 'razorpay'\n ? { method: 'razorpay', description: request.description }\n : review.gateway === 'xendit'\n ? { method: 'xenditCard' }\n : { method: 'card' }\n }\n\n // 3a. Free strictly means total === 0.\n if (review.total !== '' && Number(review.total) === 0) {\n await completeFreeRegistration(orderHash)\n const result: PlaceOrderResult = {\n orderHash,\n free: true,\n needIdVerification: false,\n currency: review.currency,\n }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n\n // Duplicate-charge guard: the server withholds the secret for intents that\n // already succeeded / are settling — skip charging, only replay finalize.\n if (review.paymentAlreadyProcessed) {\n store.progress.paymentConfirmed = true\n }\n\n const finish = (partial: PlaceOrderResult): PlaceOrderResult => {\n const result: PlaceOrderResult = { currency: review.currency, ...partial }\n store.progress = {}\n clearCartGuestToken()\n store.setState({ status: 'succeeded', order: result })\n return result\n }\n\n let confirmedPaymentIntentId: string | undefined\n\n if (!store.progress.paymentConfirmed) {\n // ---- OXXO cash voucher (own finalize: pending result) --------------\n if (request.method === 'oxxo') {\n if (!ports.confirmOxxo) throw unsupportedGatewayError()\n if (review.gateway !== 'stripe' || !review.clientSecret) {\n throw new Error('This payment method is not available for this order')\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n await prepareForOxxo(orderHash)\n const { error: oxxoError, nextAction } = await ports.confirmOxxo(\n review.clientSecret,\n billing\n )\n const voucher = oxxoVoucherFromNextAction(\n (nextAction as Record<string, unknown>) || null\n )\n if (oxxoError && !voucher) throw new Error(oxxoError || 'Payment failed')\n if (!voucher) {\n throw new Error(\n 'We couldn’t issue the OXXO voucher. Please try again or pay with a card.'\n )\n }\n store.progress.paymentConfirmed = true\n try {\n await Promise.resolve(ports.openUrl?.(voucher.voucherUrl))\n } catch {\n // The voucher is also emailed and carried on the result.\n }\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n return finish({\n orderHash,\n free: false,\n needIdVerification,\n pending: true,\n pendingVoucherUrl: voucher.voucherUrl,\n })\n }\n\n // ---- PayPal Standard (own finalize: IPN settles asynchronously) ----\n if (request.method === 'paypal') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n const paypalConfig = paypalTabConfig(await getPaymentConfigAttributes())\n if (!paypalConfig) throw new Error('PayPal is not available for this order')\n if (!review.orderId) throw new Error('PayPal is not available for this order')\n await changePaymentMethod(\n buildChangePaymentMethodAttributes({\n paymentMethodId: paypalConfig.payment_method_id,\n paymentMethodHash: paypalConfig.payment_method_hash,\n orderId: review.orderId,\n orderHash,\n })\n )\n const paypalForm = await getPayPalForm(orderHash)\n if (!paypalForm) {\n throw new Error(\n 'We couldn’t start the PayPal payment. Please try again or pay by card.'\n )\n }\n const origin = getOriginUrl()\n const sheet = await ports.providerPage({\n html: buildAutoSubmitFormHtml(paypalForm),\n baseUrl: origin,\n returnUrlPrefix: `${origin}/store/order-complete`,\n })\n if (sheet.event === 'failed') {\n throw new Error(sheet.description || 'Payment failed')\n }\n store.progress.paymentConfirmed = true\n try {\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n return finish({ orderHash, free: false, needIdVerification })\n } catch {\n return finish({\n orderHash,\n free: false,\n needIdVerification: false,\n pending: true,\n })\n }\n }\n\n // ---- Razorpay web checkout (own finalize: settle token) ------------\n if (request.method === 'razorpay') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n if (review.gateway !== 'razorpay' || !review.razorpayKeyId) {\n throw new Error('This payment method is not available for this order')\n }\n const sheet = await ports.providerPage({\n html: buildRazorpayCheckoutHtml({\n keyId: review.razorpayKeyId,\n amountMinor: Math.round(Number(review.payNow ?? review.total) * 100),\n description: request.description ?? '',\n buyerName: `${billing.firstName} ${billing.lastName}`.trim(),\n buyerEmail: billing.email,\n orderHash,\n }),\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n if (sheet.event === 'failed') {\n throw new Error(\n sheet.description ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n }\n store.progress.paymentConfirmed = true\n const paymentId =\n typeof sheet.data?.razorpay_payment_id === 'string'\n ? sheet.data.razorpay_payment_id\n : undefined\n const { needIdVerification } = await confirmOrderSuccess(\n orderHash,\n paymentId ? { token: paymentId } : undefined\n )\n return finish({ orderHash, free: false, needIdVerification })\n }\n\n // ---- Payment plan (installments; own finalize — the plan IS the record)\n if (request.method === 'paymentPlan') {\n if (review.gateway !== 'stripe') {\n throw new Error('This payment method is not available for this order')\n }\n // The SetupIntent secret's presence IS the \"plan available\" signal.\n if (!review.paymentPlanSetupSecret) {\n throw new Error(\n \"The payment plan isn't available for this order right now. Turn off installments to pay in full.\"\n )\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n\n // Saved-card shortcut: charge the plan to the card the review carries.\n const savedCard =\n request.useSavedCard === false ? null : review.paymentPlanSavedCard\n if (savedCard) {\n const charge = await chargeSavedCardPlan(orderHash, savedCard.paymentMethodId)\n if (charge.requiresAction && charge.clientSecret) {\n if (!ports.confirmSavedCardPayment) throw unsupportedGatewayError()\n await ports.confirmSavedCardPayment(\n charge.clientSecret,\n savedCard.paymentMethodId\n )\n }\n return finish({ orderHash, free: false, needIdVerification: false })\n }\n\n // New card: SAVE it via the SetupIntent (nothing charged), then create\n // the plan against the resulting PaymentMethod.\n if (!ports.confirmPaymentPlanSetup) throw unsupportedGatewayError()\n const paymentMethodId = await ports.confirmPaymentPlanSetup(\n review.paymentPlanSetupSecret,\n billing\n )\n const { needIdVerification } = await createPaymentPlan(orderHash, paymentMethodId)\n return finish({ orderHash, free: false, needIdVerification })\n }\n\n // ---- Xendit CARD (tokenize inline or via sheet; server-side charge) -\n if (request.method === 'xenditCard') {\n if (\n review.gateway !== 'xendit' ||\n !review.xenditPublishableKey ||\n !review.orderId\n ) {\n throw new Error('This payment method is not available for this order')\n }\n let token: Record<string, unknown> | undefined\n if (ports.tokenizeXenditCard) {\n token = await ports.tokenizeXenditCard({\n publishableKey: review.xenditPublishableKey,\n amount: review.payNow ?? review.total,\n billing,\n onBehalfOf: review.xenditOnBehalfOf ?? null,\n })\n } else if (ports.providerPage) {\n const sheet = await ports.providerPage({\n html: buildXenditCheckoutHtml({\n publishableKey: review.xenditPublishableKey,\n amount: review.payNow ?? review.total,\n buyerFirstName: billing.firstName,\n buyerLastName: billing.lastName,\n buyerEmail: billing.email,\n buyerPhone: billing.phone || '',\n onBehalfOf: review.xenditOnBehalfOf ?? null,\n }),\n baseUrl: 'https://js.xendit.co',\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n const t = sheet.data?.token\n if (sheet.event === 'failed' || !t || typeof t !== 'object') {\n throw new Error(\n sheet.description ||\n 'Your payment was not accepted. Please try again or use a different card.'\n )\n }\n token = t as Record<string, unknown>\n } else {\n throw unsupportedGatewayError()\n }\n await submitXenditCardCharge(review.orderId, orderHash, token)\n store.progress.paymentConfirmed = true\n }\n\n // ---- Xendit e-wallet (provider page + /success reconcile) ----------\n else if (request.method === 'xenditEWallet') {\n if (!ports.providerPage) throw unsupportedGatewayError()\n const requiredExtra = XENDIT_EWALLET_EXTRA_FIELD[request.walletKey]\n if (requiredExtra === 'cashtag' && !request.extra?.cashtag) {\n throw new Error('Please enter your cashtag to pay with this wallet.')\n }\n if (requiredExtra === 'phoneNumber' && !request.extra?.phoneNumber) {\n throw new Error('Please enter your mobile number to pay with this wallet.')\n }\n if (review.gateway !== 'xendit' || !review.orderId) {\n throw new Error('This payment method is not available for this order')\n }\n const outcome = interpretXenditChargeResponse(\n await submitXenditEWalletCharge(\n buildXenditEWalletChargeFields({\n orderId: review.orderId,\n orderHash,\n paymentType: request.walletKey,\n cashtag: request.extra?.cashtag,\n phoneNumber: request.extra?.phoneNumber,\n })\n )\n )\n if (outcome.kind !== 'redirect') throw new Error(outcome.reason)\n const sheet = await ports.providerPage({\n uri: outcome.url,\n returnUrlPrefix: `${getOriginUrl()}/store/order-complete`,\n })\n if (sheet.event === 'failed') {\n throw new Error(sheet.description || 'Payment failed')\n }\n store.progress.paymentConfirmed = true\n }\n\n // ---- Redirect-based Stripe methods (Klarna/Afterpay/iDEAL-class) ---\n else if (request.method === 'redirect') {\n if (!ports.providerPage || !ports.createRedirectPaymentMethod) {\n throw unsupportedGatewayError()\n }\n if (review.gateway !== 'stripe') {\n throw new Error('This payment method is not available for this order')\n }\n // Klarna/Afterpay-class types carry their own fees: re-price BEFORE\n // confirming (the server confirms the re-priced intent).\n if (\n requiresFeeReprice(request.methodType) &&\n review.stripeIntentId &&\n review.orderId\n ) {\n await changePaymentMethodType(orderHash, {\n paymentMethodType: request.methodType,\n orderId: review.orderId,\n orderHash,\n stripeIntentId: review.stripeIntentId,\n })\n }\n const paymentMethodId = await ports.createRedirectPaymentMethod(\n request.methodType,\n billing\n )\n if (!paymentMethodId) throw unsupportedGatewayError()\n const returnUrl = options.redirectReturnUrl || `${getOriginUrl()}/`\n const outcome = await confirmRedirect(orderHash, {\n payment_method_id: paymentMethodId,\n return_url: returnUrl,\n })\n if (outcome.kind === 'redirect') {\n const sheet = await ports.providerPage({\n uri: outcome.url,\n returnUrlPrefix: returnUrl,\n })\n if (sheet.event === 'dismiss') throw new Error('Payment was cancelled')\n if (sheet.event === 'failed') {\n throw new Error(\n sheet.description ||\n 'Your payment was not completed. Please try again or use a different payment method.'\n )\n }\n const redirectStatus = /[?&]redirect_status=([^&#]+)/.exec(\n sheet.returnUrl || ''\n )?.[1]\n if (redirectStatus === 'failed') {\n throw new Error(\n 'Your payment was not completed. Please try again or use a different payment method.'\n )\n }\n } else if (outcome.kind !== 'settled') {\n throw new Error(\n \"This payment method isn't available right now. Please pay with a card instead.\"\n )\n }\n store.progress.paymentConfirmed = true\n }\n\n // ---- Card / Apple Pay / Google Pay (the Stripe confirmer path, MSI) -\n else {\n if (!review.clientSecret) {\n throw new Error(\n \"This event's payment method isn't supported in the app yet. Please complete your purchase on the event page.\"\n )\n }\n const publishableKey = review.publishableKey ?? stripe?.publishableKey\n if (!publishableKey) throw new Error('Missing Stripe publishable key.')\n await confirmer.init({\n publishableKey,\n accountId: cleanAccountId(review.connectedAccount ?? stripe?.accountId),\n merchantIdentifier: options.merchantIdentifier,\n urlScheme: options.urlScheme,\n })\n\n // If a previous attempt already authorized this intent, reuse it rather\n // than confirming — and re-charging — again.\n const existingStatus = await confirmer.getIntentStatus(review.clientSecret)\n const alreadyConfirmed = Boolean(\n existingStatus && CONFIRMED_INTENT_STATUSES.includes(existingStatus)\n )\n\n if (!alreadyConfirmed) {\n // MSI (Mexican months without interest): offer plans between PM\n // creation and the confirm. A chosen plan confirms SERVER-SIDE — only\n // handleNextAction may run afterwards, never a second confirm.\n let confirmedViaInstallments = false\n if (\n request.method === 'card' &&\n review.currency === 'MXN' &&\n ports.onInstallmentOffers &&\n ports.createCardPaymentMethod &&\n ports.handleNextAction &&\n review.stripeIntentId\n ) {\n let offers: InstallmentOffer[] = []\n try {\n const paymentMethodId = await ports.createCardPaymentMethod(billing)\n offers = resolveInstallmentOffers(\n await getInstallmentOffers(\n orderHash,\n buildInstallmentOffersFields({\n paymentIntentId: review.stripeIntentId,\n paymentMethodId,\n })\n )\n ).installments\n } catch {\n // Offers unavailable — fall through to the normal confirm.\n }\n if (offers.length > 0) {\n const chosen = await ports.onInstallmentOffers(offers)\n if (chosen) {\n const confirmResponse = await confirmInstallments(\n orderHash,\n buildConfirmInstallmentsFields({\n paymentIntentId: review.stripeIntentId,\n offer: chosen,\n })\n )\n if (confirmInstallmentsHasNextAction(confirmResponse)) {\n await ports.handleNextAction(review.clientSecret)\n }\n confirmedViaInstallments = true\n }\n }\n }\n\n if (!confirmedViaInstallments) {\n const currencyCode = snap.breakdown?.currencyCode ?? review.currency ?? ''\n let status: string | undefined\n if (request.method === 'applePay') {\n status = await confirmer.confirmApplePay(\n review.clientSecret,\n review.total,\n currencyCode,\n {\n merchantCountryCode: options.merchantCountryCode,\n merchantName: options.merchantName,\n }\n )\n } else if (request.method === 'googlePay') {\n if (!confirmer.confirmGooglePay) throw unsupportedGatewayError()\n status = await confirmer.confirmGooglePay(\n review.clientSecret,\n review.total,\n currencyCode,\n {\n merchantCountryCode: options.merchantCountryCode,\n merchantName: options.merchantName,\n testEnv: options.googlePayTestEnv,\n }\n )\n } else {\n status = await confirmer.confirmCard(review.clientSecret, billing)\n }\n if (!status || !CONFIRMED_INTENT_STATUSES.includes(status)) {\n throw new Error(`Payment not completed (status: ${status ?? 'unknown'}).`)\n }\n }\n }\n store.progress.paymentConfirmed = true\n confirmedPaymentIntentId = review.stripeIntentId\n }\n }\n\n // 4. Record the payment server-side.\n const { needIdVerification } = await confirmOrderSuccess(orderHash)\n\n return finish({\n orderHash,\n free: false,\n needIdVerification,\n ...(confirmedPaymentIntentId ? { paymentIntentId: confirmedPaymentIntentId } : {}),\n })\n } catch (e) {\n failCheckout(store, e)\n throw e\n }\n}\n\n// ---------------------------------------------------------------------------\n// Pay an order created outside the engine (retry-safe session)\n// ---------------------------------------------------------------------------\n\nexport interface OrderPaymentSession {\n /** The order to pay (from your own on-checkout call). */\n orderHash: string\n /** Buyer details for the payment legs (billing_details, wallet sheets…). */\n billing: CheckoutBilling\n /** Engine progress store — created on first payOrder call. Carry the session\n * object so a retry after a CONFIRMED charge only replays finalization. */\n store?: CheckoutStore\n}\n\n/** Pays an ALREADY-CREATED order through the engine's rails — same duplicate-\n * charge guards, same rails, same UNSUPPORTED_GATEWAY. Order creation and its\n * pre-flights are the caller's; the engine seeds a session store with the hash. */\nexport const payOrderWith = async (\n ctx: EngineContext,\n session: OrderPaymentSession,\n method: PaymentMethod | PaymentRequest = 'card'\n): Promise<PlaceOrderResult> => {\n if (!session.store) {\n session.store = createCheckoutStore()\n session.store.setState({ status: 'ready' })\n }\n session.store.setState({ billing: session.billing })\n if (!session.store.progress.orderHash) {\n session.store.progress.orderHash = session.orderHash\n }\n return placeOrderWith(session.store, ctx, method)\n}\n\n// ---------------------------------------------------------------------------\n// Currency\n// ---------------------------------------------------------------------------\n\n/** Syncs the session currency. A bare call geo-seeds; a `code` switches it —\n * after which the catalog reprices, so the engine resets the checkout (billing/\n * holders preserved) and the consumer re-runs prime with re-fetched tickets. */\nexport const syncCurrencyWith = async (\n store: CheckoutStore,\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n): Promise<CurrencySync> => {\n const state = await setEventCurrency(eventId, code, options)\n const requiresCatalogRefresh = Boolean(code && !options?.seed)\n\n if (requiresCatalogRefresh) {\n if (store.progress.paymentConfirmed) {\n throw new Error(\n 'You already have a paid order being finalized. Please complete it before switching currency.'\n )\n }\n const { billing, holders } = store.getState()\n store.reset()\n store.setState({ billing, holders, currency: state })\n } else {\n store.setState({ currency: state })\n }\n\n return { state, requiresCatalogRefresh }\n}\n\n// ---------------------------------------------------------------------------\n// ID verification\n// ---------------------------------------------------------------------------\n\nexport interface RunIdVerificationOptions {\n /** Opens the provider verification URL. Omit to leave opening to the consumer. */\n openUrl?: (url: string) => void | Promise<void>\n /** Called once the check is confirmed required. Return true to TAKE OVER (the\n * engine stops — no open, no poll). */\n onRequired?: (info: {\n orderHash: string\n verificationUrl: string | null\n }) => boolean | void\n onPhase?: IdVerificationCallbacks['onPhase']\n schedule?: IdVerificationCallbacks['schedule']\n /** Fires `recheck` when the provider hand-off might have completed (e.g. the\n * app returns to the foreground). Return an unsubscribe. */\n registerForegroundListener?: (recheck: () => void) => () => void\n}\n\n/** Standalone poller for a NEED_ID_VERIFICATION order (mint + open the URL\n * first via `getIdVerificationStatus(hash, true)`, then start this). */\nexport const createIdVerificationPollerFor = (\n orderHash: string,\n onPhase: IdVerificationCallbacks['onPhase'],\n schedule?: IdVerificationCallbacks['schedule']\n): IdVerificationPoller =>\n createIdVerificationPoller({\n fetchStatus: () => getIdVerificationStatus(orderHash),\n onPhase,\n schedule,\n })\n\n/**\n * Runs ID verification end-to-end for a NEED_ID_VERIFICATION order: mint the\n * provider URL, open it, poll to completion. Already-verified → resolves now;\n * `onRequired` returns true → resolves undefined (consumer took over); verified\n * → resolves the status; timeout/error → REJECTS with a reassuring message (the\n * payment already settled — treat a rejection as a verification stall, never a\n * payment failure).\n */\nexport const runIdVerificationWith = (\n orderHash: string,\n options: RunIdVerificationOptions = {}\n): Promise<IdVerificationStatus | undefined> =>\n getIdVerificationStatus(orderHash, true).then((status) => {\n if (status.verified || status.required === false) return status\n\n if (\n options.onRequired?.({\n orderHash,\n verificationUrl: status.verification_url || null,\n }) === true\n ) {\n return undefined\n }\n if (status.verification_url && options.openUrl) {\n Promise.resolve(options.openUrl(status.verification_url)).catch(() => {\n // The consumer can still surface the URL via onRequired.\n })\n }\n\n return new Promise<IdVerificationStatus | undefined>((resolve, reject) => {\n let settled = false\n let unsubscribe: (() => void) | undefined\n const finish = (run: () => void) => {\n if (settled) return\n settled = true\n poller.stop()\n unsubscribe?.()\n run()\n }\n const poller = createIdVerificationPoller({\n fetchStatus: () => getIdVerificationStatus(orderHash),\n onPhase: (phase, fresh) => {\n options.onPhase?.(phase, fresh)\n if (phase === 'verified') {\n finish(() => resolve(fresh))\n } else if (phase === 'timeout' || phase === 'error') {\n finish(() =>\n reject(\n new Error(\n 'ID verification is taking longer than usual. Your payment is safe — your tickets will be emailed as soon as the check completes.'\n )\n )\n )\n }\n },\n schedule: options.schedule,\n })\n unsubscribe = options.registerForegroundListener?.(() => {\n getIdVerificationStatus(orderHash)\n .then((fresh) => {\n if (fresh.verified || fresh.required === false) finish(() => resolve(fresh))\n })\n .catch(() => {\n // Poller keeps running.\n })\n })\n poller.start()\n })\n })\n\n// ---------------------------------------------------------------------------\n// The engine facade\n// ---------------------------------------------------------------------------\n\nexport interface EngineConfig {\n /** Platform capabilities — confirmer (required) + optional rails. */\n ports: CheckoutPorts\n /** Wallet/redirect options (merchant identity, redirect URL, url scheme). */\n options?: CheckoutOptions\n /** Reuse an existing store; one is created otherwise. */\n store?: CheckoutStore\n}\n\nexport interface CheckoutEngine {\n /** The underlying store — subscribe/getState for non-React consumers. */\n store: CheckoutStore\n getSnapshot: () => CheckoutSnapshot\n subscribe: (listener: (s: CheckoutSnapshot) => void) => () => void\n /** Build + price the cart for a ticket selection. */\n prime: (eventId: string, selections: TicketSelection[]) => Promise<void>\n /** Build + price the cart for reserved SEATS (seat-map events). */\n primeSeats: (eventId: string, lines: SeatLine[]) => Promise<void>\n /** Resume an existing server-side cart without replacing its ticket lines. */\n resumeCart: (eventId: string, options?: { isFromResale?: boolean }) => Promise<void>\n /** Set the add-on selection and re-price. */\n setAddons: (addOns: AddonSelection) => Promise<void>\n setBilling: (billing: CheckoutBilling) => void\n setHolders: (holders: CheckoutHolder[]) => void\n setConsent: (consent: CheckoutConsent) => void\n setAcceptedConditions: (accepted: Record<string, boolean>) => void\n setAddonDataCapture: (capture: Record<string, CustomFieldValues>) => void\n /** Debounced existing-account check; sets `existingAccountEmail` on the snapshot. */\n checkBuyerEmail: (email: string) => Promise<void>\n /** Create the order and pay (or register free). */\n placeOrder: (method?: PaymentMethod | PaymentRequest) => Promise<PlaceOrderResult>\n /** Switch/seed the session currency. */\n syncCurrency: (\n eventId: string,\n code?: string,\n options?: CurrencySyncOptions\n ) => Promise<CurrencySync>\n /** Run ID verification for a NEED_ID_VERIFICATION order. */\n runIdVerification: (\n orderHash: string,\n options?: RunIdVerificationOptions\n ) => Promise<IdVerificationStatus | undefined>\n reset: () => void\n /**\n * Move the cart to the terminal 'expired' state. Until now this only happened\n * reactively, when the backend rejected a call with an expired-cart 422 — so a\n * reservation that simply ran out on screen left the buyer editing a form that\n * could no longer be paid for. Consumers driving the countdown call this when\n * it reaches zero.\n */\n expireCart: () => void\n}\n\n/**\n * Binds the orchestration to a store + a platform's ports. In React, wrap this\n * with `useCheckout()`; in any other JS runtime, use it directly.\n */\nexport const createEngine = (config: EngineConfig): CheckoutEngine => {\n const store = config.store ?? createCheckoutStore()\n const ctx: EngineContext = { ports: config.ports, options: config.options ?? {} }\n\n return {\n store,\n getSnapshot: () => store.getState(),\n subscribe: (listener) => store.subscribe(listener),\n prime: (eventId, selections) => primeWith(store, ctx, eventId, selections),\n primeSeats: (eventId, lines) => primeSeatsWith(store, ctx, eventId, lines),\n resumeCart: (eventId, options) => resumeCartWith(store, ctx, eventId, options),\n setAddons: (addOns) => repriceWith(store, addOns),\n setBilling: (billing) => store.setState({ billing }),\n setHolders: (holders) => store.setState({ holders }),\n setConsent: (consent) => store.setState({ consent }),\n setAcceptedConditions: (acceptedConditions) => store.setState({ acceptedConditions }),\n setAddonDataCapture: (addOnDataCapture) => store.setState({ addOnDataCapture }),\n checkBuyerEmail: async (email) => {\n const { exists } = await checkBuyerEmailApi(email)\n store.setState({ existingAccountEmail: exists ? email : null })\n },\n placeOrder: (method) => placeOrderWith(store, ctx, method),\n syncCurrency: (eventId, code, options) =>\n syncCurrencyWith(store, eventId, code, options),\n runIdVerification: (orderHash, options) => runIdVerificationWith(orderHash, options),\n reset: () => {\n clearCartGuestToken()\n store.reset()\n },\n expireCart: () => {\n clearCartGuestToken()\n store.expireCart()\n },\n }\n}\n","/**\n * `ttf` — the facade. A domain-grouped, configured view over the raw `api/`\n * calls, so app code reads like the sentence it is:\n *\n * await ttf.auth.login(email, password)\n * const tickets = await ttf.events.tickets(eventId)\n * await ttf.cart.add(eventId, selections)\n * const review = await ttf.order.review(hash)\n * await ttf.payment.prepareOxxo(hash)\n *\n * It adds no logic of its own — every method IS the api function. One place to\n * discover the whole surface; one name to import.\n */\nimport * as auth from './api/auth'\nimport * as cart from './api/cart'\nimport * as confirmation from './api/confirmation'\nimport * as delegation from './api/delegation'\nimport * as engagement from './api/engagement'\nimport * as events from './api/events'\nimport * as geo from './api/geo'\nimport * as order from './api/order'\nimport * as orders from './api/orders'\nimport * as payment from './api/payment'\nimport * as preRegistration from './api/preRegistration'\nimport * as profile from './api/profile'\nimport * as resale from './api/resale'\nimport * as seatmap from './api/seatmap'\n\nexport const ttf = {\n auth: {\n login: auth.login,\n register: auth.register,\n registerAccount: auth.registerAccount,\n logout: auth.logout,\n restorePassword: auth.restorePassword,\n restorePasswordRn: auth.restorePasswordRn,\n resetPassword: auth.resetPassword,\n checkEmailExists: auth.checkEmailExists,\n // Account identity verification (Netverify/Jumio)\n mintVerificationUrl: auth.mintVerificationUrl,\n getVerificationInfo: auth.getVerificationInfo,\n updateVerificationStatus: auth.updateVerificationStatus,\n },\n profile: {\n get: profile.getProfile,\n },\n geo: {\n countries: geo.getCountries,\n states: geo.getStates,\n },\n\n // --- checkout flow -------------------------------------------------------\n events: {\n tickets: events.getEventTickets,\n ticketsWithMeta: events.getEventTicketsWithMeta,\n info: events.getEventInfo,\n conditions: events.getEventConditions,\n timeSlotTickets: events.getEventTimeSlotTickets,\n customFields: events.getEventCustomFields,\n requiredCustomFieldLabels: events.getRequiredCustomFieldLabels,\n addons: events.getEventAddons,\n filterAddonsForTickets: events.filterAddonsForTickets,\n submitPromoCode: events.submitPromoCode,\n setCurrency: events.setEventCurrency,\n authenticate: events.authenticateEvent,\n track: events.trackEvent,\n updateOrderDataCapture: events.updateOrderDataCapture,\n updateTicketDataCapture: events.updateTicketDataCapture,\n },\n cart: {\n add: cart.addTicketsToCart,\n addSeats: cart.addSeatsToCart,\n get: cart.getCart,\n checkoutConfigs: cart.getCheckoutConfigs,\n price: cart.updateCheckout,\n priceBreakdown: cart.getPriceBreakdown,\n paymentConfig: cart.getPaymentConfigAttributes,\n preOrderMethods: cart.getPreOrderPaymentMethods,\n checkBuyerEmail: cart.checkBuyerEmail,\n },\n order: {\n create: order.createOrder,\n review: order.getOrderReview,\n mapProfileToBilling: order.mapProfileToBilling,\n completeFreeRegistration: order.completeFreeRegistration,\n confirmSuccess: order.confirmOrderSuccess,\n idVerificationStatus: order.getIdVerificationStatus,\n verifyCustomer: order.verifyCustomerOrder,\n },\n payment: {\n changeMethodType: payment.changePaymentMethodType,\n confirmRedirect: payment.confirmRedirect,\n prepareOxxo: payment.prepareForOxxo,\n xenditEWalletCharge: payment.submitXenditEWalletCharge,\n xenditCardCharge: payment.submitXenditCardCharge,\n installmentOffers: payment.getInstallmentOffers,\n confirmInstallments: payment.confirmInstallments,\n createPaymentPlan: payment.createPaymentPlan,\n chargeSavedCardPlan: payment.chargeSavedCardPlan,\n changeMethod: payment.changePaymentMethod,\n paypalForm: payment.getPayPalForm,\n },\n\n // --- account & post-purchase --------------------------------------------\n orders: {\n list: orders.getOrders,\n get: orders.getOrder,\n myTickets: orders.getMyTickets,\n updateOrderCustomFields: orders.updateOrderCustomFields,\n updateTicketHolderCustomFields: orders.updateTicketHolderCustomFields,\n },\n engagement: {\n attributeReferrer: engagement.attributeReferrer,\n joinWaitingList: engagement.joinWaitingList,\n sendRsvp: engagement.sendRsvp,\n validatePhone: engagement.validatePhone,\n },\n resale: {\n sell: resale.sellTicket,\n remove: resale.removeTicketFromResale,\n process: resale.processResale,\n decline: resale.declineResale,\n },\n confirmation: {\n get: confirmation.getConfirmation,\n },\n preRegistration: {\n confirm: preRegistration.confirmPreRegistration,\n influencers: preRegistration.getInfluencers,\n confirmationPage: preRegistration.getConfirmationPage,\n submitShareAction: preRegistration.submitShareAction,\n },\n delegation: {\n checkCustomerExists: delegation.checkCustomerExists,\n consumerPageInfo: delegation.getConsumerPageInfo,\n issueTicket: delegation.issueTicket,\n },\n seatmap: {\n data: seatmap.getSeatMapData,\n statuses: seatmap.getSeatStatuses,\n reserve: seatmap.reserveSeats,\n removeReserved: seatmap.removeReservedSeats,\n refreshReservation: seatmap.refreshReservation,\n },\n} as const\n\nexport type Ttf = typeof ttf\n","/**\n * React hooks over the `ttf` facade — one authored copy, imported unchanged by\n * both platform packages. React and @tanstack/react-query are peer deps, so a\n * consumer supplies its own QueryClientProvider.\n */\nexport * from './auth'\nexport * from './authFlow'\nexport * from './session'\nexport * from './profile'\nexport * from './geo'\nexport * from './events'\nexport * from './orders'\nexport * from './engagement'\nexport * from './checkout'\nexport { ttfKeys } from './keys'\nexport type { QueryOpts, MutationOpts } from './types'\n","/**\n * Auth hooks — React Query mutations over the `ttf.auth` facade. Authored once\n * here; both web and RN import them unchanged. Pass `onSuccess`/`onError` (or\n * any mutation option) through the `options` argument.\n */\nimport { useMutation } from '@tanstack/react-query'\n\nimport { ttf } from '../services'\nimport { AuthRegistrationInput } from '../dtos'\nimport { TfProfile } from '../types'\nimport { MutationOpts } from './types'\n\nexport const useLogin = (\n options?: MutationOpts<TfProfile, { email: string; password: string }>\n) =>\n useMutation({\n mutationFn: ({ email, password }: { email: string; password: string }) =>\n ttf.auth.login(email, password),\n ...options,\n })\n\nexport const useRegister = (\n options?: MutationOpts<TfProfile, Record<string, string | Blob>>\n) => useMutation({ mutationFn: ttf.auth.register, ...options })\n\nexport const useRegisterAccount = (\n options?: MutationOpts<TfProfile, AuthRegistrationInput>\n) => useMutation({ mutationFn: ttf.auth.registerAccount, ...options })\n\nexport const useRestorePassword = (options?: MutationOpts<void, string>) =>\n useMutation({ mutationFn: ttf.auth.restorePassword, ...options })\n\nexport const useRestorePasswordRn = (options?: MutationOpts<void, string>) =>\n useMutation({ mutationFn: ttf.auth.restorePasswordRn, ...options })\n\nexport const useResetPassword = (\n options?: MutationOpts<\n void,\n { token: string; password: string; passwordConfirmation?: string }\n >\n) => useMutation({ mutationFn: ttf.auth.resetPassword, ...options })\n\nexport const useLogout = (options?: MutationOpts<void, void>) =>\n useMutation({ mutationFn: () => ttf.auth.logout(), ...options })\n\nexport const useCheckEmailExists = (\n options?: MutationOpts<{ exists: boolean; error?: string }, string>\n) => useMutation({ mutationFn: ttf.auth.checkEmailExists, ...options })\n","/**\n * Headless authentication flow shared by every platform UI.\n *\n * This owns validation, mutations, profile-cache/session synchronization,\n * errors, success state, and view transitions. Web renders it in a modal;\n * React Native can render the same contract as screens or a native sheet.\n */\nimport { useQueryClient } from '@tanstack/react-query'\nimport { useCallback, useState } from 'react'\n\nimport type {\n AuthFieldErrors,\n AuthFieldName,\n AuthFlowView,\n AuthLoginInput,\n AuthRegistrationInput,\n} from '../dtos'\nimport {\n normalizeAuthEmail,\n validateLoginInput,\n validatePasswordResetEmail,\n validateRegistrationInput,\n} from '../logic'\nimport type { TfProfile } from '../types'\nimport {\n useLogin,\n useLogout,\n useRegisterAccount,\n useRestorePassword,\n useRestorePasswordRn,\n} from './auth'\nimport { ttfKeys } from './keys'\nimport { useAuthSession } from './session'\n\nexport interface UseAuthFlowOptions {\n initialView?: AuthFlowView\n initialEmail?: string\n /** Match the legacy modal's full account form by default. */\n requireRegistrationAddress?: boolean\n /** Web and native use different restore-password routes on the legacy API. */\n passwordResetTransport?: 'web' | 'native'\n /** Extra backend fields for specialized registration links. */\n registrationFields?: Record<string, string>\n onAuthenticated?: (profile: TfProfile) => void\n onLoggedOut?: () => void\n}\n\nexport interface RegistrationSubmitOptions {\n /** Require state only when the selected country actually exposes states. */\n requireState?: boolean\n}\n\nconst messageFrom = (error: unknown, fallback: string): string =>\n error instanceof Error && error.message ? error.message : fallback\n\nexport const useAuthFlow = (options: UseAuthFlowOptions = {}) => {\n const queryClient = useQueryClient()\n const session = useAuthSession()\n const loginMutation = useLogin()\n const registerMutation = useRegisterAccount()\n const restoreMutation = useRestorePassword()\n const restoreNativeMutation = useRestorePasswordRn()\n const logoutMutation = useLogout()\n const [view, setViewState] = useState<AuthFlowView>(options.initialView ?? 'login')\n const [suggestedEmail, setSuggestedEmail] = useState(\n normalizeAuthEmail(options.initialEmail ?? '')\n )\n const [fieldErrors, setFieldErrors] = useState<AuthFieldErrors>({})\n const [error, setError] = useState('')\n const [successMessage, setSuccessMessage] = useState('')\n\n const clearFeedback = useCallback(() => {\n setFieldErrors({})\n setError('')\n setSuccessMessage('')\n loginMutation.reset()\n registerMutation.reset()\n restoreMutation.reset()\n restoreNativeMutation.reset()\n }, [loginMutation, registerMutation, restoreMutation, restoreNativeMutation])\n\n const clearFieldError = useCallback((field: AuthFieldName) => {\n setFieldErrors((current) => {\n if (!current[field]) return current\n const next = { ...current }\n delete next[field]\n return next\n })\n setError('')\n }, [])\n\n const setView = useCallback(\n (next: AuthFlowView, email?: string) => {\n clearFeedback()\n if (email !== undefined) setSuggestedEmail(normalizeAuthEmail(email))\n setViewState(next)\n },\n [clearFeedback]\n )\n\n const showLogin = useCallback((email?: string) => setView('login', email), [setView])\n const showRegister = useCallback(\n (email?: string) => setView('register', email),\n [setView]\n )\n const showForgotPassword = useCallback(\n (email?: string) => setView('forgot-password', email),\n [setView]\n )\n\n const authenticated = useCallback(\n (profile: TfProfile) => {\n queryClient.setQueryData(ttfKeys.profile, profile)\n setSuggestedEmail(normalizeAuthEmail(profile.email))\n clearFeedback()\n options.onAuthenticated?.(profile)\n },\n [clearFeedback, options, queryClient]\n )\n\n const submitLogin = useCallback(\n async (input: AuthLoginInput): Promise<TfProfile | null> => {\n clearFeedback()\n const validation = validateLoginInput(input)\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return null\n }\n try {\n const profile = await loginMutation.mutateAsync({\n email: normalizeAuthEmail(input.email),\n password: input.password,\n })\n authenticated(profile)\n return profile\n } catch (caught) {\n setError(messageFrom(caught, 'Unable to log in. Please try again.'))\n return null\n }\n },\n [authenticated, clearFeedback, loginMutation]\n )\n\n const submitRegistration = useCallback(\n async (\n input: AuthRegistrationInput,\n submitOptions: RegistrationSubmitOptions = {}\n ): Promise<TfProfile | null> => {\n clearFeedback()\n const validation = validateRegistrationInput(input, {\n requireAddress: options.requireRegistrationAddress ?? true,\n requireState: submitOptions.requireState,\n })\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return null\n }\n try {\n const profile = await registerMutation.mutateAsync({\n ...input,\n email: normalizeAuthEmail(input.email),\n registrationFields: options.registrationFields,\n })\n authenticated(profile)\n return profile\n } catch (caught) {\n const message = messageFrom(\n caught,\n 'Unable to create your account. Please try again.'\n )\n setError(message)\n if (/exist|already|registered/i.test(message))\n setFieldErrors({ email: 'This email already has an account.' })\n return null\n }\n },\n [\n authenticated,\n clearFeedback,\n options.registrationFields,\n options.requireRegistrationAddress,\n registerMutation,\n ]\n )\n\n const submitPasswordReset = useCallback(\n async (email: string): Promise<boolean> => {\n clearFeedback()\n const validation = validatePasswordResetEmail(email)\n if (!validation.valid) {\n setFieldErrors(validation.errors)\n return false\n }\n const normalizedEmail = normalizeAuthEmail(email)\n const mutation =\n options.passwordResetTransport === 'native'\n ? restoreNativeMutation\n : restoreMutation\n try {\n await mutation.mutateAsync(normalizedEmail)\n setSuggestedEmail(normalizedEmail)\n setSuccessMessage(\n 'If an account exists for this email, password reset instructions are on the way.'\n )\n return true\n } catch (caught) {\n setError(\n messageFrom(caught, 'Unable to send reset instructions. Please try again.')\n )\n return false\n }\n },\n [\n clearFeedback,\n options.passwordResetTransport,\n restoreMutation,\n restoreNativeMutation,\n ]\n )\n\n const logout = useCallback(async (): Promise<boolean> => {\n clearFeedback()\n try {\n await logoutMutation.mutateAsync()\n queryClient.removeQueries({ queryKey: ttfKeys.profile })\n options.onLoggedOut?.()\n return true\n } catch (caught) {\n // The API always clears local tokens in a finally block, so reflect the\n // logged-out state even if the backend session-close request failed.\n queryClient.removeQueries({ queryKey: ttfKeys.profile })\n setError(messageFrom(caught, 'You have been logged out locally.'))\n options.onLoggedOut?.()\n return true\n }\n }, [clearFeedback, logoutMutation, options, queryClient])\n\n return {\n view,\n suggestedEmail,\n fieldErrors,\n error,\n successMessage,\n isAuthenticated: session.isAuthenticated,\n isSubmitting:\n loginMutation.isPending ||\n registerMutation.isPending ||\n restoreMutation.isPending ||\n restoreNativeMutation.isPending ||\n logoutMutation.isPending,\n showLogin,\n showRegister,\n showForgotPassword,\n clearFeedback,\n clearFieldError,\n submitLogin,\n submitRegistration,\n submitPasswordReset,\n logout,\n mutations: {\n login: loginMutation,\n register: registerMutation,\n restorePassword: restoreMutation,\n restorePasswordNative: restoreNativeMutation,\n logout: logoutMutation,\n },\n }\n}\n\nexport type UseAuthFlow = ReturnType<typeof useAuthFlow>\n","/** React Query cache keys for the SDK, all namespaced under `ttf`. */\nimport { OrdersQuery } from '../api/orders'\n\nexport const ttfKeys = {\n profile: ['ttf', 'profile'] as const,\n countries: ['ttf', 'countries'] as const,\n states: (countryId: string | number) => ['ttf', 'states', countryId] as const,\n event: (eventId: string) => ['ttf', 'event', eventId] as const,\n tickets: (eventId: string) => ['ttf', 'tickets', eventId] as const,\n addons: (eventId: string) => ['ttf', 'addons', eventId] as const,\n orders: (query: OrdersQuery) => ['ttf', 'orders', query] as const,\n order: (orderId: string) => ['ttf', 'order', orderId] as const,\n}\n","/** Reactive authentication state backed by the shared token session. */\nimport { useSyncExternalStore } from 'react'\n\nimport { isAuthenticated, subscribeSession } from '../client'\n\nexport const useAuthSession = (): { isAuthenticated: boolean } => {\n const authenticated = useSyncExternalStore(\n subscribeSession,\n isAuthenticated,\n () => false\n )\n return { isAuthenticated: authenticated }\n}\n","/** Profile hook — the signed-in user's record as a React Query query. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { ttf } from '../services'\nimport { TfProfile } from '../types'\nimport { ttfKeys } from './keys'\nimport { useAuthSession } from './session'\nimport { QueryOpts } from './types'\n\nexport const useProfile = (options?: QueryOpts<TfProfile>) => {\n const session = useAuthSession()\n return useQuery({\n queryKey: ttfKeys.profile,\n queryFn: () => ttf.profile.get(),\n enabled: session.isAuthenticated,\n ...options,\n })\n}\n","/** Geo hooks — countries always, states gated on a chosen country. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { TfCountry, TfState } from '../types'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\nexport const useCountries = (options?: QueryOpts<TfCountry[]>) =>\n useQuery({\n queryKey: ttfKeys.countries,\n queryFn: () => ttf.geo.countries(),\n staleTime: Infinity,\n ...options,\n })\n\nexport const useStates = (\n countryId: string | number | undefined,\n options?: QueryOpts<TfState[]>\n) =>\n useQuery({\n queryKey: ttfKeys.states(countryId ?? ''),\n queryFn: () => ttf.geo.states(countryId as string | number),\n enabled: Boolean(countryId),\n ...options,\n })\n","/** Catalog read hooks — an event's info, purchasable tickets, and add-ons. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport type { EventAddon, TicketType } from '../dtos'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\n/** Event details (seated detection, slug, name). Gated on a chosen event id. */\nexport const useEvent = (\n eventId: string | undefined,\n options?: QueryOpts<Awaited<ReturnType<typeof ttf.events.info>>>\n) =>\n useQuery({\n queryKey: ttfKeys.event(eventId ?? ''),\n queryFn: () => ttf.events.info(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Purchasable ticket types for an event. Gated on a chosen event id. */\nexport const useTickets = (\n eventId: string | undefined,\n options?: QueryOpts<TicketType[]>\n) =>\n useQuery({\n queryKey: ttfKeys.tickets(eventId ?? ''),\n queryFn: () => ttf.events.tickets(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Tickets PLUS the catalog-level promo/access-code metadata and waiting-list\n * flag the same response carries. Use this (over `useTickets`) when the ticket\n * screen needs promo codes, access codes, or waiting lists. `refetch()` after\n * applying a code to pick up updated prices / newly-unlocked tickets. */\nexport const useTicketsWithMeta = (\n eventId: string | undefined,\n options?: QueryOpts<Awaited<ReturnType<typeof ttf.events.ticketsWithMeta>>>\n) =>\n useQuery({\n queryKey: [...ttfKeys.tickets(eventId ?? ''), 'meta'],\n queryFn: () => ttf.events.ticketsWithMeta(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n\n/** Purchasable ticket types for ONE date of a time-slot / calendar event. Each\n * ticket carries its `timeSlot: { date, time }`. Gated on event id + date. */\nexport const useTimeSlotTickets = (\n eventId: string | undefined,\n date: string | undefined,\n options?: QueryOpts<TicketType[]>\n) =>\n useQuery({\n queryKey: [...ttfKeys.tickets(eventId ?? ''), 'slots', date ?? ''],\n queryFn: () => ttf.events.timeSlotTickets(eventId as string, date as string),\n enabled: Boolean(eventId && date),\n ...options,\n })\n\n/** The event's add-on catalog (upsells). Gated on a chosen event id. Filter it\n * to the primed cart with `ttf.events.filterAddonsForTickets(list, ids)`. */\nexport const useEventAddons = (\n eventId: string | undefined,\n options?: QueryOpts<EventAddon[]>\n) =>\n useQuery({\n queryKey: ttfKeys.addons(eventId ?? ''),\n queryFn: () => ttf.events.addons(eventId as string),\n enabled: Boolean(eventId),\n ...options,\n })\n","/** Order-history hooks — the buyer's list and one order's detail. */\nimport { useQuery } from '@tanstack/react-query'\n\nimport { OrdersQuery, TfOrderDetails, TfOrderSummary } from '../api/orders'\nimport { TfEnvelope, TfListEnvelope } from '../types'\nimport { ttf } from '../services'\nimport { ttfKeys } from './keys'\nimport { QueryOpts } from './types'\n\nexport const useOrders = (\n query: OrdersQuery = {},\n options?: QueryOpts<TfListEnvelope<TfOrderSummary>>\n) =>\n useQuery({\n queryKey: ttfKeys.orders(query),\n queryFn: () => ttf.orders.list(query),\n ...options,\n })\n\nexport const useOrder = (\n orderId: string | undefined,\n options?: QueryOpts<TfEnvelope<TfOrderDetails>>\n) =>\n useQuery({\n queryKey: ttfKeys.order(orderId ?? ''),\n queryFn: () => ttf.orders.get(orderId as string),\n enabled: Boolean(orderId),\n ...options,\n })\n","/** Engagement hooks — phone validation, waiting list, referral, RSVP. */\nimport { useMutation } from '@tanstack/react-query'\n\nimport { WaitingListEntry } from '../api/engagement'\nimport { ttf } from '../services'\nimport { MutationOpts } from './types'\n\nexport const useValidatePhone = (\n options?: MutationOpts<{ valid: boolean; [key: string]: unknown }, string>\n) => useMutation({ mutationFn: ttf.engagement.validatePhone, ...options })\n\nexport const useJoinWaitingList = (\n eventId: string,\n options?: MutationOpts<void, WaitingListEntry>\n) =>\n useMutation({\n mutationFn: (entry: WaitingListEntry) =>\n ttf.engagement.joinWaitingList(eventId, entry),\n ...options,\n })\n\nexport const useAttributeReferrer = (\n eventId: string,\n options?: MutationOpts<void, string | number | null>\n) =>\n useMutation({\n mutationFn: (referrer: string | number | null) =>\n ttf.engagement.attributeReferrer(eventId, referrer),\n ...options,\n })\n\nexport const useSendRsvp = (\n eventId: string,\n options?: MutationOpts<unknown, Record<string, unknown>>\n) =>\n useMutation({\n mutationFn: (data: Record<string, unknown>) => ttf.engagement.sendRsvp(eventId, data),\n ...options,\n })\n","/**\n * `useCheckout()` — the engine's React binding, with the shared DX every\n * platform wants baked in ONCE here (not re-written per platform):\n * - the snapshot is spread flat (`checkout.status`, `checkout.breakdown`, …)\n * - a reservation countdown (`secondsLeft`) and an `isBusy` flag\n * - `missingRequiredAddonNames`, `isLoggedIn`\n * - promo / referrer / waiting-list helpers over `ttf`\n * - `placeOrder(method, { autoRunIdVerification })`\n *\n * A platform lib only injects its `ports` (Stripe confirmer, provider page, …)\n * — it does NOT re-implement any of the above. Non-React apps use\n * `createEngine()` + `store.subscribe` directly.\n */\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'\n\nimport type {\n CheckoutSnapshot,\n PlaceOrderResult,\n SeatLine,\n TicketSelection,\n WaitingListEntry,\n} from '../dtos'\nimport {\n createCheckoutStore,\n createEngine,\n type CheckoutEngine,\n type CheckoutStore,\n type EngineConfig,\n type PaymentMethod,\n type PaymentRequest,\n type RunIdVerificationOptions,\n} from '../engine'\nimport { missingRequiredAddOns } from '../logic'\nimport { ttf } from '../services'\nimport { useAuthSession } from './session'\n\nexport interface PlaceOrderHookOptions {\n /** After a successful order needing ID verification, run it automatically\n * (mint + open + poll). The rejection is swallowed — payment already\n * settled — so it never surfaces as a payment failure. Uses the engine's\n * `openUrl` port to open the provider URL. */\n autoRunIdVerification?: boolean\n idVerification?: RunIdVerificationOptions\n}\n\n/**\n * A gated buyer field this event asks for BEYOND name/email — surfaced from the\n * server's checkout-configs so consumers render exactly what's needed instead of\n * guessing. Write the captured value straight to `billing[key]` (e.g.\n * `setBilling({ ...billing, instagramHandle })`); the engine forwards it in the\n * order body. `nationality` expects a country id (see `ttf.geo.countries()` /\n * `useCountries()`); `gender` expects `'M'` | `'F'`.\n */\nexport interface BuyerFieldSpec {\n key: 'nationality' | 'gender' | 'instagramHandle'\n label: string\n required: boolean\n /** How to render it: a country picker, an M/F choice, or a handle text box. */\n kind: 'nationality' | 'gender' | 'instagram'\n}\n\nexport interface UseCheckout extends CheckoutSnapshot {\n /** The whole snapshot object (the fields above are spread from it). */\n snapshot: CheckoutSnapshot\n /** True while a cart/order operation is in flight. */\n isBusy: boolean\n /** Whole-seconds countdown for the cart reservation (undefined when none).\n * Raw on purpose — format it however your UI wants. */\n secondsLeft?: number\n /** Required add-on names still missing (same rule the pre-flight enforces). */\n missingRequiredAddonNames: string[]\n /** Gated buyer fields this event needs beyond name/email (Instagram /\n * nationality / gender), each with its required flag — render these from\n * data. Empty when the event gates none. Pairs with `customFields` (the\n * order/ticket capture groups) for the full \"what must I collect\" picture. */\n buyerFields: BuyerFieldSpec[]\n /** Whether a signed-in access token is present. */\n isLoggedIn: boolean\n\n /** Build + price the cart for a ticket selection (alias for `prime`). */\n setTickets: (eventId: string, selections: TicketSelection[]) => Promise<void>\n /** Build + price the cart for reserved SEATS (alias for `primeSeats`). */\n setSeats: (eventId: string, lines: SeatLine[]) => Promise<void>\n /** Attach to an existing server-side cart (e.g. accepted resale invitation). */\n resumeCart: CheckoutEngine['resumeCart']\n setAddons: CheckoutEngine['setAddons']\n setBilling: CheckoutEngine['setBilling']\n setHolders: CheckoutEngine['setHolders']\n setConsent: CheckoutEngine['setConsent']\n setAcceptedConditions: CheckoutEngine['setAcceptedConditions']\n /** Accept/unaccept one condition block (merges into the map). */\n acceptCondition: (id: string, accepted: boolean) => void\n setAddonDataCapture: CheckoutEngine['setAddonDataCapture']\n checkBuyerEmail: CheckoutEngine['checkBuyerEmail']\n placeOrder: (\n method?: PaymentMethod | PaymentRequest,\n options?: PlaceOrderHookOptions\n ) => Promise<PlaceOrderResult>\n runIdVerification: CheckoutEngine['runIdVerification']\n syncCurrency: CheckoutEngine['syncCurrency']\n reset: CheckoutEngine['reset']\n applyPromoCode: (eventId: string, promo: string) => Promise<void>\n attributeReferrer: (eventId: string, referrer: string | number | null) => Promise<void>\n joinWaitingList: (eventId: string, entry: WaitingListEntry) => Promise<void>\n}\n\n// ONE app-wide checkout store. Every useCheckout() call — SignIn, Tickets, Pay,\n// each component mounting on its own — must read and write the SAME cart, with\n// no Context and no prop-drilling. Per-component engines all bind this single\n// store below. Without it, each component would get its own store: the step\n// that primes would flip ITS status to 'ready' while the step doing the gating\n// reads a different store still 'idle', so the pay UI silently never appears.\n// (Callers can still pass an explicit `config.store` to opt out.)\nlet sharedStore: CheckoutStore | null = null\n\nexport const useCheckout = (config: EngineConfig): UseCheckout => {\n const authSession = useAuthSession()\n // Create the engine exactly once — its store, subscribe, and actions must be\n // stable references for useSyncExternalStore and consumers' effects. The store\n // it binds is the app-wide singleton (unless the caller supplied their own),\n // so every useCheckout() across the tree shares one cart.\n const engineRef = useRef<CheckoutEngine | null>(null)\n if (engineRef.current === null) {\n if (sharedStore === null) sharedStore = createCheckoutStore()\n engineRef.current = createEngine({ ...config, store: config.store ?? sharedStore })\n }\n const engine = engineRef.current\n\n const snapshot = useSyncExternalStore(\n engine.subscribe,\n engine.getSnapshot,\n engine.getSnapshot // server snapshot === client (SSR-safe: idle checkout)\n )\n\n const isBusy =\n snapshot.status === 'priming' ||\n snapshot.status === 'repricing' ||\n snapshot.status === 'placing'\n\n // Whole-seconds countdown for the cart reservation.\n const [now, setNow] = useState(() => Date.now())\n useEffect(() => {\n if (snapshot.expiresAt == null) return\n const t = setInterval(() => setNow(Date.now()), 1000)\n return () => clearInterval(t)\n }, [snapshot.expiresAt])\n const secondsLeft =\n snapshot.expiresAt != null\n ? Math.max(0, Math.round((snapshot.expiresAt - now) / 1000))\n : undefined\n\n // The countdown used to be display-only: it sat at 0:00 while the buyer kept\n // filling in a cart the server had already released, and the truth only\n // surfaced when payment failed. Retire the cart the moment it lapses so\n // consumers can send the buyer back to ticket selection. Never while an order\n // is in flight or already paid — those own the outcome.\n useEffect(() => {\n if (secondsLeft !== 0) return\n if (snapshot.status === 'placing' || snapshot.status === 'succeeded') return\n if (snapshot.status === 'expired') return\n engine.expireCart()\n }, [engine, secondsLeft, snapshot.status])\n\n const missingRequiredAddonNames = missingRequiredAddOns(\n snapshot.requiredAddOns,\n snapshot.addOns\n )\n .map((a) => a.name || '')\n .filter(Boolean)\n\n // The event's gated buyer fields, surfaced render-ready from checkout-configs\n // so consumers stop guessing (this is what caused \"Instagram handle is\n // required\" to fail silently — the gate was in the data, just never shown).\n const gates = snapshot.fieldGates\n const buyerFields: BuyerFieldSpec[] = []\n if (gates.showNationality)\n buyerFields.push({\n key: 'nationality',\n label: 'Nationality',\n required: gates.nationalityRequired,\n kind: 'nationality',\n })\n if (gates.showGender)\n buyerFields.push({\n key: 'gender',\n label: 'Gender',\n required: gates.genderRequired,\n kind: 'gender',\n })\n if (gates.requireInstagram)\n buyerFields.push({\n key: 'instagramHandle',\n label: 'Instagram handle',\n required: true,\n kind: 'instagram',\n })\n\n const isLoggedIn = authSession.isAuthenticated\n\n // The engine's own openUrl port (the platform's) — used to open the provider\n // URL for the opt-in auto-run.\n const openUrl = config.ports.openUrl\n\n const placeOrder = useCallback(\n async (\n method?: PaymentMethod | PaymentRequest,\n options?: PlaceOrderHookOptions\n ): Promise<PlaceOrderResult> => {\n const result = await engine.placeOrder(method)\n if (options?.autoRunIdVerification && result.needIdVerification) {\n try {\n await engine.runIdVerification(result.orderHash, {\n openUrl,\n ...options.idVerification,\n })\n } catch {\n // Verification stall — payment is safe; tickets follow by email.\n }\n }\n return result\n },\n [engine, openUrl]\n )\n\n const setTickets = useCallback(\n (eventId: string, selections: TicketSelection[]) => engine.prime(eventId, selections),\n [engine]\n )\n const setSeats = useCallback(\n (eventId: string, lines: SeatLine[]) => engine.primeSeats(eventId, lines),\n [engine]\n )\n const acceptCondition = useCallback(\n (id: string, accepted: boolean) =>\n engine.setAcceptedConditions({\n ...(snapshot.acceptedConditions ?? {}),\n [id]: accepted,\n }),\n [engine, snapshot.acceptedConditions]\n )\n const applyPromoCode = useCallback(\n (eventId: string, promo: string) => ttf.events.submitPromoCode(eventId, promo),\n []\n )\n const attributeReferrer = useCallback(\n (eventId: string, referrer: string | number | null) =>\n ttf.engagement.attributeReferrer(eventId, referrer),\n []\n )\n const joinWaitingList = useCallback(\n (eventId: string, entry: WaitingListEntry) =>\n ttf.engagement.joinWaitingList(eventId, entry),\n []\n )\n\n return {\n ...snapshot,\n snapshot,\n isBusy,\n secondsLeft,\n missingRequiredAddonNames,\n buyerFields,\n isLoggedIn,\n setTickets,\n setSeats,\n resumeCart: engine.resumeCart,\n setAddons: engine.setAddons,\n setBilling: engine.setBilling,\n setHolders: engine.setHolders,\n setConsent: engine.setConsent,\n setAcceptedConditions: engine.setAcceptedConditions,\n acceptCondition,\n setAddonDataCapture: engine.setAddonDataCapture,\n checkBuyerEmail: engine.checkBuyerEmail,\n placeOrder,\n runIdVerification: engine.runIdVerification,\n syncCurrency: engine.syncCurrency,\n reset: engine.reset,\n applyPromoCode,\n attributeReferrer,\n joinWaitingList,\n }\n}\n","import type { Messages } from '../types'\n\n/**\n * English (UK) — the source of truth.\n *\n * Every key the SDK renders exists here, so a translator's job is to copy this\n * file and translate values; nothing else needs discovering. Other locales may\n * be partial and resolve missing keys through the chain in ../resolve.ts.\n *\n * Keys are namespaced by surface (`auth.`, `billing.`, `tickets.`, …) so a host\n * overriding one area does not have to know the whole catalogue. Values are the\n * strings the components previously hard-coded, moved verbatim — this file is a\n * relocation, not a rewrite, so behaviour is unchanged for anyone who never\n * sets a locale.\n */\nexport const en: Messages = {\n // --- Common ------------------------------------------------------------\n 'common.close': 'Close',\n 'common.dismiss': 'Dismiss',\n 'common.loading': 'Loading',\n 'common.required': 'Required',\n 'common.increase': 'Increase',\n 'common.decrease': 'Decrease',\n 'common.total': 'Total',\n 'common.date': 'Date',\n 'common.event': 'Event',\n 'common.currency': 'Currency',\n\n // --- Auth --------------------------------------------------------------\n 'auth.title': 'Authentication',\n 'auth.changePassword': 'Change Password',\n 'auth.email': 'Email *',\n 'auth.emailPlaceholder': 'Email',\n 'auth.password': 'Password *',\n 'auth.passwordPlaceholder': 'Password',\n 'auth.newPassword': 'New Password *',\n 'auth.confirmPassword': 'Confirm password *',\n 'auth.confirmPasswordPlaceholder': 'Confirm Password',\n 'auth.firstName': 'First name *',\n 'auth.firstNamePlaceholder': 'First Name',\n 'auth.lastName': 'Last name *',\n 'auth.lastNamePlaceholder': 'Last Name',\n 'auth.phone': 'Phone',\n 'auth.streetAddress': 'Street address *',\n 'auth.streetAddressPlaceholder': 'Street Address',\n 'auth.city': 'City *',\n 'auth.cityPlaceholder': 'City',\n 'auth.postcode': 'ZIP / postcode *',\n 'auth.postcodePlaceholder': 'Zip / Postal Code',\n 'auth.state': 'State / Province',\n 'auth.country': 'Country',\n 'auth.selectCountry': 'Select country',\n 'auth.loginSkipAhead': 'Login & skip ahead:',\n\n // --- Billing -----------------------------------------------------------\n 'billing.address': 'Billing address *',\n 'billing.email': 'Email Address *',\n 'billing.firstName': 'First Name *',\n 'billing.lastName': 'Last Name *',\n 'billing.phone': 'Phone *',\n 'billing.cityPlaceholder': 'City *',\n 'billing.streetPlaceholder': 'Street address *',\n 'billing.postcodePlaceholder': 'ZIP / Postcode *',\n 'billing.countryLabel': 'Country',\n 'billing.stateLabel': 'State / region',\n 'billing.socialPlaceholder': '@handle or profile URL',\n 'billing.male': 'Male',\n 'billing.female': 'Female',\n 'billing.ticketHolders': 'Ticket Holders',\n 'billing.emailPlaceholder': 'Email *',\n 'billing.confirmEmailPlaceholder': 'Confirm email *',\n 'billing.holderFirstName': 'First name *',\n 'billing.holderLastName': 'Last name *',\n 'billing.emailMismatch': 'The email addresses do not match.',\n\n // --- Tickets & seats ---------------------------------------------------\n 'tickets.yourTickets': 'Your Tickets',\n 'tickets.selectType': 'Please select a ticket type',\n 'tickets.soldOut': 'Sold out',\n 'tickets.guests': 'Guests',\n 'tickets.reserveTables': 'Reserve tables',\n 'tickets.noSessions': 'No sessions available on this date.',\n\n // --- Payment -----------------------------------------------------------\n 'payment.method': 'Payment method',\n 'payment.useThisCard': 'Use this card',\n 'payment.payInInstallments': 'Pay in installments?',\n 'payment.chooseInstallments': 'Choose installments',\n\n // --- Referral ----------------------------------------------------------\n 'referral.cheaperOrFree': 'Your tickets can be cheaper — or even FREE!',\n 'referral.inviteFriends': 'Invite friends',\n 'referral.howToInvite': 'How do you invite your friends?',\n 'referral.sendThisLink': 'Send them this link:',\n 'referral.howMuchCheaper': 'How much cheaper?',\n\n // --- Checkout body (localization pass) ---------------------------------\n 'common.submit': 'Submit',\n 'common.each': 'each',\n 'billing.heading': 'Billing Information',\n 'billing.continueToPayment': 'Continue to payment',\n 'billing.ttfOptIn': 'Keep me updated about future events from The Ticket Fairy',\n 'billing.fieldRequired': 'This field is required.',\n 'billing.firstNamePlaceholder': 'First name *',\n 'billing.lastNamePlaceholder': 'Last name *',\n 'billing.emailMustMatch': 'Email addresses must match.',\n 'billing.emailInvalid': 'Enter a valid email address.',\n 'billing.emailRegistered': 'This email is already registered.',\n 'billing.loginAutofill': 'Log in to autofill your details',\n 'billing.loginAutofillPlain': 'Log in to autofill your details.',\n 'billing.firstNameRequired': 'First name is required.',\n 'billing.lastNameRequired': 'Last name is required.',\n 'billing.streetRequired': 'Street address is required.',\n 'billing.cityRequired': 'City is required.',\n 'billing.postcodeRequired': 'ZIP / postcode is required.',\n 'billing.countryRequired': 'Country is required.',\n 'billing.stateRequired': 'State / county is required.',\n 'billing.countryEmpty': '— country * —',\n 'billing.stateEmpty': '— state / county —',\n 'billing.stateEmptyRequired': '— state / county * —',\n 'billing.holderTitle': 'Ticket {{number}}',\n 'billing.nationality': 'Nationality',\n 'billing.gender': 'Gender',\n 'billing.instagramHandle': 'Instagram handle',\n 'billing.phoneOptional': 'Phone',\n 'billing.phoneAria': 'Phone',\n 'billing.phoneInvalid': 'Enter a valid phone number.',\n 'billing.phonePlaceholder': 'Phone number',\n 'billing.dob': 'Date of birth *',\n 'billing.dobWithAge': 'Date of birth * (must be {{age}}+)',\n 'billing.dobRequired': 'Date of birth is required.',\n 'billing.ageMinimum': 'You must be {{age}} or older.',\n 'billing.privacyAgree': 'I have read and agree to {{brand}}',\n 'billing.privacyLink': 'Privacy Policy.',\n 'tickets.getTickets': 'Get tickets',\n 'tickets.selectOnMap': 'Select on map',\n 'tickets.selectSeats': 'Select seats',\n 'tickets.hideInfo': 'Hide info',\n 'tickets.viewInfo': 'View info',\n 'tickets.salesNotStarted': 'Sales not started',\n 'tickets.salesEnded': 'Sales Ended',\n 'tickets.accessCode': 'Access code',\n 'tickets.promoCode': 'Promo code',\n 'tickets.reserving': 'Reserving…',\n 'addons.eyebrow': 'Get Your Tickets',\n 'addons.heading': 'UPGRADES & ADD-ONS',\n 'addons.confirmSelection': 'CONFIRM SELECTION',\n 'addons.updating': 'Updating…',\n 'payment.title': 'Payment',\n 'payment.card': 'Card',\n 'payment.paymentPlan': 'Payment plan',\n 'payment.oxxo': 'OXXO (pay in cash)',\n 'payment.submitPayment': 'Submit Payment',\n 'payment.completeRegistration': 'Complete Registration',\n 'payment.placing': 'Placing…',\n 'payment.testCard': 'Test card: 4242 4242 4242 4242 · any future date · any CVC',\n 'payment.testCardXendit': 'Test card: 4000 0000 0000 0002 · any future date · any CVC',\n 'confirmation.pending': 'Payment pending',\n 'confirmation.confirmed': 'Your Tickets are Confirmed!',\n 'confirmation.pendingBody': 'We’ll email your tickets as soon as the payment settles.',\n 'confirmation.alreadyPaid': 'This order was already paid — nothing was charged again.',\n 'confirmation.available': 'Your tickets are available in the My Tickets section — please bring them with you to the event.',\n 'referral.copied': 'Copied!',\n 'referral.copyLink': 'Copy link',\n 'timer.completePurchase': 'Please complete your purchase before the timer reaches zero.',\n 'auth.logIn': 'Log in',\n 'auth.signUp': 'Sign Up',\n 'auth.passwordReset': 'Password reset',\n 'auth.backToLogin': 'Back to log in',\n 'auth.sendResetInstructions': 'Send reset instructions',\n 'auth.createAccount': 'Create Account',\n 'auth.forgotPassword': 'Forgot password?',\n 'auth.forgotIntro': 'Enter your email and we’ll send you instructions to reset your password.',\n 'auth.missingToken': 'This password-reset link is missing its token.',\n 'auth.passwordTooShort': 'Password must have at least 8 characters.',\n 'auth.passwordNeedsSpecial': 'Password must contain at least one special character.',\n 'auth.passwordsMustMatch': 'Passwords must match.',\n 'auth.passwordChanged': 'Your password has been changed. You can now log in.',\n 'auth.selectState': 'Select state / region',\n 'auth.notRequired': 'Not required',\n}\n","import { en } from './locales/en'\nimport type { LocaleCode, Messages, Translate, TranslatorOptions } from './types'\n\n/**\n * Locale bundles the SDK ships. English is the source of truth: every key\n * exists here, and every other locale is allowed to be partial.\n */\nconst CATALOGUES: Partial<Record<LocaleCode, Messages>> = { 'en-GB': en }\n\n/** Register a locale bundle. Used by ./locales/index to avoid a load cycle. */\nexport const registerCatalogue = (locale: LocaleCode, messages: Messages): void => {\n CATALOGUES[locale] = messages\n}\n\nexport const DEFAULT_LOCALE: LocaleCode = 'en-GB'\n\n/**\n * Per-locale fallback chains.\n *\n * en-US is an override-only layer (American spellings), so it MUST resolve\n * through en-GB rather than standing alone — the same structure the storefront\n * and the legacy platform use.\n */\nconst FALLBACKS: Record<LocaleCode, LocaleCode[]> = {\n 'en-GB': [],\n 'en-US': ['en-GB'],\n 'es-MX': ['en-GB'],\n fr: ['en-GB'],\n de: ['en-GB'],\n ru: ['en-GB'],\n id: ['en-GB'],\n}\n\n/** Map a raw device/browser language onto a locale we ship. */\nexport const resolveLocale = (raw?: string | null): LocaleCode => {\n if (!raw) return DEFAULT_LOCALE\n const lower = raw.toLowerCase()\n const base = lower.split('-')[0]\n\n if (base === 'en') return lower === 'en-us' ? 'en-US' : 'en-GB'\n if (base === 'es') return 'es-MX'\n if (base === 'fr' || base === 'de' || base === 'ru' || base === 'id') return base as LocaleCode\n return DEFAULT_LOCALE\n}\n\nconst INTERPOLATE = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g\n\n/**\n * Build a translator.\n *\n * Resolution order: host overrides -> requested locale -> its fallback chain\n * -> English -> the key itself. The last step means a missing string surfaces\n * as a visible key rather than an empty element, which is far easier to spot\n * in review than a silent blank.\n */\nexport const createTranslator = (options: TranslatorOptions = {}): Translate => {\n const locale = options.locale && FALLBACKS[options.locale] ? options.locale : DEFAULT_LOCALE\n const chain: Messages[] = []\n\n if (options.messages) chain.push(options.messages as Messages)\n const primary = CATALOGUES[locale]\n if (primary) chain.push(primary)\n for (const next of FALLBACKS[locale]) {\n const fallback = CATALOGUES[next]\n if (fallback) chain.push(fallback)\n }\n if (!chain.includes(en)) chain.push(en)\n\n return (key, vars) => {\n let template: string | undefined\n for (const source of chain) {\n const hit = source[key]\n if (typeof hit === 'string' && hit.length > 0) {\n template = hit\n break\n }\n }\n if (template === undefined) return key\n if (!vars) return template\n\n return template.replace(INTERPOLATE, (whole, name: string) => {\n const value = vars[name]\n return value === undefined || value === null ? whole : String(value)\n })\n }\n}\n","import type { Messages } from '../types'\n\n/**\n * Spanish (Mexico).\n *\n * Partial catalogues are legal — anything absent resolves through en-GB — but\n * this one is complete against ./en.ts so the checkout reads fully Spanish for\n * the storefronts that need it today.\n */\nexport const esMX: Messages = {\n // --- Common ------------------------------------------------------------\n 'common.close': 'Cerrar',\n 'common.dismiss': 'Descartar',\n 'common.loading': 'Cargando',\n 'common.required': 'Obligatorio',\n 'common.increase': 'Aumentar',\n 'common.decrease': 'Disminuir',\n 'common.total': 'Total',\n 'common.date': 'Fecha',\n 'common.event': 'Evento',\n 'common.currency': 'Moneda',\n\n // --- Auth --------------------------------------------------------------\n 'auth.title': 'Autenticación',\n 'auth.changePassword': 'Cambiar contraseña',\n 'auth.email': 'Correo electrónico *',\n 'auth.emailPlaceholder': 'Correo electrónico',\n 'auth.password': 'Contraseña *',\n 'auth.passwordPlaceholder': 'Contraseña',\n 'auth.newPassword': 'Nueva contraseña *',\n 'auth.confirmPassword': 'Confirma la contraseña *',\n 'auth.confirmPasswordPlaceholder': 'Confirma la contraseña',\n 'auth.firstName': 'Nombre *',\n 'auth.firstNamePlaceholder': 'Nombre',\n 'auth.lastName': 'Apellido *',\n 'auth.lastNamePlaceholder': 'Apellido',\n 'auth.phone': 'Teléfono',\n 'auth.streetAddress': 'Calle y número *',\n 'auth.streetAddressPlaceholder': 'Calle y número',\n 'auth.city': 'Ciudad *',\n 'auth.cityPlaceholder': 'Ciudad',\n 'auth.postcode': 'Código postal *',\n 'auth.postcodePlaceholder': 'Código postal',\n 'auth.state': 'Estado / Provincia',\n 'auth.country': 'País',\n 'auth.selectCountry': 'Selecciona un país',\n 'auth.loginSkipAhead': 'Inicia sesión y avanza más rápido:',\n\n // --- Billing -----------------------------------------------------------\n 'billing.address': 'Dirección de facturación *',\n 'billing.email': 'Correo electrónico *',\n 'billing.firstName': 'Nombre *',\n 'billing.lastName': 'Apellido *',\n 'billing.phone': 'Teléfono *',\n 'billing.cityPlaceholder': 'Ciudad *',\n 'billing.streetPlaceholder': 'Calle y número *',\n 'billing.postcodePlaceholder': 'Código postal *',\n 'billing.countryLabel': 'País',\n 'billing.stateLabel': 'Estado / región',\n 'billing.socialPlaceholder': '@usuario o URL del perfil',\n 'billing.male': 'Hombre',\n 'billing.female': 'Mujer',\n 'billing.ticketHolders': 'Titulares de los boletos',\n 'billing.emailPlaceholder': 'Correo electrónico *',\n 'billing.confirmEmailPlaceholder': 'Confirma tu correo *',\n 'billing.holderFirstName': 'Nombre *',\n 'billing.holderLastName': 'Apellido *',\n 'billing.emailMismatch': 'Los correos electrónicos no coinciden.',\n\n // --- Tickets & seats ---------------------------------------------------\n 'tickets.yourTickets': 'Tus boletos',\n 'tickets.selectType': 'Selecciona un tipo de boleto',\n 'tickets.soldOut': 'Agotado',\n 'tickets.guests': 'Invitados',\n 'tickets.reserveTables': 'Reservar mesas',\n 'tickets.noSessions': 'No hay funciones disponibles en esta fecha.',\n\n // --- Payment -----------------------------------------------------------\n 'payment.method': 'Método de pago',\n 'payment.useThisCard': 'Usar esta tarjeta',\n 'payment.payInInstallments': '¿Pagar a plazos?',\n 'payment.chooseInstallments': 'Elegir plazos',\n\n // --- Referral ----------------------------------------------------------\n 'referral.cheaperOrFree': 'Tus boletos pueden costar menos, ¡o incluso ser GRATIS!',\n 'referral.inviteFriends': 'Invita a tus amigos',\n 'referral.howToInvite': '¿Cómo invitas a tus amigos?',\n 'referral.sendThisLink': 'Envíales este enlace:',\n 'referral.howMuchCheaper': '¿Cuánto más barato?',\n\n // --- Checkout body (localization pass) ---------------------------------\n 'common.submit': 'Enviar',\n 'common.each': 'c/u',\n 'billing.heading': 'Información de facturación',\n 'billing.continueToPayment': 'Continuar al pago',\n 'billing.ttfOptIn': 'Quiero recibir novedades sobre próximos eventos de The Ticket Fairy',\n 'billing.fieldRequired': 'Este campo es obligatorio.',\n 'billing.firstNamePlaceholder': 'Nombre *',\n 'billing.lastNamePlaceholder': 'Apellido *',\n 'billing.emailMustMatch': 'Los correos electrónicos deben coincidir.',\n 'billing.emailInvalid': 'Ingresa un correo electrónico válido.',\n 'billing.emailRegistered': 'Este correo ya está registrado.',\n 'billing.loginAutofill': 'Inicia sesión para completar tus datos',\n 'billing.loginAutofillPlain': 'Inicia sesión para completar tus datos.',\n 'billing.firstNameRequired': 'El nombre es obligatorio.',\n 'billing.lastNameRequired': 'El apellido es obligatorio.',\n 'billing.streetRequired': 'La calle y número son obligatorios.',\n 'billing.cityRequired': 'La ciudad es obligatoria.',\n 'billing.postcodeRequired': 'El código postal es obligatorio.',\n 'billing.countryRequired': 'El país es obligatorio.',\n 'billing.stateRequired': 'El estado es obligatorio.',\n 'billing.countryEmpty': '— país * —',\n 'billing.stateEmpty': '— estado —',\n 'billing.stateEmptyRequired': '— estado * —',\n 'billing.holderTitle': 'Boleto {{number}}',\n 'billing.nationality': 'Nacionalidad',\n 'billing.gender': 'Género',\n 'billing.instagramHandle': 'Usuario de Instagram',\n 'billing.phoneOptional': 'Teléfono',\n 'billing.phoneAria': 'Teléfono',\n 'billing.phoneInvalid': 'Ingresa un número de teléfono válido.',\n 'billing.phonePlaceholder': 'Número de teléfono',\n 'billing.dob': 'Fecha de nacimiento *',\n 'billing.dobWithAge': 'Fecha de nacimiento * (debes tener {{age}}+)',\n 'billing.dobRequired': 'La fecha de nacimiento es obligatoria.',\n 'billing.ageMinimum': 'Debes tener {{age}} años o más.',\n 'billing.privacyAgree': 'He leído y acepto el',\n 'billing.privacyLink': 'Aviso de Privacidad.',\n 'tickets.getTickets': 'Comprar boletos',\n 'tickets.selectOnMap': 'Seleccionar en el mapa',\n 'tickets.selectSeats': 'Seleccionar asientos',\n 'tickets.hideInfo': 'Ocultar información',\n 'tickets.viewInfo': 'Ver información',\n 'tickets.salesNotStarted': 'Venta no iniciada',\n 'tickets.salesEnded': 'Venta finalizada',\n 'tickets.accessCode': 'Código de acceso',\n 'tickets.promoCode': 'Código promocional',\n 'tickets.reserving': 'Reservando…',\n 'addons.eyebrow': 'Obtén tus boletos',\n 'addons.heading': 'MEJORAS Y COMPLEMENTOS',\n 'addons.confirmSelection': 'CONFIRMAR SELECCIÓN',\n 'addons.updating': 'Actualizando…',\n 'payment.title': 'Pago',\n 'payment.card': 'Tarjeta',\n 'payment.paymentPlan': 'Plan de pagos',\n 'payment.oxxo': 'OXXO (pago en efectivo)',\n 'payment.submitPayment': 'Pagar',\n 'payment.completeRegistration': 'Completar registro',\n 'payment.placing': 'Procesando…',\n 'payment.testCard': 'Tarjeta de prueba: 4242 4242 4242 4242 · cualquier fecha futura · cualquier CVC',\n 'payment.testCardXendit': 'Tarjeta de prueba: 4000 0000 0000 0002 · cualquier fecha futura · cualquier CVC',\n 'confirmation.pending': 'Pago pendiente',\n 'confirmation.confirmed': '¡Tus boletos están confirmados!',\n 'confirmation.pendingBody': 'Te enviaremos tus boletos por correo en cuanto se acredite el pago.',\n 'confirmation.alreadyPaid': 'Esta orden ya estaba pagada: no se te cobró de nuevo.',\n 'confirmation.available': 'Tus boletos están disponibles en la sección Mis boletos. Recuerda llevarlos contigo al evento.',\n 'referral.copied': '¡Copiado!',\n 'referral.copyLink': 'Copiar enlace',\n 'timer.completePurchase': 'Completa tu compra antes de que el temporizador llegue a cero.',\n 'auth.logIn': 'Iniciar sesión',\n 'auth.signUp': 'Crear cuenta',\n 'auth.passwordReset': 'Restablecer contraseña',\n 'auth.backToLogin': 'Volver a iniciar sesión',\n 'auth.sendResetInstructions': 'Enviar instrucciones',\n 'auth.createAccount': 'Crear cuenta',\n 'auth.forgotPassword': '¿Olvidaste tu contraseña?',\n 'auth.forgotIntro': 'Ingresa tu correo y te enviaremos instrucciones para restablecer tu contraseña.',\n 'auth.missingToken': 'A este enlace de restablecimiento le falta el token.',\n 'auth.passwordTooShort': 'La contraseña debe tener al menos 8 caracteres.',\n 'auth.passwordNeedsSpecial': 'La contraseña debe incluir al menos un carácter especial.',\n 'auth.passwordsMustMatch': 'Las contraseñas deben coincidir.',\n 'auth.passwordChanged': 'Tu contraseña se cambió. Ya puedes iniciar sesión.',\n 'auth.selectState': 'Selecciona estado / región',\n 'auth.notRequired': 'No requerido',\n}\n","import { registerCatalogue } from '../resolve'\nimport { en } from './en'\nimport { esMX } from './es-MX'\n\n/**\n * Registers every bundle the SDK ships.\n *\n * en-GB is registered by ../resolve directly (it is the fallback of last\n * resort and must exist before any lookup). The rest register here.\n *\n * Adding a locale: create ./<code>.ts exporting a Messages object, then\n * register it below. Partial catalogues are fine — missing keys resolve\n * through the fallback chain to English.\n */\nregisterCatalogue('es-MX', esMX)\n\nexport { en, esMX }\n","/**\n * Web (stripe-js) adapter of the SDK's PaymentConfirmer port — the proof that\n * the engine in `tf-checkout-shared` is genuinely platform-free. Bind it via\n * `useCheckout({ ports: { confirmer: webConfirmer, ...webPorts } })` to run the\n * exact same cart → order → charge → finalize sequence React Native runs (same\n * retry-safety invariants, same duplicate-charge guards, same tests).\n *\n * Card payments on the web confirm against a Stripe Element the consumer\n * renders: register it via `confirmer.registerCardElement(element)` before\n * placing the order. Apple Pay is not bound on web yet (the web equivalent is\n * the Payment Request button, a different integration) — `confirmApplePay`\n * throws with a clear message.\n */\nimport {\n loadStripe,\n type Stripe,\n type StripeCardElement,\n type StripeElements,\n} from '@stripe/stripe-js'\nimport type { CheckoutBilling, CheckoutPorts, PaymentConfirmer } from 'tf-checkout-shared'\n\nimport type { WebXenditTokenizer } from './xendit'\n\n/**\n * stripe-js reports PaymentIntent statuses in snake_case; the port's\n * vocabulary is the RN SDK's PascalCase. Normalize so\n * CONFIRMED_INTENT_STATUSES matches on both platforms.\n */\nconst normalizeStatus = (status?: string): string | undefined => {\n if (!status) return undefined\n const map: Record<string, string> = {\n succeeded: 'Succeeded',\n requires_capture: 'RequiresCapture',\n processing: 'Processing',\n requires_payment_method: 'RequiresPaymentMethod',\n requires_confirmation: 'RequiresConfirmation',\n requires_action: 'RequiresAction',\n canceled: 'Canceled',\n }\n return map[status] ?? status\n}\n\nexport interface WebStripeConfirmer extends PaymentConfirmer {\n /** The card Element the consumer rendered — required before confirmCard. */\n registerCardElement(element: StripeCardElement | null): void\n /** The currently registered card Element (null before registration) —\n * the MSI port creates its PaymentMethod from it. */\n getCardElement(): StripeCardElement | null\n /**\n * The Elements GROUP backing a `<StripePaymentElement/>` (deferred mode).\n * This is how the old checkout did wallets: when a Payment Element is\n * registered, `confirmCard` confirms card + Apple Pay + Google Pay through it\n * (`elements.submit()` + `stripe.confirmPayment`), exactly as the old\n * `useStripePayment.processPayment` did. Null when only a bare card is rendered.\n */\n registerPaymentElement(elements: StripeElements | null): void\n getPaymentElement(): StripeElements | null\n /**\n * The live Stripe instance (null before the flow calls init). Elements MUST\n * be created from this instance — stripe-js rejects confirming with an\n * Element born from a different one:\n * `confirmer.getStripe()!.elements().create('card')`.\n */\n getStripe(): Stripe | null\n /** Resolves with the Stripe instance as soon as init() has run — mount UI\n * against this instead of polling getStripe(). */\n whenReady(): Promise<Stripe>\n}\n\nexport const createWebStripeConfirmer = (): WebStripeConfirmer => {\n let stripe: Stripe | null = null\n let initKey: string | null = null\n let cardElement: StripeCardElement | null = null\n let paymentElements: StripeElements | null = null\n let readyResolve: (s: Stripe) => void\n let ready = new Promise<Stripe>((r) => (readyResolve = r))\n\n const requireStripe = (): Stripe => {\n if (!stripe) {\n throw new Error(\n 'Stripe is not initialized — the flow calls confirmer.init() first.'\n )\n }\n return stripe\n }\n\n return {\n registerCardElement: (element) => {\n cardElement = element\n },\n\n getCardElement: () => cardElement,\n\n registerPaymentElement: (elements) => {\n paymentElements = elements\n },\n\n getPaymentElement: () => paymentElements,\n\n getStripe: () => stripe,\n\n whenReady: () => ready,\n\n init: async ({ publishableKey, accountId }) => {\n // Re-init only when the key/account pair changes (events on connected\n // accounts each need their own instance).\n const key = `${publishableKey}:${accountId ?? ''}`\n if (stripe && initKey === key) return\n stripe = await loadStripe(\n publishableKey,\n accountId ? { stripeAccount: accountId } : undefined\n )\n if (!stripe) throw new Error('Failed to load Stripe.js.')\n initKey = key\n readyResolve(stripe)\n // subsequent inits (new key) refresh the promise for late mounts\n ready = Promise.resolve(stripe)\n },\n\n getIntentStatus: async (clientSecret) => {\n const { paymentIntent } = await requireStripe().retrievePaymentIntent(clientSecret)\n return normalizeStatus(paymentIntent?.status)\n },\n\n confirmCard: async (clientSecret, billing: CheckoutBilling) => {\n // Wallet-capable path — the way the OLD checkout confirmed. When a\n // `<StripePaymentElement/>` is mounted, the buyer may have picked card OR\n // Apple/Google Pay INSIDE the widget; a single `elements.submit()` +\n // `stripe.confirmPayment({ elements, clientSecret })` settles whichever it\n // is (`useStripePayment.processPayment`). Billing is left to the element —\n // matching old, and avoiding Stripe's \"collected in both places\" error.\n if (paymentElements) {\n const { error: submitError } = await paymentElements.submit()\n if (submitError) throw new Error(submitError.message || 'Payment failed.')\n const returnUrl =\n window.location.href +\n (window.location.href.includes('?') ? '&' : '?') +\n 'payment_return=true'\n const { error, paymentIntent } = await requireStripe().confirmPayment({\n clientSecret,\n elements: paymentElements,\n confirmParams: { return_url: returnUrl },\n // Card + wallets settle in place; only a redirect method navigates away.\n redirect: 'if_required',\n })\n if (error) throw new Error(error.message || 'Payment failed.')\n return normalizeStatus(paymentIntent?.status)\n }\n\n // Bare-card fallback (no wallets / MSI events): the current CardElement path.\n if (!cardElement) {\n throw new Error(\n 'No card element registered — call confirmer.registerCardElement(element) with the CardElement you rendered.'\n )\n }\n const { error, paymentIntent } = await requireStripe().confirmCardPayment(\n clientSecret,\n {\n payment_method: {\n card: cardElement,\n billing_details: {\n email: billing.email,\n name: `${billing.firstName} ${billing.lastName}`.trim(),\n phone: billing.phone || undefined,\n },\n },\n }\n )\n if (error) throw new Error(error.message || 'Payment failed.')\n return normalizeStatus(paymentIntent?.status)\n },\n\n confirmApplePay: async () => {\n throw new Error(\n 'Apple Pay is not bound on web yet — use the card flow, or bind a Payment Request confirmer.'\n )\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Web bindings of the engine's alternative-rail ports\n// ---------------------------------------------------------------------------\n\nconst stripeBillingDetails = (billing: CheckoutBilling) => ({\n email: billing.email,\n name: `${billing.firstName} ${billing.lastName}`.trim(),\n phone: billing.phone || undefined,\n address: {\n line1: billing.streetAddress || undefined,\n city: billing.city || undefined,\n postal_code: billing.zip || undefined,\n // Stripe wants ISO-2 — CheckoutBilling.countryCode/stateCode carry it when\n // the consumer resolved them (backend countryId/stateId are numeric);\n // providers that require it still collect it on their own page otherwise.\n country: billing.countryCode || undefined,\n state: billing.stateCode || undefined,\n },\n})\n\n/**\n * The web half of the engine's `CheckoutPorts`:\n *\n * - `providerPage` runs the provider in a POPUP and resolves when navigation\n * lands back on `returnUrlPrefix` (same-origin, so the URL is readable);\n * a closed popup resolves as 'dismiss'. Call `placeOrder` from a click\n * handler, or the browser's popup blocker will refuse the window.\n * - `confirmOxxo` / `createCardPaymentMethod` / `createRedirectPaymentMethod`\n * / `handleNextAction` bind the same Stripe legs the RN ports bind.\n *\n * MSI's `onInstallmentOffers` picker stays consumer-supplied (pass it via\n * `placeOrder(request, ports)`).\n */\nexport const createWebPorts = (\n confirmer: WebStripeConfirmer,\n /** The Xendit card tokenizer `<XenditCardInput/>` binds to. When given, the\n * engine tokenizes Xendit cards inline instead of in a popup. */\n xenditTokenizer?: WebXenditTokenizer\n): Omit<CheckoutPorts, 'confirmer'> => {\n const requireStripe = (): Stripe => {\n const stripe = confirmer.getStripe()\n if (!stripe) {\n throw new Error(\n 'Stripe is not initialized — the flow calls confirmer.init() first.'\n )\n }\n return stripe\n }\n\n return {\n ...(xenditTokenizer\n ? {\n tokenizeXenditCard: (params) =>\n xenditTokenizer.tokenize({\n publishableKey: params.publishableKey,\n amount: params.amount,\n billing: {\n firstName: params.billing.firstName,\n lastName: params.billing.lastName,\n email: params.billing.email,\n phone: params.billing.phone,\n },\n onBehalfOf: params.onBehalfOf,\n }),\n }\n : {}),\n\n openUrl: (url: string) => {\n window.open(url, '_blank', 'noopener')\n },\n\n providerPage: ({ uri, html, returnUrlPrefix }) =>\n new Promise((resolve) => {\n const popup = window.open(\n uri ?? '',\n 'tf-checkout-gateway',\n 'width=480,height=720'\n )\n if (!popup) {\n resolve({\n event: 'failed',\n description: 'Please allow pop-ups to continue this payment.',\n })\n return\n }\n\n let settled = false\n let timer = 0\n const settle = (outcome: {\n event: 'success' | 'dismiss' | 'failed'\n returnUrl?: string\n data?: Record<string, unknown>\n description?: string\n }) => {\n if (settled) return\n settled = true\n window.clearInterval(timer)\n window.removeEventListener('message', onMessage)\n if (!popup.closed) popup.close()\n resolve(outcome)\n }\n\n // Data-driven sheets (Razorpay, Xendit card) post lifecycle JSON via\n // ReactNativeWebView.postMessage — the shim below forwards it to this\n // window, same protocol as checkout-v2's WebView onMessage.\n const onMessage = (e: MessageEvent) => {\n if (e.source !== popup) return\n const raw = (e.data as { __tfGatewaySheet?: string } | null)?.__tfGatewaySheet\n if (typeof raw !== 'string') return\n let parsed: {\n event?: string\n razorpay_payment_id?: string\n token?: Record<string, unknown>\n description?: string\n } | null = null\n try {\n parsed = JSON.parse(raw)\n } catch {\n return\n }\n if (!parsed || typeof parsed.event !== 'string') return\n if (parsed.event === 'success') {\n settle({\n event: 'success',\n data: {\n ...(parsed.razorpay_payment_id\n ? { razorpay_payment_id: parsed.razorpay_payment_id }\n : {}),\n ...(parsed.token ? { token: parsed.token } : {}),\n },\n })\n } else if (parsed.event === 'dismiss') {\n settle({ event: 'dismiss' })\n } else if (parsed.event === 'failed') {\n settle({ event: 'failed', description: parsed.description })\n }\n }\n window.addEventListener('message', onMessage)\n\n if (!uri && html) {\n const shim =\n '<script>window.ReactNativeWebView={postMessage:function(m){' +\n \"window.opener&&window.opener.postMessage({__tfGatewaySheet:m},'*')}}</script>\"\n popup.document.open()\n popup.document.write(shim + html)\n popup.document.close()\n }\n\n timer = window.setInterval(() => {\n if (popup.closed) {\n settle({ event: 'dismiss' })\n return\n }\n try {\n const href = popup.location.href\n if (href && href.startsWith(returnUrlPrefix)) {\n settle({ event: 'success', returnUrl: href })\n }\n } catch {\n // Cross-origin while on the provider's page — keep polling.\n }\n }, 500)\n }),\n\n createCardPaymentMethod: async (billing: CheckoutBilling) => {\n const card = confirmer.getCardElement()\n if (!card) {\n throw new Error(\n 'No card element registered — render <CardInput/> before placing the order.'\n )\n }\n const { paymentMethod, error } = await requireStripe().createPaymentMethod({\n type: 'card',\n card,\n billing_details: stripeBillingDetails(billing),\n })\n if (error || !paymentMethod?.id) {\n throw new Error(error?.message || 'Payment failed')\n }\n return paymentMethod.id\n },\n\n createRedirectPaymentMethod: async (methodType: string, billing: CheckoutBilling) => {\n const { paymentMethod, error } = await requireStripe().createPaymentMethod({\n type: methodType,\n billing_details: stripeBillingDetails(billing),\n } as unknown as Parameters<Stripe['createPaymentMethod']>[0])\n // An unknown/unsupported type is the platform saying \"can't express\n // this\" — the engine turns null into a typed UNSUPPORTED_GATEWAY.\n if (error) return null\n return paymentMethod?.id ?? null\n },\n\n handleNextAction: async (clientSecret: string) => {\n const stripe = requireStripe() as Stripe & {\n handleNextAction?: (options: {\n clientSecret: string\n }) => Promise<{ error?: { message?: string } }>\n }\n if (!stripe.handleNextAction) {\n throw new Error('This Stripe.js version cannot run the payment’s next step.')\n }\n const { error } = await stripe.handleNextAction({ clientSecret })\n if (error) throw new Error(error.message || 'Payment failed')\n },\n\n confirmOxxo: async (clientSecret: string, billing: CheckoutBilling) => {\n const { error, paymentIntent } = await requireStripe().confirmOxxoPayment(\n clientSecret,\n { payment_method: { billing_details: stripeBillingDetails(billing) } }\n )\n return {\n error: error?.message,\n // stripe-js reports snake_case next_action — exactly the shape the\n // shared logic's oxxoVoucherFromNextAction parses.\n nextAction: paymentIntent?.next_action as unknown,\n }\n },\n\n // Payment plan (new card): confirm the SetupIntent against the registered\n // CardElement to SAVE the card (nothing charged), returning its\n // PaymentMethod id for the server-side plan.\n confirmPaymentPlanSetup: async (clientSecret: string, billing: CheckoutBilling) => {\n const card = confirmer.getCardElement()\n if (!card) {\n throw new Error(\n 'No card element registered — render <CardInput/> before placing the order.'\n )\n }\n const { setupIntent, error } = await requireStripe().confirmCardSetup(\n clientSecret,\n {\n payment_method: { card, billing_details: stripeBillingDetails(billing) },\n }\n )\n // payment_method is a string id (or an expanded object on some responses).\n const pm = setupIntent?.payment_method\n const paymentMethodId =\n typeof pm === 'string' ? pm : (pm as { id?: string } | null)?.id\n if (error || !paymentMethodId) {\n throw new Error(error?.message || 'Card setup failed')\n }\n return paymentMethodId\n },\n\n // Payment plan (saved-card 3DS): confirm the pending charge against the\n // existing PaymentMethod when the plan comes back requires_action.\n confirmSavedCardPayment: async (clientSecret: string, paymentMethodId: string) => {\n const { error } = await requireStripe().confirmCardPayment(clientSecret, {\n payment_method: paymentMethodId,\n })\n if (error) throw new Error(error.message || 'Payment failed')\n },\n }\n}\n","/**\n * Web (xendit.js) binding for Xendit CARD tokenization — the inline,\n * natively-styled equivalent of the React Native WebView sheet. It loads\n * xendit.js into the page, tokenizes the card the consumer rendered via\n * `<XenditCardInput/>`, and runs the 3DS challenge in a full-screen overlay.\n * The engine charges the returned token server-side.\n *\n * The consumer's app must allow `https://js.xendit.co` in its CSP.\n */\n\nconst XENDIT_JS = 'https://js.xendit.co/v1/xendit.min.js'\n\n/** How long to wait for xendit.js to call our callback even ONCE before giving\n * up. The SDK can stall after its `payer/init` + `fingerprint/scans` warmup\n * without ever POSTing `/v2/credit_card_tokens`; without this the promise\n * never settles and the buyer stares at a blank 3DS overlay forever. */\nconst FIRST_RESPONSE_TIMEOUT_MS = 45_000\n\ninterface XenditToken {\n status: 'VERIFIED' | 'IN_REVIEW' | 'FAILED' | string\n payer_authentication_url?: string\n [k: string]: unknown\n}\n\ninterface XenditGlobal {\n setPublishableKey(key: string): void\n card: {\n createToken(\n data: Record<string, unknown>,\n cb: (err: XenditError | null, token: XenditToken) => void\n ): void\n /** xendit.js ships its own validators — use them so the rules match exactly\n * what `createToken` will accept, instead of re-deriving them here. */\n validateCardNumber(number: string): boolean\n validateExpiry(month: string, year: string): boolean\n validateCvn(cvn: string): boolean\n }\n}\n\n/** Luhn — the fallback used only before xendit.js has finished loading. */\nconst luhn = (digits: string): boolean => {\n let sum = 0\n let double = false\n for (let i = digits.length - 1; i >= 0; i -= 1) {\n let d = digits.charCodeAt(i) - 48\n if (d < 0 || d > 9) return false\n if (double) {\n d *= 2\n if (d > 9) d -= 9\n }\n sum += d\n double = !double\n }\n return sum % 10 === 0\n}\n\nconst xenditGlobal = (): XenditGlobal | undefined =>\n typeof window === 'undefined'\n ? undefined\n : (window as unknown as { Xendit?: XenditGlobal }).Xendit\n\n/**\n * Field-level card checks, matching what `createToken` enforces. Prefers\n * xendit.js's own validators and falls back to equivalent local rules while the\n * script is still loading, so a form can validate on blur from the first\n * keystroke. `expYear` accepts \"YY\" or \"YYYY\".\n */\nexport const xenditCardChecks = {\n number: (value: string): boolean => {\n const digits = value.replace(/\\D/g, '')\n if (digits.length < 12) return false\n const X = xenditGlobal()\n return X?.card?.validateCardNumber\n ? X.card.validateCardNumber(digits)\n : digits.length <= 19 && luhn(digits)\n },\n expiry: (month: string, year: string): boolean => {\n const mm = month.trim()\n const yyyy = year.trim().length === 2 ? `20${year.trim()}` : year.trim()\n if (!/^\\d{1,2}$/.test(mm) || !/^\\d{4}$/.test(yyyy)) return false\n const X = xenditGlobal()\n if (X?.card?.validateExpiry) return X.card.validateExpiry(mm, yyyy)\n const m = Number(mm)\n const y = Number(yyyy)\n if (m < 1 || m > 12) return false\n const now = new Date()\n return y > now.getFullYear() || (y === now.getFullYear() && m >= now.getMonth() + 1)\n },\n cvn: (value: string): boolean => {\n const digits = value.replace(/\\D/g, '')\n const X = xenditGlobal()\n return X?.card?.validateCvn\n ? X.card.validateCvn(digits)\n : digits.length >= 3 && digits.length <= 4\n },\n}\n\n/**\n * Human copy for Xendit's `failure_reason` codes — the same map the hosted PHP\n * checkout shows (`XenditHelper::FAILURE_REASONS`). Without it a decline\n * surfaces as a bare code like `INVALID_CVV`, which means nothing to a buyer.\n */\nexport const XENDIT_FAILURE_REASONS: Record<string, string> = {\n EXPIRED_CARD: 'This card has expired. Please use a different card.',\n ISSUER_SUSPECT_FRAUD:\n 'Your bank declined this card as a suspected fraud risk. Please use a different card.',\n DECLINED_BY_PROCESSOR:\n 'This card was declined by the payment processor. Please use a different card.',\n INSUFFICIENT_BALANCE: 'This card does not have enough balance to complete the payment.',\n STOLEN_CARD: 'This card has been reported lost or stolen.',\n INACTIVE_OR_UNAUTHORIZED_CARD:\n 'This card is inactive, or not authorised for this type of payment.',\n PROCESSOR_ERROR:\n 'The payment could not be processed by your bank. Please try again shortly.',\n INVALID_CVV: 'The security code (CVC) does not match this card.',\n DECLINED_BY_ISSUER: 'Your bank declined this payment. Please use a different card.',\n AUTHENTICATION_FAILED:\n 'Card authentication failed. Please try again or use a different card.',\n ENROLLMENT_STATUS_UNAVAILABLE:\n 'Your bank could not verify this card right now. Please try again or use a different card.',\n DEFAULT: 'Your payment was not accepted. Please try again or use a different card.',\n}\n\n/**\n * Xendit accepts only ASCII + Latin-1 in `card_holder_*` names, and requires a\n * letter first:\n * /^[A-Za-z][\\x20-\\x7EÀ-ÖØ-öø-ÿ]*$/\n * A name with an emoji or non-Latin script (\"Babken 🇦🇲\", \"Բաբկեն\") is rejected\n * with API_VALIDATION_ERROR and the whole payment fails. Strip what Xendit\n * can't take and keep the rest; the group is optional, so a name that reduces\n * to nothing is dropped instead of blocking the buyer.\n */\nconst XENDIT_NAME_BODY = /[^\\x20-\\x7EÀ-ÖØ-öø-ÿ]/g\n\nexport const sanitizeXenditHolderName = (value: string): string => {\n const stripped = (value ?? '').replace(XENDIT_NAME_BODY, '').trim()\n // Must begin with a plain A–Z letter — trim any leading punctuation/digits.\n const fromFirstLetter = stripped.replace(/^[^A-Za-z]+/, '')\n return fromFirstLetter.trim()\n}\n\n/** The error shape xendit.js hands back, including per-field validation rows. */\ninterface XenditError {\n message?: string\n error_code?: string\n errors?: Array<{\n message?: string\n path?: string[]\n context?: { key?: string }\n }>\n}\n\n/** Field key → buyer-facing sentence, for API_VALIDATION_ERROR responses. */\nconst VALIDATION_FIELD_COPY: Record<string, string> = {\n card_number: 'Card number is invalid',\n card_exp_month: 'Card expiry date is invalid',\n card_exp_year: 'Card expiry date is invalid',\n card_cvn: 'Card security code is invalid',\n card_holder_first_name: 'Please check the first name on the card.',\n card_holder_last_name: 'Please check the last name on the card.',\n card_holder_email: 'Please check the email address.',\n card_holder_phone_number: 'Please check the phone number.',\n amount: 'This order could not be charged. Please refresh and try again.',\n}\n\n/**\n * Turn a raw xendit.js error into something a buyer can act on. Xendit's own\n * `message` for a rejected field is \"There was an error with the format\n * submitted to the server\", which says nothing — the useful detail is in\n * `errors[].context.key`.\n */\nexport const describeXenditError = (err: XenditError): string => {\n const first = Array.isArray(err.errors) ? err.errors[0] : undefined\n const key = first?.context?.key ?? first?.path?.[first.path.length - 1]\n if (key && VALIDATION_FIELD_COPY[key]) return VALIDATION_FIELD_COPY[key]\n if (err.error_code && XENDIT_FAILURE_REASONS[err.error_code]) {\n return XENDIT_FAILURE_REASONS[err.error_code]\n }\n // Xendit's generic format message is noise — prefer our own wording.\n if (!err.message || /format submitted to the server/i.test(err.message)) {\n return XENDIT_FAILURE_REASONS.DEFAULT\n }\n return err.message\n}\n\n/** Raw card field values, read at tokenize time (never held in JS state). */\nexport interface XenditCardFields {\n number: string\n /** \"MM\" */\n expMonth: string\n /** \"YY\" or \"YYYY\" — 2-digit is expanded to 20YY. */\n expYear: string\n cvn: string\n}\n\nexport interface WebXenditTokenizer {\n /** `<XenditCardInput/>` registers a getter for its live field values (or\n * null on unmount). */\n registerFields(getFields: (() => XenditCardFields) | null): void\n /** Tokenizes the registered card (running inline 3DS when the bank asks) and\n * resolves with the token the engine charges. Rejects on validation error,\n * decline, or a failed 3DS challenge. */\n tokenize(params: {\n publishableKey: string\n amount: string | number\n billing: { firstName: string; lastName: string; email: string; phone?: string }\n onBehalfOf?: string | null\n }): Promise<Record<string, unknown>>\n}\n\nlet scriptPromise: Promise<XenditGlobal> | null = null\n\nconst loadXendit = (): Promise<XenditGlobal> => {\n if (scriptPromise) return scriptPromise\n scriptPromise = new Promise<XenditGlobal>((resolve, reject) => {\n const w = window as unknown as { Xendit?: XenditGlobal }\n if (w.Xendit) {\n return resolve(w.Xendit)\n }\n const script = document.createElement('script')\n script.src = XENDIT_JS\n script.async = true\n script.onload = () => {\n if (w.Xendit) {\n resolve(w.Xendit)\n } else {\n reject(new Error('The payment service could not be loaded.'))\n }\n }\n script.onerror = () => {\n reject(new Error('The payment service could not be loaded.'))\n }\n document.head.appendChild(script)\n })\n return scriptPromise\n}\n\n/** Warm xendit.js so field validation uses Xendit's own rules immediately. */\nexport const preloadXendit = (): void => {\n void loadXendit().catch(() => {\n // Pre-warming is best-effort; tokenize() surfaces a real load failure.\n })\n}\n\nexport const createWebXenditTokenizer = (): WebXenditTokenizer => {\n let getFields: (() => XenditCardFields) | null = null\n\n /**\n * Full-screen overlay hosting the 3DS challenge iframe. Returns a disposer.\n *\n * The iframe is layered OVER a status strip rather than shown bare: an\n * issuer page that is slow, blank (frictionless auth), or blocked would\n * otherwise leave the buyer staring at a plain white rectangle with no way\n * out — indistinguishable from a crash. `onCancel` gives them that way out.\n */\n const showThreeDs = (url: string, onCancel: () => void): (() => void) => {\n const overlay = document.createElement('div')\n overlay.setAttribute(\n 'style',\n 'position:fixed;inset:0;z-index:2147483647;background:#fff;display:flex;flex-direction:column'\n )\n\n const bar = document.createElement('div')\n bar.setAttribute(\n 'style',\n 'display:flex;align-items:center;gap:12px;padding:12px 16px;border-bottom:1px solid #e7e7f0;font:14px system-ui,sans-serif;color:#16162e;flex:none'\n )\n const status = document.createElement('span')\n status.textContent = 'Verifying with your bank…'\n const cancel = document.createElement('button')\n cancel.type = 'button'\n cancel.textContent = 'Cancel'\n cancel.setAttribute(\n 'style',\n 'margin-left:auto;padding:6px 14px;border:1px solid #e7e7f0;border-radius:8px;background:#fff;font:inherit;cursor:pointer'\n )\n cancel.onclick = () => {\n onCancel()\n }\n bar.append(status, cancel)\n\n const frame = document.createElement('iframe')\n frame.setAttribute('style', 'width:100%;flex:1;border:0')\n // Assigning src is what starts the challenge — it must run unconditionally.\n frame.src = url\n\n overlay.append(bar, frame)\n document.body.appendChild(overlay)\n return () => overlay.remove()\n }\n\n return {\n registerFields: (fn) => {\n getFields = fn\n },\n\n tokenize: async ({ publishableKey, amount, billing, onBehalfOf }) => {\n if (!getFields) {\n throw new Error('Render <XenditCardInput/> before paying with a Xendit card.')\n }\n const f = getFields()\n const number = f.number.replace(/\\s+/g, '')\n const expMonth = f.expMonth.trim()\n let expYear = f.expYear.trim()\n if (expYear.length === 2) expYear = '20' + expYear\n const cvn = f.cvn.trim()\n if (!number || !expMonth || !expYear || !cvn) {\n throw new Error('Please fill in your card details.')\n }\n\n const Xendit = await loadXendit()\n Xendit.setPublishableKey(publishableKey)\n\n // Check the fields with Xendit's own validators before spending a network\n // round trip, so the buyer is told WHICH field is wrong rather than\n // getting a generic decline back from the API.\n if (!xenditCardChecks.number(number)) {\n throw new Error('Card number is invalid')\n }\n if (!xenditCardChecks.expiry(expMonth, expYear)) {\n throw new Error('Card expiry date is invalid')\n }\n if (!xenditCardChecks.cvn(cvn)) {\n throw new Error('Card security code is invalid')\n }\n\n return new Promise<Record<string, unknown>>((resolve, reject) => {\n let dismissThreeDs: (() => void) | null = null\n let settled = false\n let answered = false\n const finish = (fn: () => void) => {\n if (settled) return\n settled = true\n clearTimeout(watchdog)\n dismissThreeDs?.()\n fn()\n }\n\n // xendit.js can complete its `payer/init` + `fingerprint/scans` warmup\n // and then never POST /v2/credit_card_tokens — no callback, no error.\n // Fail loudly instead of hanging on a blank overlay forever.\n const watchdog = setTimeout(() => {\n if (answered) return\n finish(() =>\n reject(\n new Error(\n 'The payment service did not respond. Please try again — if it keeps happening, try a different card or browser.'\n )\n )\n )\n }, FIRST_RESPONSE_TIMEOUT_MS)\n\n // The Xendit SDK re-invokes this handler after the 3DS challenge, so\n // IN_REVIEW then VERIFIED/FAILED all flow through here.\n const handler = (err: XenditError | null, token: XenditToken) => {\n answered = true\n if (err) {\n finish(() => reject(new Error(describeXenditError(err))))\n return\n }\n // A callback with neither an error nor a token would throw on\n // `token.status` INSIDE xendit.js, where the try/catch below can't\n // reach it — leaving the promise permanently unsettled.\n if (!token || typeof token !== 'object') {\n finish(() =>\n reject(new Error('The payment service returned an unexpected response.'))\n )\n return\n }\n if (token.status === 'VERIFIED') {\n finish(() => resolve(token as Record<string, unknown>))\n return\n }\n if (token.status === 'IN_REVIEW' && token.payer_authentication_url) {\n // The buyer now drives the bank's challenge — no fixed deadline.\n clearTimeout(watchdog)\n dismissThreeDs?.()\n dismissThreeDs = showThreeDs(token.payer_authentication_url, () =>\n finish(() => reject(new Error('Payment was cancelled')))\n )\n return\n }\n // Translate Xendit's failure_reason the way the hosted checkout does\n // — a bare code like INVALID_CVV tells the buyer nothing.\n const code =\n typeof token.failure_reason === 'string' ? token.failure_reason : ''\n finish(() =>\n reject(\n new Error(XENDIT_FAILURE_REASONS[code] ?? XENDIT_FAILURE_REASONS.DEFAULT)\n )\n )\n }\n try {\n // card_holder_* fields are ALL-OR-NOTHING peers in Xendit's\n // validation (\"card_holder_first_name missing required peer\n // card_holder_phone_number\" — observed live): send the group only\n // when every field is present, else omit it entirely (it's optional\n // as a whole).\n // …and the names must additionally satisfy Xendit's Latin-only\n // pattern, so strip anything it rejects (emoji, non-Latin scripts).\n const holderFirst = sanitizeXenditHolderName(billing.firstName)\n const holderLast = sanitizeXenditHolderName(billing.lastName)\n const holder =\n holderFirst && holderLast && billing.email && billing.phone\n ? {\n card_holder_first_name: holderFirst,\n card_holder_last_name: holderLast,\n card_holder_email: billing.email,\n card_holder_phone_number: billing.phone,\n }\n : {}\n Xendit.card.createToken(\n {\n amount: String(amount),\n card_number: number,\n card_exp_month: expMonth,\n card_exp_year: expYear,\n card_cvn: cvn,\n is_multiple_use: false,\n should_authenticate: true,\n ...holder,\n ...(onBehalfOf ? { on_behalf_of: onBehalfOf } : {}),\n },\n handler\n )\n } catch (e) {\n finish(() =>\n reject(\n e instanceof Error\n ? e\n : new Error('Something went wrong. Please try again.')\n )\n )\n }\n })\n },\n }\n}\n","/**\n * The package-level web platform instances. Created once at module load\n * (SSR-safe — nothing touches the DOM until `init()` / `tokenize()` run), so the\n * hook and the UI components all bind to the SAME confirmer/tokenizer.\n */\nimport {\n createWebPorts,\n createWebStripeConfirmer,\n type WebStripeConfirmer,\n} from './confirmer'\nimport { createWebXenditTokenizer, type WebXenditTokenizer } from './xendit'\n\n/** The confirmer every `useCheckout`/`<CardInput/>` binds to. */\nexport const webConfirmer: WebStripeConfirmer = createWebStripeConfirmer()\n\n/** The Xendit card tokenizer `<XenditCardInput/>` binds to. */\nexport const webXenditTokenizer: WebXenditTokenizer = createWebXenditTokenizer()\n\n/** The web ports the alternative rails run on: the popup provider page, OXXO /\n * MSI Stripe legs, and inline Xendit tokenization. */\nexport const webPorts = createWebPorts(webConfirmer, webXenditTokenizer)\n","/**\n * Web `useCheckout` — a thin injector: the SDK's `useCheckout` with the web\n * platform ports pre-wired (Stripe confirmer, popup provider page, inline\n * Xendit). ALL the DX (countdown, isBusy, promo/referrer/waiting-list, auto ID\n * verification, the flat snapshot) lives in the SDK's hook, so web and React\n * Native share it — this file only supplies what's browser-specific.\n *\n * configureCheckout({ env: 'PROD', clientId, clientSecret }) // once, at app start\n * const checkout = useCheckout()\n * await checkout.setTickets(eventId, selections)\n * checkout.setBilling(b)\n * await checkout.placeOrder('card') // <CardInput/> rendered\n */\nimport {\n useCheckout as useSharedCheckout,\n type CheckoutOptions,\n type CheckoutPorts,\n type UseCheckout,\n} from 'tf-checkout-shared'\n\nimport { webConfirmer, webPorts } from './instance'\n\nexport interface UseCheckoutOptions {\n /** Extra platform ports merged over the web defaults — e.g. MSI's\n * `onInstallmentOffers` picker. Read once, at first render. */\n ports?: Omit<CheckoutPorts, 'confirmer'>\n /** Wallet/redirect engine options (merchant identity, redirect URL). */\n options?: CheckoutOptions\n}\n\nexport const useCheckout = (opts: UseCheckoutOptions = {}): UseCheckout =>\n useSharedCheckout({\n ports: { confirmer: webConfirmer, ...webPorts, ...opts.ports },\n options: opts.options,\n })\n","/**\n * One-time SDK setup for the web. Wraps the shared `configure()` and defaults\n * the storage adapter to `localStorage` (SSR-safe — no-ops on the server). Call\n * once at app start, before any `useCheckout`/`ttf` call:\n *\n * configureCheckout({ env: 'PROD', clientId, clientSecret })\n */\nimport { configure, type StorageAdapter, type TtfConfig } from 'tf-checkout-shared'\n\nconst isBrowser =\n typeof window !== 'undefined' && typeof window.localStorage !== 'undefined'\n\n/** localStorage-backed token storage. No-ops on the server (SSR). */\nexport const localStorageAdapter: StorageAdapter = {\n getItem: (key) => (isBrowser ? window.localStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (isBrowser) window.localStorage.setItem(key, value)\n },\n removeItem: (key) => {\n if (isBrowser) window.localStorage.removeItem(key)\n },\n}\n\nexport const configureCheckout = (config: TtfConfig): void =>\n configure({ storage: localStorageAdapter, ...config })\n","/**\n * The card fields. `<CardInput/>` mounts a Stripe Element as soon as the engine\n * has initialized Stripe (via the confirmer's `whenReady()` — no races, renders\n * before or after init) and registers it with the confirmer. `<XenditCardInput/>`\n * is the inline, formatted equivalent for Xendit events.\n */\nimport React, { useEffect, useRef, useState, type CSSProperties, type FC } from 'react'\nimport type {\n StripeCardElementOptions,\n StripeElements,\n StripeElementsOptionsMode,\n StripePaymentElementOptions,\n} from '@stripe/stripe-js'\n\nimport { webConfirmer, webXenditTokenizer } from './instance'\nimport { preloadXendit, xenditCardChecks } from './xendit'\n\ntype Field = 'number' | 'expiry' | 'cvc'\n\n/**\n * The Stripe card field. Mounts against the engine's Stripe instance and\n * registers itself with the confirmer; unregisters on unmount.\n *\n * Stripe Elements live in a cross-origin iframe and DON'T inherit page CSS, so\n * by default they render black text — invisible on a dark surface. We read the\n * host element's computed color/font and feed them to the Element so it matches\n * whatever theme the consumer uses, no config needed. Pass `style` to override.\n */\nexport const CardInput: FC<{\n className?: string\n /** Stripe base-style overrides, merged onto the inherited color/font. */\n style?: StripeCardElementOptions['style']\n}> = ({ className, style }) => {\n const hostRef = useRef<HTMLDivElement | null>(null)\n\n useEffect(() => {\n let element: { mount: (el: HTMLElement) => void; unmount: () => void } | null = null\n let cancelled = false\n webConfirmer.whenReady().then((stripe) => {\n if (cancelled || !hostRef.current) return\n const cs = getComputedStyle(hostRef.current)\n const color = cs.color || '#ffffff'\n const fontSize = cs.fontSize && parseFloat(cs.fontSize) > 0 ? cs.fontSize : '16px'\n // Stripe's Element style parser only accepts hex / rgb / rgba / hsl / named\n // colors — NOT color-mix() or CSS vars (it silently drops the whole style,\n // leaving a blank, dead field). Derive a muted placeholder as a plain rgba\n // of the inherited text color.\n const rgb = color.match(/\\d+(?:\\.\\d+)?/g)\n const placeholder =\n rgb && rgb.length >= 3 ? `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, 0.5)` : color\n const card = stripe.elements().create('card', {\n style: {\n ...style,\n base: {\n color,\n fontFamily: cs.fontFamily,\n fontSize,\n iconColor: color,\n '::placeholder': { color: placeholder },\n ...style?.base,\n },\n },\n })\n card.mount(hostRef.current)\n webConfirmer.registerCardElement(card)\n element = card\n })\n return () => {\n cancelled = true\n if (element) {\n webConfirmer.registerCardElement(null)\n element.unmount()\n }\n }\n }, [])\n\n return <div ref={hostRef} className={className} />\n}\n\n/**\n * Build a Stripe Appearance from the live `--tf-checkout-*` tokens on the host\n * element. This is what keeps the Payment Element CONSISTENT with the rest of the\n * checkout: it inherits the same surface / text / accent / border / radius / font\n * a consumer set — via the provider `theme`, their own CSS, or the default\n * light/dark — so retheming the checkout (flat, branded, whatever) reflows the\n * Stripe widget too, instead of it being a generic Stripe `night`/`stripe` box.\n */\nconst checkoutAppearance = (host: HTMLElement) => {\n const cs = getComputedStyle(host)\n const v = (name: string) => cs.getPropertyValue(name).trim() || undefined\n const surface = v('--tf-checkout-surface')\n const text = v('--tf-checkout-text')\n const muted = v('--tf-checkout-muted')\n const border = v('--tf-checkout-border')\n const accent = v('--tf-checkout-accent')\n const danger = v('--tf-checkout-error')\n const font = v('--tf-checkout-font')\n const radius = v('--tf-checkout-radius-control')\n\n // Pick the closest Stripe base theme from the surface luminance, then override\n // its palette with our tokens so it matches exactly.\n const bgRgb = ((surface ?? cs.backgroundColor).match(/\\d+(?:\\.\\d+)?/g) ?? []).map(\n Number\n )\n const isDark =\n bgRgb.length >= 3 &&\n (0.299 * bgRgb[0] + 0.587 * bgRgb[1] + 0.114 * bgRgb[2]) / 255 < 0.5\n\n const variables: Record<string, string> = {}\n const set = (k: string, val?: string) => {\n if (val) variables[k] = val\n }\n set('colorPrimary', accent)\n set('colorBackground', surface)\n set('colorText', text)\n set('colorTextSecondary', muted)\n set('colorTextPlaceholder', muted)\n set('colorDanger', danger)\n set('fontFamily', font)\n set('borderRadius', radius)\n\n const rules: Record<string, Record<string, string>> = {}\n if (border) {\n rules['.Input'] = { border: `1px solid ${border}` }\n rules['.Input:focus'] = {\n border: `1px solid ${accent ?? border}`,\n boxShadow: 'none',\n }\n rules['.Tab'] = { border: `1px solid ${border}` }\n rules['.Block'] = { border: `1px solid ${border}` }\n }\n\n return {\n theme: isDark ? 'night' : 'stripe',\n ...(Object.keys(variables).length ? { variables } : {}),\n ...(Object.keys(rules).length ? { rules } : {}),\n }\n}\n\n/**\n * The wallet-capable card widget — a Stripe **Payment Element** in DEFERRED mode,\n * exactly how the OLD checkout rendered payment. It shows the card fields AND,\n * when the event's `stripe_wallets` gate is on, the Apple Pay / Google Pay\n * buttons that the buyer picks *inside* the widget. There is no separate \"Apple\n * Pay\" method row — wallets are a property of the card widget, as in old.\n *\n * Confirmation rides the same `placeOrder({ method: 'card' })` rail: this mounts\n * the Elements group and registers it with the confirmer, whose `confirmCard`\n * then runs `elements.submit()` + `stripe.confirmPayment` (old\n * `useStripePayment.processPayment`). Mount this instead of `<CardInput/>` for a\n * Stripe event with wallets available — see `<Payment/>`. It needs the server's\n * deferred Elements config (`checkout.stripeElementsConfig`: mode/amount/currency).\n */\nexport const StripePaymentElement: FC<{\n className?: string\n /** Server deferred Elements config from `checkout.stripeElementsConfig`. */\n elementsConfig?: Record<string, unknown>\n /** Wallet gate from `checkout.walletAvailability`. */\n wallets?: { applePay?: boolean; googlePay?: boolean }\n /** Extra Payment Element options, merged over the wallet gate. */\n options?: StripePaymentElementOptions\n}> = ({ className, elementsConfig, wallets, options }) => {\n const hostRef = useRef<HTMLDivElement | null>(null)\n\n // Re-mount when the deferred amount/currency or the wallet gate changes.\n const configKey = JSON.stringify(elementsConfig ?? null)\n const applePay = Boolean(wallets?.applePay)\n const googlePay = Boolean(wallets?.googlePay)\n\n useEffect(() => {\n let group: StripeElements | null = null\n let element: { unmount: () => void } | null = null\n let cancelled = false\n\n webConfirmer.whenReady().then((stripe) => {\n if (cancelled || !hostRef.current) return\n // Deferred mode — the same `{ mode, amount, currency }` shape the old\n // `<Elements options={elements_config}>` used.\n const mode = (elementsConfig ?? {\n mode: 'payment',\n amount: 0,\n currency: 'usd',\n }) as unknown as StripeElementsOptionsMode\n // Theme the widget from the checkout's own tokens (read live off the host)\n // so it matches whatever the consumer set — not a generic Stripe preset.\n // (The server sends `theme:'automatic'`, which isn't a real Stripe theme and\n // just defaults to light — hence the white box on a dark checkout.)\n group = stripe.elements({\n ...mode,\n appearance: checkoutAppearance(hostRef.current),\n } as unknown as StripeElementsOptionsMode)\n const pe = group.create('payment', {\n ...options,\n wallets: {\n applePay: applePay ? 'auto' : 'never',\n googlePay: googlePay ? 'auto' : 'never',\n ...(options?.wallets ?? {}),\n },\n })\n pe.mount(hostRef.current)\n webConfirmer.registerPaymentElement(group)\n element = pe\n })\n\n return () => {\n cancelled = true\n if (element) {\n webConfirmer.registerPaymentElement(null)\n element.unmount()\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [configKey, applePay, googlePay])\n\n return <div ref={hostRef} className={className} />\n}\n\nconst onlyDigits = (v: string) => v.replace(/\\D/g, '')\n/** \"1234567812345678\" → \"1234 5678 1234 5678\" (max 19 digits). */\nconst formatCardNumber = (v: string) =>\n onlyDigits(v)\n .slice(0, 19)\n .replace(/(\\d{4})(?=\\d)/g, '$1 ')\n/**\n * Digits → \"MM/YY\" (max 4 digits), inserting the slash after the month.\n * A leading digit above 1 can only be a single-digit month, so it's expanded\n * (\"4\" → \"04/\"); a two-digit month is clamped to 12. Without this the field\n * happily accepted \"44/44\" and only Xendit ever objected.\n */\nconst formatExpiry = (v: string) => {\n let d = onlyDigits(v).slice(0, 4)\n if (d.length === 1 && Number(d) > 1) d = `0${d}`\n if (d.length >= 2) {\n const mm = Math.min(Math.max(Number(d.slice(0, 2)), 1), 12)\n d = String(mm).padStart(2, '0') + d.slice(2)\n }\n return d.length > 2 ? `${d.slice(0, 2)}/${d.slice(2)}` : d\n}\nconst formatCvc = (v: string) => onlyDigits(v).slice(0, 4)\n\n/**\n * Inline card field for a Xendit event — the formatted, no-popup equivalent of\n * `<CardInput/>`. Render it when the gateway is Xendit and the buyer picks card,\n * then `placeOrder({ method: 'xenditCard' })`: the engine tokenizes these fields\n * with xendit.js (3DS inline) and charges server-side.\n */\nexport const XenditCardInput: FC<{\n className?: string\n inputClassName?: string\n /**\n * Reports the current field-level problem (or null when the fields are fine).\n * The message is deliberately NOT rendered here: this component is mounted\n * inside the consumer's bordered card box, and an error printed in there sits\n * inside the border instead of beneath it. The consumer places it — see\n * `<Payment/>`, which renders it under the box like every other field error.\n */\n onValidationChange?: (message: string | null) => void\n}> = ({ className, inputClassName, onValidationChange }) => {\n const [number, setNumber] = useState('')\n const [expiry, setExpiry] = useState('')\n const [cvc, setCvc] = useState('')\n // Per-field messages, revealed on blur so the buyer isn't scolded mid-typing.\n const [touched, setTouched] = useState<Record<Field, boolean>>({\n number: false,\n expiry: false,\n cvc: false,\n })\n\n const [mm = '', yy = ''] = expiry.split('/')\n const errors: Record<Field, string | null> = {\n number: number && !xenditCardChecks.number(number) ? 'Card number is invalid' : null,\n expiry:\n expiry.length >= 5 && !xenditCardChecks.expiry(mm, yy)\n ? 'Expiry date is invalid'\n : null,\n cvc: cvc && !xenditCardChecks.cvn(cvc) ? 'Security code is invalid' : null,\n }\n const show = (f: Field) => (touched[f] ? errors[f] : null)\n const markTouched = (f: Field) => setTouched((t) => ({ ...t, [f]: true }))\n\n // The tokenizer reads the live values at pay time via this ref (registered\n // once) — no stale closure over state.\n const latest = useRef({ number, expiry, cvc })\n latest.current = { number, expiry, cvc }\n\n useEffect(() => {\n // Warm xendit.js so the checks above use Xendit's own rules from the first\n // blur, not just the local fallback.\n preloadXendit()\n webXenditTokenizer.registerFields(() => {\n const [m = '', y = ''] = latest.current.expiry.split('/')\n return {\n number: latest.current.number,\n expMonth: m.trim(),\n expYear: y.trim(),\n cvn: latest.current.cvc,\n }\n })\n return () => webXenditTokenizer.registerFields(null)\n }, [])\n\n // Borderless inner inputs (unless the consumer styles them) so the three\n // fields read as one card field inside `className`.\n const blend: CSSProperties = inputClassName\n ? {}\n : {\n border: 0,\n background: 'transparent',\n outline: 'none',\n padding: 0,\n color: 'inherit',\n font: 'inherit',\n }\n\n // First message wins. Reported upward (never rendered here) so the consumer\n // can place it below its card box.\n const message = show('number') || show('expiry') || show('cvc')\n\n const reportRef = useRef(onValidationChange)\n reportRef.current = onValidationChange\n useEffect(() => {\n // Re-report on every EDIT, not just when the message text changes. A field\n // that was never blurred has no message of its own, so if the consumer is\n // showing a pay-time failure (\"Card number is invalid\" from the submit\n // attempt) a message-only dependency would never fire again and that error\n // would sit there while the buyer types a perfectly good number.\n //\n // The callback identity is deliberately NOT a dependency — a consumer's\n // inline arrow changes every render and would loop.\n reportRef.current?.(message)\n }, [message, number, expiry, cvc])\n\n return (\n <div\n className={className}\n style={{ display: 'flex', alignItems: 'center', gap: 10 }}\n data-checkout-invalid={message ? 'true' : undefined}\n >\n <input\n className={inputClassName}\n style={{ ...blend, flex: 1, minWidth: 0 }}\n inputMode=\"numeric\"\n autoComplete=\"cc-number\"\n placeholder=\"Card number\"\n aria-invalid={Boolean(show('number'))}\n value={number}\n onChange={(e) => setNumber(formatCardNumber(e.target.value))}\n onBlur={() => markTouched('number')}\n />\n <input\n className={inputClassName}\n style={{ ...blend, width: 64, textAlign: 'center' }}\n inputMode=\"numeric\"\n autoComplete=\"cc-exp\"\n placeholder=\"MM / YY\"\n aria-invalid={Boolean(show('expiry'))}\n value={expiry}\n onChange={(e) => setExpiry(formatExpiry(e.target.value))}\n onBlur={() => markTouched('expiry')}\n />\n <input\n className={inputClassName}\n style={{ ...blend, width: 44, textAlign: 'center' }}\n inputMode=\"numeric\"\n autoComplete=\"cc-csc\"\n placeholder=\"CVC\"\n aria-invalid={Boolean(show('cvc'))}\n value={cvc}\n onChange={(e) => setCvc(formatCvc(e.target.value))}\n onBlur={() => markTouched('cvc')}\n />\n </div>\n )\n}\n","/**\n * `<CheckoutProvider>` — wrap your checkout UI once. It:\n * - provides the checkout to every section via context — so `<Tickets/>`,\n * `<Payment/>`, … just read it, no prop-drilling. By default it runs\n * `useCheckout()` for you (the web-wired engine: Stripe/Xendit + shared\n * store); pass your own instance as `value` to bring your own;\n * - applies the `theme` as `--tf-checkout-*` CSS variables on its root and\n * scopes all styles under `.tf-checkout`.\n *\n * This is the single styling + context boundary shared by all three usage\n * tiers: the batteries-included `<EmbeddedCheckout/>`, à-la-carte sections, and (via\n * `value`) a consumer who already holds a `useCheckout()` of their own.\n *\n * Styles load automatically from the package entry point.\n */\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport type { LocaleCode, Messages, UseCheckout } from 'tf-checkout-shared'\n\nimport { useCheckout } from '../useCheckout'\nimport { cx } from './cx'\nimport { I18nProvider } from './I18nProvider'\nimport { useInstallmentPicker } from './InstallmentPicker'\nimport { themeToVars, type CheckoutTheme } from './theme'\n\nconst CheckoutCtx = createContext<UseCheckout | null>(null)\nconst CheckoutValidationCtx = createContext<{\n attempt: number\n requestValidation: () => void\n} | null>(null)\n\nexport interface CheckoutProviderProps {\n /**\n * Bring your own checkout instance (from a top-level `useCheckout()`). Omit\n * and the provider runs `useCheckout()` itself. Either way the sections read\n * the same shared cart (the engine store is a module singleton).\n */\n value?: UseCheckout\n /** Retheme via design tokens. */\n theme?: CheckoutTheme\n /**\n * Language for the checkout's own copy. Defaults to `en-GB`, so omitting it\n * leaves every existing consumer's rendering byte-for-byte unchanged.\n */\n locale?: LocaleCode\n /**\n * Per-key overrides merged over the locale, for brands that need to reword\n * individual strings without shipping a whole catalogue.\n */\n messages?: Partial<Messages>\n /** Extra class on the `.tf-checkout` root. */\n className?: string\n children: ReactNode\n}\n\n/** The `.tf-checkout` root + context — given a resolved checkout instance. */\nconst CheckoutRoot: FC<{\n checkout: UseCheckout\n theme?: CheckoutTheme\n className?: string\n children: ReactNode\n}> = ({ checkout, theme, className, children }) => {\n const rootRef = useRef<HTMLDivElement | null>(null)\n const [attempt, setAttempt] = useState(0)\n const requestValidation = useCallback(() => setAttempt((current) => current + 1), [])\n\n // Every section marks its own invalid controls. Keeping the navigation here\n // makes validation work for EmbeddedCheckout and for consumers composing the\n // sections themselves.\n useEffect(() => {\n if (attempt === 0) return\n const frame = window.requestAnimationFrame(() => {\n const invalid = rootRef.current?.querySelector<HTMLElement>(\n '[data-checkout-invalid=\"true\"]'\n )\n if (!invalid) return\n const behavior = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n ? 'auto'\n : 'smooth'\n invalid.scrollIntoView({ behavior, block: 'center' })\n const focusTarget = invalid.matches('input, select, textarea, button')\n ? invalid\n : invalid.querySelector<HTMLElement>('input, select, textarea, button')\n focusTarget?.focus({ preventScroll: true })\n })\n return () => window.cancelAnimationFrame(frame)\n }, [attempt])\n\n return (\n <CheckoutCtx.Provider value={checkout}>\n <CheckoutValidationCtx.Provider value={{ attempt, requestValidation }}>\n <div\n ref={rootRef}\n className={cx(\n 'tf-checkout',\n // No colorScheme → auto-follow the OS/browser (prefers-color-scheme).\n // Set it to force one: 'dark' → --dark, 'light' → --light (opt out of auto-dark).\n theme?.colorScheme === 'dark' && 'tf-checkout--dark',\n theme?.colorScheme === 'light' && 'tf-checkout--light',\n className\n )}\n style={themeToVars(theme)}\n >\n {children}\n </div>\n </CheckoutValidationCtx.Provider>\n </CheckoutCtx.Provider>\n )\n}\n\n/** Default path: the provider owns the `useCheckout()` call. Wires the MSI\n * installment picker so Mexican card payments can split into installments. */\nconst SelfProvidedCheckout: FC<Omit<CheckoutProviderProps, 'value'>> = ({\n children,\n ...rest\n}) => {\n const { onInstallmentOffers, picker } = useInstallmentPicker()\n const checkout = useCheckout({ ports: { onInstallmentOffers } })\n return (\n <CheckoutRoot checkout={checkout} {...rest}>\n {children}\n {picker}\n </CheckoutRoot>\n )\n}\n\nexport const CheckoutProvider: FC<CheckoutProviderProps> = ({\n value,\n locale,\n messages,\n ...rest\n}) => (\n // I18n wraps the whole checkout tree so every section can call `useT()`.\n // Outside CheckoutRoot so the translator is in scope for the provider's own\n // children as well as the sections.\n <I18nProvider locale={locale} messages={messages}>\n {\n // `value` present ⇒ don't call `useCheckout()` at all (no second\n // binding); absent ⇒ the self-providing branch owns it. The choice is\n // static per mount, so the two branches never swap and violate the rules\n // of hooks.\n value ? (\n <CheckoutRoot checkout={value} {...rest} />\n ) : (\n <SelfProvidedCheckout {...rest} />\n )\n }\n </I18nProvider>\n)\n\n/** Read the shared checkout inside any component under `<CheckoutProvider>`. */\nexport const useCheckoutContext = (): UseCheckout => {\n const ctx = useContext(CheckoutCtx)\n if (!ctx) {\n throw new Error('useCheckoutContext must be used within <CheckoutProvider>.')\n }\n return ctx\n}\n\n/** Coordinate submit-attempt validation across separately composed sections. */\nexport const useCheckoutValidation = () => {\n const ctx = useContext(CheckoutValidationCtx)\n if (!ctx) {\n throw new Error('useCheckoutValidation must be used within <CheckoutProvider>.')\n }\n return ctx\n}\n","/** Join truthy class names (tiny, dependency-free). */\nexport const cx = (...parts: Array<string | false | null | undefined>): string =>\n parts.filter(Boolean).join(' ')\n","import React, { createContext, useContext, useMemo, type FC, type ReactNode } from 'react'\nimport {\n createTranslator,\n DEFAULT_LOCALE,\n type LocaleCode,\n type Messages,\n type Translate,\n} from 'tf-checkout-shared'\n\n/**\n * React binding for the shared core's translator.\n *\n * The resolution itself lives in `tf-checkout-shared` so native gets the same\n * behaviour; this file only carries it through React context.\n *\n * The default context value is a real English translator, not null, so any\n * component calling `useT()` outside a provider still renders correct copy.\n * That keeps this change backwards compatible: a host that never passes\n * `locale` sees exactly the strings it saw before.\n */\nconst I18nCtx = createContext<Translate>(createTranslator({ locale: DEFAULT_LOCALE }))\n\nexport interface I18nProviderProps {\n locale?: LocaleCode\n /** Per-key overrides, merged over the locale. */\n messages?: Partial<Messages>\n children?: ReactNode\n}\n\nexport const I18nProvider: FC<I18nProviderProps> = ({ locale, messages, children }) => {\n const t = useMemo(() => createTranslator({ locale, messages }), [locale, messages])\n return <I18nCtx.Provider value={t}>{children}</I18nCtx.Provider>\n}\n\n/** Returns the active translator. Safe to call anywhere in the SDK tree. */\nexport const useT = (): Translate => useContext(I18nCtx)\n","/**\n * MSI (meses sin intereses) picker. Mexican card payments can be split into\n * interest-free installments: mid-payment the engine calls `onInstallmentOffers`\n * with the available plans and waits for the buyer's choice. This hook bridges\n * that callback to an overlay — `<CheckoutProvider>` wires it by default, so\n * `<EmbeddedCheckout/>` gets MSI for free. Returns the port + the overlay to render.\n */\nimport React, { useCallback, useState } from 'react'\n\nimport type { InstallmentOffer } from 'tf-checkout-shared'\n\nimport { Button } from './Button'\nimport { useT } from './I18nProvider'\n\nexport const useInstallmentPicker = () => {\n const t = useT()\n const [pending, setPending] = useState<{\n offers: InstallmentOffer[]\n resolve: (o: InstallmentOffer | null) => void\n } | null>(null)\n\n // Stable across renders (useCheckout reads ports once) — resolves when the\n // buyer picks a plan (or declines) below.\n const onInstallmentOffers = useCallback(\n (offers: InstallmentOffer[]) =>\n new Promise<InstallmentOffer | null>((resolve) => setPending({ offers, resolve })),\n []\n )\n\n const choose = (o: InstallmentOffer | null) => {\n pending?.resolve(o)\n setPending(null)\n }\n\n const picker = pending ? (\n <div\n className=\"tf-checkout-installments\"\n role=\"dialog\"\n aria-label={t('payment.chooseInstallments')}\n >\n <div className=\"tf-checkout-installments__box\">\n <strong>{t('payment.payInInstallments')}</strong>\n <div className=\"tf-checkout-installments__list\">\n {pending.offers.map((o, i) => (\n <button\n key={i}\n type=\"button\"\n className=\"tf-checkout-installments__opt\"\n onClick={() => choose(o)}\n >\n <span>\n {o.count} × {o.per_installment_formatted ?? o.per_installment}\n </span>\n <span className=\"tf-checkout-installments__meta\">\n {o.total_formatted ? `${o.total_formatted} total` : ''}\n {o.diff_from_original_formatted\n ? ` · ${o.diff_from_original_formatted}`\n : ''}\n </span>\n </button>\n ))}\n </div>\n <Button variant=\"ghost\" block onClick={() => choose(null)}>\n Pay in full instead\n </Button>\n </div>\n </div>\n ) : null\n\n return { onInstallmentOffers, picker }\n}\n","import React, { forwardRef, type ButtonHTMLAttributes } from 'react'\n\nimport { cx } from './cx'\nimport { Loader } from './Loader'\n\nexport interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n /** Visual weight. */\n variant?: 'primary' | 'secondary' | 'ghost'\n /** Stretch to full width. */\n block?: boolean\n /** Show a spinner and disable. */\n loading?: boolean\n}\n\n/** The one shared button — token-driven variants, loading state, `className`. */\nexport const Button = forwardRef<HTMLButtonElement, ButtonProps>(\n (\n { variant = 'primary', block, loading, className, disabled, children, ...rest },\n ref\n ) => (\n <button\n ref={ref}\n type=\"button\"\n className={cx(\n 'tf-checkout-button',\n `tf-checkout-button--${variant}`,\n block && 'tf-checkout-button--block',\n className\n )}\n disabled={disabled || loading}\n {...rest}\n >\n {loading && <Loader />}\n {children}\n </button>\n )\n)\nButton.displayName = 'Button'\n","import React, { type FC } from 'react'\n\nimport { cx } from './cx'\n\n/** A spinner that inherits `currentColor` (so it works inside buttons/text). */\nexport const Loader: FC<{ className?: string }> = ({ className }) => (\n <span\n className={cx('tf-checkout-loader', className)}\n role=\"status\"\n aria-label=\"Loading\"\n />\n)\n","/**\n * The checkout theme — a structured, documented token set. Pass any subset to\n * `<CheckoutProvider theme={…}>`; each token maps to a `--tf-checkout-*` CSS\n * custom property that `checkout.css` (and every component) reads. Anything you\n * omit falls back to the stylesheet default.\n */\nimport type { CSSProperties } from 'react'\n\nexport interface CheckoutTheme {\n /** `'dark'` adds the `tf-checkout--dark` class (dark default palette). */\n colorScheme?: 'light' | 'dark'\n\n // color\n /** Primary color — buttons, step badges, focus ring, links. */\n accent?: string\n /** Hover state for `accent` (defaults near `accent`). */\n accentHover?: string\n /** Text/icon color on top of `accent`. */\n accentContrast?: string\n /** Card background. */\n surface?: string\n /** Subtle fill (summary rows, muted pills). */\n surfaceMuted?: string\n /** Primary text. */\n text?: string\n /** Secondary text (labels, \"incl. fees\", hints). */\n muted?: string\n /** Borders + dividers. */\n border?: string\n /** Error text + invalid field borders. */\n error?: string\n /** Success (confirmation check). */\n success?: string\n\n // shape\n /** Corner radius for cards. */\n radiusCard?: string\n /** Corner radius for inputs / buttons. */\n radiusControl?: string\n /** Card shadow. */\n shadow?: string\n\n // type\n /** Font family for the whole component tree. */\n font?: string\n /** Base font size (e.g. `15px`). */\n fontSize?: string\n\n // layout\n /** Max width of the checkout column. */\n maxWidth?: string\n}\n\nconst MAP: Record<keyof Omit<CheckoutTheme, 'colorScheme'>, string> = {\n accent: '--tf-checkout-accent',\n accentHover: '--tf-checkout-accent-hover',\n accentContrast: '--tf-checkout-accent-contrast',\n surface: '--tf-checkout-surface',\n surfaceMuted: '--tf-checkout-surface-muted',\n text: '--tf-checkout-text',\n muted: '--tf-checkout-muted',\n border: '--tf-checkout-border',\n error: '--tf-checkout-error',\n success: '--tf-checkout-success',\n radiusCard: '--tf-checkout-radius-card',\n radiusControl: '--tf-checkout-radius-control',\n shadow: '--tf-checkout-shadow',\n font: '--tf-checkout-font',\n fontSize: '--tf-checkout-font-size',\n maxWidth: '--tf-checkout-max-width',\n}\n\n/** Turn a theme into inline `--tf-checkout-*` custom properties for the root. */\nexport const themeToVars = (theme?: CheckoutTheme): CSSProperties => {\n const out: Record<string, string> = {}\n if (theme) {\n for (const key of Object.keys(MAP) as (keyof typeof MAP)[]) {\n const value = theme[key]\n if (value != null) out[MAP[key]] = value\n }\n }\n return out as CSSProperties\n}\n","/**\n * `Card` + `SectionHeader` — the shell every checkout section shares: a rounded\n * surface with a numbered step badge, a title, and optional right-aligned pills\n * (totals, a countdown, a loading chip). Keeps all sections visually identical\n * without each re-authoring the header markup.\n */\nimport React, { type FC, type HTMLAttributes, type ReactNode } from 'react'\n\nimport { cx } from './cx'\n\nexport interface CardProps extends HTMLAttributes<HTMLDivElement> {\n className?: string\n}\n\n/** A themed surface (`.tf-checkout-card`). Spreads through any div props. */\nexport const Card: FC<CardProps> = ({ className, children, ...rest }) => (\n <div className={cx('tf-checkout-card', className)} {...rest}>\n {children}\n </div>\n)\n\nexport interface SectionHeaderProps {\n /** Badge content — a step number, an icon, `✓`. Omit for no badge. */\n step?: ReactNode\n title: ReactNode\n /** Right-aligned chips (total, timer, \"loading…\"). */\n pills?: ReactNode\n className?: string\n}\n\nexport const SectionHeader: FC<SectionHeaderProps> = ({\n step,\n title,\n pills,\n className,\n}) => (\n <div className={cx('tf-checkout-card__header', className)}>\n {step != null && <span className=\"tf-checkout-card__step\">{step}</span>}\n <span className=\"tf-checkout-card__title\">{title}</span>\n {pills != null && <span className=\"tf-checkout-card__pills\">{pills}</span>}\n </div>\n)\n\n/** A single right-aligned chip for a `SectionHeader`'s `pills`. */\nexport const Pill: FC<{ muted?: boolean; children: ReactNode }> = ({\n muted,\n children,\n}) => (\n <span\n className={cx('tf-checkout-card__pill', muted && 'tf-checkout-card__pill--muted')}\n >\n {children}\n </span>\n)\n","import React, {\n forwardRef,\n type FC,\n type InputHTMLAttributes,\n type ReactNode,\n type SelectHTMLAttributes,\n type TextareaHTMLAttributes,\n} from 'react'\n\nimport { cx } from './cx'\n\n/** Labeled wrapper — owns the label + error row so controls stay consistent. */\nexport const Field: FC<{\n label?: ReactNode\n error?: ReactNode\n invalid?: boolean\n className?: string\n children: ReactNode\n}> = ({ label, error, invalid, className, children }) => (\n <label\n className={cx(\n 'tf-checkout-field',\n invalid && 'tf-checkout-field--invalid',\n className\n )}\n data-checkout-invalid={invalid || undefined}\n >\n {label != null && <span className=\"tf-checkout-field__label\">{label}</span>}\n {children}\n {error != null && (\n <span className=\"tf-checkout-field__error\" role=\"alert\">\n {error}\n </span>\n )}\n </label>\n)\n\n/** Lay out two fields side by side. */\nexport const FieldRow: FC<{ className?: string; children: ReactNode }> = ({\n className,\n children,\n}) => (\n <div className={cx('tf-checkout-field', 'tf-checkout-field--row', className)}>\n {children}\n </div>\n)\n\nexport interface InputProps extends InputHTMLAttributes<HTMLInputElement> {\n invalid?: boolean\n}\nexport const Input = forwardRef<HTMLInputElement, InputProps>(\n ({ invalid, className, ...rest }, ref) => (\n <input\n ref={ref}\n className={cx(\n 'tf-checkout-input',\n invalid && 'tf-checkout-input--invalid',\n className\n )}\n {...rest}\n />\n )\n)\nInput.displayName = 'Input'\n\nexport interface TextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {\n invalid?: boolean\n}\nexport const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(\n ({ invalid, className, ...rest }, ref) => (\n <textarea\n ref={ref}\n className={cx(\n 'tf-checkout-input',\n 'tf-checkout-textarea',\n invalid && 'tf-checkout-input--invalid',\n className\n )}\n {...rest}\n />\n )\n)\nTextarea.displayName = 'Textarea'\n\nexport interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {\n invalid?: boolean\n}\nexport const Select = forwardRef<HTMLSelectElement, SelectProps>(\n ({ invalid, className, children, ...rest }, ref) => (\n <select\n ref={ref}\n className={cx(\n 'tf-checkout-select',\n invalid && 'tf-checkout-select--invalid',\n className\n )}\n {...rest}\n >\n {children}\n </select>\n )\n)\nSelect.displayName = 'Select'\n\nexport interface CheckboxProps extends InputHTMLAttributes<HTMLInputElement> {\n label?: ReactNode\n}\n/** A checkbox is its own label — don't wrap it in `<Field>`. */\nexport const Checkbox: FC<CheckboxProps> = ({ label, className, ...rest }) => (\n <label className={cx('tf-checkout-checkbox', className)}>\n <input type=\"checkbox\" className=\"tf-checkout-checkbox__box\" {...rest} />\n {label != null && <span className=\"tf-checkout-checkbox__label\">{label}</span>}\n </label>\n)\n","/**\n * Data-driven custom fields. The event describes what to collect\n * (`EventCustomField[]`, order- / ticket- / add-on-scoped); these render it —\n * text, textarea, phone, email, select, radio, checkbox, multi-select — and\n * report values back. No per-brand form code: pass the group, hold the values.\n *\n * const [vals, setVals] = useState<CustomFieldValues>({})\n * <CustomFieldGroupFields group={group} values={vals}\n * onChange={(name, v) => setVals(s => ({ ...s, [name]: v }))} />\n */\nimport React, { type FC, type ReactNode } from 'react'\n\nimport type {\n CustomFieldValues,\n EventCustomField,\n EventCustomFieldGroup,\n} from 'tf-checkout-shared'\nimport { ticketFieldsFor } from 'tf-checkout-shared'\n\nimport { Checkbox, Field, Input, Select, Textarea } from './Field'\n\ntype FieldValue = string | string[]\n\nconst asString = (v: FieldValue | undefined): string =>\n Array.isArray(v) ? (v[0] ?? '') : (v ?? '')\nconst asArray = (v: FieldValue | undefined): string[] =>\n Array.isArray(v) ? v : v ? [v] : []\n\nexport interface CustomFieldInputProps {\n field: EventCustomField\n value: FieldValue | undefined\n onChange: (value: FieldValue) => void\n error?: ReactNode\n}\n\n/** Render one custom field by its declared `type`. */\nexport const CustomFieldInput: FC<CustomFieldInputProps> = ({\n field,\n value,\n onChange,\n error,\n}) => {\n const label = `${field.label}${field.required ? ' *' : ''}`\n const invalid = error != null\n const desc = field.description ? (\n <span className=\"tf-checkout-field__hint\">{field.description}</span>\n ) : undefined\n\n switch (field.type) {\n case 'textarea':\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <Textarea\n value={asString(value)}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(e) => onChange(e.target.value)}\n />\n </Field>\n )\n case 'select':\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <Select\n value={asString(value)}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(e) => onChange(e.target.value)}\n >\n <option value=\"\">— select —</option>\n {field.options.map((o) => (\n <option key={o.id} value={o.value}>\n {o.name}\n </option>\n ))}\n </Select>\n </Field>\n )\n case 'radio':\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <div className=\"tf-checkout-choices\">\n {field.options.map((o) => (\n <label key={o.id} className=\"tf-checkout-choice\">\n <input\n type=\"radio\"\n name={field.name}\n checked={asString(value) === o.value}\n onChange={() => onChange(o.value)}\n />\n <span>{o.name}</span>\n </label>\n ))}\n </div>\n </Field>\n )\n case 'select_multi': {\n const picked = asArray(value)\n const toggle = (v: string, on: boolean) =>\n onChange(on ? [...picked, v] : picked.filter((x) => x !== v))\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <div className=\"tf-checkout-choices\">\n {field.options.map((o) => (\n <Checkbox\n key={o.id}\n checked={picked.includes(o.value)}\n onChange={(e) => toggle(o.value, e.target.checked)}\n label={o.name}\n />\n ))}\n </div>\n </Field>\n )\n }\n case 'checkbox':\n return (\n <div\n className={invalid ? 'tf-checkout-consent--error' : undefined}\n data-checkout-invalid={invalid || undefined}\n >\n <Checkbox\n checked={asString(value) === '1'}\n aria-invalid={invalid}\n onChange={(e) => onChange(e.target.checked ? '1' : '')}\n label={label}\n />\n {error != null && <div className=\"tf-checkout-consent__error\">{error}</div>}\n </div>\n )\n case 'image':\n // File capture needs an upload rail the SDK doesn't own yet — surface it\n // rather than silently dropping a required field.\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <span className=\"tf-checkout-note\">\n Image upload isn’t supported in this build.\n </span>\n </Field>\n )\n default:\n // text / phone / email\n return (\n <Field label={label} error={error} invalid={invalid}>\n {desc}\n <Input\n type={\n field.type === 'email' ? 'email' : field.type === 'phone' ? 'tel' : 'text'\n }\n value={asString(value)}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(e) => onChange(e.target.value)}\n />\n </Field>\n )\n }\n}\n\nexport interface CustomFieldGroupFieldsProps {\n group: EventCustomFieldGroup\n values: CustomFieldValues\n onChange: (name: string, value: FieldValue) => void\n /** Restrict to fields scoped to this holder's ticket type (ticket groups). */\n ticketTypeId?: string\n}\n\n/** Render every field in a group, wired to a values map. */\nexport const CustomFieldGroupFields: FC<CustomFieldGroupFieldsProps> = ({\n group,\n values,\n onChange,\n ticketTypeId,\n}) => (\n <>\n {ticketFieldsFor(group.fields, ticketTypeId).map((f) => (\n <CustomFieldInput\n key={f.id}\n field={f}\n value={values[f.name]}\n onChange={(v) => onChange(f.name, v)}\n />\n ))}\n </>\n)\n\n/** True when every required field in the group has a non-empty value.\n * Re-exported from the SDK so web, native and the engine preflight all apply\n * one rule (including its \"image uploads are server-authoritative\" carve-out). */\nexport { customFieldsComplete } from 'tf-checkout-shared'\n","/**\n * `<PaymentMethods>` — a controlled radio-list of payment methods (icon + label\n * per row), matching the hosted checkout's iconed selector. Presentational only:\n * it renders the choices + the selected row's extra input (and hosts a card\n * field in the card row via `children`/`inputSlotFor`). It does NOT own the Pay\n * button or `placeOrder` — `<Payment/>` builds the options and maps a selection\n * back to a `placeOrder` request.\n */\nimport React, { type FC, type ReactNode } from 'react'\n\nimport { cx } from './cx'\nimport { useT } from './I18nProvider'\nimport { Field, Input } from './Field'\n\n// The method descriptor + row shape live in the SDK so both platforms render\n// the SAME option list. Imported for local use and re-exported for consumers\n// that already import them from here.\nimport type { PaymentMethodId, PaymentMethodOption } from 'tf-checkout-shared'\n\nexport type { PaymentMethodId, PaymentMethodOption }\n\nexport interface PaymentMethodsProps {\n options: PaymentMethodOption[]\n /** Selected `option.value` (controlled). */\n selected: string\n onSelect: (value: string) => void\n /** Extra-field values keyed by `option.value`. */\n extraValues: Record<string, { cashtag?: string; phoneNumber?: string }>\n onExtraChange: (\n value: string,\n patch: { cashtag?: string; phoneNumber?: string }\n ) => void\n /** Reveal required extra-field errors after the buyer attempts payment. */\n showValidation?: boolean\n /** Rendered inside the row whose `value === inputSlotFor` (e.g. `<CardInput/>`). */\n children?: ReactNode\n inputSlotFor?: string\n className?: string\n}\n\nconst EXTRA_LABEL: Record<'cashtag' | 'phoneNumber', string> = {\n cashtag: 'Jenius $cashtag',\n phoneNumber: 'OVO phone number',\n}\n\nexport const PaymentMethods: FC<PaymentMethodsProps> = ({\n options,\n selected,\n onSelect,\n extraValues,\n onExtraChange,\n showValidation = false,\n children,\n inputSlotFor,\n className,\n}) => {\n const t = useT()\n\n return (\n <div\n className={cx('tf-checkout-payment__methods', className)}\n role=\"radiogroup\"\n aria-label={t('payment.method')}\n >\n {options.map((o) => {\n const isSelected = o.value === selected\n const extraValue =\n o.extra === 'phoneNumber'\n ? extraValues[o.value]?.phoneNumber\n : extraValues[o.value]?.cashtag\n const extraInvalid =\n Boolean(isSelected && o.extra && showValidation) && !extraValue?.trim()\n return (\n <label\n key={o.value}\n className={cx(\n 'tf-checkout-payment__method',\n isSelected && 'tf-checkout-payment__method--selected'\n )}\n >\n <span className=\"tf-checkout-payment__method-head\">\n <input\n type=\"radio\"\n name=\"tf-pay-method\"\n className=\"tf-checkout-payment__method-radio\"\n checked={isSelected}\n onChange={() => onSelect(o.value)}\n />\n {o.iconUrl && (\n <img\n className=\"tf-checkout-payment__method-icon\"\n src={o.iconUrl}\n alt=\"\"\n />\n )}\n <span className=\"tf-checkout-payment__method-label\">{o.label}</span>\n </span>\n\n {isSelected && (o.value === inputSlotFor || o.extra) && (\n <div className=\"tf-checkout-payment__method-body\">\n {o.value === inputSlotFor && children}\n {o.extra && (\n <Field\n label={`${EXTRA_LABEL[o.extra]} *`}\n error={extraInvalid ? t('billing.fieldRequired') : undefined}\n invalid={extraInvalid}\n >\n <Input\n inputMode={o.extra === 'phoneNumber' ? 'tel' : 'text'}\n required\n invalid={extraInvalid}\n aria-invalid={extraInvalid}\n placeholder={\n o.extra === 'phoneNumber' ? 'e.g. 081234567890' : '$cashtag'\n }\n value={\n o.extra === 'phoneNumber'\n ? (extraValues[o.value]?.phoneNumber ?? '')\n : (extraValues[o.value]?.cashtag ?? '')\n }\n onChange={(e) =>\n onExtraChange(\n o.value,\n o.extra === 'phoneNumber'\n ? { phoneNumber: e.target.value }\n : { cashtag: e.target.value }\n )\n }\n />\n </Field>\n )}\n </div>\n )}\n </label>\n )\n })}\n </div>\n )\n}\n","import React, { type FC } from 'react'\n\nimport { cx } from './cx'\n\n/** Quantity ± control (ticket / add-on quantities). */\nexport const Stepper: FC<{\n value: number\n onChange: (value: number) => void\n min?: number\n max?: number\n step?: number\n disabled?: boolean\n className?: string\n}> = ({ value, onChange, min = 0, max = Infinity, step = 1, disabled, className }) => (\n <div className={cx('tf-checkout-stepper', className)}>\n <button\n type=\"button\"\n className=\"tf-checkout-stepper__btn\"\n aria-label=\"Decrease\"\n disabled={disabled || value <= min}\n onClick={() => onChange(Math.max(min, value - step))}\n >\n −\n </button>\n <span className=\"tf-checkout-stepper__value\">{value}</span>\n <button\n type=\"button\"\n className=\"tf-checkout-stepper__btn\"\n aria-label=\"Increase\"\n disabled={disabled || value >= max}\n onClick={() => onChange(Math.min(max, value + step))}\n >\n +\n </button>\n </div>\n)\n","/**\n * `<QuantitySelect>` — a compact quantity dropdown (0…max), the control the old\n * checkout used for tickets and add-ons (not a +/- stepper).\n */\nimport React, { type FC } from 'react'\n\nimport { cx } from './cx'\n\nexport interface QuantitySelectProps {\n value: number\n onChange: (value: number) => void\n /** Minimum purchasable quantity when buying (0 = none is always allowed). */\n min?: number\n max?: number\n /** Step between options (the old checkout's `multiplier`). */\n step?: number\n disabled?: boolean\n className?: string\n}\n\nexport const QuantitySelect: FC<QuantitySelectProps> = ({\n value,\n onChange,\n min = 0,\n max = 10,\n step = 1,\n disabled,\n className,\n}) => {\n // 0 (buy none) is always offered; the first non-zero option honors the ticket's\n // minimum, then steps up to the cap — so a min-2 type offers 0, 2, 3, … not 1.\n const cap = Math.min(max, 50)\n const lo = Math.max(1, min)\n const options: number[] = [0]\n for (let n = lo; n <= cap; n += step) options.push(n)\n return (\n <select\n className={cx('tf-checkout-qty', className)}\n value={value}\n disabled={disabled}\n onChange={(e) => onChange(Number(e.target.value))}\n >\n {options.map((n) => (\n <option key={n} value={n}>\n {n}\n </option>\n ))}\n </select>\n )\n}\n","import React, { type FC, type ReactNode } from 'react'\n\nimport { cx } from './cx'\n\n/** A price with optional struck-through original + a fees/deposit note. */\nexport const PriceLine: FC<{\n currency?: string\n amount: number | string\n /** Struck-through pre-discount price. */\n original?: number | string\n /** e.g. \"incl. fees\" or \"50% deposit\". */\n note?: ReactNode\n className?: string\n}> = ({ currency, amount, original, note, className }) => (\n <span className={cx('tf-checkout-price', className)}>\n {original != null && (\n <span className=\"tf-checkout-price__original\">\n {currency} {original}\n </span>\n )}\n {currency} {amount}\n {note != null && <span className=\"tf-checkout-price__fees\">{note}</span>}\n </span>\n)\n","import React, { type FC, type ReactNode } from 'react'\n\nimport { cx } from './cx'\n\nconst clock = (s: number) => {\n const v = Math.max(0, Math.floor(s))\n return v >= 3600\n ? `${Math.floor(v / 3600)}:${String(Math.floor((v % 3600) / 60)).padStart(\n 2,\n '0'\n )}:${String(v % 60).padStart(2, '0')}`\n : `${Math.floor(v / 60)}:${String(v % 60).padStart(2, '0')}`\n}\n\n/** Reservation countdown. Pass `checkout.secondsLeft`. */\nexport const Timer: FC<{\n seconds: number\n /** Below this many seconds it turns urgent (default 60). */\n urgentAt?: number\n /** Text before the clock, e.g. \"Reserved for\". */\n label?: ReactNode\n className?: string\n}> = ({ seconds, urgentAt = 60, label, className }) => (\n <span\n className={cx(\n 'tf-checkout-timer',\n seconds <= urgentAt && 'tf-checkout-timer--urgent',\n className\n )}\n >\n {label != null && <span>{label}</span>}\n {clock(seconds)}\n </span>\n)\n","/**\n * `<TimerBanner>` — the reservation countdown banner the old checkout showed at\n * the top of the add-ons / billing / payment steps: \"Please complete your\n * purchase before the timer reaches zero.\" + mm:ss, with a dismiss X. Feed it\n * `checkout.secondsLeft`. Renders nothing when there's no live reservation.\n */\nimport React, { useState, type FC } from 'react'\n\nimport { cx } from './cx'\nimport { useT } from './I18nProvider'\n\nconst clock = (s: number) => {\n const m = String(Math.floor(s / 60)).padStart(2, '0')\n const ss = String(s % 60).padStart(2, '0')\n return `${m}:${ss}`\n}\n\nexport interface TimerBannerProps {\n seconds?: number\n /** Show red styling at/under this many seconds. Default 60. */\n urgentAt?: number\n message?: string\n className?: string\n}\n\nexport const TimerBanner: FC<TimerBannerProps> = ({\n seconds,\n urgentAt = 60,\n message,\n className,\n}) => {\n const t = useT()\n const [dismissed, setDismissed] = useState(false)\n if (seconds === undefined || seconds <= 0 || dismissed) return null\n const urgent = seconds <= urgentAt\n return (\n <div\n role=\"status\"\n className={cx(\n 'tf-checkout-timerbanner',\n urgent && 'tf-checkout-timerbanner--urgent',\n className\n )}\n >\n <span className=\"tf-checkout-timerbanner__msg\">\n {message ?? t('timer.completePurchase')}\n </span>\n <span className=\"tf-checkout-timerbanner__clock\">{clock(seconds)}</span>\n <button\n type=\"button\"\n className=\"tf-checkout-timerbanner__close\"\n aria-label={t('common.dismiss')}\n onClick={() => setDismissed(true)}\n >\n ×\n </button>\n </div>\n )\n}\n","import { useT } from '../ui/I18nProvider'\nimport React, { useCallback, useEffect, useRef, type FC, type MouseEvent } from 'react'\n\nimport { hooks, type AuthFlowView, type TfProfile } from 'tf-checkout-shared'\n\nimport { cx } from '../ui/cx'\nimport { ForgotPasswordForm } from './ForgotPasswordForm'\nimport { LoginForm } from './LoginForm'\nimport { RegisterForm } from './RegisterForm'\n\nconst DEFAULT_LOGO = 'https://www.ticketfairy.com/resources/images/logo-ttf-black.svg'\n\nexport interface AuthModalProps {\n open: boolean\n onClose: () => void\n initialView?: AuthFlowView\n initialEmail?: string\n /** Optional context shown above the active form. */\n message?: string\n allowRegistration?: boolean\n allowPasswordReset?: boolean\n requireRegistrationAddress?: boolean\n /** Extra backend fields for specialized registrations such as delegations. */\n registrationFields?: Record<string, string>\n logoUrl?: string\n onAuthenticated?: (profile: TfProfile) => void\n className?: string\n}\n\n/** Accessible web presentation over `hooks.useAuthFlow()`. Render it inside\n * `<CheckoutProvider>` so it inherits the checkout theme tokens. */\nexport const AuthModal: FC<AuthModalProps> = ({\n open,\n onClose,\n initialView = 'login',\n initialEmail,\n message,\n allowRegistration = true,\n allowPasswordReset = true,\n requireRegistrationAddress = true,\n registrationFields,\n logoUrl = DEFAULT_LOGO,\n onAuthenticated,\n className,\n}) => {\n const t = useT()\n const closeAfterAuth = useCallback(\n (profile: TfProfile) => {\n onAuthenticated?.(profile)\n onClose()\n },\n [onAuthenticated, onClose]\n )\n const auth = hooks.useAuthFlow({\n initialView: initialView === 'register' && !allowRegistration ? 'login' : initialView,\n initialEmail,\n requireRegistrationAddress,\n registrationFields,\n onAuthenticated: closeAfterAuth,\n })\n const dialogRef = useRef<HTMLDivElement | null>(null)\n const previouslyFocused = useRef<HTMLElement | null>(null)\n const submittingRef = useRef(auth.isSubmitting)\n submittingRef.current = auth.isSubmitting\n // Consumers pass `onClose` as an inline arrow, so its identity changes on\n // every parent render — and the parent re-renders once a second while the\n // reservation timer counts down. Held in a ref so the setup effect below can\n // depend on `open` alone; with `onClose` in its deps it tore down and re-ran\n // each tick, stealing focus back to the first field mid-typing.\n const onCloseRef = useRef(onClose)\n onCloseRef.current = onClose\n\n useEffect(() => {\n if (!open) return\n previouslyFocused.current = document.activeElement as HTMLElement | null\n const previousOverflow = document.body.style.overflow\n document.body.style.overflow = 'hidden'\n const focusable = () =>\n Array.from(\n dialogRef.current?.querySelectorAll<HTMLElement>(\n 'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex=\"-1\"])'\n ) ?? []\n ).filter((element) => element.offsetParent !== null)\n const initialFocus =\n dialogRef.current?.querySelector<HTMLElement>(\n 'input:not([disabled]), select:not([disabled]), textarea:not([disabled])'\n ) ??\n focusable()[0] ??\n dialogRef.current\n initialFocus?.focus()\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape' && !submittingRef.current) onCloseRef.current()\n if (event.key !== 'Tab') return\n const elements = focusable()\n if (elements.length === 0) {\n event.preventDefault()\n dialogRef.current?.focus()\n return\n }\n const first = elements[0]\n const last = elements[elements.length - 1]\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault()\n last.focus()\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault()\n first.focus()\n }\n }\n document.addEventListener('keydown', onKeyDown)\n return () => {\n document.removeEventListener('keydown', onKeyDown)\n document.body.style.overflow = previousOverflow\n previouslyFocused.current?.focus()\n }\n }, [open])\n\n if (!open) return null\n\n const closeFromBackdrop = (event: MouseEvent<HTMLDivElement>) => {\n if (event.target === event.currentTarget && !auth.isSubmitting) onClose()\n }\n const isPasswordReset = auth.view === 'forgot-password'\n const title = isPasswordReset ? t('auth.passwordReset') : t('auth.title')\n\n return (\n <div className={cx('tf-checkout-auth', className)} onMouseDown={closeFromBackdrop}>\n <div\n ref={dialogRef}\n className=\"tf-checkout-auth__dialog\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={isPasswordReset ? undefined : title}\n aria-labelledby={isPasswordReset ? 'tf-checkout-auth-title' : undefined}\n tabIndex={-1}\n >\n <button\n type=\"button\"\n className=\"tf-checkout-auth__close\"\n aria-label={t('common.close')}\n disabled={auth.isSubmitting}\n onClick={onClose}\n >\n ×\n </button>\n {allowRegistration && !isPasswordReset && (\n <div\n className=\"tf-checkout-auth__tabs\"\n role=\"tablist\"\n aria-label={t('auth.title')}\n >\n <button\n type=\"button\"\n role=\"tab\"\n aria-selected={auth.view === 'login'}\n className={cx(\n 'tf-checkout-auth__tab',\n auth.view === 'login' && 'tf-checkout-auth__tab--active'\n )}\n onClick={() => auth.showLogin(auth.suggestedEmail)}\n >\n {t('auth.logIn')}\n </button>\n <button\n type=\"button\"\n role=\"tab\"\n aria-selected={auth.view === 'register'}\n className={cx(\n 'tf-checkout-auth__tab',\n auth.view === 'register' && 'tf-checkout-auth__tab--active'\n )}\n onClick={() => auth.showRegister(auth.suggestedEmail)}\n >\n {t('auth.signUp')}\n </button>\n </div>\n )}\n\n {logoUrl && (\n <div className=\"tf-checkout-auth__logo-wrap\">\n <img\n className=\"tf-checkout-auth__logo\"\n src={logoUrl}\n alt=\"The Ticket Fairy\"\n />\n </div>\n )}\n\n {isPasswordReset && (\n <h2 id=\"tf-checkout-auth-title\" className=\"tf-checkout-auth__title\">\n {title}\n </h2>\n )}\n\n {message && !isPasswordReset && (\n <p className=\"tf-checkout-auth__message\">{message}</p>\n )}\n\n {auth.view === 'login' && (\n <LoginForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n loading={auth.isSubmitting}\n allowPasswordReset={allowPasswordReset}\n onSubmit={auth.submitLogin}\n onForgotPassword={auth.showForgotPassword}\n onFieldChange={auth.clearFieldError}\n />\n )}\n {auth.view === 'register' && allowRegistration && (\n <RegisterForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n loading={auth.isSubmitting}\n requireAddress={requireRegistrationAddress}\n onSubmit={auth.submitRegistration}\n onFieldChange={auth.clearFieldError}\n />\n )}\n {auth.view === 'forgot-password' && (\n <ForgotPasswordForm\n initialEmail={auth.suggestedEmail}\n errors={auth.fieldErrors}\n error={auth.error}\n successMessage={auth.successMessage}\n loading={auth.isSubmitting}\n onSubmit={auth.submitPasswordReset}\n onBackToLogin={auth.showLogin}\n onFieldChange={() => auth.clearFieldError('email')}\n />\n )}\n </div>\n </div>\n )\n}\n","import { useT } from '../ui/I18nProvider'\nimport React, { useEffect, useState, type FC, type FormEvent } from 'react'\n\nimport type { AuthFieldErrors } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Field, Input } from '../ui/Field'\n\nexport interface ForgotPasswordFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n successMessage?: string\n loading?: boolean\n onSubmit: (email: string) => void | Promise<unknown>\n onBackToLogin: (email: string) => void\n onFieldChange?: () => void\n}\n\n/** Password-recovery presentation over the shared auth-flow controller. */\nexport const ForgotPasswordForm: FC<ForgotPasswordFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n successMessage,\n loading = false,\n onSubmit,\n onBackToLogin,\n onFieldChange,\n}) => {\n const t = useT()\n const [email, setEmail] = useState(initialEmail)\n\n useEffect(() => {\n if (initialEmail && !email) setEmail(initialEmail)\n }, [email, initialEmail])\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n void onSubmit(email)\n }\n\n if (successMessage) {\n return (\n <div className=\"tf-checkout-auth__form\">\n <div className=\"tf-checkout-auth__success\" role=\"status\">\n {successMessage}\n </div>\n <Button type=\"button\" block onClick={() => onBackToLogin(email)}>\n {t('auth.backToLogin')}\n </Button>\n </div>\n )\n }\n\n return (\n <form className=\"tf-checkout-auth__form\" onSubmit={submit} noValidate>\n <p className=\"tf-checkout-auth__intro\">{t('auth.forgotIntro')}</p>\n {error && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {error}\n </div>\n )}\n <Field label={t('auth.email')} error={errors.email}>\n <Input\n type=\"email\"\n name=\"email\"\n autoComplete=\"email\"\n autoFocus\n required\n value={email}\n invalid={Boolean(errors.email)}\n onChange={(event) => {\n setEmail(event.target.value)\n onFieldChange?.()\n }}\n />\n </Field>\n <Button type=\"submit\" block loading={loading}>\n {t('auth.sendResetInstructions')}\n </Button>\n <button\n type=\"button\"\n className=\"tf-checkout-auth__text-button tf-checkout-auth__back\"\n onClick={() => onBackToLogin(email)}\n >\n {t('auth.backToLogin')}\n </button>\n </form>\n )\n}\n","import { useT } from '../ui/I18nProvider'\nimport React, { useEffect, useState, type FC, type FormEvent } from 'react'\n\nimport type { AuthFieldErrors, AuthLoginInput } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Field, Input } from '../ui/Field'\nimport { PasswordInput } from './PasswordInput'\n\nexport interface LoginFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n loading?: boolean\n allowPasswordReset?: boolean\n onSubmit: (input: AuthLoginInput) => void | Promise<unknown>\n onForgotPassword?: (email: string) => void\n onFieldChange?: (field: keyof AuthLoginInput) => void\n}\n\n/** Pure web form: it renders fields and delegates all auth work to its caller. */\nexport const LoginForm: FC<LoginFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n loading = false,\n allowPasswordReset = true,\n onSubmit,\n onForgotPassword,\n onFieldChange,\n}) => {\n const t = useT()\n const [email, setEmail] = useState(initialEmail)\n const [password, setPassword] = useState('')\n\n useEffect(() => {\n if (initialEmail && !email) setEmail(initialEmail)\n }, [email, initialEmail])\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n void onSubmit({ email, password })\n }\n\n return (\n <form className=\"tf-checkout-auth__form\" onSubmit={submit} noValidate>\n {error && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {error}\n </div>\n )}\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.email')}\n error={errors.email}\n >\n <Input\n type=\"email\"\n name=\"email\"\n placeholder={t('auth.emailPlaceholder')}\n autoComplete=\"email\"\n autoFocus\n required\n value={email}\n invalid={Boolean(errors.email)}\n onChange={(event) => {\n setEmail(event.target.value)\n onFieldChange?.('email')\n }}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.password')}\n error={errors.password}\n >\n <PasswordInput\n name=\"password\"\n placeholder={t('auth.passwordPlaceholder')}\n autoComplete=\"current-password\"\n required\n value={password}\n invalid={Boolean(errors.password)}\n onChange={(event) => {\n setPassword(event.target.value)\n onFieldChange?.('password')\n }}\n />\n </Field>\n <Button type=\"submit\" block loading={loading}>\n {t('auth.logIn')}\n </Button>\n {allowPasswordReset && onForgotPassword && (\n <button\n type=\"button\"\n className=\"tf-checkout-auth__text-button tf-checkout-auth__forgot\"\n onClick={() => onForgotPassword(email)}\n >\n {t('auth.forgotPassword')}\n </button>\n )}\n </form>\n )\n}\n","import React, { forwardRef, useState } from 'react'\n\nimport { Input, type InputProps } from '../ui/Field'\n\n/** Password control with the same reveal affordance as the legacy checkout. */\nexport const PasswordInput = forwardRef<HTMLInputElement, InputProps>(\n ({ className, ...props }, ref) => {\n const [visible, setVisible] = useState(false)\n\n return (\n <span className=\"tf-checkout-auth__password\">\n <Input\n {...props}\n ref={ref}\n className={className}\n type={visible ? 'text' : 'password'}\n />\n <button\n type=\"button\"\n className=\"tf-checkout-auth__password-toggle\"\n aria-label={visible ? 'Hide password' : 'Show password'}\n aria-pressed={visible}\n onClick={() => setVisible((current) => !current)}\n >\n <svg aria-hidden=\"true\" viewBox=\"0 0 24 24\">\n <path d=\"M12 5c5.3 0 9.3 4.8 10.5 6.4a1 1 0 0 1 0 1.2C21.3 14.2 17.3 19 12 19S2.7 14.2 1.5 12.6a1 1 0 0 1 0-1.2C2.7 9.8 6.7 5 12 5Zm0 2c-3.8 0-7 3.2-8.4 5 1.4 1.8 4.6 5 8.4 5s7-3.2 8.4-5C19 10.2 15.8 7 12 7Zm0 2.1a2.9 2.9 0 1 1 0 5.8 2.9 2.9 0 0 1 0-5.8Z\" />\n </svg>\n </button>\n </span>\n )\n }\n)\nPasswordInput.displayName = 'PasswordInput'\n","import { useT } from '../ui/I18nProvider'\nimport React, { useEffect, useMemo, useState, type FC, type FormEvent } from 'react'\nimport { PhoneInput, type CountryIso2 } from 'react-international-phone'\n\nimport {\n hooks,\n type AuthFieldErrors,\n type AuthFieldName,\n type AuthRegistrationInput,\n} from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Field, FieldRow, Input, Select } from '../ui/Field'\nimport { PasswordInput } from './PasswordInput'\n\nexport interface RegisterFormProps {\n initialEmail?: string\n errors?: AuthFieldErrors\n error?: string\n loading?: boolean\n requireAddress?: boolean\n onSubmit: (\n input: AuthRegistrationInput,\n options: { requireState: boolean }\n ) => void | Promise<unknown>\n onFieldChange?: (field: AuthFieldName) => void\n}\n\nconst emptyRegistration = (email: string): AuthRegistrationInput => ({\n firstName: '',\n lastName: '',\n email,\n password: '',\n passwordConfirmation: '',\n phone: '',\n streetAddress: '',\n city: '',\n zip: '',\n countryId: '',\n stateId: '',\n})\n\n/** Legacy-compatible account fields with no API or validation logic inside. */\nexport const RegisterForm: FC<RegisterFormProps> = ({\n initialEmail = '',\n errors = {},\n error,\n loading = false,\n requireAddress = true,\n onSubmit,\n onFieldChange,\n}) => {\n const t = useT()\n const [values, setValues] = useState<AuthRegistrationInput>(() =>\n emptyRegistration(initialEmail)\n )\n const countriesQuery = hooks.useCountries()\n const countries = useMemo(() => countriesQuery.data ?? [], [countriesQuery.data])\n const statesQuery = hooks.useStates(values.countryId, {\n enabled: requireAddress && Boolean(values.countryId),\n })\n const states = useMemo(() => statesQuery.data ?? [], [statesQuery.data])\n\n useEffect(() => {\n if (initialEmail && !values.email)\n setValues((current) => ({ ...current, email: initialEmail }))\n }, [initialEmail, values.email])\n\n // The old form defaults to the US. Resolve it by ISO code rather than the\n // old hard-coded country id so this remains backend/environment safe.\n useEffect(() => {\n if (!requireAddress || values.countryId || countries.length === 0) return\n const preferred =\n countries.find((country) => country.code?.toLowerCase() === 'us') ?? countries[0]\n setValues((current) => ({\n ...current,\n countryId: String(preferred.id),\n phone:\n current.phone || (preferred.code?.toLowerCase() === 'us' ? '+1' : current.phone),\n }))\n }, [countries, requireAddress, values.countryId])\n\n const patch = (next: Partial<AuthRegistrationInput>) =>\n setValues((current) => ({ ...current, ...next }))\n const setField = (field: AuthFieldName, value: string) => {\n setValues((current) => ({ ...current, [field]: value }))\n onFieldChange?.(field)\n }\n\n const selectedCountry = countries.find(\n (country) => String(country.id) === String(values.countryId)\n )\n const phoneCountry = (selectedCountry?.code?.toLowerCase() ?? 'us') as CountryIso2\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n void onSubmit(values, { requireState: states.length > 0 })\n }\n\n return (\n <form\n className=\"tf-checkout-auth__form tf-checkout-auth__form--register\"\n onSubmit={submit}\n noValidate\n >\n {error && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {error}\n </div>\n )}\n\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.firstName')}\n error={errors.firstName}\n >\n <Input\n name=\"firstName\"\n placeholder={t('auth.firstNamePlaceholder')}\n autoComplete=\"given-name\"\n autoFocus\n required\n value={values.firstName}\n invalid={Boolean(errors.firstName)}\n onChange={(event) => setField('firstName', event.target.value)}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.lastName')}\n error={errors.lastName}\n >\n <Input\n name=\"lastName\"\n placeholder={t('auth.lastNamePlaceholder')}\n autoComplete=\"family-name\"\n required\n value={values.lastName}\n invalid={Boolean(errors.lastName)}\n onChange={(event) => setField('lastName', event.target.value)}\n />\n </Field>\n </FieldRow>\n\n {requireAddress ? (\n <>\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.email')}\n error={errors.email}\n >\n <Input\n type=\"email\"\n name=\"email\"\n placeholder={t('auth.emailPlaceholder')}\n autoComplete=\"email\"\n required\n value={values.email}\n invalid={Boolean(errors.email)}\n onChange={(event) => setField('email', event.target.value)}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.streetAddress')}\n error={errors.streetAddress}\n >\n <Input\n name=\"streetAddress\"\n placeholder={t('auth.streetAddressPlaceholder')}\n autoComplete=\"street-address\"\n required\n value={values.streetAddress}\n invalid={Boolean(errors.streetAddress)}\n onChange={(event) => setField('streetAddress', event.target.value)}\n />\n </Field>\n </FieldRow>\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.postcode')}\n error={errors.zip}\n >\n <Input\n name=\"zip\"\n placeholder={t('auth.postcodePlaceholder')}\n autoComplete=\"postal-code\"\n required\n value={values.zip}\n invalid={Boolean(errors.zip)}\n onChange={(event) => setField('zip', event.target.value)}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__select-field\"\n label={t('auth.country')}\n error={errors.countryId}\n >\n <Select\n name=\"countryId\"\n autoComplete=\"country\"\n required\n value={values.countryId}\n invalid={Boolean(errors.countryId)}\n onChange={(event) => {\n patch({ countryId: event.target.value, stateId: '' })\n onFieldChange?.('countryId')\n onFieldChange?.('stateId')\n }}\n >\n <option value=\"\">{t('auth.selectCountry')}</option>\n {countries.map((country) => (\n <option key={country.id} value={country.id}>\n {country.name}\n </option>\n ))}\n </Select>\n </Field>\n </FieldRow>\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__select-field\"\n label={t('auth.state')}\n error={errors.stateId}\n >\n <Select\n name=\"stateId\"\n autoComplete=\"address-level1\"\n value={values.stateId}\n disabled={!values.countryId || states.length === 0}\n required={states.length > 0}\n invalid={Boolean(errors.stateId)}\n onChange={(event) => setField('stateId', event.target.value)}\n >\n <option value=\"\">\n {states.length > 0 ? t('auth.selectState') : t('auth.notRequired')}\n </option>\n {states.map((state) => (\n <option key={state.id} value={state.id}>\n {state.name}\n </option>\n ))}\n </Select>\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.city')}\n error={errors.city}\n >\n <Input\n name=\"city\"\n placeholder={t('auth.cityPlaceholder')}\n autoComplete=\"address-level2\"\n required\n value={values.city}\n invalid={Boolean(errors.city)}\n onChange={(event) => setField('city', event.target.value)}\n />\n </Field>\n </FieldRow>\n </>\n ) : (\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.email')}\n error={errors.email}\n >\n <Input\n type=\"email\"\n name=\"email\"\n placeholder={t('auth.emailPlaceholder')}\n autoComplete=\"email\"\n required\n value={values.email}\n invalid={Boolean(errors.email)}\n onChange={(event) => setField('email', event.target.value)}\n />\n </Field>\n )}\n\n <Field className=\"tf-checkout-auth__phone-field\" label={t('auth.phone')}>\n <PhoneInput\n className=\"tf-checkout-phone\"\n inputClassName=\"tf-checkout-input tf-checkout-phone__input\"\n defaultCountry={phoneCountry}\n value={values.phone ?? ''}\n placeholder=\"\"\n inputProps={{ autoComplete: 'tel', 'aria-label': 'Phone' }}\n onChange={(phone) => setField('phone', phone)}\n />\n </Field>\n\n <FieldRow>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.password')}\n error={errors.password}\n >\n <PasswordInput\n name=\"password\"\n placeholder={t('auth.passwordPlaceholder')}\n autoComplete=\"new-password\"\n required\n value={values.password}\n invalid={Boolean(errors.password)}\n onChange={(event) => setField('password', event.target.value)}\n />\n </Field>\n <Field\n className=\"tf-checkout-auth__input-field\"\n label={t('auth.confirmPassword')}\n error={errors.passwordConfirmation}\n >\n <PasswordInput\n name=\"passwordConfirmation\"\n placeholder={t('auth.confirmPasswordPlaceholder')}\n autoComplete=\"new-password\"\n required\n value={values.passwordConfirmation}\n invalid={Boolean(errors.passwordConfirmation)}\n onChange={(event) => setField('passwordConfirmation', event.target.value)}\n />\n </Field>\n </FieldRow>\n <Button type=\"submit\" block loading={loading}>\n {t('auth.createAccount')}\n </Button>\n </form>\n )\n}\n","import { useT } from '../ui/I18nProvider'\nimport React, { useMemo, useState, type FC, type FormEvent } from 'react'\n\nimport { errorMessage, hooks } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Field, Input } from '../ui/Field'\n\nexport interface ResetPasswordFormProps {\n /** Token from the password-reset email. */\n token: string\n onSuccess?: () => void\n onBackToLogin?: () => void\n}\n\n/** Complete the password-reset flow started by `<ForgotPasswordForm/>`. */\nexport const ResetPasswordForm: FC<ResetPasswordFormProps> = ({\n token,\n onSuccess,\n onBackToLogin,\n}) => {\n const t = useT()\n const [password, setPassword] = useState('')\n const [confirmation, setConfirmation] = useState('')\n const [submitted, setSubmitted] = useState(false)\n const [success, setSuccess] = useState(false)\n\n const validation = useMemo(() => {\n if (!submitted) return {}\n return {\n token: token ? '' : t('auth.missingToken'),\n password:\n password.length < 8\n ? t('auth.passwordTooShort')\n : !/[@$!%*#?&]/.test(password)\n ? t('auth.passwordNeedsSpecial')\n : '',\n confirmation: password !== confirmation ? t('auth.passwordsMustMatch') : '',\n }\n }, [confirmation, password, submitted, token])\n\n const reset = hooks.useResetPassword({\n onSuccess: () => {\n setSuccess(true)\n onSuccess?.()\n },\n })\n\n const submit = (event: FormEvent) => {\n event.preventDefault()\n setSubmitted(true)\n const passwordValid = password.length >= 8 && /[@$!%*#?&]/.test(password)\n if (!token || !passwordValid || password !== confirmation) return\n reset.mutate({ token, password, passwordConfirmation: confirmation })\n }\n\n if (success) {\n return (\n <div className=\"tf-checkout-auth__form\">\n <div className=\"tf-checkout-auth__success\" role=\"status\">\n {t('auth.passwordChanged')}\n </div>\n {onBackToLogin && (\n <Button type=\"button\" block onClick={onBackToLogin}>\n {t('auth.logIn')}\n </Button>\n )}\n </div>\n )\n }\n\n return (\n <form className=\"tf-checkout-auth__form\" onSubmit={submit} noValidate>\n <h2 className=\"tf-checkout-auth__title\">{t('auth.changePassword')}</h2>\n {validation.token && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {validation.token}\n </div>\n )}\n {reset.error && (\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {errorMessage(reset.error)}\n </div>\n )}\n <Field label={t('auth.newPassword')} error={validation.password}>\n <Input\n type=\"password\"\n name=\"password\"\n autoComplete=\"new-password\"\n required\n value={password}\n invalid={Boolean(validation.password)}\n onChange={(event) => setPassword(event.target.value)}\n />\n </Field>\n <Field label={t('auth.confirmPassword')} error={validation.confirmation}>\n <Input\n type=\"password\"\n name=\"password_confirmation\"\n autoComplete=\"new-password\"\n required\n value={confirmation}\n invalid={Boolean(validation.confirmation)}\n onChange={(event) => setConfirmation(event.target.value)}\n />\n </Field>\n <Button type=\"submit\" block loading={reset.isPending} disabled={!token}>\n {t('common.submit')}\n </Button>\n </form>\n )\n}\n","/**\n * `<Tickets/>` — ticket selection. Lists the event's ticket types with a\n * quantity dropdown, applies promo / access codes (re-pricing + unlocking\n * tickets), offers a waiting-list sign-up on sold-out types, and primes the\n * cart. Matches the old checkout: no running total, a `GET TICKETS` CTA.\n */\nimport React, {\n Fragment,\n useEffect,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport {\n errorMessage,\n hooks,\n ticketQuantityRange,\n type TicketType,\n type WaitingListEntry,\n} from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { useT } from '../ui/I18nProvider'\nimport { cx } from '../ui/cx'\nimport { Field, FieldRow, Input } from '../ui/Field'\nimport { Loader } from '../ui/Loader'\nimport { QuantitySelect } from '../ui/QuantitySelect'\n\n/** Inline waiting-list sign-up for a sold-out type. */\nconst WaitingListForm: FC<{\n ticket: TicketType\n onJoin: (entry: WaitingListEntry) => Promise<void>\n}> = ({ ticket, onJoin }) => {\n const [form, setForm] = useState({ firstName: '', lastName: '', email: '' })\n const [state, setState] = useState<'idle' | 'busy' | 'done' | 'error'>('idle')\n const [error, setError] = useState('')\n const ok = form.firstName.trim() && form.lastName.trim() && form.email.trim()\n\n if (state === 'done')\n return (\n <p className=\"tf-checkout-note tf-checkout-tickets__wl-done\">\n You’re on the waiting list — we’ll email you if a spot opens.\n </p>\n )\n\n return (\n <div className=\"tf-checkout-tickets__wl\">\n <FieldRow>\n <Field>\n <Input\n placeholder=\"First name\"\n value={form.firstName}\n onChange={(e) => setForm((f) => ({ ...f, firstName: e.target.value }))}\n />\n </Field>\n <Field>\n <Input\n placeholder=\"Last name\"\n value={form.lastName}\n onChange={(e) => setForm((f) => ({ ...f, lastName: e.target.value }))}\n />\n </Field>\n </FieldRow>\n <Field>\n <Input\n placeholder=\"Email\"\n value={form.email}\n onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}\n />\n </Field>\n <Button\n onClick={() => {\n setState('busy')\n setError('')\n onJoin({ ...form, ticketTypeId: ticket.id })\n .then(() => setState('done'))\n .catch((e) => {\n setState('error')\n setError(errorMessage(e))\n })\n }}\n loading={state === 'busy'}\n disabled={!ok || state === 'busy'}\n variant=\"secondary\"\n >\n Join the waiting list\n </Button>\n {error && <p className=\"tf-checkout-error-text\">{error}</p>}\n </div>\n )\n}\n\nexport interface TicketsProps {\n eventId: string\n /** Optional heading above the catalog. The legacy storefront does not show\n * one, so the default is intentionally hidden. */\n title?: ReactNode | false\n /** Fired once the cart is primed (tickets added) — e.g. reveal `<AddOns/>`. */\n onContinue?: () => void\n /** CTA label. Old storefront uses \"Get tickets\". */\n buttonLabel?: string\n /** Force time-slot mode + supply the selectable session dates (ISO yyyy-mm-dd).\n * Omit to auto-detect from the event (`isTimeSlotEvent` / `availableDates`). */\n timeSlotDates?: string[]\n /** Optional numbered badge (old checkout shows none — omitted by default). */\n step?: ReactNode\n /** SEATED events: fired when the buyer clicks \"Select seats\". Wire this to\n * reveal `<SeatMap/>`. Without it the seat CTA is hidden (the seat-map ticket\n * types then have no way to be bought — provide it for seated events). */\n onSelectSeats?: () => void\n /** Apply this code once when the ticket catalog mounts. */\n initialPromoCode?: string\n /** Attribute this visit once. URL values use `ttf_r` / `referrer_id`. */\n referrer?: string | number\n /** Also read promo/referral values from the current URL. Defaults true. */\n readAttributionFromUrl?: boolean\n className?: string\n}\n\nexport const Tickets: FC<TicketsProps> = ({\n eventId,\n title = false,\n onContinue,\n buttonLabel,\n timeSlotDates,\n step,\n onSelectSeats,\n initialPromoCode,\n referrer,\n readAttributionFromUrl = true,\n className,\n}) => {\n const tr = useT()\n const checkout = useCheckoutContext()\n const buttonText = buttonLabel ?? tr('tickets.getTickets')\n const ticketsQuery = hooks.useTicketsWithMeta(eventId)\n const promoMeta = ticketsQuery.data?.promo\n const showWaitingList = ticketsQuery.data?.showWaitingList ?? false\n\n const [qty, setQty] = useState<Record<string, number>>({})\n const [slotDate, setSlotDate] = useState('')\n\n // Time-slot / calendar events: pick a date, then buy from that session's slots.\n const eventInfo = hooks.useEvent(eventId).data\n const isTimeSlot = Boolean(timeSlotDates?.length || eventInfo?.isTimeSlotEvent)\n const dates = timeSlotDates ?? eventInfo?.availableDates ?? []\n useEffect(() => {\n if (isTimeSlot && !slotDate && dates.length) setSlotDate(dates[0])\n }, [isTimeSlot, slotDate, dates])\n const slotQuery = hooks.useTimeSlotTickets(eventId, isTimeSlot ? slotDate : undefined)\n\n const tickets = isTimeSlot ? (slotQuery.data ?? []) : (ticketsQuery.data?.tickets ?? [])\n const [error, setError] = useState('')\n const [code, setCode] = useState('')\n const [codeState, setCodeState] = useState<'idle' | 'busy'>('idle')\n const [promoOpen, setPromoOpen] = useState(false)\n const [wlOpen, setWlOpen] = useState<Record<string, boolean>>({})\n const [visibleDescription, setVisibleDescription] = useState<string | null>(null)\n const attributionEvent = useRef<string | null>(null)\n\n // Match hosted links: attribute referral visits and apply a carried promo\n // once per event. Explicit props win; URL support can be disabled by hosts\n // that manage routing/attribution themselves.\n useEffect(() => {\n if (attributionEvent.current === eventId) return\n attributionEvent.current = eventId\n\n let promo = initialPromoCode?.trim() ?? ''\n let referral: string | number | undefined = referrer\n if (readAttributionFromUrl && typeof window !== 'undefined') {\n const params = new URLSearchParams(window.location.search)\n promo ||= params.get('promo')?.trim() || params.get('promo_code')?.trim() || ''\n referral ??= params.get('ttf_r') || params.get('referrer_id') || undefined\n }\n\n if (referral !== undefined && String(referral).trim()) {\n checkout.attributeReferrer(eventId, referral).catch(() => undefined)\n }\n if (promo) {\n setCode(promo)\n setPromoOpen(true)\n setCodeState('busy')\n checkout\n .applyPromoCode(eventId, promo)\n .catch(() => undefined)\n .finally(() => {\n ticketsQuery.refetch().finally(() => setCodeState('idle'))\n })\n }\n // Checkout actions and query functions are stable; this effect is scoped to\n // one attribution pass per event rather than every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [eventId, initialPromoCode, referrer, readAttributionFromUrl])\n\n // Seed the currency state once so a multi-currency event can offer a switcher\n // on the ticket screen (before the cart is primed). No-op for single-currency.\n useEffect(() => {\n checkout.syncCurrency(eventId, undefined, { seed: true }).catch(() => undefined)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [eventId])\n\n const changeCurrency = (code: string) => {\n checkout\n .syncCurrency(eventId, code)\n .then((res) => {\n if (res.requiresCatalogRefresh) {\n setQty({})\n ticketsQuery.refetch()\n }\n })\n .catch(() => undefined)\n }\n\n // Remember each type's first-seen (pre-promo) price so a discount can strike it.\n const originals = useRef<Record<string, number>>({})\n useEffect(() => {\n for (const t of tickets)\n if (originals.current[t.id] == null) originals.current[t.id] = t.price\n }, [tickets])\n\n const selected = tickets.filter((t) => (qty[t.id] ?? 0) > 0)\n // The current selection's kind — drives the CTA label and the mutual-exclusion\n // rule below (a table order and a ticket order can't be combined).\n const selectionIsTable = selected.some((t) => t.isTable)\n const allowMultiple = eventInfo?.allowMultipleTicketTypePurchases === true\n\n // Ported from the old checkout's `handleTicketSelect`: unless the event opts\n // into multiple types (`allowMultipleTicketTypePurchases`), a new selection\n // REPLACES the previous one — one ticket type per order. Even when multiple\n // are allowed, switching between a table and a regular ticket clears the rest.\n const selectQty = (t: TicketType, value: number) =>\n setQty((prev) => {\n const activeIds = Object.keys(prev).filter((k) => (prev[k] ?? 0) > 0)\n const prevIsTable = activeIds.length\n ? Boolean(tickets.find((x) => x.id === activeIds[0])?.isTable)\n : t.isTable\n const switchingKind = activeIds.length > 0 && prevIsTable !== t.isTable\n\n if (!allowMultiple) return value > 0 ? { [t.id]: value } : {}\n if (switchingKind && value > 0) return { [t.id]: value }\n const next = { ...prev }\n if (value > 0) next[t.id] = value\n else delete next[t.id]\n return next\n })\n\n const money = (sym: string, n: number) => `${sym} ${Number(n).toFixed(2)}`\n\n // Seated events: the buyer picks on a seat map, so seat-map ticket types show\n // read-only (no quantity dropdown) and the CTA becomes \"Select seats\". A type\n // with `allowDirectPurchase` opts out and keeps its dropdown.\n const isSeated = eventInfo?.isSeatedEvent ?? false\n const seatMapRow = (t: TicketType) => isSeated && !t.allowDirectPurchase\n const hasSeatMapTickets = tickets.some(seatMapRow)\n // Types that can still be bought with a quantity dropdown (all of them for a\n // non-seated event). When empty on a seated event, only \"Select seats\" shows.\n const directPurchasable = tickets.filter((t) => !seatMapRow(t))\n const seatCtaLabel = eventInfo?.tableMapEnabled\n ? tr('tickets.selectOnMap')\n : tr('tickets.selectSeats')\n\n // A \"Tables\" divider before the first table type — only when regular tickets\n // actually precede it (a tables-first list gets no stray divider).\n const firstTableIndex = tickets.findIndex((t) => t.isTable)\n const firstTableId =\n firstTableIndex > 0 && tickets.slice(0, firstTableIndex).some((t) => !t.isTable)\n ? tickets[firstTableIndex].id\n : undefined\n\n const prime = () => {\n setError('')\n checkout\n .setTickets(\n eventId,\n selected.map((t) => ({ ...t, quantity: qty[t.id] }))\n )\n .then(() => onContinue?.())\n .catch((e) => setError(errorMessage(e)))\n }\n\n const applyCode = () => {\n if (!code.trim()) return\n setCodeState('busy')\n checkout\n .applyPromoCode(eventId, code.trim())\n .catch(() => undefined)\n .finally(() => {\n ticketsQuery.refetch().finally(() => setCodeState('idle'))\n })\n }\n\n const isAccess = promoMeta?.isAccessCodeEnabled\n const showCodeInput = promoMeta?.isPromotionsEnabled || isAccess\n const listQuery = isTimeSlot ? slotQuery : ticketsQuery\n\n const renderRow = (t: TicketType) => {\n const notStarted = !t.salesStarted\n const unavailable = t.soldOut || t.salesEnded || notStarted\n const original = originals.current[t.id]\n const discounted = original != null && original > t.price\n const canWaitlist =\n t.soldOut && (t.waitingListEnabled || showWaitingList) && !t.salesEnded\n const isFree = Number(t.price) === 0\n const sym = t.priceSymbol || t.currency\n const range = ticketQuantityRange(t)\n const ticketIndex = tickets.findIndex((candidate) => candidate.id === t.id)\n const previousTicket = ticketIndex > 0 ? tickets[ticketIndex - 1] : undefined\n const startsNamedGroup =\n Boolean(t.groupName) && t.groupName !== previousTicket?.groupName\n return (\n <Fragment key={t.id}>\n {startsNamedGroup ? (\n <div className=\"tf-checkout-tickets__group\">{t.groupName}</div>\n ) : (\n t.id === firstTableId && (\n <div className=\"tf-checkout-tickets__group\">\n {tr('tickets.reserveTables')}\n </div>\n )\n )}\n <div className=\"tf-checkout-tickets__row-wrap\">\n <div className=\"tf-checkout-tickets__row\">\n <div className=\"tf-checkout-tickets__info\">\n <div className=\"tf-checkout-tickets__name\">\n <span>{t.name}</span>\n {t.descriptionRich && (\n <button\n type=\"button\"\n className=\"tf-checkout-tickets__description-toggle\"\n aria-expanded={visibleDescription === t.id}\n aria-controls={`ticket-description-${t.id}`}\n onClick={() =>\n setVisibleDescription((current) => (current === t.id ? null : t.id))\n }\n >\n {visibleDescription === t.id\n ? tr('tickets.hideInfo')\n : tr('tickets.viewInfo')}\n </button>\n )}\n </div>\n <div className=\"tf-checkout-tickets__price\">\n {discounted && (\n <span className=\"tf-checkout-tickets__old\">\n {money(sym, original!)}\n </span>\n )}\n <span\n className={cx(\n 'tf-checkout-tickets__amount',\n isFree && 'tf-checkout-tickets__amount--free'\n )}\n >\n {isFree ? 'FREE' : money(sym, t.price)}\n </span>\n {/* Fees sub-line (the \"(… with fees)\" the old checkout shows) —\n omitted for free/sold-out types. */}\n {!isFree && !t.soldOut && (\n <span className=\"tf-checkout-tickets__fees\">\n ({money(sym, t.priceWithFees)} with fees)\n </span>\n )}\n {t.depositPercent != null && (\n <span className=\"tf-checkout-tickets__deposit\">\n {t.depositPercent.toFixed(2)}% DEPOSIT\n </span>\n )}\n </div>\n </div>\n {/* Seat-map types are read-only here — no quantity control; the buyer\n picks them on the map via \"Select seats\". */}\n {seatMapRow(t) ? null : unavailable ? (\n <span className=\"tf-checkout-tickets__soldout\">\n {t.soldOut\n ? tr('tickets.soldOut')\n : notStarted\n ? tr('tickets.salesNotStarted')\n : tr('tickets.salesEnded')}\n </span>\n ) : (\n <div className=\"tf-checkout-tickets__qty\">\n {/* Tables pick a number of GUESTS (bounded by minGuests/maxGuests),\n not a count of tickets — the label makes that explicit, matching\n the old checkout's \"GUESTS\" affordance. */}\n {t.isTable && (\n <span className=\"tf-checkout-tickets__guests\">\n {tr('tickets.guests')}\n </span>\n )}\n <QuantitySelect\n value={qty[t.id] ?? 0}\n min={range.min}\n max={range.max}\n step={range.step}\n onChange={(v) => selectQty(t, v)}\n />\n </div>\n )}\n </div>\n {t.descriptionRich && visibleDescription === t.id && (\n <div\n id={`ticket-description-${t.id}`}\n className=\"tf-checkout-tickets__description\"\n dangerouslySetInnerHTML={{ __html: t.descriptionRich }}\n />\n )}\n {canWaitlist &&\n (wlOpen[t.id] ? (\n <WaitingListForm\n ticket={t}\n onJoin={(entry) => checkout.joinWaitingList(eventId, entry)}\n />\n ) : (\n <button\n type=\"button\"\n className=\"tf-checkout-tickets__wl-toggle\"\n onClick={() => setWlOpen((w) => ({ ...w, [t.id]: true }))}\n >\n Join the waiting list\n </button>\n ))}\n </div>\n </Fragment>\n )\n }\n\n // Time-slot layout groups the date's tickets under their time heading.\n const timeGroups: { time: string; items: TicketType[] }[] = []\n if (isTimeSlot)\n for (const t of tickets) {\n const time = t.timeSlot?.time ?? ''\n const g = timeGroups.find((x) => x.time === time)\n if (g) g.items.push(t)\n else timeGroups.push({ time, items: [t] })\n }\n\n return (\n <Card className={cx('tf-checkout-tickets', className)}>\n {(title !== false || step != null) && (\n <SectionHeader\n step={step}\n title={title || ''}\n pills={listQuery.isFetching && !listQuery.isLoading ? <Loader /> : undefined}\n />\n )}\n\n {listQuery.isLoading && (\n <div className=\"tf-checkout-tickets__loading\">\n <Loader className=\"tf-checkout-tickets__loading-spinner\" />\n </div>\n )}\n\n {listQuery.error && (\n <p className=\"tf-checkout-error-text\">{(listQuery.error as Error).message}</p>\n )}\n\n {isTimeSlot && dates.length > 0 && (\n <div className=\"tf-checkout-tickets__currency\">\n <span className=\"tf-checkout-tickets__currency-label\">{tr('common.date')}</span>\n <select\n className=\"tf-checkout-select\"\n value={slotDate}\n onChange={(e) => {\n setSlotDate(e.target.value)\n setQty({})\n }}\n >\n {dates.map((d) => (\n <option key={d} value={d}>\n {d}\n </option>\n ))}\n </select>\n </div>\n )}\n\n {checkout.currency && checkout.currency.available.length > 1 && (\n <div className=\"tf-checkout-tickets__currency\">\n <span className=\"tf-checkout-tickets__currency-label\">\n {tr('common.currency')}\n </span>\n <select\n className=\"tf-checkout-select\"\n value={checkout.currency.currency}\n onChange={(e) => changeCurrency(e.target.value)}\n >\n {checkout.currency.available.map((c) => (\n <option key={c.code} value={c.code}>\n {c.name} ({c.code})\n </option>\n ))}\n </select>\n </div>\n )}\n\n {isTimeSlot && !slotQuery.isLoading && tickets.length === 0 && slotDate && (\n <p className=\"tf-checkout-note\">{tr('tickets.noSessions')}</p>\n )}\n\n {isTimeSlot\n ? timeGroups.map((g) => (\n <Fragment key={g.time}>\n {g.time && <div className=\"tf-checkout-tickets__slot-time\">{g.time}</div>}\n {g.items.map(renderRow)}\n </Fragment>\n ))\n : tickets.map(renderRow)}\n\n {/* Promo / access code */}\n {showCodeInput && (\n <div className=\"tf-checkout-tickets__promo\">\n {!isAccess && !promoOpen ? (\n <button\n type=\"button\"\n className=\"tf-checkout-tickets__promo-toggle\"\n onClick={() => setPromoOpen(true)}\n >\n Got a promo code? Click here\n </button>\n ) : (\n <>\n <FieldRow>\n <Field>\n <Input\n placeholder={\n isAccess ? tr('tickets.accessCode') : tr('tickets.promoCode')\n }\n value={code}\n onChange={(e) => setCode(e.target.value)}\n onKeyDown={(e) => e.key === 'Enter' && applyCode()}\n />\n </Field>\n <Button\n variant=\"secondary\"\n onClick={applyCode}\n loading={codeState === 'busy'}\n disabled={codeState === 'busy' || !code.trim()}\n >\n {isAccess ? 'ENTER' : 'APPLY'}\n </Button>\n </FieldRow>\n {promoMeta?.promoCodeMessage && (\n <p\n className={cx(\n 'tf-checkout-note',\n promoMeta.promoCodeValid === false && 'tf-checkout-error-text'\n )}\n >\n {promoMeta.promoCodeMessage}\n </p>\n )}\n </>\n )}\n </div>\n )}\n\n {/* Direct-purchase CTA — hidden on a fully-seated event (nothing to buy by\n quantity; the seat map is the only path). */}\n {directPurchasable.length > 0 && (\n <Button\n block\n onClick={prime}\n loading={checkout.isBusy}\n disabled={checkout.isBusy || selected.length === 0}\n >\n {checkout.isBusy\n ? tr('tickets.reserving')\n : selectionIsTable\n ? tr('tickets.reserveTables')\n : buttonText}\n </Button>\n )}\n\n {/* Seated events: hand off to the seat map instead of quantity selection. */}\n {hasSeatMapTickets && (\n <Button block onClick={() => onSelectSeats?.()}>\n {seatCtaLabel}\n </Button>\n )}\n\n {(error || checkout.error) && (\n <p className=\"tf-checkout-error-text\">{error || checkout.error}</p>\n )}\n </Card>\n )\n}\n","/**\n * `<SeatMap/>` — the venue seat picker for seated events, rebuilt to match the\n * legacy `seatMapContainer` exactly (the REAL seat wire, not the earlier\n * inferred mapping):\n *\n * 1. Fetch the chart (`seat-map-data`) → `seatData`, `ticketTypeTierRelations`,\n * `eventSeats`, `seatReservationTime`, `seatMapType`, `tierPrices`,\n * `predefinedSeats`. Poll `seats/status` every 3s and derive the seats this\n * buyer owns (status `'OR'`).\n * 2. Clicking a seat reserves it (`ttf.seatmap.reserve`, one seat per call);\n * clicking a held seat releases it (`ttf.seatmap.removeReserved`). Blocked /\n * reserved-by-others seats and the 10-seat cap are enforced like legacy.\n * 3. Each held seat gets a ticket-type dropdown (auto-selected when its tier\n * offers only one) and, for table/group types, a guest-count dropdown.\n * 4. \"Get tickets\" turns the held seats into `SeatLine`s and calls\n * `checkout.setSeats(eventId, lines)` → the seat-aware add-to-cart + price.\n *\n * Boundaries (documented, not hidden):\n * - `tf-seat-map-view` is an OPTIONAL peer dependency. Install it and import its\n * CSS (`import 'tf-seat-map-view/dist/index.css'`) to use this section; it is\n * lazy-loaded + externalized, so it never weighs on the base SDK.\n * - Guest-count → cart shape follows the spec's model: a `SeatLine` carries\n * `guests` ONLY for guest-capable (table) types, so plain seated events post\n * aggregated per-type quantities and table events post one indexed line per\n * seat with `quantity = guests`. Validate against a real table-map event.\n */\nimport React, {\n useCallback,\n useEffect,\n useRef,\n useState,\n type ComponentType,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport { errorMessage, ttf, type SeatLine } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { Field, Select } from '../ui/Field'\nimport { Loader } from '../ui/Loader'\nimport { Timer } from '../ui/Timer'\nimport {\n getOwnReservationsBasedOnStatuses,\n getTierIdBasedOnSeatId,\n getTierRelationsArray,\n isGuestCapable,\n MAX_SEATS,\n ticketTypesForTier,\n UNSELECTABLE_STATUSES,\n type EventSeatLike,\n type ReservedSeat,\n type SeatRelation,\n type SeatStatuses,\n type TierRelations,\n} from './seatMap.utils'\n\n// tf-seat-map-view ships no types (see src/.d.ts ambient module) — treat the\n// default export as an opaque component rendered with the legacy prop contract.\ntype SeatMapWidget = ComponentType<Record<string, unknown>>\n\n/** The seat click payload the widget emits: `{ seat: { tierId, seatId, status } }`. */\ninterface SeatClick {\n seat: { tierId: string; seatId: string; status: string }\n}\n\ninterface Chart {\n seatData: unknown\n ticketTypeTierRelations: TierRelations\n eventSeats: EventSeatLike[]\n seatReservationTime: number\n seatMapType: string | null\n tierPrices: unknown\n predefinedSeats: unknown\n}\n\ntype Load<T> =\n | { state: 'loading' }\n | { state: 'ready'; data: T }\n | { state: 'empty' }\n | { state: 'error' }\n\nexport interface SeatMapProps {\n eventId: string\n /** Fired once seats are added to the cart + priced — e.g. reveal billing. */\n onContinue?: () => void\n /** Badge content. Defaults to a seat glyph. */\n step?: ReactNode\n className?: string\n}\n\nexport const SeatMap: FC<SeatMapProps> = ({\n eventId,\n onContinue,\n step = '💺',\n className,\n}) => {\n const checkout = useCheckoutContext()\n const [chart, setChart] = useState<Load<Chart>>({ state: 'loading' })\n const [Widget, setWidget] = useState<SeatMapWidget | null>(null)\n const [widgetMissing, setWidgetMissing] = useState(false)\n\n const [statuses, setStatuses] = useState<SeatStatuses>({})\n const [reserved, setReserved] = useState<ReservedSeat[]>([])\n const [selectedTypes, setSelectedTypes] = useState<Record<string, string>>({})\n const [guestCounts, setGuestCounts] = useState<Record<string, number>>({})\n const [reserving, setReserving] = useState(false)\n const [adding, setAdding] = useState(false)\n const [error, setError] = useState('')\n const [deadline, setDeadline] = useState<number | null>(null)\n const [nowTick, setNowTick] = useState(0)\n\n // The poll's setInterval closure reads these without re-subscribing.\n const eventSeatsRef = useRef<EventSeatLike[]>([])\n const relationsRef = useRef<TierRelations>({})\n const reservationTimeRef = useRef(0)\n const canvasRef = useRef<HTMLDivElement | null>(null)\n\n // Lazy-load the optional widget; a consumer who never installed it just gets\n // the \"unavailable\" note instead of a hard module-resolution crash.\n useEffect(() => {\n let active = true\n import('tf-seat-map-view')\n .then((m) => active && setWidget(() => (m.default ?? m) as SeatMapWidget))\n .catch(() => active && setWidgetMissing(true))\n return () => {\n active = false\n }\n }, [])\n\n // Fetch the chart. `get()` returns the JSON:API envelope, so read\n // `.data.attributes`; `seatData` is a JSON string the widget wants parsed.\n useEffect(() => {\n let active = true\n setChart({ state: 'loading' })\n console.log('[SeatMap] Fetching chart for eventId:', eventId)\n ttf.seatmap\n .data(eventId)\n .then((resp) => {\n if (!active) return\n console.log('[SeatMap] Raw response from ttf.seatmap.data:', resp)\n console.log('[SeatMap] typeof resp:', typeof resp)\n console.log('[SeatMap] resp?.data:', (resp as any)?.data)\n console.log('[SeatMap] resp?.data?.attributes:', (resp as any)?.data?.attributes)\n const attrs = (resp as { data?: { attributes?: Record<string, unknown> } })?.data\n ?.attributes\n console.log('[SeatMap] Parsed attrs:', attrs)\n console.log('[SeatMap] attrs?.seatData:', attrs?.seatData)\n console.log('[SeatMap] attrs?.seatData == null:', attrs?.seatData == null)\n if (!attrs || attrs.seatData == null) {\n console.warn(\n '[SeatMap] Setting chart to EMPTY because:',\n !attrs ? 'attrs is falsy' : 'seatData is null/undefined'\n )\n setChart({ state: 'empty' })\n return\n }\n const rawSeatData = attrs.seatData\n let seatData: unknown = rawSeatData\n if (typeof rawSeatData === 'string') {\n try {\n seatData = JSON.parse(rawSeatData)\n } catch {\n seatData = rawSeatData\n }\n }\n const relations = (attrs.ticketTypeTierRelations ?? {}) as TierRelations\n const eventSeats = (attrs.eventSeats ?? []) as EventSeatLike[]\n eventSeatsRef.current = eventSeats\n relationsRef.current = relations\n reservationTimeRef.current = Number(attrs.seatReservationTime) || 0\n // The widget reads tier prices off a global (legacy \"temp solution\").\n if (typeof window !== 'undefined') {\n ;(window as unknown as { tierPrices?: unknown }).tierPrices = attrs.tierPrices\n }\n console.log('[SeatMap] Setting chart to READY', {\n seatMapType: attrs.seatMapType,\n seatReservationTime: reservationTimeRef.current,\n eventSeatsCount: eventSeats.length,\n relationsKeys: Object.keys(relations),\n seatDataType: typeof seatData,\n })\n setChart({\n state: 'ready',\n data: {\n seatData,\n ticketTypeTierRelations: relations,\n eventSeats,\n seatReservationTime: reservationTimeRef.current,\n seatMapType: (attrs.seatMapType ?? null) as string | null,\n tierPrices: attrs.tierPrices,\n predefinedSeats: attrs.predefinedSeats,\n },\n })\n })\n .catch((err) => {\n console.error('[SeatMap] Fetch FAILED — setting chart to ERROR', err)\n if (active) setChart({ state: 'error' })\n })\n return () => {\n active = false\n }\n }, [eventId])\n\n // Poll live statuses every 3s (like legacy) once the chart is ready: derive the\n // seats this buyer owns, auto-select single-type tiers, prune released seats.\n const refreshStatuses = useCallback(async () => {\n try {\n const resp = await ttf.seatmap.statuses(eventId)\n const attrs = ((resp as { data?: { attributes?: SeatStatuses } })?.data\n ?.attributes ?? {}) as SeatStatuses\n const own = getOwnReservationsBasedOnStatuses(attrs) // mutates 'H' → 'BLOCKED'\n const nextReserved: ReservedSeat[] = own.map((seatId) => ({\n seatId,\n tierId: getTierIdBasedOnSeatId(seatId, eventSeatsRef.current),\n }))\n setStatuses(attrs)\n setReserved(nextReserved)\n const ownSet = new Set(own)\n setSelectedTypes((prev) => {\n const next: Record<string, string> = {}\n for (const r of nextReserved) {\n if (prev[r.seatId] != null) {\n next[r.seatId] = prev[r.seatId]\n } else {\n const types = ticketTypesForTier(relationsRef.current, r.tierId)\n next[r.seatId] = types.length === 1 ? types[0].ticket_type_id : ''\n }\n }\n return next\n })\n setGuestCounts((prev) => {\n const next: Record<string, number> = {}\n for (const seatId of Object.keys(prev))\n if (ownSet.has(seatId)) next[seatId] = prev[seatId]\n return next\n })\n } catch {\n // A transient status poll failure is non-fatal — keep the last snapshot.\n }\n }, [eventId])\n\n useEffect(() => {\n if (chart.state !== 'ready') return\n refreshStatuses()\n const id = setInterval(refreshStatuses, 3000)\n return () => clearInterval(id)\n }, [chart.state, refreshStatuses])\n\n // Reservation countdown: arm it when the first seat is held; clear when none\n // remain. The server is the source of truth — expiry drops seats via the poll.\n useEffect(() => {\n if (reserved.length && deadline == null && reservationTimeRef.current) {\n setDeadline(Date.now() + reservationTimeRef.current * 60000)\n } else if (!reserved.length && deadline != null) {\n setDeadline(null)\n }\n }, [reserved.length, deadline])\n useEffect(() => {\n if (deadline == null) return\n const id = setInterval(() => setNowTick((n) => n + 1), 1000)\n return () => clearInterval(id)\n }, [deadline])\n const secondsLeft =\n deadline != null ? Math.max(0, Math.round((deadline - Date.now()) / 1000)) : undefined\n // referenced so the 1s tick re-renders the timer\n void nowTick\n\n const reserve = async (tierId: string, seatId: string) => {\n setError('')\n setReserving(true)\n try {\n await ttf.seatmap.reserve(eventId, { tierId, seatId, ttl: 10 })\n await refreshStatuses()\n // Auto-select the tier's type if it's the only one (legacy behaviour).\n const types = ticketTypesForTier(relationsRef.current, tierId)\n if (types.length === 1) {\n setSelectedTypes((s) => ({ ...s, [seatId]: types[0].ticket_type_id }))\n }\n } catch (e) {\n setError(errorMessage(e))\n } finally {\n setReserving(false)\n }\n }\n\n const cancel = async (tierId: string, seatId: string) => {\n setError('')\n setReserving(true)\n try {\n await ttf.seatmap.removeReserved(eventId, tierId, [seatId])\n await refreshStatuses()\n } catch (e) {\n setError(errorMessage(e))\n } finally {\n setReserving(false)\n }\n }\n\n const onSeatClick = (info: SeatClick) => {\n const { tierId, seatId, status } = info.seat\n if (UNSELECTABLE_STATUSES.has(status)) return\n if (reserved.some((r) => r.seatId === seatId)) {\n cancel(tierId, seatId)\n } else if (reserved.length >= MAX_SEATS) {\n setError(`You can hold at most ${MAX_SEATS} seats.`)\n } else {\n reserve(tierId, seatId)\n }\n }\n\n const relationFor = (seatId: string): SeatRelation | undefined => {\n const seat = reserved.find((r) => r.seatId === seatId)\n const typeId = selectedTypes[seatId]\n if (!seat || !typeId) return undefined\n return ticketTypesForTier(relationsRef.current, seat.tierId).find(\n (t) => t.ticket_type_id === typeId\n )\n }\n\n // \"Get tickets\" is enabled only once every held seat has a type chosen.\n const allChosen =\n reserved.length > 0 && reserved.every((r) => Boolean(selectedTypes[r.seatId]))\n\n const getTickets = () => {\n setError('')\n const lines: SeatLine[] = []\n for (const r of reserved) {\n const rel = relationFor(r.seatId)\n if (!rel) continue\n const guestCapable = isGuestCapable(rel)\n const min = Number(rel.ticket_type_min_number_of_guests) || 0\n lines.push({\n seatId: r.seatId,\n tierId: r.tierId,\n ticketTypeId: rel.ticket_type_id,\n optionName: rel.ticket_type_option,\n price: Number(rel.ticket_type_price),\n ...(guestCapable ? { guests: guestCounts[r.seatId] ?? min } : {}),\n })\n }\n if (!lines.length) {\n setError('Please choose a ticket type for each seat.')\n return\n }\n setAdding(true)\n checkout\n .setSeats(eventId, lines)\n .then(() => onContinue?.())\n .catch((e) => setError(errorMessage(e)))\n .finally(() => setAdding(false))\n }\n\n const symbol = checkout.breakdown?.currencySymbol ?? ''\n\n return (\n <Card className={className}>\n <SectionHeader\n step={step}\n title=\"Select your seats\"\n pills={secondsLeft != null ? <Timer seconds={secondsLeft} /> : undefined}\n />\n\n {chart.state === 'loading' && (\n <div className=\"tf-checkout-seatmap__loading\">\n <Loader />\n </div>\n )}\n\n {chart.state === 'empty' && (\n <p className=\"tf-checkout-note\">\n This event has no seating chart — choose tickets above instead.\n </p>\n )}\n\n {chart.state === 'error' && (\n <p className=\"tf-checkout-note\">\n This seat map is currently unavailable in the checkout widget. If this event\n uses Seats.io, please return to the main event page to pick your seats.\n </p>\n )}\n\n {chart.state === 'ready' && widgetMissing && (\n <p className=\"tf-checkout-note\">\n Seat map unavailable — install <code>tf-seat-map-view</code> and import its CSS\n to enable the picker.\n </p>\n )}\n\n {chart.state === 'ready' && !widgetMissing && (\n <>\n <div className=\"tf-checkout-seatmap__canvas\" ref={canvasRef}>\n {Widget ? (\n <Widget\n seatData={chart.data.seatData}\n statuses={statuses}\n isSelectionOn={false}\n disabled={reserving}\n loading={reserving}\n events={{ onSeatClick }}\n ticketTypeTireRelationsArray={getTierRelationsArray(\n chart.data.ticketTypeTierRelations\n )}\n width={Math.min(canvasRef.current?.clientWidth || 800, 800)}\n height={Math.min(canvasRef.current?.clientWidth || 800, 800)}\n isBlockMap={chart.data.seatMapType === 'block'}\n isTableMap={chart.data.seatMapType === 'table'}\n predefinedSeats={chart.data.predefinedSeats}\n />\n ) : (\n <Loader />\n )}\n </div>\n\n {reserved.length > 0 && (\n <div className=\"tf-checkout-seatmap__seats\">\n {reserved.map((r) => {\n const types = ticketTypesForTier(relationsRef.current, r.tierId)\n const rel = relationFor(r.seatId)\n const guestCapable = isGuestCapable(rel)\n const min = Number(rel?.ticket_type_min_number_of_guests) || 0\n const max = Number(rel?.ticket_type_max_number_of_guests) || 0\n const guests = guestCounts[r.seatId] ?? min\n const unitPrice = Number(rel?.ticket_type_price ?? 0)\n const guestPrice = guestCapable\n ? (guests - min) * Number(rel?.guest_price ?? 0)\n : 0\n const total = (unitPrice + guestPrice).toFixed(2)\n return (\n <div key={r.seatId} className=\"tf-checkout-seatmap__seat\">\n <Field label={`Seat ${r.seatId}`}>\n <Select\n value={selectedTypes[r.seatId] || ''}\n onChange={(e) =>\n setSelectedTypes((s) => ({ ...s, [r.seatId]: e.target.value }))\n }\n >\n <option value=\"\">Please select a ticket type</option>\n {types.map((t) => (\n <option key={t.ticket_type_id} value={t.ticket_type_id}>\n {t.ticket_type_name}\n </option>\n ))}\n </Select>\n </Field>\n\n {guestCapable && (\n <Field label=\"Guests\">\n <Select\n value={guests}\n onChange={(e) =>\n setGuestCounts((g) => ({\n ...g,\n [r.seatId]: Number(e.target.value),\n }))\n }\n >\n {Array.from(\n { length: Math.max(0, max - min + 1) },\n (_, i) => min + i\n ).map((n) => (\n <option key={n} value={n}>\n {n}\n </option>\n ))}\n </Select>\n </Field>\n )}\n\n <div className=\"tf-checkout-seatmap__seat-foot\">\n {rel && (\n <span className=\"tf-checkout-seatmap__seat-price\">\n {symbol}\n {total}\n <span className=\"tf-checkout-note\">\n {rel.fee_included ? ' incl. fees' : ' excl. fees'}\n </span>\n </span>\n )}\n <button\n type=\"button\"\n className=\"tf-checkout-seatmap__seat-remove\"\n onClick={() => cancel(r.tierId, r.seatId)}\n disabled={reserving}\n >\n Remove\n </button>\n </div>\n </div>\n )\n })}\n\n <Button\n block\n onClick={getTickets}\n loading={adding}\n disabled={adding || reserving || !allChosen}\n >\n {adding\n ? 'Reserving…'\n : `Get ${reserved.length} seat${reserved.length > 1 ? 's' : ''}`}\n </Button>\n </div>\n )}\n {error && <p className=\"tf-checkout-error-text\">{error}</p>}\n </>\n )}\n </Card>\n )\n}\n","/**\n * Seat-wire helpers — a faithful port of the legacy `seatMapContainer/utils.ts`\n * (the real seat-map logic), rewritten in dependency-free TS. These translate\n * the `seat-map-data` + `seats/status` responses into the shapes `<SeatMap/>`\n * and the `tf-seat-map-view` widget need.\n */\n\n/** `{ [tierId]: { [ticketTypeId]: Relation } }` — from `seat-map-data`. */\nexport interface SeatRelation {\n ticket_type_id: string\n ticket_type_option: string\n ticket_type_price: number\n ticket_type_name: string\n ticket_type_min_number_of_guests?: string | number | null\n ticket_type_max_number_of_guests?: string | number | null\n ticket_type_deposit?: string\n guest_price?: string\n fee_included?: boolean\n description?: string | null\n}\nexport type TierRelations = Record<string, Record<string, SeatRelation>>\n\n/** `{ [groupRowId]: { [seatIndex]: statusCode } }` — from `seats/status`. */\nexport type SeatStatuses = Record<string, Record<string, string>>\n\n/** `seat-map-data`'s `eventSeats` — used only to resolve seatId → tierId. */\nexport interface EventSeatLike {\n tier_id: number | string\n seats: Record<string, number>\n}\n\n/** A seat the buyer holds: its id + resolved tier. */\nexport interface ReservedSeat {\n seatId: string\n tierId: string\n}\n\n/** Statuses the widget won't let the buyer act on (blocked / reserved-by-others). */\nexport const UNSELECTABLE_STATUSES = new Set(['B', 'R', 'BLOCKED', 'RE'])\n\n/** Max seats a single order may hold (legacy cap). */\nexport const MAX_SEATS = 10\n\n/**\n * `seatId` (`\"rowId:seatIndex\"`) → its tier id, by finding the `eventSeats`\n * group whose `seats[rowId]` covers `seatIndex`. Port of legacy\n * `getTierIdBasedOnSeatId`.\n */\nexport const getTierIdBasedOnSeatId = (\n seatId: string,\n eventSeats: EventSeatLike[]\n): string => {\n const [rowId, seatIndex] = seatId.split(':')\n for (const group of eventSeats ?? []) {\n for (const [row, count] of Object.entries(group.seats ?? {})) {\n if (row === rowId && Number(seatIndex) <= Number(count)) {\n return String(group.tier_id)\n }\n }\n }\n return ''\n}\n\n/**\n * Statuses → the seat ids the buyer currently OWNS (status `'OR'`). Also rewrites\n * `'H'` (held by someone else) to `'BLOCKED'` so the widget greys it out — the\n * mutation the legacy container did in place. Pass a status object you own\n * (freshly fetched), not shared React state.\n */\nexport const getOwnReservationsBasedOnStatuses = (statuses: SeatStatuses): string[] => {\n const own: string[] = []\n for (const groupRowId of Object.keys(statuses ?? {})) {\n const row = statuses[groupRowId]\n for (const seatIndex of Object.keys(row ?? {})) {\n if (row[seatIndex] === 'OR') own.push(`${groupRowId}:${seatIndex}`)\n else if (row[seatIndex] === 'H') row[seatIndex] = 'BLOCKED'\n }\n }\n return own\n}\n\n/**\n * Tier→type relations → the flat relation array the `tf-seat-map-view` widget\n * wants (its prop is the legacy-typo'd `ticketTypeTireRelationsArray`). Port of\n * legacy `getTierRelationsArray`.\n */\nexport const getTierRelationsArray = (relations: TierRelations): SeatRelation[] => {\n const out: SeatRelation[] = []\n for (const tier of Object.values(relations ?? {})) out.push(...Object.values(tier))\n return out\n}\n\n/** The ticket types a tier offers (dropdown options for its seats). */\nexport const ticketTypesForTier = (\n relations: TierRelations,\n tierId: string\n): SeatRelation[] => (relations[tierId] ? Object.values(relations[tierId]) : [])\n\n/** Whether a relation is guest-capable (a table / group ticket): it declares a\n * real min AND max guest count. Only then does a SeatLine carry `guests`. */\nexport const isGuestCapable = (rel: SeatRelation | undefined): boolean => {\n const min = Number(rel?.ticket_type_min_number_of_guests)\n const max = Number(rel?.ticket_type_max_number_of_guests)\n return Boolean(min && max)\n}\n","/**\n * `<AddOns/>` — optional upsells for the primed cart. Lists the event's add-ons\n * (filtered to the tickets in the cart), lets the buyer pick quantities, and\n * captures any per-add-on custom fields. On continue it writes the selection\n * (`setAddons`, which reprices) and the captured fields (`setAddonDataCapture`).\n *\n * Renders nothing when the event has no applicable add-ons, so it's safe to\n * always place between `<Tickets/>` and `<BillingInfo/>`.\n */\nimport React, { Fragment, useEffect, useMemo, useState, type FC } from 'react'\n\nimport {\n addOnMaxQuantity,\n errorMessage,\n hooks,\n ttf,\n type CustomFieldValues,\n type EventAddon,\n} from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { useT } from '../ui/I18nProvider'\nimport { CustomFieldGroupFields } from '../ui/CustomFields'\nimport { Loader } from '../ui/Loader'\nimport { PriceLine } from '../ui/PriceLine'\nimport { QuantitySelect } from '../ui/QuantitySelect'\n\nexport interface AddOnsProps {\n eventId: string\n /** Fired once add-ons are saved to the cart — e.g. reveal `<BillingInfo/>`. */\n onContinue?: () => void\n /** Fired when the buyer skips add-ons. Hidden when a required add-on exists. */\n onSkip?: () => void\n /** CTA label. Old checkout uses \"CONFIRM SELECTION\". */\n buttonLabel?: string\n /** Eyebrow above the title. Old checkout uses \"Get Your Tickets\". */\n eyebrow?: string\n /** Section heading. Old checkout uses \"UPGRADES & ADD-ONS\". */\n heading?: string\n className?: string\n}\n\nexport const AddOns: FC<AddOnsProps> = ({\n eventId,\n onContinue,\n onSkip,\n buttonLabel,\n eyebrow,\n heading,\n className,\n}) => {\n const t = useT()\n const checkout = useCheckoutContext()\n const buttonText = buttonLabel ?? t('addons.confirmSelection')\n const eyebrowText = eyebrow ?? t('addons.eyebrow')\n const headingText = heading ?? t('addons.heading')\n // No onContinue ⇒ combined form (inside <EmbeddedCheckout/>): apply the selection live\n // (no \"confirm\" click) — the old checkout applied add-ons at checkout too.\n const combined = !onContinue\n const addonsQuery = hooks.useEventAddons(eventId)\n const all = addonsQuery.data ?? []\n const addons = ttf.events.filterAddonsForTickets(all, checkout.ticketTypeIds)\n // Tickets reserved in the cart — the bound for ticket-scoped add-on caps\n // (the hosted partial's `selectedTotalQty()`).\n const ticketQuantity = (checkout.breakdown?.tickets ?? []).reduce(\n (total, line) => total + (line.quantity || 0),\n 0\n )\n\n const [qty, setQty] = useState<Record<string, number>>(checkout.addOns ?? {})\n const [capture, setCapture] = useState<Record<string, CustomFieldValues>>(\n checkout.addOnDataCapture ?? {}\n )\n const [error, setError] = useState('')\n\n // Custom-field groups keyed by add-on id (scope 'add-on', group id = add-on id).\n const fieldGroups = useMemo(() => {\n const map: Record<string, (typeof checkout.customFields)[number]> = {}\n for (const g of checkout.customFields) if (g.scope === 'add-on') map[g.id] = g\n return map\n }, [checkout.customFields])\n\n // Combined mode: debounce-apply the selection to the cart (which reprices)\n // as it changes, instead of gating behind a \"confirm\" button.\n useEffect(() => {\n if (!combined) return\n const selection = Object.fromEntries(Object.entries(qty).filter(([, n]) => n > 0))\n if (JSON.stringify(selection) === JSON.stringify(checkout.addOns ?? {})) return\n const captureForSelected = Object.fromEntries(\n Object.entries(capture).filter(([id]) => (selection[id] ?? 0) > 0)\n )\n const t = setTimeout(() => {\n checkout.setAddonDataCapture(captureForSelected)\n checkout.setAddons(selection).catch((e) => setError(errorMessage(e)))\n }, 500)\n return () => clearTimeout(t)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [combined, qty, capture])\n\n const hasRequired = (checkout.requiredAddOns ?? []).some((a) => a.required)\n const head = (\n <div className=\"tf-checkout-addons__head\">\n {eyebrowText && <span className=\"tf-checkout-addons__eyebrow\">{eyebrowText}</span>}\n <span className=\"tf-checkout-addons__heading\">{headingText}</span>\n {onSkip && !hasRequired && (\n <button type=\"button\" className=\"tf-checkout-addons__skip\" onClick={onSkip}>\n Skip\n </button>\n )}\n </div>\n )\n\n if (addonsQuery.isLoading) {\n return (\n <Card className={className}>\n {head}\n <div className=\"tf-checkout-section-loader\">\n <Loader />\n </div>\n </Card>\n )\n }\n if (addons.length === 0) return null\n // A catalog containing only unavailable rows is not a useful checkout step.\n // Required sold-out add-ons are already exempted by the engine preflight.\n if (addons.every((addon) => addon.stock === 0)) return null\n\n // The hosted cap — ticket-quantity / per-ticket / max-quantity bounds. The\n // server hard-rejects anything above it, so never offer a larger number.\n const max = (a: EventAddon) => addOnMaxQuantity(a, ticketQuantity)\n const soldOut = (a: EventAddon) => a.stock === 0\n\n // Group add-ons under their groupName heading (nulls fall under no heading).\n const groups: { heading: string | null; items: EventAddon[] }[] = []\n for (const a of addons) {\n const last = groups[groups.length - 1]\n if (last && last.heading === (a.groupName ?? null)) last.items.push(a)\n else groups.push({ heading: a.groupName ?? null, items: [a] })\n }\n\n const missing = checkout.missingRequiredAddonNames\n const save = () => {\n setError('')\n const selection = Object.fromEntries(Object.entries(qty).filter(([, n]) => n > 0))\n // Only keep captured fields for add-ons that are actually selected.\n const captureForSelected = Object.fromEntries(\n Object.entries(capture).filter(([id]) => (selection[id] ?? 0) > 0)\n )\n checkout.setAddonDataCapture(captureForSelected)\n checkout\n .setAddons(selection)\n .then(() => onContinue?.())\n .catch((e) => setError(errorMessage(e)))\n }\n\n const selectedCount = Object.values(qty).filter((n) => n > 0).length\n\n return (\n <Card className={className}>\n {head}\n <p className=\"tf-checkout-addons__subtitle\">\n PLEASE SELECT FROM THE OPTIONAL ADD-ONS BELOW\n </p>\n\n {groups.map((g, gi) => (\n <Fragment key={g.heading ?? `g${gi}`}>\n {g.heading && <div className=\"tf-checkout-addons__group\">{g.heading}</div>}\n {g.items.map((a) => {\n const n = qty[a.id] ?? 0\n const group = fieldGroups[a.id]\n return (\n <div key={a.id} className=\"tf-checkout-addons__item\">\n <div className=\"tf-checkout-addons__row\">\n <div className=\"tf-checkout-addons__info\">\n <div className=\"tf-checkout-addons__name\">\n {a.name}\n {a.required && (\n <span className=\"tf-checkout-addons__req\"> · required</span>\n )}\n </div>\n <div className=\"tf-checkout-addons__meta\">\n <PriceLine\n currency={a.currency}\n amount={a.price}\n note={a.feeIncluded ? 'incl. fees' : undefined}\n />\n </div>\n {a.description && (\n <div\n className=\"tf-checkout-addons__desc\"\n dangerouslySetInnerHTML={{ __html: a.description }}\n />\n )}\n </div>\n {soldOut(a) ? (\n <span className=\"tf-checkout-tickets__soldout\">\n {t('tickets.soldOut')}\n </span>\n ) : (\n <QuantitySelect\n value={n}\n min={0}\n max={max(a)}\n onChange={(v) => setQty((q) => ({ ...q, [a.id]: v }))}\n />\n )}\n </div>\n {n > 0 && group && (\n <div className=\"tf-checkout-addons__fields\">\n <CustomFieldGroupFields\n group={group}\n values={capture[a.id] ?? {}}\n onChange={(name, val) =>\n setCapture((c) => ({\n ...c,\n [a.id]: { ...(c[a.id] ?? {}), [name]: val },\n }))\n }\n />\n </div>\n )}\n </div>\n )\n })}\n </Fragment>\n ))}\n\n {!combined && (\n <Button\n block\n onClick={save}\n loading={checkout.isBusy}\n disabled={checkout.isBusy || selectedCount === 0}\n >\n {checkout.isBusy ? t('addons.updating') : buttonText}\n </Button>\n )}\n {missing.length > 0 && (\n <p className=\"tf-checkout-note\">Required add-on: {missing.join(', ')}.</p>\n )}\n {(error || checkout.error) && (\n <p className=\"tf-checkout-error-text\">{error || checkout.error}</p>\n )}\n </Card>\n )\n}\n","/**\n * `<BillingInfo/>` — the buyer + attendee details step. Collects: the buyer's\n * name/email + event-gated buyer fields (Instagram/nationality/gender), any\n * ORDER-level custom fields, PER-HOLDER name + ticket-level custom fields (when\n * the event requires holder names or has ticket-scoped fields), and marketing\n * opt-ins. Writes it all into the engine (`setBilling` with `dataCapture`,\n * `setHolders` with `ticketDataCapture`, `setConsent`) so `<Payment/>`'s\n * pre-flight passes. Use it alongside `<Payment/>`, or set those yourself.\n */\nimport React, {\n Fragment,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ChangeEvent,\n type FC,\n type ReactNode,\n} from 'react'\n\nimport {\n hooks,\n mapProfileToBilling,\n missingCheckoutDetails,\n isEmail,\n ticketFieldsFor,\n type CheckoutBilling,\n type CheckoutHolder,\n type CustomFieldValues,\n type EventCustomFieldGroup,\n} from 'tf-checkout-shared'\nimport { PhoneInput, type CountryIso2 } from 'react-international-phone'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext, useCheckoutValidation } from '../ui/CheckoutProvider'\nimport { useT } from '../ui/I18nProvider'\nimport { CustomFieldInput } from '../ui/CustomFields'\nimport { Checkbox, Field, FieldRow, Input } from '../ui/Field'\nimport { BillingAddressFields } from './billing/BillingAddressFields'\nimport { BuyerField } from './billing/BuyerField'\nimport { DOB_MIN, isBlankPhone, toDateInputValue, todayISO } from './billing/fieldRules'\nimport { TicketHoldersCard } from './billing/TicketHoldersCard'\nimport type { BillingDraft, HolderDraft } from './billing/types'\n\nexport interface BillingInfoProps {\n /** Event context is used to default the country and phone dial code. */\n eventId?: string\n /** Fired once billing is saved to the engine — e.g. reveal `<Payment/>`. */\n onContinue?: () => void\n /** Section heading. Old checkout uses \"Billing Information\". */\n heading?: string\n /** CTA label. */\n buttonLabel?: string\n /** When provided and the buyer isn't signed in, shows a \"Login & skip ahead\"\n * row. The current email is passed when login follows an account match. */\n onLogin?: (email?: string) => void\n /** Hide this card only after a signed-in profile satisfies every ordinary\n * billing requirement and the event needs no extra buyer/holder answers. */\n skipWhenProfileComplete?: boolean\n /** Ask guests to repeat their email and require an exact match. */\n requireEmailConfirmation?: boolean\n /** Always collect one named holder per selected ticket. EmbeddedCheckout uses\n * this to match tf-sports; standalone sections default to backend gates. */\n collectTicketHolders?: boolean\n /** When holder details are enabled, also collect each holder's email and phone. */\n collectHolderContact?: boolean\n /** Marketing opt-in labels. Render a checkbox for each provided (unchecked). */\n ttfOptInLabel?: string\n brandOptInLabel?: string\n /** Required host privacy acknowledgement. The URL is supplied by the consumer. */\n privacyPolicy?: CheckoutPrivacyPolicy\n /** Show the legacy inline \"Required\" error after a failed payment attempt. */\n showPrivacyError?: boolean\n /** Optional numbered badge (old checkout shows none — omitted by default). */\n step?: ReactNode\n className?: string\n}\n\nexport interface CheckoutPrivacyPolicy {\n url: string\n brandName: string\n linkLabel?: string\n}\n\nexport const BillingInfo: FC<BillingInfoProps> = ({\n eventId,\n onContinue,\n heading,\n buttonLabel,\n onLogin,\n skipWhenProfileComplete = false,\n requireEmailConfirmation = false,\n collectTicketHolders = false,\n collectHolderContact = false,\n ttfOptInLabel,\n brandOptInLabel,\n privacyPolicy,\n showPrivacyError = false,\n step,\n className,\n}) => {\n const t = useT()\n const checkout = useCheckoutContext()\n const validation = useCheckoutValidation()\n const headingText = heading ?? t('billing.heading')\n const buttonText = buttonLabel ?? t('billing.continueToPayment')\n const ttfOptInText = ttfOptInLabel ?? t('billing.ttfOptIn')\n const profile = hooks.useProfile({ retry: false })\n const event = hooks.useEvent(eventId)\n // No onContinue ⇒ this is one combined form (inside <EmbeddedCheckout/>): mirror the\n // fields into the engine live and drop the \"continue\" button, so the buyer\n // fills billing + pays with ONE button — the way the old checkout flowed.\n const combined = !onContinue\n\n const [billing, setBilling] = useState<BillingDraft>({\n firstName: checkout.billing?.firstName ?? '',\n lastName: checkout.billing?.lastName ?? '',\n email: checkout.billing?.email ?? '',\n confirmEmail: checkout.billing?.confirmEmail ?? '',\n phone: checkout.billing?.phone,\n streetAddress: checkout.billing?.streetAddress,\n city: checkout.billing?.city,\n zip: checkout.billing?.zip,\n countryId: checkout.billing?.countryId,\n stateId: checkout.billing?.stateId,\n countryCode: checkout.billing?.countryCode,\n stateCode: checkout.billing?.stateCode,\n nationality: checkout.billing?.nationality,\n gender: checkout.billing?.gender,\n instagramHandle: checkout.billing?.instagramHandle,\n })\n const [dataCapture, setDataCapture] = useState<CustomFieldValues>(\n checkout.billing?.dataCapture ?? {}\n )\n const [holders, setHolders] = useState<HolderDraft[]>(() =>\n checkout.holders.map((holder) => ({\n firstName: holder.firstName,\n lastName: holder.lastName,\n email: holder.email,\n phone: holder.phone ?? '',\n ticketTypeId: holder.ticketTypeId,\n ticketDataCapture: holder.ticketDataCapture ?? {},\n }))\n )\n const [consent, setConsent] = useState({ ttfOptIn: false, brandOptIn: false })\n const [dob, setDob] = useState(() => {\n const b = checkout.billing\n if (!b?.dobDay || !b.dobMonth || !b.dobYear) return ''\n return `${b.dobYear}-${String(b.dobMonth).padStart(2, '0')}-${String(\n b.dobDay\n ).padStart(2, '0')}`\n }) // ISO yyyy-mm-dd\n const restoredHolders = useRef(checkout.holders)\n const profileSeeded = useRef(false)\n const countryDefaultApplied = useRef(Boolean(checkout.billing?.countryId))\n\n const gates = checkout.fieldGates\n\n // Custom-field groups by scope.\n const orderGroups = useMemo(\n () => checkout.customFields.filter((g) => g.scope === 'order'),\n [checkout.customFields]\n )\n const ticketGroups = useMemo(\n () => checkout.customFields.filter((g) => g.scope === 'ticket'),\n [checkout.customFields]\n )\n const ticketFields = useMemo(\n () => ticketGroups.flatMap((g) => g.fields),\n [ticketGroups]\n )\n const holderNamesRequired = checkout.holderNamesRequired || collectTicketHolders\n const showHolders = holderNamesRequired || ticketFields.length > 0\n\n // One holder slot per ticket, tagged with its ticket type (drives ticket-field\n // scoping + the engine's per-holder validation).\n const slots = useMemo(() => {\n const out: { ticketTypeId?: string; ticketName?: string }[] = []\n const lines = checkout.breakdown?.tickets ?? []\n for (const line of lines)\n for (let i = 0; i < line.quantity; i++)\n out.push({ ticketTypeId: line.ticketTypeId, ticketName: line.name })\n if (!out.length) {\n const total = checkout.selections.reduce((n, s) => n + s.quantity, 0)\n for (let i = 0; i < total; i++) out.push({})\n }\n return out\n }, [checkout.breakdown, checkout.selections])\n\n // The initial state above restores anything already on the engine. A profile\n // that arrives later may fill blanks ONCE, but must never be consulted again\n // while the buyer edits — otherwise clearing the final character restores the\n // previous engine value on the next live commit.\n useEffect(() => {\n const p = profile.data\n if (!p || profileSeeded.current) return\n profileSeeded.current = true\n const profileBilling = mapProfileToBilling(p)\n setBilling((prev) => {\n const next = {\n ...prev,\n firstName: prev.firstName || profileBilling.firstName || '',\n lastName: prev.lastName || profileBilling.lastName || '',\n email: prev.email || profileBilling.email || '',\n confirmEmail:\n prev.confirmEmail || (checkout.isLoggedIn ? profileBilling.email : '') || '',\n phone:\n (isBlankPhone(prev.phone) ? undefined : prev.phone) || profileBilling.phone,\n streetAddress: prev.streetAddress || profileBilling.streetAddress,\n city: prev.city || profileBilling.city,\n zip: prev.zip || profileBilling.zip,\n countryId: prev.countryId || profileBilling.countryId,\n stateId: prev.stateId || profileBilling.stateId,\n }\n const keys = Object.keys(next) as (keyof BillingDraft)[]\n return keys.every((k) => next[k] === prev[k]) ? prev : next\n })\n // Date of birth lives outside `billing`, so it has to be seeded here too —\n // and it has to be here rather than in its own effect or in the useState\n // initialiser: the initialiser runs before the profile resolves, and a\n // separate effect would re-fire and overwrite the buyer, since the live\n // commit below depends on `dob`. This effect already runs exactly once.\n setDob((prev) => {\n if (prev) return prev\n const { dobYear, dobMonth, dobDay } = profileBilling\n return toDateInputValue(dobYear, dobMonth, dobDay) ?? prev\n })\n }, [profile.data, checkout.isLoggedIn])\n\n // Resize holders to the slot count, preserving typed values; tag ticket type.\n useEffect(() => {\n setHolders((prev) =>\n slots.map((s, i) => ({\n firstName: prev[i]?.firstName ?? restoredHolders.current[i]?.firstName ?? '',\n lastName: prev[i]?.lastName ?? restoredHolders.current[i]?.lastName ?? '',\n email: prev[i]?.email ?? restoredHolders.current[i]?.email ?? '',\n phone: prev[i]?.phone ?? restoredHolders.current[i]?.phone ?? '',\n ticketDataCapture:\n prev[i]?.ticketDataCapture ??\n restoredHolders.current[i]?.ticketDataCapture ??\n {},\n ticketTypeId: s.ticketTypeId,\n ticketName: s.ticketName,\n }))\n )\n }, [slots])\n\n // Match the storefront: ticket 1 silently starts as the buyer. The legacy\n // checkout has no extra \"use buyer details\" control.\n useEffect(() => {\n if (!showHolders) return\n setHolders((prev) =>\n prev.map((holder, index) =>\n index === 0\n ? {\n ...holder,\n firstName: billing.firstName,\n lastName: billing.lastName,\n email: billing.email,\n phone: billing.phone ?? '',\n }\n : holder\n )\n )\n }, [showHolders, billing.firstName, billing.lastName, billing.email, billing.phone])\n\n // Debounced \"this email already has an account\" check → nudges the buyer to\n // sign in (autofill + avoid duplicate accounts). Skips signed-in buyers.\n useEffect(() => {\n const email = billing.email.trim()\n if (checkout.isLoggedIn || !isEmail(email)) return\n const t = setTimeout(\n () => checkout.checkBuyerEmail(email).catch(() => undefined),\n 600\n )\n return () => clearTimeout(t)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [billing.email, checkout.isLoggedIn])\n const emailTaken =\n !checkout.isLoggedIn && checkout.existingAccountEmail === billing.email.trim()\n\n const needsNationality = checkout.buyerFields.some((f) => f.kind === 'nationality')\n const countriesQuery = hooks.useCountries({\n enabled: needsNationality || gates.showAddress,\n })\n const countries = useMemo(() => countriesQuery.data ?? [], [countriesQuery.data])\n const statesQuery = hooks.useStates(billing.countryId, {\n enabled: Boolean(billing.countryId),\n })\n const states = useMemo(() => statesQuery.data ?? [], [statesQuery.data])\n\n // Event country → signed-in profile → US, matching the hosted checkout's\n // country preference order. Also retain the ISO code for Stripe + phone UI.\n useEffect(() => {\n if (\n countryDefaultApplied.current ||\n billing.countryId ||\n countries.length === 0 ||\n profile.isLoading ||\n (eventId && event.isLoading)\n ) {\n return\n }\n const eventCode = event.data?.countryCode?.toLowerCase()\n const preferred =\n countries.find((country) => country.code?.toLowerCase() === eventCode) ??\n countries.find(\n (country) =>\n profile.data?.countryId !== null &&\n profile.data?.countryId !== undefined &&\n String(country.id) === String(profile.data.countryId)\n ) ??\n countries.find((country) => country.code?.toLowerCase() === 'us')\n if (!preferred) return\n countryDefaultApplied.current = true\n setBilling((current) => {\n // The profile-seed effect above can run in this same commit, so the\n // `billing` this effect closed over is stale — it still shows no country\n // even though the seed just supplied one (with its state). Re-check the\n // live value here: without it the default overwrote the seeded country\n // and blanked `stateId`, which is why a returning buyer's State/County\n // came back empty while every other saved field prefilled.\n if (current.countryId) return current\n return {\n ...current,\n countryId: String(preferred.id),\n countryCode: preferred.code?.toUpperCase(),\n stateId: undefined,\n stateCode: undefined,\n }\n })\n }, [\n billing.countryId,\n countries,\n profile.isLoading,\n profile.data?.countryId,\n eventId,\n event.isLoading,\n event.data?.countryCode,\n ])\n\n useEffect(() => {\n if (!billing.countryId) return\n const country = countries.find(\n (candidate) => String(candidate.id) === String(billing.countryId)\n )\n const countryCode = country?.code?.toUpperCase()\n if (countryCode && countryCode !== billing.countryCode) {\n setBilling((current) => ({ ...current, countryCode }))\n }\n }, [billing.countryId, billing.countryCode, countries])\n\n useEffect(() => {\n if (!billing.stateId) return\n const state = states.find(\n (candidate) => String(candidate.id) === String(billing.stateId)\n )\n const stateCode = state?.code\n if (stateCode && stateCode !== billing.stateCode) {\n setBilling((current) => ({ ...current, stateCode }))\n }\n }, [billing.stateId, billing.stateCode, states])\n\n const setB = (k: keyof BillingDraft) => (e: ChangeEvent<HTMLInputElement>) =>\n setBilling((b) => ({ ...b, [k]: e.target.value }))\n\n const patchHolder = (i: number, patch: Partial<HolderDraft>) =>\n setHolders((hs) => hs.map((h, j) => (j === i ? { ...h, ...patch } : h)))\n\n const dobMax = useMemo(todayISO, [])\n const [dobYear, dobMonth, dobDay] = dob ? dob.split('-').map(Number) : []\n // A dial code on its own is not a phone number — see `isBlankPhone`.\n const buyerPhone = isBlankPhone(billing.phone) ? undefined : billing.phone\n const committedBilling: CheckoutBilling = {\n ...checkout.billing,\n ...billing,\n phone: buyerPhone,\n stateRequired: gates.showAddress && Boolean(billing.countryId) && states.length > 0,\n dataCapture,\n dobDay,\n dobMonth,\n dobYear,\n }\n const committedHolders: CheckoutHolder[] = holders.map((holder) => {\n const holderPhone = isBlankPhone(holder.phone) ? '' : holder.phone\n return {\n firstName: holderNamesRequired\n ? holder.firstName\n : holder.firstName || billing.firstName,\n lastName: holderNamesRequired\n ? holder.lastName\n : holder.lastName || billing.lastName,\n email:\n showHolders && collectHolderContact\n ? holder.email\n : holder.email || billing.email,\n phone:\n showHolders && collectHolderContact\n ? holderPhone\n : holderPhone || buyerPhone || '',\n ticketTypeId: holder.ticketTypeId,\n ticketDataCapture: holder.ticketDataCapture,\n }\n })\n const missingDetails = missingCheckoutDetails(\n {\n billing: committedBilling,\n holders: committedHolders,\n selections: checkout.selections,\n breakdown: checkout.breakdown,\n holderNamesRequired: checkout.holderNamesRequired,\n fieldGates: checkout.fieldGates,\n customFields: checkout.customFields,\n },\n {\n requireEmailConfirmation,\n collectTicketHolders,\n requireHolderContact: collectHolderContact,\n }\n )\n const complete = missingDetails.length === 0\n const showValidation = validation.attempt > 0\n const missingSet = new Set(missingDetails)\n const fieldError = (key: string, message = t('billing.fieldRequired')) =>\n showValidation && missingSet.has(key) ? message : undefined\n const dobError = showValidation\n ? missingDetails.find(\n (detail) => detail === 'Date of birth' || detail.startsWith('Age ')\n )\n : undefined\n const phoneCountry = (\n billing.countryCode ??\n event.data?.countryCode ??\n 'US'\n )?.toLowerCase() as CountryIso2\n\n const commit = () => {\n checkout.setBilling(committedBilling)\n checkout.setHolders(committedHolders)\n if (ttfOptInText || brandOptInLabel) checkout.setConsent(consent)\n }\n\n // Combined mode: keep the engine in sync as the form is filled, so <Payment/>\n // is always chargeable without a separate \"continue\" click.\n useEffect(() => {\n if (combined) commit()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [combined, billing, holders, consent, dob, dataCapture])\n\n const renderGroupFields = (\n group: EventCustomFieldGroup,\n values: CustomFieldValues,\n onChange: (name: string, v: string | string[]) => void,\n ticketTypeId?: string,\n ticketIndex?: number\n ) =>\n ticketFieldsFor(group.fields, ticketTypeId).map((f) => {\n const label = f.label || f.name\n const missingKey =\n ticketIndex === undefined ? label : `${label} (ticket ${ticketIndex + 1})`\n return (\n <CustomFieldInput\n key={f.id}\n field={f}\n value={values[f.name]}\n error={fieldError(missingKey)}\n onChange={(v) => onChange(f.name, v)}\n />\n )\n })\n\n const hasEventSpecificDetails =\n checkout.buyerFields.length > 0 ||\n checkout.customFields.some((group) => group.fields.length > 0) ||\n showHolders ||\n gates.showDob\n const skipBilling =\n skipWhenProfileComplete &&\n checkout.isLoggedIn &&\n profile.isSuccess &&\n complete &&\n !hasEventSpecificDetails\n\n // This is the safe EmbeddedCheckout interpretation of legacy\n // `skip_billing_page`: payment remains visible; only a fully satisfied,\n // ordinary billing card disappears.\n if (skipBilling) return null\n\n return (\n <>\n <Card className={className}>\n <SectionHeader step={step} title={headingText} />\n\n {onLogin && !checkout.isLoggedIn && (\n <div className=\"tf-checkout-billing__login\">\n <span>Login & skip ahead:</span>\n <button\n type=\"button\"\n className=\"tf-checkout-billing__login-btn\"\n onClick={() => onLogin()}\n >\n Login\n </button>\n </div>\n )}\n\n <FieldRow>\n <Field\n error={fieldError('First name', 'First name is required.')}\n invalid={Boolean(fieldError('First name'))}\n >\n <Input\n placeholder={t('billing.firstNamePlaceholder')}\n value={billing.firstName}\n required\n invalid={Boolean(fieldError('First name'))}\n aria-invalid={Boolean(fieldError('First name'))}\n onChange={setB('firstName')}\n />\n </Field>\n <Field\n error={fieldError('Last name', 'Last name is required.')}\n invalid={Boolean(fieldError('Last name'))}\n >\n <Input\n placeholder={t('billing.lastNamePlaceholder')}\n value={billing.lastName}\n required\n invalid={Boolean(fieldError('Last name'))}\n aria-invalid={Boolean(fieldError('Last name'))}\n onChange={setB('lastName')}\n />\n </Field>\n </FieldRow>\n <FieldRow>\n <Field\n error={fieldError('Valid email address', 'Enter a valid email address.')}\n invalid={Boolean(fieldError('Valid email address'))}\n >\n <Input\n type=\"email\"\n autoComplete=\"email\"\n placeholder={t('billing.emailPlaceholder')}\n value={billing.email}\n required\n invalid={Boolean(fieldError('Valid email address'))}\n aria-invalid={Boolean(fieldError('Valid email address'))}\n onChange={setB('email')}\n />\n </Field>\n {requireEmailConfirmation && !checkout.isLoggedIn && (\n <Field\n error={fieldError(\n 'Matching email confirmation',\n t('billing.emailMustMatch')\n )}\n invalid={Boolean(fieldError('Matching email confirmation'))}\n >\n <Input\n type=\"email\"\n autoComplete=\"email\"\n placeholder={t('billing.confirmEmailPlaceholder')}\n value={billing.confirmEmail ?? ''}\n required\n invalid={Boolean(fieldError('Matching email confirmation'))}\n aria-invalid={Boolean(fieldError('Matching email confirmation'))}\n onChange={setB('confirmEmail')}\n />\n </Field>\n )}\n </FieldRow>\n {!showValidation &&\n requireEmailConfirmation &&\n billing.confirmEmail &&\n billing.confirmEmail.trim().toLowerCase() !==\n billing.email.trim().toLowerCase() && (\n <p className=\"tf-checkout-error-text\">{t('billing.emailMismatch')}</p>\n )}\n {emailTaken && (\n <p className=\"tf-checkout-note tf-checkout-billing__email-taken\">\n {t('billing.emailRegistered')}{' '}\n {onLogin ? (\n <button\n type=\"button\"\n className=\"tf-checkout-billing__login-link\"\n onClick={() => onLogin(billing.email)}\n >\n {t('billing.loginAutofill')}\n </button>\n ) : (\n t('billing.loginAutofillPlain')\n )}\n </p>\n )}\n\n {checkout.buyerFields.map((f) => (\n <BuyerField\n key={f.key}\n field={f}\n value={String(billing[f.key] ?? '')}\n onChange={(v) => setBilling((b) => ({ ...b, [f.key]: v }))}\n countries={countries}\n error={fieldError(\n f.kind === 'nationality'\n ? t('billing.nationality')\n : f.kind === 'gender'\n ? t('billing.gender')\n : t('billing.instagramHandle')\n )}\n />\n ))}\n\n {gates.showPhone && (\n <Field\n label={gates.phoneRequired ? t('billing.phone') : t('billing.phoneOptional')}\n error={fieldError('Valid phone number', t('billing.phoneInvalid'))}\n invalid={Boolean(fieldError('Valid phone number'))}\n >\n <PhoneInput\n className=\"tf-checkout-phone\"\n inputClassName={`tf-checkout-input tf-checkout-phone__input${\n fieldError('Valid phone number') ? ' tf-checkout-input--invalid' : ''\n }`}\n defaultCountry={phoneCountry}\n // The flag owns the country; the input holds the national number\n // only. Without `disableDialCodeAndPrefix` the empty field still\n // expects a full international number, so a Mexican buyer typing\n // \"5512345678\" has it read as a dial code and the country guess\n // flips them to Brazil (+55) — submitting the wrong code.\n disableDialCodeAndPrefix\n showDisabledDialCodeAndPrefix\n disableDialCodePrefill\n value={billing.phone ?? ''}\n required={gates.phoneRequired}\n placeholder={t('billing.phonePlaceholder')}\n inputProps={{\n autoComplete: 'tel',\n 'aria-label': t('billing.phoneAria'),\n 'aria-invalid': Boolean(fieldError('Valid phone number')),\n }}\n onChange={(phone) => setBilling((current) => ({ ...current, phone }))}\n />\n </Field>\n )}\n\n {gates.showDob && (\n <Field\n label={\n gates.minimumAge\n ? t('billing.dobWithAge', { age: gates.minimumAge })\n : t('billing.dob')\n }\n error={\n dobError === 'Date of birth'\n ? t('billing.dobRequired')\n : dobError\n ? t('billing.ageMinimum', { age: gates.minimumAge ?? '' })\n : undefined\n }\n invalid={Boolean(dobError)}\n >\n <Input\n type=\"date\"\n value={dob}\n required\n // A date input with no bounds lets the browser's year segment run\n // to six digits (\"202555\") and accept dates in the future. The\n // range both caps the year at four digits and keeps the value a\n // date someone could actually have been born on.\n min={DOB_MIN}\n max={dobMax}\n invalid={Boolean(dobError)}\n aria-invalid={Boolean(dobError)}\n onChange={(e) => setDob(e.target.value)}\n />\n </Field>\n )}\n\n {gates.showAddress && (\n <BillingAddressFields\n billing={billing}\n countries={countries}\n states={states}\n fieldError={fieldError}\n setBilling={setBilling}\n />\n )}\n\n {/* Order-level custom fields */}\n {orderGroups.map((g) => (\n <Fragment key={g.id}>\n {g.label && (\n <div className=\"tf-checkout-billing__section-label\">{g.label}</div>\n )}\n {renderGroupFields(g, dataCapture, (name, v) =>\n setDataCapture((d) => ({ ...d, [name]: v }))\n )}\n </Fragment>\n ))}\n\n {/* Marketing opt-ins (optional) */}\n {brandOptInLabel && (\n <Checkbox\n checked={consent.brandOptIn}\n onChange={(e) => setConsent((c) => ({ ...c, brandOptIn: e.target.checked }))}\n className=\"tf-checkout-checkbox--consent\"\n label={brandOptInLabel}\n />\n )}\n {privacyPolicy ? (\n <div\n className={\n (showPrivacyError || showValidation) && !consent.ttfOptIn\n ? 'tf-checkout-consent--error'\n : ''\n }\n data-checkout-invalid={\n ((showPrivacyError || showValidation) && !consent.ttfOptIn) || undefined\n }\n >\n <Checkbox\n required\n checked={consent.ttfOptIn}\n aria-invalid={(showPrivacyError || showValidation) && !consent.ttfOptIn}\n onChange={(e) => setConsent((c) => ({ ...c, ttfOptIn: e.target.checked }))}\n className=\"tf-checkout-checkbox--consent\"\n label={\n <>\n {t('billing.privacyAgree', { brand: privacyPolicy.brandName })}{' '}\n <a href={privacyPolicy.url} target=\"_blank\" rel=\"noreferrer\">\n {privacyPolicy.linkLabel || t('billing.privacyLink')}\n </a>\n {' *'}\n </>\n }\n />\n {(showPrivacyError || showValidation) && !consent.ttfOptIn && (\n <div className=\"tf-checkout-consent__error\">{t('common.required')}</div>\n )}\n </div>\n ) : ttfOptInText ? (\n <Checkbox\n checked={consent.ttfOptIn}\n onChange={(e) => setConsent((c) => ({ ...c, ttfOptIn: e.target.checked }))}\n className=\"tf-checkout-checkbox--consent\"\n label={ttfOptInText}\n />\n ) : null}\n {!combined && (\n <>\n <Button\n block\n onClick={() => {\n if (!complete) {\n validation.requestValidation()\n return\n }\n commit()\n onContinue?.()\n }}\n >\n {buttonText}\n </Button>\n </>\n )}\n </Card>\n {showHolders && (\n <TicketHoldersCard\n holders={holders}\n holderNamesRequired={holderNamesRequired}\n collectHolderContact={collectHolderContact}\n phoneCountry={phoneCountry}\n fieldError={fieldError}\n patchHolder={patchHolder}\n renderCustomFields={(holder, index) =>\n ticketGroups.map((group) =>\n renderGroupFields(\n group,\n holder.ticketDataCapture,\n (name, value) =>\n patchHolder(index, {\n ticketDataCapture: {\n ...holder.ticketDataCapture,\n [name]: value,\n },\n }),\n holder.ticketTypeId,\n index\n )\n )\n }\n />\n )}\n </>\n )\n}\n","import React, { type Dispatch, type FC, type SetStateAction } from 'react'\n\nimport { Field, FieldRow, Input, Select } from '../../ui/Field'\nimport { useT } from '../../ui/I18nProvider'\nimport type { BillingDraft, BillingFieldError, LocationOption } from './types'\n\ninterface BillingAddressFieldsProps {\n billing: BillingDraft\n countries: LocationOption[]\n states: LocationOption[]\n fieldError: BillingFieldError\n setBilling: Dispatch<SetStateAction<BillingDraft>>\n}\n\n/** Address fields shared by the embedded and stepped billing experiences. */\nexport const BillingAddressFields: FC<BillingAddressFieldsProps> = ({\n billing,\n countries,\n states,\n fieldError,\n setBilling,\n}) => {\n const t = useT()\n const setValue =\n (key: keyof BillingDraft) => (event: React.ChangeEvent<HTMLInputElement>) =>\n setBilling((current) => ({ ...current, [key]: event.target.value }))\n\n return (\n <>\n <div className=\"tf-checkout-billing__section-label\">{t('billing.address')}</div>\n <Field\n error={fieldError('Street address', t('billing.streetRequired'))}\n invalid={Boolean(fieldError('Street address'))}\n >\n <Input\n placeholder={t('billing.streetPlaceholder')}\n autoComplete=\"street-address\"\n value={billing.streetAddress ?? ''}\n required\n invalid={Boolean(fieldError('Street address'))}\n aria-invalid={Boolean(fieldError('Street address'))}\n onChange={setValue('streetAddress')}\n />\n </Field>\n <FieldRow>\n <Field\n error={fieldError('City', t('billing.cityRequired'))}\n invalid={Boolean(fieldError('City'))}\n >\n <Input\n placeholder={t('billing.cityPlaceholder')}\n autoComplete=\"address-level2\"\n value={billing.city ?? ''}\n required\n invalid={Boolean(fieldError('City'))}\n aria-invalid={Boolean(fieldError('City'))}\n onChange={setValue('city')}\n />\n </Field>\n <Field\n error={fieldError('ZIP / postcode', t('billing.postcodeRequired'))}\n invalid={Boolean(fieldError('ZIP / postcode'))}\n >\n <Input\n placeholder={t('billing.postcodePlaceholder')}\n autoComplete=\"postal-code\"\n value={billing.zip ?? ''}\n required\n invalid={Boolean(fieldError('ZIP / postcode'))}\n aria-invalid={Boolean(fieldError('ZIP / postcode'))}\n onChange={setValue('zip')}\n />\n </Field>\n </FieldRow>\n <FieldRow>\n <Field\n error={fieldError('Country', t('billing.countryRequired'))}\n invalid={Boolean(fieldError('Country'))}\n >\n <Select\n value={billing.countryId ?? ''}\n aria-label={t('billing.countryLabel')}\n required\n invalid={Boolean(fieldError('Country'))}\n aria-invalid={Boolean(fieldError('Country'))}\n onChange={(event) => {\n const country = countries.find(\n (candidate) => String(candidate.id) === event.target.value\n )\n setBilling((current) => ({\n ...current,\n countryId: event.target.value,\n countryCode: country?.code?.toUpperCase(),\n stateId: undefined,\n stateCode: undefined,\n }))\n }}\n >\n <option value=\"\">{t('billing.countryEmpty')}</option>\n {countries.map((country) => (\n <option key={country.id} value={country.id}>\n {country.name}\n </option>\n ))}\n </Select>\n </Field>\n <Field\n error={fieldError('State / county', t('billing.stateRequired'))}\n invalid={Boolean(fieldError('State / county'))}\n >\n <Select\n value={billing.stateId ?? ''}\n disabled={!billing.countryId || states.length === 0}\n aria-label={t('billing.stateLabel')}\n required={states.length > 0}\n invalid={Boolean(fieldError('State / county'))}\n aria-invalid={Boolean(fieldError('State / county'))}\n onChange={(event) => {\n const state = states.find(\n (candidate) => String(candidate.id) === event.target.value\n )\n setBilling((current) => ({\n ...current,\n stateId: event.target.value,\n stateCode: state?.code,\n }))\n }}\n >\n <option value=\"\">\n {states.length > 0\n ? t('billing.stateEmptyRequired')\n : t('billing.stateEmpty')}\n </option>\n {states.map((state) => (\n <option key={state.id} value={state.id}>\n {state.name}\n </option>\n ))}\n </Select>\n </Field>\n </FieldRow>\n </>\n )\n}\n","import React, { type FC, type ReactNode } from 'react'\n\nimport type { BuyerFieldSpec } from 'tf-checkout-shared'\n\nimport { Field, Input, Select } from '../../ui/Field'\nimport type { LocationOption } from './types'\n\ninterface BuyerFieldProps {\n field: BuyerFieldSpec\n value: string\n countries: LocationOption[]\n error?: ReactNode\n onChange: (value: string) => void\n}\n\n/** Renders one backend-configured buyer field without owning form state. */\nexport const BuyerField: FC<BuyerFieldProps> = ({\n field,\n value,\n countries,\n error,\n onChange,\n}) => {\n const label = `${field.label}${field.required ? ' *' : ''}`\n const invalid = error !== undefined && error !== null\n\n if (field.kind === 'gender') {\n return (\n <Field label={label} error={error} invalid={invalid}>\n <Select\n value={value}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(event) => onChange(event.target.value)}\n >\n <option value=\"\">— select —</option>\n <option value=\"M\">Male</option>\n <option value=\"F\">Female</option>\n </Select>\n </Field>\n )\n }\n\n if (field.kind === 'nationality') {\n return (\n <Field label={label} error={error} invalid={invalid}>\n <Select\n value={value}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(event) => onChange(event.target.value)}\n >\n <option value=\"\">— select —</option>\n {countries.map((country) => (\n <option key={country.id} value={country.id}>\n {country.name}\n </option>\n ))}\n </Select>\n </Field>\n )\n }\n\n return (\n <Field label={label} error={error} invalid={invalid}>\n <Input\n placeholder=\"@handle or profile URL\"\n value={value}\n invalid={invalid}\n aria-invalid={invalid}\n onChange={(event) => onChange(event.target.value)}\n />\n </Field>\n )\n}\n","/**\n * Small value rules shared by the billing form's inputs. They live here rather\n * than in `../BillingInfo.tsx` so that file stays inside the checkout\n * architecture budget, and because each one encodes a non-obvious constraint\n * worth stating once.\n */\n\n/**\n * The phone control keeps the dial code outside the input, so it reports a bare\n * `\"+52\"` the moment it mounts — before the buyer has typed anything. A string\n * that short is a country prefix, not a number, so treat it as blank: it must\n * not out-rank a saved profile number, and it must never reach the API as a\n * phone in its own right.\n */\nexport const isBlankPhone = (phone?: string) =>\n !phone || /^\\+?\\d{0,4}$/.test(phone.trim())\n\n/** Earliest date of birth the form accepts. Nobody alive predates it. */\nexport const DOB_MIN = '1900-01-01'\n\n/**\n * Today as `yyyy-mm-dd` in the buyer's own timezone. Built from the local\n * calendar parts rather than `toISOString()`, which would roll over to\n * tomorrow's date for anyone east of Greenwich late in the day.\n */\nexport const todayISO = () => {\n const now = new Date()\n return [\n now.getFullYear(),\n String(now.getMonth() + 1).padStart(2, '0'),\n String(now.getDate()).padStart(2, '0'),\n ].join('-')\n}\n\n/** `dobDay/dobMonth/dobYear` → the `yyyy-mm-dd` a date input expects. */\nexport const toDateInputValue = (\n year?: number,\n month?: number,\n day?: number\n): string | undefined =>\n year && month && day\n ? `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`\n : undefined\n","import React, { type FC, type ReactNode } from 'react'\nimport { PhoneInput, type CountryIso2 } from 'react-international-phone'\n\nimport { Card, SectionHeader } from '../../ui/Card'\nimport { Field, FieldRow, Input } from '../../ui/Field'\nimport { useT } from '../../ui/I18nProvider'\nimport type { BillingFieldError, HolderDraft } from './types'\n\ninterface TicketHoldersCardProps {\n holders: HolderDraft[]\n holderNamesRequired: boolean\n collectHolderContact: boolean\n phoneCountry: CountryIso2\n fieldError: BillingFieldError\n renderCustomFields: (holder: HolderDraft, index: number) => ReactNode\n patchHolder: (index: number, patch: Partial<HolderDraft>) => void\n}\n\n/** Ticket-holder card kept separate from buyer billing for parity and reuse. */\nexport const TicketHoldersCard: FC<TicketHoldersCardProps> = ({\n holders,\n holderNamesRequired,\n collectHolderContact,\n phoneCountry,\n fieldError,\n renderCustomFields,\n patchHolder,\n}) => {\n const t = useT()\n\n return (\n <Card className=\"tf-checkout-billing__holders-card\">\n <SectionHeader title={t('billing.ticketHolders')} />\n {holders.map((holder, index) => {\n const firstNameKey = `Ticket ${index + 1} holder first name`\n const lastNameKey = `Ticket ${index + 1} holder last name`\n const emailKey = `Ticket ${index + 1} holder email`\n const phoneKey = `Ticket ${index + 1} holder phone`\n\n return (\n <div key={index} className=\"tf-checkout-billing__holder\">\n <div className=\"tf-checkout-billing__holder-title\">\n {t('billing.holderTitle', { number: index + 1 })}\n </div>\n {holderNamesRequired && (\n <FieldRow>\n <Field\n label={t('billing.holderFirstName')}\n error={fieldError(firstNameKey, t('billing.firstNameRequired'))}\n invalid={Boolean(fieldError(firstNameKey))}\n >\n <Input\n value={holder.firstName}\n required\n invalid={Boolean(fieldError(firstNameKey))}\n aria-invalid={Boolean(fieldError(firstNameKey))}\n onChange={(event) =>\n patchHolder(index, { firstName: event.target.value })\n }\n />\n </Field>\n <Field\n label={t('billing.holderLastName')}\n error={fieldError(lastNameKey, t('billing.lastNameRequired'))}\n invalid={Boolean(fieldError(lastNameKey))}\n >\n <Input\n value={holder.lastName}\n required\n invalid={Boolean(fieldError(lastNameKey))}\n aria-invalid={Boolean(fieldError(lastNameKey))}\n onChange={(event) =>\n patchHolder(index, { lastName: event.target.value })\n }\n />\n </Field>\n </FieldRow>\n )}\n {collectHolderContact && (\n <FieldRow>\n <Field\n label={t('billing.email')}\n error={fieldError(emailKey, t('billing.emailInvalid'))}\n invalid={Boolean(fieldError(emailKey))}\n >\n <Input\n type=\"email\"\n autoComplete=\"email\"\n value={holder.email}\n required\n invalid={Boolean(fieldError(emailKey))}\n aria-invalid={Boolean(fieldError(emailKey))}\n onChange={(event) =>\n patchHolder(index, { email: event.target.value })\n }\n />\n </Field>\n <Field\n label={t('billing.phone')}\n error={fieldError(phoneKey, t('billing.phoneInvalid'))}\n invalid={Boolean(fieldError(phoneKey))}\n >\n <PhoneInput\n className=\"tf-checkout-phone\"\n inputClassName={`tf-checkout-input tf-checkout-phone__input${\n fieldError(phoneKey) ? ' tf-checkout-input--invalid' : ''\n }`}\n defaultCountry={phoneCountry}\n // Matches the buyer phone field in ../BillingInfo.tsx — see\n // the note there on why the dial code must stay out of the\n // input.\n disableDialCodeAndPrefix\n showDisabledDialCodeAndPrefix\n disableDialCodePrefill\n value={holder.phone}\n required\n inputProps={{\n autoComplete: 'tel',\n 'aria-label': phoneKey,\n 'aria-invalid': Boolean(fieldError(phoneKey)),\n }}\n onChange={(phone) => patchHolder(index, { phone })}\n />\n </Field>\n </FieldRow>\n )}\n {renderCustomFields(holder, index)}\n </div>\n )\n })}\n </Card>\n )\n}\n","/**\n * `<Payment/>` — order review + payment-method selection + T&C, then place the\n * order. Buyer details come from `<BillingInfo/>` (read back off the shared\n * checkout). The method list is built from the event's gateway + `preOrderMethods()`\n * + the priced snapshot, and each selection maps to the right `placeOrder` rail\n * (Stripe card, Xendit card/e-wallet, PayPal, redirect rails, payment plan).\n */\nimport React, { useEffect, useMemo, useRef, useState, type FC } from 'react'\n\nimport {\n XENDIT_EWALLET_EXTRA_FIELD,\n errorMessage,\n missingCheckoutDetails,\n paymentPlanTerms,\n planConfirmLabel,\n planTermsTitle,\n ttf,\n type EventCondition,\n type PaymentRequest,\n type PlaceOrderResult,\n} from 'tf-checkout-shared'\n\nimport { CardInput, StripePaymentElement, XenditCardInput } from '../CardInput'\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext, useCheckoutValidation } from '../ui/CheckoutProvider'\nimport { useT } from '../ui/I18nProvider'\nimport { Checkbox } from '../ui/Field'\nimport { cx } from '../ui/cx'\nimport { Loader } from '../ui/Loader'\nimport { PaymentMethods, type PaymentMethodOption } from '../ui/PaymentMethods'\nimport { OrderSummary } from './OrderSummary'\n\ntype PreOrderMethods = Awaited<ReturnType<typeof ttf.cart.preOrderMethods>>\n\n/** Server spellings → display labels for Stripe redirect rails. */\nconst REDIRECT_LABELS: Record<string, string> = {\n klarna: 'Klarna',\n afterpay_clearpay: 'Afterpay / Clearpay',\n affirm: 'Affirm',\n ideal: 'iDEAL',\n bancontact: 'Bancontact',\n eps: 'EPS',\n giropay: 'giropay',\n p24: 'Przelewy24',\n alipay: 'Alipay',\n grabpay: 'GrabPay',\n cashapp: 'Cash App Pay',\n paypal: 'PayPal',\n}\nconst redirectLabel = (t: string) =>\n REDIRECT_LABELS[t] ?? t.replace(/_/g, ' ').replace(/\\b\\w/g, (c) => c.toUpperCase())\n\nconst isCardFieldError = (message: string) =>\n /(?:card|expiry|expiration|security code|cvc).*(?:incomplete|required|invalid)|(?:incomplete|required|invalid).*(?:card|expiry|expiration|security code|cvc)/i.test(\n message\n )\n\n/**\n * Anything the buyer would fix AT THE CARD FIELD — a bad number, a wrong CVC,\n * an expired or declined card, missing details. These belong beside the card\n * box; only order-level problems (conditions, billing, network) belong down by\n * the pay button, where a card message is easy to miss entirely.\n */\nconst isCardAreaError = (message: string) =>\n isCardFieldError(message) ||\n /card details|security code|cvc|cvv|expired|declined|not accepted|balance|stolen|inactive|authentication failed|name on the card|different card/i.test(\n message\n )\n\nexport interface PaymentProps {\n onComplete?: (order: PlaceOrderResult) => void\n /** Optional event context adds the event name to the order review. */\n eventId?: string\n /** Must match the policy used by the paired `<BillingInfo/>`. */\n requireEmailConfirmation?: boolean\n /** Must match the holder policy used by the paired `<BillingInfo/>`. */\n collectTicketHolders?: boolean\n /** Must match the holder-contact policy used by the paired `<BillingInfo/>`. */\n requireHolderContact?: boolean\n /** Host-owned acknowledgements such as a brand privacy policy. */\n additionalConditions?: EventCondition[]\n /** Require the privacy checkbox managed by BillingInfo before payment. */\n requirePrivacyPolicy?: boolean\n /** Called when payment is attempted before required privacy consent. */\n onPrivacyRequired?: () => void\n /** Test card copy is useful in examples, but should never appear by default. */\n showTestCardHint?: boolean\n className?: string\n}\n\nexport const Payment: FC<PaymentProps> = ({\n onComplete,\n eventId,\n requireEmailConfirmation = false,\n collectTicketHolders = false,\n requireHolderContact = false,\n additionalConditions = [],\n requirePrivacyPolicy = false,\n onPrivacyRequired,\n showTestCardHint = false,\n className,\n}) => {\n const t = useT()\n const checkout = useCheckoutContext()\n const validation = useCheckoutValidation()\n const [error, setError] = useState('')\n /** Field-level problem reported by `<XenditCardInput/>` (it renders none). */\n const [cardFieldError, setCardFieldError] = useState<string | null>(null)\n /** Card problem from the last pay attempt (declined, wrong CVC, expired…). */\n const [payCardError, setPayCardError] = useState<string | null>(null)\n /** True once the buyer edits the card after a failed attempt — their fix\n * supersedes both our message and the engine's stale one. */\n const [cardEditedSincePay, setCardEditedSincePay] = useState(true)\n const [methods, setMethods] = useState<PreOrderMethods | null>(null)\n const [selected, setSelected] = useState('')\n const [extras, setExtras] = useState<\n Record<string, { cashtag?: string; phoneNumber?: string }>\n >({})\n const [useSavedCard, setUseSavedCard] = useState(true)\n const cardSectionRef = useRef<HTMLDivElement | null>(null)\n\n useEffect(() => {\n let active = true\n ttf.cart\n .preOrderMethods()\n .then((m) => active && setMethods(m))\n .catch(() => active && setMethods(null))\n return () => {\n active = false\n }\n }, [])\n\n const bd = checkout.breakdown\n const isFree = bd != null && Number(bd.total) === 0\n const isXendit = checkout.gateway === 'xendit'\n\n // Whether the server put OXXO on the deferred Elements config. This is\n // `Checkout::get_payment_method_types()`'s verdict — the event's own OXXO\n // flag, the voucher-expiry window against the event date, an MX Stripe\n // account, a MXN 10–10,000 total, and no manual capture. Several of those\n // inputs (the Stripe account's country, per-ticket ID verification, the\n // event's timezone) have no client-side equivalent, so this must never be\n // re-derived here. Absent config (free carts, Xendit, Razorpay) → false,\n // which is what the legacy checkout does too.\n const serverMethodTypes = (\n checkout.stripeElementsConfig as { paymentMethodTypes?: unknown } | undefined\n )?.paymentMethodTypes\n const offersOxxo =\n Array.isArray(serverMethodTypes) && serverMethodTypes.includes('oxxo')\n\n // Build the selectable method rows from gateway + probe + snapshot.\n const options = useMemo<PaymentMethodOption[]>(() => {\n if (isFree || !methods) return []\n const out: PaymentMethodOption[] = []\n if (isXendit) {\n if (methods.xenditCard)\n out.push({\n id: { kind: 'xenditCard' },\n value: 'xenditCard',\n label: t('payment.card'),\n })\n for (const w of methods.xenditEWallets)\n out.push({\n id: { kind: 'xenditEWallet', walletKey: w.key },\n value: `ew:${w.key}`,\n label: w.label,\n iconUrl: w.icon,\n extra: (XENDIT_EWALLET_EXTRA_FIELD[w.key] as 'cashtag' | 'phoneNumber') ?? null,\n })\n } else if (checkout.gateway === 'razorpay') {\n out.push({ id: { kind: 'razorpay' }, value: 'razorpay', label: 'Razorpay' })\n } else {\n // Stripe (or unknown → fail open to card).\n out.push({ id: { kind: 'card' }, value: 'card', label: t('payment.card') })\n for (const t of checkout.redirectPaymentMethods ?? []) {\n if (t === 'paypal' && methods.paypal) continue // dedupe vs PayPal Standard\n out.push({\n id: { kind: 'redirect', methodType: t },\n value: `rd:${t}`,\n label: redirectLabel(t),\n })\n }\n if (checkout.paymentPlan?.available)\n out.push({\n id: { kind: 'paymentPlan' },\n value: 'paymentPlan',\n label: t('payment.paymentPlan'),\n })\n // OXXO cash voucher. `oxxo` is deliberately absent from\n // SUPPORTED_REDIRECT_METHODS, so it never arrives via the loop above.\n if (offersOxxo)\n out.push({ id: { kind: 'oxxo' }, value: 'oxxo', label: t('payment.oxxo') })\n }\n if (methods.paypal)\n out.push({ id: { kind: 'paypal' }, value: 'paypal', label: 'PayPal' })\n return out\n }, [\n isFree,\n methods,\n isXendit,\n checkout.gateway,\n checkout.redirectPaymentMethods,\n checkout.paymentPlan,\n offersOxxo,\n ])\n\n // Default the selection to the first row once options exist.\n useEffect(() => {\n if (options.length && !options.some((o) => o.value === selected))\n setSelected(options[0].value)\n }, [options, selected])\n\n const cardValue = isXendit ? 'xenditCard' : 'card'\n const selectedOption = options.find((o) => o.value === selected)\n const isCardSelected = selected === cardValue\n const isPlanSelected = selectedOption?.id.kind === 'paymentPlan'\n const savedLast4 = checkout.paymentPlan?.savedCardLast4\n /**\n * \"Reuse the card on file\" only means something when there IS one. The raw\n * `useSavedCard` toggle defaults to true (matching the hosted default-checked\n * box), so reading it directly made a first-time buyer look like a returning\n * one: `inputSlotFor` collapsed to undefined, the card field and the plan\n * terms never mounted, and \"Confirm Payment Plan\" then failed in the\n * confirmer with \"No card element registered\". Always gate on the card.\n */\n const reuseSavedCard = Boolean(savedLast4) && useSavedCard\n const usesCardDetails =\n !isFree && (isCardSelected || (isPlanSelected && !reuseSavedCard))\n // Stripe's CardElement renders its own inline \"Card number is invalid\" text, so\n // the pay handler can stay quiet and just scroll to it. Xendit's card form is\n // three plain inputs with no error slot — there, the message MUST be shown or\n // a declined/invalid card looks like the button simply did nothing.\n const cardWidgetReportsItsOwnError = usesCardDetails && !isXendit\n\n // Wallets the old-checkout way: when the event's `stripe_wallets` gate is on,\n // render the Payment Element (card + Apple/Google Pay in one widget) instead of\n // the bare card field. Held back for MXN so the CardElement-based MSI path\n // (Mexican months-without-interest) keeps working — matching old, which didn't\n // run MSI off its web Payment Element either.\n const hasWallets = Boolean(\n checkout.walletAvailability?.applePay || checkout.walletAvailability?.googlePay\n )\n // A payment plan NEVER rides the wallet element, matching the hosted flow's\n // `wallets: planMode ? { applePay: 'never', googlePay: 'never' }`. Two\n // reasons, both load-bearing:\n // 1. A plan charges installments off-session, so it needs a REUSABLE card.\n // Wallet tokens are typically single-use and can't be charged later.\n // 2. Mechanically: the plan rail confirms via `confirmer.getCardElement()`,\n // which only exists for `<CardInput/>`. The Payment Element registers\n // itself through `registerPaymentElement` instead, so mounting it here\n // made `confirmPaymentPlanSetup` throw \"No card element registered\" —\n // the plan could never be completed on a wallet-enabled event.\n const useWalletElement =\n !isXendit &&\n !isPlanSelected &&\n hasWallets &&\n checkout.breakdown?.currencyCode !== 'MXN' &&\n Boolean((checkout.stripeElementsConfig as { mode?: unknown } | undefined)?.mode)\n\n // When there's only ONE way to pay and it's a card, there's nothing to\n // *choose* — the old checkout just showed the card form, no radio wrapper.\n // Render the field directly; keep the radio list only when there's a choice.\n const onlyOption = options.length === 1 ? options[0] : undefined\n const singleCard =\n onlyOption?.id.kind === 'card' || onlyOption?.id.kind === 'xenditCard'\n\n // Gating: buyer + every configured holder/custom field complete, required\n // conditions accepted, and payment-method extras filled.\n const b = checkout.billing\n const missingDetails = missingCheckoutDetails(\n {\n billing: b,\n holders: checkout.holders,\n selections: checkout.selections,\n breakdown: checkout.breakdown,\n holderNamesRequired: checkout.holderNamesRequired,\n fieldGates: checkout.fieldGates,\n customFields: checkout.customFields,\n },\n { requireEmailConfirmation, collectTicketHolders, requireHolderContact }\n )\n const billingReady = missingDetails.length === 0\n const conditions = [...(checkout.conditions ?? []), ...additionalConditions]\n const requiredConditions = conditions.filter((c) => c.isRequired)\n const conditionsOk = requiredConditions.every(\n (c) => checkout.acceptedConditions?.[c.id]\n )\n const extra = selectedOption?.extra\n const extrasOk =\n !extra ||\n (extra === 'cashtag'\n ? Boolean(extras[selected]?.cashtag?.trim())\n : Boolean(extras[selected]?.phoneNumber?.trim()))\n const privacyOk = !requirePrivacyPolicy || checkout.consent.ttfOptIn\n // The plan CTA carries the brand's terminology (\"Confirm Layaway\"), and the\n // terms sentence quotes this same label — they must agree.\n const payLabel = isFree\n ? t('payment.completeRegistration')\n : isPlanSelected\n ? planConfirmLabel(checkout.paymentPlan?.configuration)\n : t('payment.submitPayment')\n const planTerms = paymentPlanTerms(checkout.paymentPlan?.configuration)\n // 'placing' → order in flight; 'succeeded' → placed, host navigating away.\n // Both keep the CTA busy so it can't be re-clicked during the handoff.\n const finalizing = checkout.status === 'placing' || checkout.status === 'succeeded'\n\n const pay = () => {\n setError('')\n setPayCardError(null)\n setCardEditedSincePay(false)\n if (!billingReady || !conditionsOk || !extrasOk || !privacyOk) {\n if (!privacyOk) onPrivacyRequired?.()\n validation.requestValidation()\n return\n }\n // Backfill one holder per ticket if billing was set without holders.\n if (checkout.holders.length === 0 && b) {\n const n = checkout.selections.reduce((acc, s) => acc + s.quantity, 0) || 1\n checkout.setHolders(\n Array.from({ length: n }, () => ({\n firstName: b.firstName,\n lastName: b.lastName,\n email: b.email,\n }))\n )\n }\n let req: PaymentRequest = { method: 'auto' }\n const id = selectedOption?.id\n if (isFree || !id) req = { method: 'auto' }\n else if (id.kind === 'xenditEWallet')\n req = { method: 'xenditEWallet', walletKey: id.walletKey, extra: extras[selected] }\n else if (id.kind === 'redirect')\n req = { method: 'redirect', methodType: id.methodType }\n else if (id.kind === 'paymentPlan')\n req = { method: 'paymentPlan', useSavedCard: reuseSavedCard }\n else req = { method: id.kind } as PaymentRequest\n // NOTE: called synchronously in the click handler — popup rails (e-wallet,\n // redirect, razorpay, paypal) need the user gesture or the browser blocks them.\n checkout\n .placeOrder(req)\n .then((order) => onComplete?.(order))\n .catch((e) => {\n const message = errorMessage(e)\n if (usesCardDetails && isCardAreaError(message)) {\n const behavior = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n ? 'auto'\n : 'smooth'\n cardSectionRef.current?.scrollIntoView({ behavior, block: 'center' })\n // Stripe's CardElement prints the message inside its own widget, so\n // scrolling to it is enough. Ours doesn't — show it AT the card box,\n // not down by the button where it reads as an unrelated failure.\n if (cardWidgetReportsItsOwnError) return\n setPayCardError(message)\n return\n }\n setError(message)\n })\n }\n\n // A card problem surfaced by the engine belongs at the box too, not under the\n // pay button — same rule as the ones we catch in `pay()`.\n // Whether the engine's error is a CARD problem at all. This must not depend on\n // whether the buyer has since edited: the edit decides if we still SHOW it, it\n // must never decide whether it may fall through to the button (it may not — a\n // card error belongs at the card, always).\n const engineErrorIsCardArea = Boolean(\n isXendit && checkout.error && isCardAreaError(checkout.error)\n )\n const engineCardError =\n engineErrorIsCardArea && !cardEditedSincePay ? checkout.error : ''\n // The buyer's live field state wins over a stale decline from a past attempt.\n const cardAreaError = cardFieldError || payCardError || engineCardError\n const checkoutError =\n checkout.error &&\n !(cardWidgetReportsItsOwnError && isCardFieldError(checkout.error)) &&\n !engineErrorIsCardArea\n ? checkout.error\n : ''\n // Single gate for the message under the pay button: whatever the source, a\n // card problem is shown at the card and NEVER duplicated down here.\n const bottomMessage = error || checkoutError\n const bottomError =\n bottomMessage && isXendit && isCardAreaError(bottomMessage) ? '' : bottomMessage\n\n // The card/plan field + its note + plan terms. Rendered inside the selected\n // method row when there's a choice, or directly when there's only a card.\n const paymentInput = (\n <>\n {(isCardSelected || (isPlanSelected && !reuseSavedCard)) && (\n <>\n {useWalletElement ? (\n // The Payment Element frames itself — don't box it again.\n <div ref={cardSectionRef} className=\"tf-checkout-payment__element\">\n <StripePaymentElement\n elementsConfig={checkout.stripeElementsConfig}\n wallets={checkout.walletAvailability}\n />\n </div>\n ) : (\n <div\n ref={cardSectionRef}\n className={cx(\n 'tf-checkout-payment__cardbox',\n isXendit && cardAreaError && 'tf-checkout-payment__cardbox--invalid'\n )}\n >\n {isXendit ? (\n <XenditCardInput\n onValidationChange={(m) => {\n setCardFieldError(m)\n // Any edit supersedes the previous attempt's verdict — the\n // buyer shouldn't be told a number is invalid while they're\n // typing a valid one.\n setPayCardError(null)\n setCardEditedSincePay(true)\n }}\n />\n ) : (\n <CardInput />\n )}\n </div>\n )}\n {/* Below the box, not inside it — Stripe prints its own message within\n its iframe, but the Xendit fields are ours to caption. */}\n {isXendit && cardAreaError && (\n <p className=\"tf-checkout-error-text\">{cardAreaError}</p>\n )}\n {showTestCardHint && (\n <p className=\"tf-checkout-note\">\n {isXendit ? t('payment.testCardXendit') : t('payment.testCard')}\n </p>\n )}\n </>\n )}\n {/* The full hosted terms block. Composed in the SDK so web and native\n state the identical schedule, admin fee and non-refundable clause —\n these are disclosures, not summary copy. */}\n {isPlanSelected && planTerms.length > 0 && (\n <div className=\"tf-checkout-payment__plan\">\n <strong>{planTermsTitle(checkout.paymentPlan!.configuration!)}</strong>\n {planTerms.map((part) => (\n <p key={part.id} className=\"tf-checkout-note\">\n {part.text}\n </p>\n ))}\n </div>\n )}\n {/* Returning plan buyer with a reusable card on file. Ticked by default,\n and when it stays ticked the card fields never mount — the plan is\n created straight off the saved payment method, like the hosted flow. */}\n {isPlanSelected && savedLast4 && (\n <div className=\"tf-checkout-payment__plan-savedcard\">\n <p className=\"tf-checkout-note\">\n Your payment will proceed with the card ending in{' '}\n <strong>**** {savedLast4}</strong>\n </p>\n <Checkbox\n checked={useSavedCard}\n onChange={(e) => setUseSavedCard(e.target.checked)}\n label={t('payment.useThisCard')}\n />\n </div>\n )}\n </>\n )\n\n return (\n <div className={['tf-checkout-payment-stack', className].filter(Boolean).join(' ')}>\n <Card>\n <SectionHeader title={t('payment.title')} />\n\n {/* Payment method */}\n {!isFree && (\n <>\n {!singleCard && (\n <div className=\"tf-checkout-payment__label\">{t('payment.method')}</div>\n )}\n {!methods ? (\n <div className=\"tf-checkout-payment__cardbox\">\n <Loader />\n </div>\n ) : singleCard ? (\n paymentInput\n ) : (\n <PaymentMethods\n options={options}\n selected={selected}\n onSelect={setSelected}\n extraValues={extras}\n onExtraChange={(v, patch) =>\n setExtras((s) => ({ ...s, [v]: { ...s[v], ...patch } }))\n }\n showValidation={validation.attempt > 0}\n /**\n * The plan row ALWAYS owns the slot when it's selected. This\n * used to be conditional on needing a card field, which meant a\n * returning buyer reusing their saved card got `undefined` — and\n * `undefined` renders the children nowhere, so the plan terms\n * AND the \"card ending in ****\" block both vanished. The card\n * field inside is separately gated on `!reuseSavedCard`, so the\n * slot itself never needs to be.\n */\n inputSlotFor={isPlanSelected ? 'paymentPlan' : cardValue}\n >\n {paymentInput}\n </PaymentMethods>\n )}\n </>\n )}\n\n {/* Conditions */}\n {conditions.map((c) => {\n const invalid =\n validation.attempt > 0 && c.isRequired && !checkout.acceptedConditions?.[c.id]\n return (\n <div\n key={c.id}\n className={invalid ? 'tf-checkout-consent--error' : undefined}\n data-checkout-invalid={invalid || undefined}\n >\n <Checkbox\n required={c.isRequired}\n checked={Boolean(checkout.acceptedConditions?.[c.id])}\n aria-invalid={invalid}\n onChange={(e) => checkout.acceptCondition(c.id, e.target.checked)}\n label={\n <>\n <span dangerouslySetInnerHTML={{ __html: c.content || c.name }} />\n {c.isRequired && ' *'}\n </>\n }\n />\n {invalid && (\n <div className=\"tf-checkout-consent__error\">\n You must accept this condition to continue.\n </div>\n )}\n </div>\n )\n })}\n </Card>\n\n <OrderSummary eventId={eventId} />\n\n <div className=\"tf-checkout-payment__cta\">\n <Button\n onClick={pay}\n // Stay busy through 'succeeded' too: in redirect mode the checkout\n // remains mounted while the host navigates away, so the button must\n // not flicker back to a clickable state before the redirect lands.\n loading={finalizing}\n disabled={checkout.isBusy || finalizing || (!isFree && !methods)}\n >\n {finalizing ? t('payment.placing') : payLabel}\n </Button>\n </div>\n {bottomError && <p className=\"tf-checkout-error-text\">{bottomError}</p>}\n </div>\n )\n}\n","import React, { type FC } from 'react'\n\nimport { hooks } from 'tf-checkout-shared'\n\nimport { Card } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { useT } from '../ui/I18nProvider'\n\nexport interface OrderSummaryProps {\n eventId?: string\n className?: string\n}\n\n/** Storefront-compatible order summary shown after the checkout controls. */\nexport const OrderSummary: FC<OrderSummaryProps> = ({ eventId, className }) => {\n const t = useT()\n const checkout = useCheckoutContext()\n const event = hooks.useEvent(eventId)\n const breakdown = checkout.breakdown\n const detailed = checkout.priceBreakdown\n\n if (!breakdown || breakdown.tickets.length === 0) return null\n\n return (\n <Card className={['tf-checkout-order-summary', className].filter(Boolean).join(' ')}>\n {event.data?.name && (\n <div className=\"tf-checkout-order-summary__group\">\n <div className=\"tf-checkout-order-summary__label\">{t('common.event')}</div>\n <div className=\"tf-checkout-order-summary__event\">{event.data.name}</div>\n </div>\n )}\n\n <div className=\"tf-checkout-order-summary__group\">\n <div className=\"tf-checkout-order-summary__label\">{t('tickets.yourTickets')}</div>\n {breakdown.tickets.map((ticket, index) => {\n const detail = detailed?.tickets[index]\n return (\n <div\n key={`${ticket.ticketTypeId}-${index}`}\n className=\"tf-checkout-order-summary__item\"\n >\n <div className=\"tf-checkout-order-summary__ticket\">\n {ticket.quantity} x {ticket.name} - {detail?.unit_price ?? ticket.unit}{' '}\n {t('common.each')}\n </div>\n {detail?.line_total && detail.line_total !== detail.unit_price && (\n <div className=\"tf-checkout-order-summary__fees\">\n ({detail.line_total} with fees)\n </div>\n )}\n </div>\n )\n })}\n </div>\n\n {(detailed?.add_ons.length ?? 0) > 0 && (\n <div className=\"tf-checkout-order-summary__group\">\n <div className=\"tf-checkout-order-summary__label\">\n {detailed?.add_ons_title || 'Add-ons'}\n </div>\n {detailed?.add_ons.map((addOn, index) => (\n <div\n key={`${addOn.name}-${index}`}\n className=\"tf-checkout-order-summary__item\"\n >\n <div className=\"tf-checkout-order-summary__ticket\">\n {addOn.quantity} x {addOn.name}\n {addOn.show_price ? ` - ${addOn.unit_price} ${t('common.each')}` : ''}\n </div>\n </div>\n ))}\n </div>\n )}\n\n <div className=\"tf-checkout-order-summary__total\">\n <div className=\"tf-checkout-order-summary__label\">{t('common.total')}</div>\n <div className=\"tf-checkout-order-summary__amount\">\n {detailed?.total ??\n `${breakdown.currencySymbol || `${breakdown.currencyCode} `}${Number(\n breakdown.total\n ).toFixed(2)}`}\n </div>\n </div>\n </Card>\n )\n}\n","/**\n * `<IDVerification/>` — shown after an order that needs identity verification\n * (`order.needIdVerification`). Kicks off the engine's verify flow: mint the\n * provider URL, open it, and poll to completion, reflecting each phase. The\n * order is already paid — a stall here never means a failed payment.\n *\n * If you place your order with `placeOrder(method, { autoRunIdVerification:true })`\n * the engine runs this for you; this section is the manual, visible counterpart.\n */\nimport React, { useState, type FC } from 'react'\n\nimport { errorMessage, type IdVerificationPhase } from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { cx } from '../ui/cx'\n\ntype UiPhase = IdVerificationPhase | 'starting'\n\nconst MESSAGE: Record<UiPhase, string> = {\n idle: 'To complete the purchase, please verify your identity.',\n starting: 'Opening the verification page…',\n polling: 'Waiting for verification to complete in the other tab…',\n verified: 'Identity verified — your tickets are on their way.',\n timeout: 'Still not confirmed. Finish in the other tab, then check again.',\n error: 'We couldn’t reach the verification service. Try again.',\n}\n\nexport interface IDVerificationProps {\n className?: string\n}\n\nexport const IDVerification: FC<IDVerificationProps> = ({ className }) => {\n const checkout = useCheckoutContext()\n const order = checkout.order\n const [phase, setPhase] = useState<UiPhase>('idle')\n const [error, setError] = useState('')\n\n if (!order?.needIdVerification) return null\n\n const done = phase === 'verified'\n const running = phase === 'starting' || phase === 'polling'\n\n const run = () => {\n setError('')\n setPhase('starting')\n checkout\n .runIdVerification(order.orderHash, {\n openUrl: (url) => {\n if (url) window.open(url, '_blank', 'noopener,noreferrer')\n },\n onPhase: (p) => setPhase(p),\n })\n .then((status) => setPhase(status?.verified ? 'verified' : 'polling'))\n .catch((e) => {\n setPhase('error')\n setError(errorMessage(e))\n })\n }\n\n return (\n <Card className={cx('tf-checkout-idverify', className)}>\n <SectionHeader title=\"Account Verification\" />\n <p className={cx('tf-checkout-note', done && 'tf-checkout-idverify__done')}>\n {MESSAGE[phase]}\n </p>\n {!done && (\n <Button block onClick={run} loading={running} disabled={running}>\n {phase === 'idle' ? 'Verify' : running ? 'Verifying…' : 'Check again'}\n </Button>\n )}\n {error && <p className=\"tf-checkout-error-text\">{error}</p>}\n </Card>\n )\n}\n","/**\n * `<Confirmation/>` — the order-placed receipt + a referral/share growth block\n * (invite friends → cheaper/free tickets). Reads the settled order off the\n * shared checkout; returns null until an order exists.\n *\n * Fire purchase tracking (Meta Pixel / GTM) from the `onComplete(order)` callback\n * you already pass to `<Payment/>` / `<EmbeddedCheckout/>` — the SDK stays analytics-\n * agnostic. The referral REWARD ladder (\"how much cheaper\") needs the order\n * confirmation payload, which is left to the consumer (pass `children`); the\n * share affordances below need no backend data.\n */\nimport React, { useState, type FC, type ReactNode } from 'react'\n\nimport { Button } from '../ui/Button'\nimport { Card } from '../ui/Card'\nimport { useCheckoutContext } from '../ui/CheckoutProvider'\nimport { useT } from '../ui/I18nProvider'\nimport { cx } from '../ui/cx'\n\nexport interface ConfirmationProps {\n /** URL friends land on (referral/event page). Defaults to the current page. */\n shareUrl?: string\n /** Message prefilled into social shares. */\n shareMessage?: string\n /** Link to the buyer's tickets/order — renders a \"View my tickets\" button. */\n viewOrderUrl?: string\n /** Extra content (e.g. your own referral-reward ladder from the order payload). */\n children?: ReactNode\n className?: string\n}\n\nexport const Confirmation: FC<ConfirmationProps> = ({\n shareUrl,\n shareMessage = 'I just got my tickets — grab yours!',\n viewOrderUrl,\n children,\n className,\n}) => {\n const t = useT()\n const checkout = useCheckoutContext()\n const order = checkout.order\n const [copied, setCopied] = useState(false)\n\n if (!order) return null\n const pending = order.pending\n\n const url = shareUrl ?? (typeof window !== 'undefined' ? window.location.href : '')\n const enc = encodeURIComponent\n const shares: { label: string; href: string }[] = url\n ? [\n {\n label: 'Facebook',\n href: `https://www.facebook.com/sharer/sharer.php?u=${enc(url)}`,\n },\n {\n label: 'X',\n href: `https://twitter.com/intent/tweet?url=${enc(url)}&text=${enc(\n shareMessage\n )}`,\n },\n {\n label: 'WhatsApp',\n href: `https://wa.me/?text=${enc(`${shareMessage} ${url}`)}`,\n },\n ]\n : []\n\n const copy = () => {\n if (!url || typeof navigator === 'undefined' || !navigator.clipboard) return\n navigator.clipboard.writeText(url).then(\n () => {\n setCopied(true)\n setTimeout(() => setCopied(false), 1500)\n },\n () => undefined\n )\n }\n\n return (\n <Card className={cx('tf-checkout-confirmation', className)}>\n <span className=\"tf-checkout-confirmation__check\">{pending ? '⏳' : '✓'}</span>\n <strong className=\"tf-checkout-confirmation__title\">\n {pending ? t('confirmation.pending') : t('confirmation.confirmed')}\n </strong>\n <p className=\"tf-checkout-note\">\n {pending\n ? t('confirmation.pendingBody')\n : order.alreadyPaid\n ? t('confirmation.alreadyPaid')\n : t('confirmation.available')}\n </p>\n {order.orderHash && (\n <p className=\"tf-checkout-confirmation__ref\">Reference: {order.orderHash}</p>\n )}\n\n {pending && order.pendingVoucherUrl && (\n <a\n className=\"tf-checkout-button tf-checkout-button--secondary tf-checkout-button--block\"\n href={order.pendingVoucherUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n View payment voucher\n </a>\n )}\n\n {viewOrderUrl && (\n <a\n className=\"tf-checkout-button tf-checkout-button--secondary tf-checkout-button--block\"\n href={viewOrderUrl}\n >\n View my tickets\n </a>\n )}\n\n {children}\n\n {/* Referral / share — invite friends for cheaper (or free) tickets. */}\n {!pending && url && (\n <div className=\"tf-checkout-confirmation__share\">\n <strong>{t('referral.cheaperOrFree')}</strong>\n <p className=\"tf-checkout-note\">\n Invite friends with your link. When they buy, you get rewarded.\n </p>\n <div className=\"tf-checkout-confirmation__share-link\">\n <input className=\"tf-checkout-input\" readOnly value={url} />\n <Button variant=\"secondary\" onClick={copy}>\n {copied ? t('referral.copied') : t('referral.copyLink')}\n </Button>\n </div>\n <div className=\"tf-checkout-confirmation__socials\">\n {shares.map((s) => (\n <a\n key={s.label}\n className=\"tf-checkout-button tf-checkout-button--ghost\"\n href={s.href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n {s.label}\n </a>\n ))}\n </div>\n </div>\n )}\n </Card>\n )\n}\n","import React, { useEffect, useRef, useState, type FC, type ReactNode } from 'react'\n\nimport { errorMessage, ttf } from 'tf-checkout-shared'\n\nimport { cx } from '../ui/cx'\nimport { Loader } from '../ui/Loader'\n\ntype ConfirmationData = Record<string, any>\ntype ReferralPrice = {\n label: string\n subLabel?: string\n price: string\n}\n\nconst attributesOf = (response: Record<string, unknown>): ConfirmationData => {\n const data = response?.data as Record<string, unknown> | undefined\n const attributes = data?.attributes\n if (attributes && typeof attributes === 'object') return attributes as ConfirmationData\n if (data && typeof data === 'object') return data as ConfirmationData\n return response\n}\n\nexport interface OrderConfirmationProps {\n orderHash: string\n title?: ReactNode\n message?: ReactNode\n helper?: ReactNode\n eventTitle?: ReactNode\n eventDate?: ReactNode\n eventLocation?: ReactNode\n viewOrderUrl?: string | ((data: ConfirmationData) => string)\n showReferral?: boolean\n showShareButtons?: boolean\n onLoaded?: (data: ConfirmationData) => void\n onError?: (error: unknown) => void\n className?: string\n}\n\n/**\n * Reloadable post-purchase confirmation. Its markup intentionally preserves\n * the proven legacy checkout class contract so existing white-label themes do\n * not lose their confirmation-page UX when they adopt Checkout Kit.\n */\nexport const OrderConfirmation: FC<OrderConfirmationProps> = ({\n orderHash,\n title = 'Your order has been confirmed!',\n message,\n helper,\n eventTitle,\n eventDate,\n eventLocation,\n viewOrderUrl,\n showReferral = true,\n showShareButtons = true,\n onLoaded,\n onError,\n className,\n}) => {\n const [data, setData] = useState<ConfirmationData | null>(null)\n const [failure, setFailure] = useState('')\n const [copied, setCopied] = useState(false)\n const loadedRef = useRef(onLoaded)\n const errorRef = useRef(onError)\n\n useEffect(() => {\n loadedRef.current = onLoaded\n errorRef.current = onError\n }, [onError, onLoaded])\n\n useEffect(() => {\n if (!orderHash) {\n setFailure('The order reference is missing.')\n return\n }\n\n let active = true\n ttf.confirmation.get(orderHash).then(\n (response) => {\n if (!active) return\n const attributes = attributesOf(response)\n if (!attributes.order_hash) attributes.order_hash = orderHash\n setData(attributes)\n loadedRef.current?.(attributes)\n },\n (error) => {\n if (!active) return\n setFailure(errorMessage(error))\n errorRef.current?.(error)\n }\n )\n\n return () => {\n active = false\n }\n }, [orderHash])\n\n if (failure) {\n return (\n <div className={cx('confirmation-page tf-checkout-confirmation-page', className)}>\n <div className=\"tf-checkout-auth__alert\" role=\"alert\">\n {failure}\n </div>\n </div>\n )\n }\n\n if (!data) {\n return (\n <div className=\"tf-checkout-confirmation-page__loading\">\n <Loader className=\"tf-checkout-loader--page\" />\n </div>\n )\n }\n\n const customText = String(data.custom_confirmation_page_text ?? '')\n const customReplacement = Boolean(data.custom_confirmation_page_text_full_replacement)\n const attachTickets = Boolean(data.attach_tickets)\n const shareUrl = String(data.personal_share_link ?? '')\n const orderUrl = typeof viewOrderUrl === 'function' ? viewOrderUrl(data) : viewOrderUrl\n const sales = Array.isArray(data.personal_share_sales) ? data.personal_share_sales : []\n const symbol = String(data.currency?.symbol ?? '')\n const currentPrice = Number(data.product_price)\n const pricing: ReferralPrice[] = [\n ...(Number.isFinite(currentPrice)\n ? [\n {\n label: 'Your ticket is currently',\n price: `${symbol}${currentPrice.toFixed(2)}`,\n },\n ]\n : []),\n ...sales.map((sale: ConfirmationData) => ({\n label: `If your friends buy ${sale.sales} tickets`,\n subLabel:\n Number(sale.price) === 0 ? 'Your ticket becomes' : 'Your ticket goes down to',\n price:\n Number(sale.price) === 0 ? 'FREE!' : `${symbol}${Number(sale.price).toFixed(2)}`,\n })),\n ]\n\n const copy = () => {\n if (!shareUrl || typeof navigator === 'undefined' || !navigator.clipboard) return\n void navigator.clipboard.writeText(shareUrl).then(() => {\n setCopied(true)\n window.setTimeout(() => setCopied(false), 1500)\n })\n }\n\n return (\n <div className={cx('confirmation-page tf-checkout-confirmation-page', className)}>\n <div className=\"header-container\">\n <div className=\"header-product-text\">\n <p className=\"title\">{title}</p>\n {(eventTitle || eventDate || eventLocation) && (\n <div className=\"event-details\">\n {eventTitle && <div className=\"event-title\">{eventTitle}</div>}\n {eventDate && <div className=\"event-date\">{eventDate}</div>}\n {eventLocation && <div className=\"event-location\">{eventLocation}</div>}\n </div>\n )}\n <div className=\"share-message-section\">\n {customReplacement ? (\n <div dangerouslySetInnerHTML={{ __html: customText }} />\n ) : (\n <>\n <span className=\"main\">\n {attachTickets\n ? 'Your tickets have been emailed to you'\n : (message ?? 'Your tickets are available in My Tickets.')}\n </span>\n <span className=\"helper\">\n {attachTickets ? 'Please bring them with you to the event' : helper}\n </span>\n </>\n )}\n </div>\n </div>\n </div>\n\n {customText && !customReplacement && (\n <div\n className=\"custom-confirmation-page-text tf-checkout-confirmation-page__custom\"\n dangerouslySetInnerHTML={{ __html: customText }}\n />\n )}\n\n {orderUrl && (\n <div className=\"order-details-button-container\">\n <a className=\"view-order-button\" href={orderUrl}>\n View Order\n </a>\n </div>\n )}\n\n {showReferral && data.disable_referral === false && shareUrl && (\n <>\n <div className=\"referral_text_image_section\">\n <div className=\"referral_text_section\">\n <div className=\"referral_title_text\">\n Your ticket can become\n <span className=\"strong-text\"> cheaper </span>\n or even\n <span className=\"strong-text\"> FREE!</span>\n </div>\n <div className=\"referral_text\">\n <span className=\"strong-text\">Invite friends </span>\n and we'll refund up to\n <span className=\"strong-text\"> 100% </span>\n of your ticket money, if they buy tickets as well!\n </div>\n </div>\n </div>\n <div className=\"share_wrapper\">\n <div className=\"share_section\">\n <div className=\"invitation_section\">\n <div className=\"invitation_title\">How do you invite your friends?</div>\n <div className=\"share_buttons\">\n <div className=\"share-by-link\">\n <h5 className=\"share-by-link label\">Send them this link:</h5>\n <div className=\"share-btn-inner\">\n <input className=\"share-input\" readOnly value={shareUrl} />\n <button\n className=\"share-by-link-copy-icon\"\n type=\"button\"\n onClick={copy}\n >\n <span className=\"copy-icon\">{copied ? 'Copied!' : 'Copy'}</span>\n </button>\n </div>\n </div>\n {showShareButtons && (\n <div className=\"social-media-btns\">\n <a\n className=\"social-media-sharing\"\n href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(\n shareUrl\n )}`}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n Facebook\n </a>\n <a\n className=\"social-media-sharing\"\n href={`https://wa.me/?text=${encodeURIComponent(shareUrl)}`}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n WhatsApp\n </a>\n </div>\n )}\n </div>\n </div>\n </div>\n {pricing.length > 0 && (\n <div className=\"pricing-section\">\n <div className=\"invitation_title\">How much cheaper?</div>\n {pricing.map((item, index) => (\n <div className=\"pricing-section_wrapper\" key={`${item.label}-${index}`}>\n <div className=\"pricing-section_label\">\n {item.label}\n {item.subLabel && (\n <div className=\"pricing-section_sublabel\">{item.subLabel}</div>\n )}\n </div>\n <div className=\"pricing-section_price\">{item.price}</div>\n </div>\n ))}\n </div>\n )}\n </div>\n </>\n )}\n </div>\n )\n}\n","import React, { useEffect, useState, type FC } from 'react'\n\nimport {\n errorMessage,\n runIdVerificationWith,\n ttf,\n type IdVerificationPhase,\n} from 'tf-checkout-shared'\n\nimport { Button } from '../ui/Button'\nimport { Card, SectionHeader } from '../ui/Card'\nimport { cx } from '../ui/cx'\n\ntype UiPhase = IdVerificationPhase | 'checking' | 'starting'\n\nconst PHASE_MESSAGE: Record<UiPhase, string> = {\n checking: 'Checking your verification status…',\n idle: 'To complete the purchase, please verify your identity.',\n starting: 'Opening the verification page…',\n polling: 'Waiting for verification to complete in the other tab…',\n verified: 'Identity verified — your tickets are on their way.',\n timeout: 'Verification is taking longer than usual. Your payment is safe.',\n error: 'We couldn’t reach the verification service. Try again.',\n}\n\nexport interface OrderIDVerificationProps {\n orderHash: string\n onVerified?: () => void\n className?: string\n}\n\n/** Routed ID-verification UI that survives a full page navigation. */\nexport const OrderIDVerification: FC<OrderIDVerificationProps> = ({\n orderHash,\n onVerified,\n className,\n}) => {\n const [phase, setPhase] = useState<UiPhase>('checking')\n const [failure, setFailure] = useState('')\n\n useEffect(() => {\n if (!orderHash) {\n setPhase('error')\n setFailure('The order reference is missing.')\n return\n }\n let active = true\n ttf.order.idVerificationStatus(orderHash).then(\n (status) => {\n if (!active) return\n if (status.verified || status.required === false) {\n setPhase('verified')\n onVerified?.()\n } else {\n setPhase('idle')\n }\n },\n (error) => {\n if (!active) return\n setPhase('error')\n setFailure(errorMessage(error))\n }\n )\n return () => {\n active = false\n }\n }, [onVerified, orderHash])\n\n const running = phase === 'checking' || phase === 'starting' || phase === 'polling'\n const run = () => {\n setFailure('')\n setPhase('starting')\n runIdVerificationWith(orderHash, {\n openUrl: (url) => {\n window.open(url, '_blank', 'noopener,noreferrer')\n },\n onPhase: (next) => setPhase(next),\n registerForegroundListener: (recheck) => {\n const listener = () => {\n if (document.visibilityState === 'visible') recheck()\n }\n document.addEventListener('visibilitychange', listener)\n return () => document.removeEventListener('visibilitychange', listener)\n },\n }).then(\n (status) => {\n if (status?.verified || status?.required === false) {\n setPhase('verified')\n onVerified?.()\n }\n },\n (error) => {\n setPhase('error')\n setFailure(errorMessage(error))\n }\n )\n }\n\n return (\n <Card className={cx('tf-checkout-idverify', className)}>\n <SectionHeader title=\"Account Verification\" />\n <p\n className={cx(\n 'tf-checkout-note',\n phase === 'verified' && 'tf-checkout-idverify__done'\n )}\n >\n {failure || PHASE_MESSAGE[phase]}\n </p>\n {phase !== 'verified' && orderHash && (\n <Button block onClick={run} loading={running} disabled={running || !orderHash}>\n {phase === 'idle' ? 'Verify' : running ? 'Verifying…' : 'Try again'}\n </Button>\n )}\n </Card>\n )\n}\n","/**\n * `<EmbeddedCheckout eventId=\"…\" />` — the batteries-included checkout. It\n * follows the legacy storefront UX: ticket selection and checkout are separate\n * views, with a compact selection summary + Edit action once the cart is\n * reserved. Want a different layout? Compose the sections yourself — they all\n * read the same `useCheckout()` from the provider.\n */\nimport React, { useCallback, useEffect, useRef, useState, type FC } from 'react'\n\nimport type {\n CheckoutBilling,\n CheckoutConsent,\n CheckoutHolder,\n EventCondition,\n LocaleCode,\n Messages,\n PlaceOrderResult,\n TfProfile,\n} from 'tf-checkout-shared'\n\nimport { AuthModal } from './auth/AuthModal'\nimport { AddOns } from './sections/AddOns'\nimport { BillingInfo } from './sections/BillingInfo'\nimport type { CheckoutPrivacyPolicy } from './sections/BillingInfo'\nimport { Confirmation } from './sections/Confirmation'\nimport { IDVerification } from './sections/IDVerification'\nimport { Payment } from './sections/Payment'\nimport { SeatMap } from './sections/SeatMap'\nimport { Tickets } from './sections/Tickets'\nimport { CheckoutProvider, useCheckoutContext } from './ui/CheckoutProvider'\nimport { TimerBanner } from './ui/TimerBanner'\nimport type { CheckoutTheme } from './ui/theme'\n\nexport interface EmbeddedCheckoutProps {\n /** The event whose tickets to sell. */\n eventId: string\n /** Called with the placed order once payment settles. */\n onComplete?: (order: PlaceOrderResult) => void\n /**\n * `inline` renders verification/confirmation inside the checkout. `redirect`\n * leaves completion routing to `onComplete` and shows a short transition\n * state while the host navigates. Defaults to `inline`.\n */\n confirmationMode?: 'inline' | 'redirect'\n /** Initial checkout screen. Useful for preserving an existing `/seat-map` route. */\n initialView?: 'tickets' | 'seats'\n /** Reports the visible flow view so host storefronts can coordinate mobile UI. */\n onViewChange?: (view: CheckoutView) => void\n /** Smooth-scroll to buyer details after tickets/seats are reserved. Default true. */\n autoScroll?: boolean\n /** Require guests to repeat their email. Defaults to storefront-compatible true. */\n requireEmailConfirmation?: boolean\n /** Collect one named holder per ticket. Defaults true to match tf-sports. */\n collectTicketHolders?: boolean\n /** Collect email/phone when ticket-holder details are required. Defaults true. */\n collectHolderContact?: boolean\n /** Open the host application's login UI instead of the built-in modal. The\n * current buyer email is passed when an existing account was detected. */\n onLogin?: (email?: string) => void\n /** Configure the built-in login/create-account/password-reset modal, or set\n * false to remove auth UI. Ignored when `onLogin` is provided. */\n auth?: false | EmbeddedCheckoutAuthOptions\n /** Legacy skip-billing equivalent for complete signed-in profiles. Payment is\n * never skipped. Defaults false; incompatible holder/custom fields prevent it. */\n skipBillingWhenProfileComplete?: boolean\n /** Optional marketing copy controlled by the embedding brand. */\n ttfOptInLabel?: string\n brandOptInLabel?: string\n /** Consumer-owned privacy policy link and brand name. Required when provided. */\n privacyPolicy?: CheckoutPrivacyPolicy\n /** Host-owned required/optional acknowledgements, e.g. a privacy policy. */\n additionalConditions?: EventCondition[]\n /** Apply/attribute hosted links without requiring a custom Tickets section. */\n initialPromoCode?: string\n referrer?: string | number\n readAttributionFromUrl?: boolean\n /** Opt into sandbox card copy in demos. Defaults false. */\n showTestCardHint?: boolean\n /** Recolor via design tokens. */\n theme?: CheckoutTheme\n /**\n * Language for the checkout's own copy. Defaults to `en-GB`, so existing\n * consumers that never set it render exactly as before.\n */\n locale?: LocaleCode\n /** Per-key copy overrides, merged over the locale. */\n messages?: Partial<Messages>\n className?: string\n}\n\nexport interface EmbeddedCheckoutAuthOptions {\n allowRegistration?: boolean\n allowPasswordReset?: boolean\n requireRegistrationAddress?: boolean\n logoUrl?: string\n onAuthenticated?: (profile: TfProfile) => void\n}\n\ntype SelectionView = 'tickets' | 'seats'\nexport type CheckoutView = SelectionView | 'checkout'\ntype FlowView = CheckoutView\ninterface PreservedDetails {\n billing?: CheckoutBilling\n holders: CheckoutHolder[]\n consent: CheckoutConsent\n}\n\nconst Flow: FC<{\n eventId: string\n onComplete?: (o: PlaceOrderResult) => void\n confirmationMode: 'inline' | 'redirect'\n initialView: SelectionView\n onViewChange?: (view: CheckoutView) => void\n autoScroll: boolean\n requireEmailConfirmation: boolean\n collectTicketHolders: boolean\n collectHolderContact: boolean\n onLogin?: (email?: string) => void\n auth?: false | EmbeddedCheckoutAuthOptions\n skipBillingWhenProfileComplete: boolean\n ttfOptInLabel?: string\n brandOptInLabel?: string\n privacyPolicy?: CheckoutPrivacyPolicy\n additionalConditions: EventCondition[]\n initialPromoCode?: string\n referrer?: string | number\n readAttributionFromUrl: boolean\n showTestCardHint: boolean\n}> = ({\n eventId,\n onComplete,\n confirmationMode,\n initialView,\n onViewChange,\n autoScroll,\n requireEmailConfirmation,\n collectTicketHolders,\n collectHolderContact,\n onLogin,\n auth,\n skipBillingWhenProfileComplete,\n ttfOptInLabel,\n brandOptInLabel,\n privacyPolicy,\n additionalConditions,\n initialPromoCode,\n referrer,\n readAttributionFromUrl,\n showTestCardHint,\n}) => {\n const checkout = useCheckoutContext()\n const [view, setView] = useState<FlowView>(initialView)\n const [selectionView, setSelectionView] = useState<SelectionView>(initialView)\n const checkoutViewRef = useRef<HTMLDivElement | null>(null)\n const editedDetailsRef = useRef<PreservedDetails | null>(null)\n const [authRequest, setAuthRequest] = useState<{\n email?: string\n key: number\n } | null>(null)\n const [privacyAttempted, setPrivacyAttempted] = useState(false)\n\n const openBuiltInAuth = useCallback((email?: string) => {\n setAuthRequest((current) => ({\n email,\n key: (current?.key ?? 0) + 1,\n }))\n }, [])\n const requestLogin = onLogin ?? (auth !== false ? openBuiltInAuth : undefined)\n\n // The engine store is intentionally shared across SDK consumers.\n // Never let state from another event/run select this component's UI view.\n const checkoutBelongsToEvent = checkout.eventId === eventId\n const checkoutViewAvailable = checkoutBelongsToEvent && checkout.status !== 'expired'\n const visibleView: FlowView =\n view === 'checkout' && !checkoutViewAvailable ? 'tickets' : view\n\n useEffect(() => {\n if (\n view === 'checkout' &&\n (!checkoutBelongsToEvent || checkout.status === 'expired')\n ) {\n setView('tickets')\n setSelectionView('tickets')\n }\n }, [checkout.status, checkoutBelongsToEvent, view])\n\n useEffect(() => {\n if (!autoScroll || visibleView !== 'checkout') return\n const timeout = window.setTimeout(() => {\n const behavior = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n ? 'auto'\n : 'smooth'\n checkoutViewRef.current?.scrollIntoView({ behavior, block: 'start' })\n }, 0)\n return () => window.clearTimeout(timeout)\n }, [autoScroll, visibleView])\n\n useEffect(() => {\n onViewChange?.(visibleView)\n }, [onViewChange, visibleView])\n\n const enterCheckout = (from: SelectionView) => {\n const preserved = editedDetailsRef.current\n if (preserved) {\n if (preserved.billing) checkout.setBilling(preserved.billing)\n checkout.setHolders(preserved.holders)\n checkout.setConsent(preserved.consent)\n editedDetailsRef.current = null\n }\n setSelectionView(from)\n setView('checkout')\n }\n\n const editSelection = () => {\n editedDetailsRef.current = {\n billing: checkout.billing,\n holders: checkout.holders,\n consent: checkout.consent,\n }\n setView(selectionView)\n }\n\n const breakdown = checkout.breakdown\n const selectedCount =\n breakdown?.tickets.reduce((total, ticket) => total + ticket.quantity, 0) ??\n checkout.selections.reduce((total, ticket) => total + ticket.quantity, 0)\n // Match the storefront summary: show the reserved tickets' amount, not a\n // moving order total that changes while the buyer picks add-ons.\n const selectedTicketsTotal = breakdown?.tickets.reduce(\n (total, ticket) => total + Number(ticket.total),\n 0\n )\n const formattedTotal = breakdown\n ? breakdown.currencySymbol\n ? `${breakdown.currencySymbol}${Number(selectedTicketsTotal).toFixed(2)}`\n : `${breakdown.currencyCode} ${Number(selectedTicketsTotal).toFixed(2)}`\n : null\n\n // Inline mode renders the receipt in place. Redirect mode intentionally does\n // NOT swap the UI on success — it keeps the checkout mounted (the pay button\n // stays busy) while the host navigates to its own confirmation page, so the\n // checkout never flashes an empty card during the handoff.\n if (\n visibleView === 'checkout' &&\n checkout.status === 'succeeded' &&\n checkout.order &&\n confirmationMode === 'inline'\n ) {\n return (\n <>\n <IDVerification />\n <Confirmation />\n </>\n )\n }\n\n return (\n <>\n {/* Keep Tickets mounted while hidden so Edit restores the buyer's exact\n quantities, promo state, date, and currency instead of starting over. */}\n <div hidden={visibleView !== 'tickets'}>\n <Tickets\n eventId={eventId}\n onContinue={() => enterCheckout('tickets')}\n onSelectSeats={() => setView('seats')}\n initialPromoCode={initialPromoCode}\n referrer={referrer}\n readAttributionFromUrl={readAttributionFromUrl}\n />\n </div>\n\n {visibleView === 'seats' && (\n <div className=\"tf-checkout-flow__seat-view\">\n <button\n type=\"button\"\n className=\"tf-checkout-flow__back\"\n onClick={() => setView('tickets')}\n >\n ← Back to tickets\n </button>\n <SeatMap eventId={eventId} onContinue={() => enterCheckout('seats')} />\n </div>\n )}\n\n {visibleView === 'checkout' && (\n <div ref={checkoutViewRef} className=\"tf-checkout-flow__checkout\">\n <TimerBanner seconds={checkout.secondsLeft} />\n <div className=\"tf-checkout-flow__selection\">\n <span className=\"tf-checkout-flow__selection-text\">\n {selectedCount} {selectedCount === 1 ? 'ticket' : 'tickets'} selected\n {formattedTotal ? ` · ${formattedTotal}` : ''}\n </span>\n <button\n type=\"button\"\n className=\"tf-checkout-flow__edit\"\n onClick={editSelection}\n >\n Edit\n </button>\n </div>\n <AddOns eventId={eventId} />\n <BillingInfo\n eventId={eventId}\n onLogin={requestLogin}\n skipWhenProfileComplete={skipBillingWhenProfileComplete}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n collectHolderContact={collectHolderContact}\n ttfOptInLabel={ttfOptInLabel}\n brandOptInLabel={brandOptInLabel}\n privacyPolicy={privacyPolicy}\n showPrivacyError={privacyAttempted}\n />\n <Payment\n onComplete={onComplete}\n eventId={eventId}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n requireHolderContact={collectHolderContact}\n additionalConditions={additionalConditions}\n requirePrivacyPolicy={Boolean(privacyPolicy)}\n onPrivacyRequired={() => setPrivacyAttempted(true)}\n showTestCardHint={showTestCardHint}\n />\n </div>\n )}\n {authRequest && auth !== false && !onLogin && (\n <AuthModal\n key={authRequest.key}\n open\n initialEmail={authRequest.email}\n message={\n authRequest.email\n ? 'This email already has an account. Log in to autofill your checkout details.'\n : undefined\n }\n allowRegistration={auth?.allowRegistration}\n allowPasswordReset={auth?.allowPasswordReset}\n requireRegistrationAddress={auth?.requireRegistrationAddress}\n logoUrl={auth?.logoUrl}\n onAuthenticated={auth?.onAuthenticated}\n onClose={() => setAuthRequest(null)}\n />\n )}\n </>\n )\n}\n\nexport const EmbeddedCheckout: FC<EmbeddedCheckoutProps> = ({\n eventId,\n onComplete,\n confirmationMode = 'inline',\n initialView = 'tickets',\n onViewChange,\n autoScroll = true,\n requireEmailConfirmation = true,\n collectTicketHolders = true,\n collectHolderContact = true,\n onLogin,\n auth,\n skipBillingWhenProfileComplete = false,\n ttfOptInLabel,\n brandOptInLabel,\n privacyPolicy,\n additionalConditions = [],\n initialPromoCode,\n referrer,\n readAttributionFromUrl = true,\n showTestCardHint = false,\n theme,\n locale,\n messages,\n className,\n}) => (\n <CheckoutProvider\n theme={theme}\n locale={locale}\n messages={messages}\n className={className}\n >\n <Flow\n key={eventId}\n eventId={eventId}\n onComplete={onComplete}\n confirmationMode={confirmationMode}\n initialView={initialView}\n onViewChange={onViewChange}\n autoScroll={autoScroll}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n collectHolderContact={collectHolderContact}\n onLogin={onLogin}\n auth={auth}\n skipBillingWhenProfileComplete={skipBillingWhenProfileComplete}\n ttfOptInLabel={ttfOptInLabel}\n brandOptInLabel={brandOptInLabel}\n privacyPolicy={privacyPolicy}\n additionalConditions={additionalConditions}\n initialPromoCode={initialPromoCode}\n referrer={referrer}\n readAttributionFromUrl={readAttributionFromUrl}\n showTestCardHint={showTestCardHint}\n />\n </CheckoutProvider>\n)\n","import React, { useEffect, useRef, useState, type FC } from 'react'\n\nimport {\n errorMessage,\n type EventCondition,\n type PlaceOrderResult,\n} from 'tf-checkout-shared'\n\nimport { AuthModal } from './auth/AuthModal'\nimport { BillingInfo, type CheckoutPrivacyPolicy } from './sections/BillingInfo'\nimport { Confirmation } from './sections/Confirmation'\nimport { IDVerification } from './sections/IDVerification'\nimport { Payment } from './sections/Payment'\nimport { CheckoutProvider, useCheckoutContext } from './ui/CheckoutProvider'\nimport { Loader } from './ui/Loader'\nimport { TimerBanner } from './ui/TimerBanner'\nimport type { CheckoutTheme } from './ui/theme'\n\nexport interface ResumedCheckoutProps {\n eventId: string\n isFromResale?: boolean\n onComplete?: (order: PlaceOrderResult) => void\n confirmationMode?: 'inline' | 'redirect'\n requireEmailConfirmation?: boolean\n collectTicketHolders?: boolean\n collectHolderContact?: boolean\n privacyPolicy?: CheckoutPrivacyPolicy\n brandOptInLabel?: string\n additionalConditions?: EventCondition[]\n theme?: CheckoutTheme\n className?: string\n}\n\nconst ResumedFlow: FC<Omit<ResumedCheckoutProps, 'theme' | 'className'>> = ({\n eventId,\n isFromResale = false,\n onComplete,\n confirmationMode = 'redirect',\n requireEmailConfirmation = true,\n collectTicketHolders = true,\n collectHolderContact = true,\n privacyPolicy,\n brandOptInLabel,\n additionalConditions = [],\n}) => {\n const checkout = useCheckoutContext()\n const started = useRef(false)\n const [failure, setFailure] = useState('')\n const [authRequest, setAuthRequest] = useState<{ email?: string; key: number } | null>(\n null\n )\n const [privacyAttempted, setPrivacyAttempted] = useState(false)\n\n useEffect(() => {\n if (started.current) return\n started.current = true\n checkout.resumeCart(eventId, { isFromResale }).catch((error) => {\n setFailure(errorMessage(error))\n })\n }, [checkout, eventId, isFromResale])\n\n if (failure) return <p className=\"tf-checkout-error-text\">{failure}</p>\n if (checkout.status === 'idle' || checkout.status === 'priming') {\n return (\n <div className=\"tf-checkout-flow__redirecting\">\n <Loader className=\"tf-checkout-loader--page\" />\n </div>\n )\n }\n if (checkout.status === 'succeeded' && checkout.order) {\n if (confirmationMode === 'redirect') {\n return (\n <div className=\"tf-checkout-flow__redirecting\">\n <Loader className=\"tf-checkout-loader--page\" />\n </div>\n )\n }\n return (\n <>\n <IDVerification />\n <Confirmation />\n </>\n )\n }\n\n return (\n <div className=\"tf-checkout-flow__checkout\">\n <TimerBanner seconds={checkout.secondsLeft} />\n <BillingInfo\n eventId={eventId}\n onLogin={(email) =>\n setAuthRequest((current) => ({ email, key: (current?.key ?? 0) + 1 }))\n }\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n collectHolderContact={collectHolderContact}\n privacyPolicy={privacyPolicy}\n brandOptInLabel={brandOptInLabel}\n showPrivacyError={privacyAttempted}\n />\n <Payment\n eventId={eventId}\n onComplete={onComplete}\n requireEmailConfirmation={requireEmailConfirmation}\n collectTicketHolders={collectTicketHolders}\n requireHolderContact={collectHolderContact}\n additionalConditions={additionalConditions}\n requirePrivacyPolicy={Boolean(privacyPolicy)}\n onPrivacyRequired={() => setPrivacyAttempted(true)}\n />\n {authRequest && (\n <AuthModal\n key={authRequest.key}\n open\n initialEmail={authRequest.email}\n onClose={() => setAuthRequest(null)}\n />\n )}\n </div>\n )\n}\n\n/** Checkout UI for a cart created by a preceding server flow, such as resale. */\nexport const ResumedCheckout: FC<ResumedCheckoutProps> = ({\n theme,\n className,\n ...props\n}) => (\n <CheckoutProvider theme={theme} className={className}>\n <ResumedFlow {...props} />\n </CheckoutProvider>\n)\n"],"mappings":";;;;;;;AAWA,OAAO;AACP,OAAO;;;ACMA,IAAM,sBAAsB,MAAsB;AACvD,QAAM,MAAM,oBAAI,IAAoB;AACpC,SAAO;AAAA,IACL,SAAS,CAAC,QAAS,IAAI,IAAI,GAAG,IAAK,IAAI,IAAI,GAAG,IAAe;AAAA,IAC7D,SAAS,CAAC,KAAK,UAAU,KAAK,IAAI,IAAI,KAAK,KAAK;AAAA,IAChD,YAAY,CAAC,QAAQ,KAAK,IAAI,OAAO,GAAG;AAAA,EAC1C;AACF;;;ACdO,IAAM,YAAoC;AAAA,EAC/C,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KAAK;AACP;AAKO,IAAM,cAAc,CAAC,KAAc,YAA6B;AACrE,MAAI,YAAY,OAAW,QAAO,UAAU,oBAAO,MAAM;AACzD,QAAM,UAAU,QAAQ,QAAQ,QAAQ,EAAE;AAC1C,SAAO,SAAS,KAAK,OAAO,IAAI,QAAQ,QAAQ,UAAU,EAAE,IAAI;AAClE;AA+CA,IAAI,UAAoC;AAGjC,IAAM,YAAY,CAAC,WAA4B;AA1EtD;AA2EE,QAAM,OAAO,YAAY,OAAO,KAAK,OAAO,OAAO;AACnD,YAAU;AAAA,IACR,GAAG;AAAA,IACH,UAAS,YAAO,YAAP,YAAkB,oBAAoB;AAAA,IAC/C;AAAA,IACA,YAAY,GAAG,IAAI;AAAA,EACrB;AACF;AAGO,IAAM,YAAY,MAAyB;AAChD,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;A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","result","hasValue","g","f","_a","result","needIdVerification","messageFrom","current","_a","logout","_b","useQuery","useQuery","useQuery","useQuery","useQuery","useQuery","useMutation","useMutation","useCallback","useState","useSyncExternalStore","useSyncExternalStore","useState","useCallback","result","_a","attributeReferrer","joinWaitingList","error","paymentIntent","e","useCheckout","useEffect","useRef","useState","useRef","useEffect","useState","React","createContext","useCallback","useContext","useEffect","useRef","useState","React","React","React","useCallback","useState","React","React","React","React","useState","useCallback","React","createContext","useRef","useState","useCallback","current","useEffect","React","useCheckout","useContext","React","React","React","forwardRef","React","forwardRef","React","React","React","React","React","React","React","React","React","React","React","React","React","useState","clock","useState","React","React","useCallback","useEffect","useRef","React","useEffect","useState","useState","useEffect","React","React","useEffect","useState","React","forwardRef","useState","forwardRef","useState","React","current","useState","useEffect","React","React","useEffect","useMemo","useState","useState","useMemo","_a","useEffect","current","patch","React","useCallback","useRef","useEffect","_a","_b","React","React","useMemo","useState","useState","useMemo","React","React","useEffect","useRef","useState","useState","React","useEffect","useRef","_a","_b","_c","code","current","React","useCallback","useEffect","useRef","useState","useState","useRef","useEffect","_a","_b","_c","_d","useCallback","React","React","Fragment","useEffect","useMemo","useState","useState","useMemo","useEffect","_a","t","React","Fragment","_b","React","Fragment","useEffect","useMemo","useRef","useState","PhoneInput","React","current","React","_a","React","React","React","PhoneInput","React","PhoneInput","useState","_a","_b","useRef","useMemo","useEffect","dobYear","dobMonth","dobDay","_c","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","_p","_q","_r","_s","_t","t","current","patch","React","PhoneInput","Fragment","React","useEffect","useMemo","useRef","useState","React","React","_a","useState","useRef","useEffect","useMemo","_a","_b","_c","t","React","patch","React","useState","useState","React","React","useState","useState","React","React","useEffect","useRef","useState","useState","useRef","useEffect","_a","React","React","useEffect","useState","useState","useEffect","React","React","useCallback","useEffect","useRef","useState","useState","useRef","useCallback","current","_a","useEffect","React","React","useEffect","useRef","useState","useRef","useState","useEffect","React","current"]}
|